From 3f77685e193f1dfff6a6afe1bc777efb4807983c Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Tue, 1 Dec 2026 11:57:33 +1000 Subject: [PATCH 1/7] Speed up WebP and JPEG XL encode and decode - JPEG XL lossless: port the libjxl effort 1 fast lossless mode (global per-channel tree, YCoCg, sampled histograms, bounded code lengths, zero runs, palette detection), with SIMD field operators. - JPEG XL entropy: SIMD token count and 64-bit field writer for the general sample streams. - WebP: codec performance work and simplification. - Shared: vector helpers (variable shifts with SSE fallbacks, gather), modular forward YCoCg, hybrid integer 0/0/0 vector split, tests. --- .../Common/Helpers/ColorNumerics.cs | 14 +- .../Common/Helpers/IBitwiseReduction.cs | 104 + src/ImageSharp/Common/Helpers/Numerics.cs | 141 +- .../Common/Helpers/SimdUtils.AddLeft.cs | 251 ++ .../Common/Helpers/SimdUtils.Convert.cs | 11 +- .../Common/Helpers/SimdUtils.ExtractBytes.cs | 108 + .../Common/Helpers/SimdUtils.HwIntrinsics.cs | 91 +- .../Common/Helpers/SimdUtils.Pack.cs | 193 +- .../Common/Helpers/SimdUtils.Reduce.cs | 113 + .../Common/Helpers/Vector128Utilities.cs | 166 +- .../Common/Helpers/Vector256Utilities.cs | 94 + .../Common/Helpers/Vector512Utilities.cs | 123 + src/ImageSharp/Common/InlineArray.cs | 18 + src/ImageSharp/Common/InlineArray.tt | 8 +- .../Compression/HuffmanCodeLengths.cs | 151 + .../Lossless => Compression}/HuffmanTree.cs | 4 +- src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs | 87 +- ...traSuperblockEncoder.TransformTypeModel.cs | 368 ++ .../ColorConverters/HeifSampleConversion.cs | 12 +- .../JpegColorConverter.CmykOperator.cs | 39 +- .../JpegColorConverter.GrayScaleOperator.cs | 15 +- .../ColorConverters/JpegColorConverter.Icc.cs | 18 +- .../JpegColorConverter.Operator.cs | 11 +- .../JpegColorConverter.RgbOperator.cs | 31 +- .../JpegColorConverter.TiffCmykOperator.cs | 39 +- .../JpegColorConverter.TiffYccKOperator.cs | 42 +- .../JpegColorConverter.YCbCrOperator.cs | 55 +- .../JpegColorConverter.YccKOperator.cs | 39 +- .../ColorConverters/JxlSampleConverter.cs | 87 +- .../Jxl/Components/Decoder/JxlIccReader.cs | 7 +- .../Jxl/Components/Entropy/JxlHybridUint.cs | 188 + .../Modular/JxlModularColorTransform.cs | 83 +- .../Jxl/Components/Modular/JxlModularTree.cs | 7 +- .../Jxl/Components/VarDct/JxlAcContexts.cs | 58 + .../VarDct/JxlVarDctDecoder.Coefficients.cs | 30 +- .../Jxl/Components/VarDct/JxlVarDctDecoder.cs | 12 +- src/ImageSharp/Formats/Jxl/JxlConstants.cs | 11 + .../Formats/Jxl/JxlEncoderCore.Ac.cs | 395 ++ .../Formats/Jxl/JxlEncoderCore.Entropy.cs | 1596 +++++++ .../Jxl/JxlEncoderCore.FastLossless.cs | 1671 +++++++ ...xlEncoderCore.FastLosslessFieldOperator.cs | 231 + .../Jxl/JxlEncoderCore.PrefixFieldOperator.cs | 151 + src/ImageSharp/Formats/Jxl/JxlEncoderCore.cs | 1027 ++--- src/ImageSharp/Formats/PaletteExpander.cs | 327 +- .../Formats/Png/Filters/IPngFilterOperator.cs | 31 +- .../Formats/Png/Filters/PngFilterDecoder.cs | 8 + src/ImageSharp/Formats/Webp/AlphaDecoder.cs | 468 +- src/ImageSharp/Formats/Webp/AlphaEncoder.cs | 224 +- .../Formats/Webp/BitReader/BitReaderBase.cs | 37 +- .../Formats/Webp/BitReader/Vp8BitReader.cs | 212 +- .../Formats/Webp/BitReader/Vp8LBitReader.cs | 228 +- .../Formats/Webp/BitWriter/BitWriterBase.cs | 111 +- .../Formats/Webp/BitWriter/Vp8BitWriter.cs | 338 +- .../Formats/Webp/BitWriter/Vp8LBitWriter.cs | 119 +- .../WebpColorConverter.Decoding.cs | 1217 ------ .../WebpColorConverter.Encoding.cs | 524 --- .../ColorConverters/WebpColorConverter.Icc.cs | 208 + .../WebpColorConverter.Operator.cs | 687 ++- .../WebpColorConverter.RgbOperator.cs | 125 +- .../WebpColorConverter.YCbCrIccOperator.cs | 91 - .../WebpColorConverter.YCbCrOperator.cs | 237 +- .../ColorConverters/WebpColorConverterBase.cs | 243 +- .../Webp/{EntropyIx.cs => EntropyIndex.cs} | 2 +- src/ImageSharp/Formats/Webp/HistoIx.cs | 35 - src/ImageSharp/Formats/Webp/HistogramIndex.cs | 81 + .../Webp/Lossless/BackwardReferenceEncoder.cs | 998 +++-- .../Formats/Webp/Lossless/ColorCache.cs | 88 +- .../Webp/Lossless/ColorSpaceTransformUtils.cs | 604 +-- .../Webp/Lossless/CostCacheInterval.cs | 17 +- .../Formats/Webp/Lossless/CostInterval.cs | 44 +- .../Formats/Webp/Lossless/CostManager.cs | 400 +- .../Formats/Webp/Lossless/CostModel.cs | 145 +- .../Formats/Webp/Lossless/CrunchConfig.cs | 11 - .../Webp/Lossless/CrunchConfiguration.cs | 20 + .../Formats/Webp/Lossless/CrunchSubConfig.cs | 11 - .../Webp/Lossless/CrunchSubConfiguration.cs | 20 + .../Formats/Webp/Lossless/HTreeGroup.cs | 58 - .../Formats/Webp/Lossless/HistogramEncoder.cs | 322 +- .../Formats/Webp/Lossless/HistogramPair.cs | 23 +- .../{HuffIndex.cs => HuffmanIndex.cs} | 2 +- .../Formats/Webp/Lossless/HuffmanTreeCode.cs | 25 - .../Formats/Webp/Lossless/HuffmanTreeGroup.cs | 85 + .../Formats/Webp/Lossless/HuffmanTreeToken.cs | 5 +- .../Formats/Webp/Lossless/HuffmanUtils.cs | 261 +- .../Webp/Lossless/LosslessUtils.Operators.cs | 249 ++ .../Lossless/LosslessUtils.PixelTransforms.cs | 388 ++ .../Webp/Lossless/LosslessUtils.Predictors.cs | 1256 ++++++ .../Formats/Webp/Lossless/LosslessUtils.cs | 1970 ++++----- .../Formats/Webp/Lossless/NearLosslessEnc.cs | 122 - .../Webp/Lossless/NearLosslessEncoder.cs | 427 ++ .../Formats/Webp/Lossless/PixOrCopy.cs | 41 - .../Formats/Webp/Lossless/PixOrCopyMode.cs | 15 - .../Formats/Webp/Lossless/PixelOrCopy.cs | 106 + .../Formats/Webp/Lossless/PixelOrCopyMode.cs | 30 + .../Formats/Webp/Lossless/PredictorEncoder.cs | 1189 +++-- .../Webp/Lossless/Vp8LBackwardReferences.cs | 148 + .../Formats/Webp/Lossless/Vp8LBackwardRefs.cs | 28 - .../Formats/Webp/Lossless/Vp8LBitEntropy.cs | 93 +- .../Formats/Webp/Lossless/Vp8LDecoder.cs | 49 +- .../Formats/Webp/Lossless/Vp8LEncoder.cs | 2033 +++++---- .../Formats/Webp/Lossless/Vp8LHashChain.cs | 183 +- .../Formats/Webp/Lossless/Vp8LHistogram.cs | 769 ++-- .../Formats/Webp/Lossless/Vp8LHistogramSet.cs | 145 +- .../Formats/Webp/Lossless/Vp8LMetadata.cs | 109 +- .../Formats/Webp/Lossless/Vp8LStreaks.cs | 51 +- .../Webp/Lossless/WebpLosslessDecoder.cs | 1215 ++++-- .../Formats/Webp/Lossy/ChromaDownsampler.cs | 192 + .../Formats/Webp/Lossy/ChromaUpsampler.cs | 226 + .../Formats/Webp/Lossy/LossyUtils.cs | 3822 +++++++++++------ .../Formats/Webp/Lossy/PassStatistics.cs | 127 + .../Formats/Webp/Lossy/PassStats.cs | 75 - src/ImageSharp/Formats/Webp/Lossy/QuantEnc.cs | 886 ---- .../Webp/Lossy/RgbToYuvConverter{TPixel}.cs | 178 + .../Formats/Webp/Lossy/Vp8BandProbas.cs | 27 - .../Formats/Webp/Lossy/Vp8CostArray.cs | 14 - src/ImageSharp/Formats/Webp/Lossy/Vp8Costs.cs | 24 - .../Formats/Webp/Lossy/Vp8Decoder.cs | 184 +- .../Formats/Webp/Lossy/Vp8DiffusionErrors.cs | 27 + .../Formats/Webp/Lossy/Vp8EncIterator.cs | 973 ----- .../Formats/Webp/Lossy/Vp8EncProba.cs | 263 -- .../Formats/Webp/Lossy/Vp8Encoder.cs | 1125 ++++- .../Formats/Webp/Lossy/Vp8EncoderIterator.cs | 1435 +++++++ .../Webp/Lossy/Vp8EncoderProbabilities.cs | 330 ++ ...ntHeader.cs => Vp8EncoderSegmentHeader.cs} | 9 +- .../Webp/Lossy/Vp8Encoding.Operators.cs | 136 + .../Formats/Webp/Lossy/Vp8Encoding.cs | 1498 +++++-- .../Formats/Webp/Lossy/Vp8FilterInfo.cs | 64 +- .../Formats/Webp/Lossy/Vp8Histogram.cs | 143 +- src/ImageSharp/Formats/Webp/Lossy/Vp8Io.cs | 65 - .../Formats/Webp/Lossy/Vp8MacroBlock.cs | 6 +- .../Formats/Webp/Lossy/Vp8MacroBlockData.cs | 31 +- .../Formats/Webp/Lossy/Vp8MacroBlockInfo.cs | 24 +- .../Formats/Webp/Lossy/Vp8ModeScore.cs | 39 +- .../Formats/Webp/Lossy/Vp8PictureHeader.cs | 10 - src/ImageSharp/Formats/Webp/Lossy/Vp8Proba.cs | 43 - .../Formats/Webp/Lossy/Vp8ProbaArray.cs | 20 - .../Formats/Webp/Lossy/Vp8Probabilities.cs | 59 + .../Formats/Webp/Lossy/Vp8QuantMatrix.cs | 33 - .../Formats/Webp/Lossy/Vp8Quantization.cs | 1594 +++++++ .../Webp/Lossy/Vp8QuantizationMatrix.cs | 25 + ...p8RDLevel.cs => Vp8RateDistortionLevel.cs} | 2 +- .../Formats/Webp/Lossy/Vp8Residual.cs | 448 +- .../Formats/Webp/Lossy/Vp8SegmentHeader.cs | 3 + .../Formats/Webp/Lossy/Vp8SegmentInfo.cs | 42 +- src/ImageSharp/Formats/Webp/Lossy/Vp8Stats.cs | 21 - .../Formats/Webp/Lossy/Vp8StatsArray.cs | 14 - .../Formats/Webp/Lossy/Vp8TokenBuffer.cs | 183 + .../Formats/Webp/Lossy/Vp8TopSamples.cs | 13 - .../Formats/Webp/Lossy/WebpLossyDecoder.cs | 927 ++-- .../Webp/Lossy/YuvToRgbConverter{TPixel}.cs | 215 + src/ImageSharp/Formats/Webp/RiffHelper.cs | 64 +- .../Formats/Webp/WebpAnimationDecoder.cs | 75 +- .../Formats/Webp/WebpChunkParsingUtils.cs | 29 +- .../Formats/Webp/WebpCommonUtils.cs | 180 +- src/ImageSharp/Formats/Webp/WebpConstants.cs | 206 +- .../Formats/Webp/WebpDecoderCore.cs | 29 +- .../Formats/Webp/WebpEncoderCore.cs | 54 +- src/ImageSharp/Formats/Webp/WebpImageInfo.cs | 33 +- .../Formats/Webp/WebpLookupTables.cs | 463 +- .../PixelBlenders/PorterDuffFunctions.cs | 48 +- .../PixelImplementations/Abgr32.cs | 13 +- .../PixelImplementations/Abgr32P.cs | 16 - .../PixelImplementations/Argb32.cs | 10 +- .../PixelImplementations/Argb32P.cs | 16 - .../PixelImplementations/Bgr24.cs | 9 +- .../PixelImplementations/Bgra32.cs | 10 +- .../PixelImplementations/Bgra32P.cs | 16 - .../PixelFormats/PixelImplementations/L8.cs | 15 +- .../PixelFormats/PixelImplementations/La16.cs | 16 +- .../PixelOperations/Rgba32.PixelOperations.cs | 15 + .../PixelImplementations/Rgb24.cs | 9 +- .../PixelImplementations/Rgba32.cs | 10 +- .../PixelImplementations/Rgba32P.cs | 16 - .../PixelImplementations/RgbaVector.cs | 12 +- .../PixelFormats/PixelOperations{TPixel}.cs | 67 + ...Rgba32CompatiblePixelOperations{TPixel}.cs | 22 +- .../Utils/PixelConverter.Rgba32Sources.cs | 57 +- .../Utils/PixelConverter.Rgba64Sources.cs | 42 +- .../ImageSharp.Tests/Common/SimdUtilsTests.cs | 11 +- .../Common/Vector128UtilitiesTests.cs | 71 + .../Formats/Jxl/JxlHybridUintTests.cs | 194 + .../Formats/WebP/LosslessUtilsTests.cs | 52 +- .../Formats/WebP/PredictorEncoderTests.cs | 29 +- .../Formats/WebP/Vp8BitWriterTests.cs | 24 +- .../Formats/WebP/Vp8EncodingTests.cs | 19 +- .../Formats/WebP/Vp8LHistogramTests.cs | 17 +- ...antEncTests.cs => Vp8QuantizationTests.cs} | 7 +- .../Formats/WebP/Vp8ResidualTests.cs | 225 +- .../Formats/WebP/WebpDecoderTests.cs | 41 + .../Formats/WebP/WebpEncoderTests.cs | 91 +- .../Formats/WebP/YuvConversionTests.cs | 25 +- .../PixelFormats/AssociatedAlphaPixelTests.cs | 35 +- .../PixelFormats/PixelBlenderTests.cs | 9 +- ...tColor_WithHexadecatreeQuantizer_rgb32.bmp | 2 +- ...Encode_8BitColor_WithWuQuantizer_rgb32.bmp | 2 +- ...Processor_TestPattern200x100_R16_C1_G3.png | 4 +- ...Processor_TestPattern200x100_R16_C2_G3.png | 4 +- ...onFilterInBox_Rgba32_CalliphoraPartial.png | 4 +- ...DependOnSinglePixelType_Bgra32_filter0.png | 4 +- ...tDependOnSinglePixelType_Rgb24_filter0.png | 4 +- ...DependOnSinglePixelType_Rgba32_filter0.png | 4 +- ...rksWithAllErrorDiffusers_Bike_Atkinson.png | 4 +- ..._WorksWithAllErrorDiffusers_Bike_Burks.png | 4 +- ...hAllErrorDiffusers_Bike_FloydSteinberg.png | 4 +- ...lErrorDiffusers_Bike_JarvisJudiceNinke.png | 4 +- ...orksWithAllErrorDiffusers_Bike_Sierra2.png | 4 +- ...orksWithAllErrorDiffusers_Bike_Sierra3.png | 4 +- ...sWithAllErrorDiffusers_Bike_SierraLite.png | 4 +- ...thAllErrorDiffusers_Bike_StevensonArce.png | 4 +- ...WorksWithAllErrorDiffusers_Bike_Stucki.png | 4 +- ...orDiffusers_CalliphoraPartial_Atkinson.png | 4 +- ...ErrorDiffusers_CalliphoraPartial_Burks.png | 4 +- ...users_CalliphoraPartial_FloydSteinberg.png | 4 +- ...rs_CalliphoraPartial_JarvisJudiceNinke.png | 4 +- ...rorDiffusers_CalliphoraPartial_Sierra2.png | 4 +- ...rorDiffusers_CalliphoraPartial_Sierra3.png | 4 +- ...Diffusers_CalliphoraPartial_SierraLite.png | 4 +- ...fusers_CalliphoraPartial_StevensonArce.png | 4 +- ...rrorDiffusers_CalliphoraPartial_Stucki.png | 4 +- ...ackWhiteFilter_Rgba32_TestPattern48x48.png | 4 +- ...rastFilter_Rgba32_TestPattern48x48_0.5.png | 4 +- ...rastFilter_Rgba32_TestPattern48x48_1.5.png | 4 +- ...leFilter_Rgba32_TestPattern48x48_Bt601.png | 4 +- ...leFilter_Rgba32_TestPattern48x48_Bt709.png | 4 +- ...HueFilter_Rgba32_TestPattern48x48_-180.png | 4 +- ...yHueFilter_Rgba32_TestPattern48x48_180.png | 4 +- ...lyInvertFilter_Rgba32_TestPattern48x48.png | 4 +- ...dachromeFilter_Rgba32_TestPattern48x48.png | 4 +- ...omographFilter_Rgba32_TestPattern48x48.png | 4 +- ...lphaFilter_Rgba32_TestPattern48x48_0.2.png | 4 +- ...PolaroidFilter_Rgba32_TestPattern48x48.png | 4 +- ...tionFilter_Rgba32_TestPattern48x48_0.5.png | 4 +- ...tionFilter_Rgba32_TestPattern48x48_1.5.png | 4 +- ...plySepiaFilter_Rgba32_TestPattern48x48.png | 4 +- ...r_Decode_Resize_Box_Calliphora_140_140.png | 4 +- .../00.png | 4 +- .../08.png | 4 +- .../104.png | 4 +- .../112.png | 4 +- .../16.png | 4 +- .../24.png | 4 +- .../32.png | 4 +- .../40.png | 4 +- .../48.png | 4 +- .../56.png | 4 +- .../64.png | 4 +- .../72.png | 4 +- .../80.png | 4 +- .../88.png | 4 +- .../96.png | 4 +- .../00.png | 4 +- .../08.png | 4 +- ...zed_Encode_Artifacts_Rgba32_issue_2469.png | 4 +- ...antized_Encode_Alpha_Rgba32_Issue_2668.png | 4 +- ...id_HexadecatreeQuantizer_ErrorDither_1.png | 4 +- ...bSafePaletteQuantizer_ErrorDither_0.75.png | 4 +- ..._WebSafePaletteQuantizer_ErrorDither_1.png | 4 +- ...ernerPaletteQuantizer_ErrorDither_0.75.png | 4 +- ...d_WernerPaletteQuantizer_ErrorDither_1.png | 4 +- ...gScale_david_WuQuantizer_ErrorDither_1.png | 4 +- ...Bike_HexadecatreeQuantizer_ErrorDither.png | 4 +- ...ke_WebSafePaletteQuantizer_ErrorDither.png | 4 +- ...ike_WernerPaletteQuantizer_ErrorDither.png | 4 +- ...ntization_Bike_WuQuantizer_ErrorDither.png | 4 +- ...tial_HexadecatreeQuantizer_ErrorDither.png | 4 +- ...al_WebSafePaletteQuantizer_ErrorDither.png | 4 +- ...ial_WernerPaletteQuantizer_ErrorDither.png | 4 +- ...liphoraPartial_WuQuantizer_ErrorDither.png | 4 +- ...llResamplers_CalliphoraPartial_Box-0.5.png | 4 +- ...AppliedCorrectly_TestPattern100x100_50.png | 4 +- ...AppliedCorrectly_TestPattern100x100_60.png | 4 +- ...ppliedCorrectly_TestPattern100x400_110.png | 4 +- .../Flip_TestPattern20x37_Horizontal.png | 4 +- .../FlipTests/Flip_TestPattern20x37_None.png | 4 +- .../Flip_TestPattern20x37_Vertical.png | 4 +- 275 files changed, 30541 insertions(+), 14968 deletions(-) create mode 100644 src/ImageSharp/Common/Helpers/IBitwiseReduction.cs create mode 100644 src/ImageSharp/Common/Helpers/SimdUtils.AddLeft.cs create mode 100644 src/ImageSharp/Common/Helpers/SimdUtils.ExtractBytes.cs create mode 100644 src/ImageSharp/Common/Helpers/SimdUtils.Reduce.cs create mode 100644 src/ImageSharp/Compression/HuffmanCodeLengths.cs rename src/ImageSharp/{Formats/Webp/Lossless => Compression}/HuffmanTree.cs (89%) create mode 100644 src/ImageSharp/Formats/Jxl/Components/VarDct/JxlAcContexts.cs create mode 100644 src/ImageSharp/Formats/Jxl/JxlEncoderCore.Ac.cs create mode 100644 src/ImageSharp/Formats/Jxl/JxlEncoderCore.Entropy.cs create mode 100644 src/ImageSharp/Formats/Jxl/JxlEncoderCore.FastLossless.cs create mode 100644 src/ImageSharp/Formats/Jxl/JxlEncoderCore.FastLosslessFieldOperator.cs create mode 100644 src/ImageSharp/Formats/Jxl/JxlEncoderCore.PrefixFieldOperator.cs delete mode 100644 src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Decoding.cs delete mode 100644 src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Encoding.cs create mode 100644 src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Icc.cs delete mode 100644 src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.YCbCrIccOperator.cs rename src/ImageSharp/Formats/Webp/{EntropyIx.cs => EntropyIndex.cs} (91%) delete mode 100644 src/ImageSharp/Formats/Webp/HistoIx.cs create mode 100644 src/ImageSharp/Formats/Webp/HistogramIndex.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossless/CrunchConfig.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossless/CrunchConfiguration.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossless/CrunchSubConfig.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossless/CrunchSubConfiguration.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossless/HTreeGroup.cs rename src/ImageSharp/Formats/Webp/Lossless/{HuffIndex.cs => HuffmanIndex.cs} (95%) delete mode 100644 src/ImageSharp/Formats/Webp/Lossless/HuffmanTreeCode.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossless/HuffmanTreeGroup.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.Operators.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.PixelTransforms.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.Predictors.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossless/NearLosslessEnc.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossless/NearLosslessEncoder.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossless/PixOrCopy.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossless/PixOrCopyMode.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossless/PixelOrCopy.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossless/PixelOrCopyMode.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossless/Vp8LBackwardReferences.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossless/Vp8LBackwardRefs.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossy/ChromaDownsampler.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossy/ChromaUpsampler.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossy/PassStatistics.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossy/PassStats.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossy/QuantEnc.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossy/RgbToYuvConverter{TPixel}.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8BandProbas.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8CostArray.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8Costs.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8DiffusionErrors.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8EncIterator.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8EncProba.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderIterator.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderProbabilities.cs rename src/ImageSharp/Formats/Webp/Lossy/{Vp8EncSegmentHeader.cs => Vp8EncoderSegmentHeader.cs} (72%) create mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.Operators.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8Io.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8Proba.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8ProbaArray.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8Probabilities.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8QuantMatrix.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8Quantization.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8QuantizationMatrix.cs rename src/ImageSharp/Formats/Webp/Lossy/{Vp8RDLevel.cs => Vp8RateDistortionLevel.cs} (94%) delete mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8Stats.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8StatsArray.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8TokenBuffer.cs delete mode 100644 src/ImageSharp/Formats/Webp/Lossy/Vp8TopSamples.cs create mode 100644 src/ImageSharp/Formats/Webp/Lossy/YuvToRgbConverter{TPixel}.cs create mode 100644 tests/ImageSharp.Tests/Common/Vector128UtilitiesTests.cs create mode 100644 tests/ImageSharp.Tests/Formats/Jxl/JxlHybridUintTests.cs rename tests/ImageSharp.Tests/Formats/WebP/{QuantEncTests.cs => Vp8QuantizationTests.cs} (94%) diff --git a/src/ImageSharp/Common/Helpers/ColorNumerics.cs b/src/ImageSharp/Common/Helpers/ColorNumerics.cs index 98a59dbade..25c7fcbefb 100644 --- a/src/ImageSharp/Common/Helpers/ColorNumerics.cs +++ b/src/ImageSharp/Common/Helpers/ColorNumerics.cs @@ -84,7 +84,7 @@ CicpColorPrimaries.ItuRBt601_7_525 or CicpColorPrimaries.SmpteSt240 /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte Get8BitBT709Luminance(byte r, byte g, byte b) - => (byte)((r * .2126F) + (g * .7152F) + (b * .0722F) + 0.5F); + => (byte)MathF.Round((r * .2126F) + (g * .7152F) + (b * .0722F)); /// /// Gets the luminance from the rgb components using the formula @@ -96,9 +96,7 @@ public static byte Get8BitBT709Luminance(byte r, byte g, byte b) /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte Get8BitBT709Luminance(ushort r, ushort g, ushort b) - => (byte)((From16BitTo8Bit(r) * .2126F) + - (From16BitTo8Bit(g) * .7152F) + - (From16BitTo8Bit(b) * .0722F) + 0.5F); + => (byte)MathF.Round((From16BitTo8Bit(r) * .2126F) + (From16BitTo8Bit(g) * .7152F) + (From16BitTo8Bit(b) * .0722F)); /// /// Gets the luminance from the rgb components using the formula as @@ -110,9 +108,7 @@ public static byte Get8BitBT709Luminance(ushort r, ushort g, ushort b) /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ushort Get16BitBT709Luminance(byte r, byte g, byte b) - => (ushort)((From8BitTo16Bit(r) * .2126F) + - (From8BitTo16Bit(g) * .7152F) + - (From8BitTo16Bit(b) * .0722F) + 0.5F); + => (ushort)MathF.Round((From8BitTo16Bit(r) * .2126F) + (From8BitTo16Bit(g) * .7152F) + (From8BitTo16Bit(b) * .0722F)); /// /// Gets the luminance from the rgb components using the formula as @@ -124,7 +120,7 @@ public static ushort Get16BitBT709Luminance(byte r, byte g, byte b) /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ushort Get16BitBT709Luminance(ushort r, ushort g, ushort b) - => (ushort)((r * .2126F) + (g * .7152F) + (b * .0722F) + 0.5F); + => (ushort)MathF.Round((r * .2126F) + (g * .7152F) + (b * .0722F)); /// /// Gets the luminance from the rgb components using the formula as specified @@ -136,7 +132,7 @@ public static ushort Get16BitBT709Luminance(ushort r, ushort g, ushort b) /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ushort Get16BitBT709Luminance(float r, float g, float b) - => (ushort)((r * .2126F) + (g * .7152F) + (b * .0722F) + 0.5F); + => (ushort)MathF.Round((r * .2126F) + (g * .7152F) + (b * .0722F)); /// /// Scales a value from a 16 bit to an diff --git a/src/ImageSharp/Common/Helpers/IBitwiseReduction.cs b/src/ImageSharp/Common/Helpers/IBitwiseReduction.cs new file mode 100644 index 0000000000..7a90ecc9d7 --- /dev/null +++ b/src/ImageSharp/Common/Helpers/IBitwiseReduction.cs @@ -0,0 +1,104 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; + +namespace SixLabors.ImageSharp; + +/// +/// Defines an associative and commutative bitwise operation that reduces packed 32-bit values to one value. +/// +/// +/// The operation must give the same result for any order and grouping of its operands. +/// relies on this rule when it combines lanes and vectors. +/// +internal interface IBitwiseReduction +{ + /// + /// Gets the value that does not change an operand when the operation combines them. + /// + public static abstract uint Identity { get; } + + /// + /// Combines two values. + /// + /// The first value. + /// The second value. + /// The combined value. + public static abstract uint Invoke(uint left, uint right); + + /// + /// Combines two 128-bit vectors lane by lane. + /// + /// The first vector. + /// The second vector. + /// The combined vector. + public static abstract Vector128 Invoke(Vector128 left, Vector128 right); + + /// + /// Combines two 256-bit vectors lane by lane. + /// + /// The first vector. + /// The second vector. + /// The combined vector. + public static abstract Vector256 Invoke(Vector256 left, Vector256 right); + + /// + /// Combines two 512-bit vectors lane by lane. + /// + /// The first vector. + /// The second vector. + /// The combined vector. + public static abstract Vector512 Invoke(Vector512 left, Vector512 right); +} + +/// +/// Reduces values with bitwise AND. A bit of the result is set only when that bit is set in every value. +/// +internal readonly struct BitwiseAndReduction : IBitwiseReduction +{ + /// + public static uint Identity => uint.MaxValue; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint Invoke(uint left, uint right) => left & right; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 Invoke(Vector128 left, Vector128 right) => left & right; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 Invoke(Vector256 left, Vector256 right) => left & right; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector512 Invoke(Vector512 left, Vector512 right) => left & right; +} + +/// +/// Reduces values with bitwise OR. A bit of the result is set when that bit is set in any value. +/// +internal readonly struct BitwiseOrReduction : IBitwiseReduction +{ + /// + public static uint Identity => 0; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint Invoke(uint left, uint right) => left | right; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 Invoke(Vector128 left, Vector128 right) => left | right; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 Invoke(Vector256 left, Vector256 right) => left | right; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector512 Invoke(Vector512 left, Vector512 right) => left | right; +} diff --git a/src/ImageSharp/Common/Helpers/Numerics.cs b/src/ImageSharp/Common/Helpers/Numerics.cs index 2f81f8bb83..a3644734d4 100644 --- a/src/ImageSharp/Common/Helpers/Numerics.cs +++ b/src/ImageSharp/Common/Helpers/Numerics.cs @@ -2,7 +2,6 @@ // Licensed under the Six Labors Split License. using System.Numerics; -using System.Numerics.Tensors; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; @@ -17,12 +16,23 @@ namespace SixLabors.ImageSharp; /// internal static class Numerics { + /// + /// The control that takes lanes 3 and 7 (the W lanes) from the second operand. + /// All other lanes come from the first operand. + /// public const int BlendAlphaControl = 0b_10_00_10_00; + + /// + /// The shuffle control that copies element 3 (W) of each four-lane group into all four lanes of that group. + /// private const int ShuffleAlphaControl = 0b_11_11_11_11; /// /// Determine the Greatest CommonDivisor (GCD) of two numbers. /// + /// The first value. + /// The second value. + /// The greatest common divisor, or zero when both values are zero. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GreatestCommonDivisor(int a, int b) { @@ -60,6 +70,9 @@ public static ulong GreatestCommonDivisor(ulong a, ulong b) /// Determine the Least Common Multiple (LCM) of two numbers. /// See https://en.wikipedia.org/wiki/Least_common_multiple#Reduction_by_the_greatest_common_divisor. /// + /// The first value. + /// The second value. + /// The least common multiple of the two values. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LeastCommonMultiple(int a, int b) => a / GreatestCommonDivisor(a, b) * b; @@ -67,60 +80,93 @@ public static int LeastCommonMultiple(int a, int b) /// /// Calculates % 2 /// + /// The value to divide. + /// The non-negative remainder, in the range 0 to 1. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Modulo2(int x) => x & 1; /// /// Calculates % 4 /// + /// The value to divide. + /// The non-negative remainder, in the range 0 to 3. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Modulo4(int x) => x & 3; + /// + /// Clamps a value to the range 0 to 255. + /// + /// + /// A value in range passes the unsigned compare. A negative value has its high bits set, so its complement shifted down by 24 is 0. A value above 255 + /// and less than 2^24 has its high 8 bits clear, so the same shift gives 255. The callers clamp sums and differences of a few bytes, which are in + /// that range. + /// + /// The value. + /// The clamped value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte ClampToByte(int value) => (uint)value < 256 ? (byte)value : (byte)(~(uint)value >> 24); + /// /// Calculates % 4 /// + /// The value to divide. + /// The non-negative remainder, in the range 0 to 3. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static nint Modulo4(nint x) => x & 3; /// /// Calculates % 4 /// + /// The value to divide. + /// The remainder, in the range 0 to 3. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static nuint Modulo4(nuint x) => x & 3; /// /// Calculates % 8 /// + /// The value to divide. + /// The non-negative remainder, in the range 0 to 7. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Modulo8(int x) => x & 7; /// /// Calculates % 8 /// + /// The value to divide. + /// The non-negative remainder, in the range 0 to 7. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static nint Modulo8(nint x) => x & 7; /// /// Calculates % 64 /// + /// The value to divide. + /// The non-negative remainder, in the range 0 to 63. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Modulo64(int x) => x & 63; /// /// Calculates % 64 /// + /// The value to divide. + /// The non-negative remainder, in the range 0 to 63. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static nint Modulo64(nint x) => x & 63; /// /// Calculates % 256 /// + /// The value to divide. + /// The non-negative remainder, in the range 0 to 255. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Modulo256(int x) => x & 255; /// /// Calculates % 256 /// + /// The value to divide. + /// The non-negative remainder, in the range 0 to 255. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static nint Modulo256(nint x) => x & 255; @@ -128,6 +174,9 @@ public static int LeastCommonMultiple(int a, int b) /// Fast (x mod m) calculator, with the restriction that /// should be power of 2. /// + /// The value to divide. + /// The divisor. The value must be a positive power of 2. + /// The non-negative remainder, in the range 0 to - 1. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int ModuloP2(int x, int m) => x & (m - 1); @@ -303,7 +352,7 @@ public static void Premultiply(Span vectors) while (Unsafe.IsAddressLessThan(ref vectorsBase, ref vectorsEnd)) { vectorsBase = Premultiply(vectorsBase); - vectorsBase = ref Unsafe.Add(ref vectorsBase, 1); + vectorsBase = ref Unsafe.Add(ref vectorsBase, 1U); } vectors = vectors[(vectors.Length - (vectors.Length % vectorsPerVector))..]; @@ -318,7 +367,7 @@ public static void Premultiply(Span vectors) while (Unsafe.IsAddressLessThan(ref vectorsBase, ref vectorsEnd)) { vectorsBase = Premultiply(vectorsBase); - vectorsBase = ref Unsafe.Add(ref vectorsBase, 1); + vectorsBase = ref Unsafe.Add(ref vectorsBase, 1U); } vectors = vectors[(vectors.Length - (vectors.Length % vectorsPerVector))..]; @@ -332,7 +381,7 @@ public static void Premultiply(Span vectors) while (Unsafe.IsAddressLessThan(ref remainderBase, ref remainderEnd)) { remainderBase = Premultiply(remainderBase); - remainderBase = ref Unsafe.Add(ref remainderBase, 1); + remainderBase = ref Unsafe.Add(ref remainderBase, 1U); } } @@ -353,7 +402,7 @@ public static void UnPremultiply(Span vectors) while (Unsafe.IsAddressLessThan(ref vectorsBase, ref vectorsEnd)) { vectorsBase = UnPremultiply(vectorsBase); - vectorsBase = ref Unsafe.Add(ref vectorsBase, 1); + vectorsBase = ref Unsafe.Add(ref vectorsBase, 1U); } vectors = vectors[(vectors.Length - (vectors.Length % vectorsPerVector))..]; @@ -368,7 +417,7 @@ public static void UnPremultiply(Span vectors) while (Unsafe.IsAddressLessThan(ref vectorsBase, ref vectorsEnd)) { vectorsBase = UnPremultiply(vectorsBase); - vectorsBase = ref Unsafe.Add(ref vectorsBase, 1); + vectorsBase = ref Unsafe.Add(ref vectorsBase, 1U); } vectors = vectors[(vectors.Length - (vectors.Length % vectorsPerVector))..]; @@ -382,7 +431,7 @@ public static void UnPremultiply(Span vectors) while (Unsafe.IsAddressLessThan(ref remainderBase, ref remainderEnd)) { remainderBase = UnPremultiply(remainderBase); - remainderBase = ref Unsafe.Add(ref remainderBase, 1); + remainderBase = ref Unsafe.Add(ref remainderBase, 1U); } } @@ -703,7 +752,7 @@ public static void WithW(Span destination, ReadOnlySpan w) // One source value supplies lane 3 of one complete vector. Unaligned access needs no row padding. nuint offset = (nuint)(uint)i * (nuint)Vector128.Count; Vector128 value = Vector128.LoadUnsafe(ref output, offset); - WithW(value, Vector128.Create(Unsafe.Add(ref weights, i))).StoreUnsafe(ref output, offset); + WithW(value, Vector128.Create(Unsafe.Add(ref weights, (uint)i))).StoreUnsafe(ref output, offset); } } @@ -869,31 +918,7 @@ public static void CubePowOnXYZ(Span vectors) v = WithW(v, a); baseRef = v; - baseRef = ref Unsafe.Add(ref baseRef, 1); - } - } - - /// - /// Performs a linear interpolation between two values based on the given weighting. - /// - /// The first value. - /// The second value. - /// Values between 0 and 1 that indicates the weight of . - /// The . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Vector256 Lerp( - in Vector256 value1, - in Vector256 value2, - in Vector256 amount) - { - Vector256 diff = Avx.Subtract(value2, value1); - if (Fma.IsSupported) - { - return Fma.MultiplyAdd(diff, amount, value1); - } - else - { - return Avx.Add(Avx.Multiply(diff, amount), value1); + baseRef = ref Unsafe.Add(ref baseRef, 1U); } } @@ -938,55 +963,6 @@ public static void Accumulate(ref Vector accumulator, Vector values) accumulator += intHigh; } - /// - /// Reduces elements of the vector into one sum. - /// - /// The accumulator to reduce. - /// The sum of all elements. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int ReduceSum(Vector256 accumulator) - { - // Add upper lane to lower lane. - Vector128 vsum = Sse2.Add(accumulator.GetLower(), accumulator.GetUpper()); - - // Add odd to even. - vsum = Sse2.Add(vsum, Sse2.Shuffle(vsum, 0b_11_11_01_01)); - - // Add high to low. - vsum = Sse2.Add(vsum, Sse2.Shuffle(vsum, 0b_11_10_11_10)); - - return Sse2.ConvertToInt32(vsum); - } - - /// - /// Reduces even elements of the vector into one sum. - /// - /// The accumulator to reduce. - /// The sum of even elements. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int EvenReduceSum(Vector128 accumulator) - { - // Add high to low. - Vector128 vsum = Sse2.Add(accumulator, Sse2.Shuffle(accumulator, 0b_11_10_11_10)); - - return Sse2.ConvertToInt32(vsum); - } - - /// - /// Reduces even elements of the vector into one sum. - /// - /// The accumulator to reduce. - /// The sum of even elements. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int EvenReduceSum(Vector256 accumulator) - { - Vector128 vsum = Sse2.Add(accumulator.GetLower(), accumulator.GetUpper()); // add upper lane to lower lane - vsum = Sse2.Add(vsum, Sse2.Shuffle(vsum, 0b_11_10_11_10)); // add high to low - - // Vector128.ToScalar() isn't optimized pre-net5.0 https://github.com/dotnet/runtime/pull/37882 - return Sse2.ConvertToInt32(vsum); - } - /// /// Fast division with ceiling for numbers. /// @@ -1001,6 +977,7 @@ public static int EvenReduceSum(Vector256 accumulator) /// Value. /// Minimum value, inclusive. /// Maximum value, inclusive. + /// if the value is outside the inclusive range; otherwise, . [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsOutOfRange(int value, int min, int max) => (uint)(value - min) > (uint)(max - min); diff --git a/src/ImageSharp/Common/Helpers/SimdUtils.AddLeft.cs b/src/ImageSharp/Common/Helpers/SimdUtils.AddLeft.cs new file mode 100644 index 0000000000..fcafbafc27 --- /dev/null +++ b/src/ImageSharp/Common/Helpers/SimdUtils.AddLeft.cs @@ -0,0 +1,251 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Common.Helpers; + +namespace SixLabors.ImageSharp; + +/// +/// Reconstructs runs of pixels that a left predictor coded. +/// +internal static partial class SimdUtils +{ + /// + /// Defines the prefix sum and the left pixel copies of one pixel size in a 16-byte vector. + /// + private interface IAddLeftOperator + { + /// + /// Gets the byte count of one pixel. + /// + static abstract int BytesPerPixel { get; } + + /// + /// Copies the pixel in the low bytes of to each pixel of a vector. + /// + /// The pixel, first byte lowest. + /// The copies. + static abstract Vector128 Broadcast(ulong left); + + /// + /// Copies the last pixel of a vector to each pixel of the vector. + /// + /// The reconstructed bytes of a block. + /// The copies. + static abstract Vector128 BroadcastLast(Vector128 value); + + /// + /// Gets the sum of the residuals of each byte and the residuals at the same position of the pixels before it in the vector, modulo 256. + /// + /// The residuals of a block. + /// The prefix sums. + static abstract Vector128 PrefixSum(Vector128 value); + } + + /// + /// Reconstructs a run of pixels that the left predictor coded, in place. Each byte becomes its residual plus the reconstructed byte at the same + /// position of the pixel to its left, modulo 256. + /// + /// + /// + /// The PNG Sub filter, the WebP alpha horizontal filter, the WebP lossless left predictor (mode 1) and the WebP color table use this rule. See PNG + /// Third Edition, section 9.2, https://www.w3.org/TR/png-3/#9Filter-types, and the WebP Lossless Bitstream Specification, sections 4.1 and 4.4, + /// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// + /// + /// The scalar form waits for the pixel to its left at each pixel. For 1, 2, 4 and 8 bytes per pixel, the vector form adds the residuals of 16 bytes + /// with a prefix sum: each step adds the vector shifted by the pixel size, then by twice that size, and so on. After the steps, byte j holds the sum + /// of the residuals at j, j - b, j - 2b and so on in the block, for pixel size b. Then one add of the left pixel, copied to each pixel of the block, + /// gives the reconstructed bytes. Thus the dependency chain is one shuffle and one add for each 16 bytes. A wider vector would need shifts across + /// its 128-bit lanes, and it would not shorten the chain, so the form uses 128 bits. + /// + /// + /// The residuals. On return, the reconstructed bytes. The length is a whole number of pixels. + /// The byte count of one pixel, from 1 to 8. + /// The pixel to the left of the first pixel, in the low bytes, first byte lowest. + public static void AddLeft(Span values, int bytesPerPixel, ulong left) + { + DebugGuard.IsTrue(bytesPerPixel is >= 1 and <= 8, "A pixel has 1 to 8 bytes."); + DebugGuard.IsTrue(values.Length % bytesPerPixel == 0, "The values hold whole pixels."); + + if (Vector128.IsHardwareAccelerated) + { + switch (bytesPerPixel) + { + case 1: + AddLeft(values, left); + return; + case 2: + AddLeft(values, left); + return; + case 4: + AddLeft(values, left); + return; + case 8: + AddLeft(values, left); + return; + } + } + + AddLeftScalar(values, 0, (uint)bytesPerPixel, left); + } + + /// + /// Reconstructs a run of left-predicted pixels of in blocks of 16 bytes, then the remainder with the scalar form. + /// + /// The pixel size operator. + /// The residuals. On return, the reconstructed bytes. + /// The pixel to the left of the first pixel, in the low bytes. + private static void AddLeft(Span values, ulong left) + where TOperator : struct, IAddLeftOperator + { + ref byte valuesRef = ref MemoryMarshal.GetReference(values); + nuint length = (uint)values.Length; + nuint i = 0; + + // Lane layout: the left pixel is copied to each pixel of the 16 byte lanes. 16 is a multiple of the pixel size, so the copies line up with the + // pixels of the block. + Vector128 leftPixels = TOperator.Broadcast(left); + for (; i + 16 <= length; i += 16) + { + Vector128 sums = TOperator.PrefixSum(Vector128.LoadUnsafe(ref valuesRef, i)); + leftPixels = sums + leftPixels; + leftPixels.StoreUnsafe(ref valuesRef, i); + + // The last pixel of the block is the left pixel of the next block. + leftPixels = TOperator.BroadcastLast(leftPixels); + } + + // The left pixel of the remainder is in the low bytes of the copies. + AddLeftScalar(values, i, (uint)TOperator.BytesPerPixel, leftPixels.AsUInt64().ToScalar()); + } + + /// + /// Reconstructs the left-predicted bytes from to the end, one byte at a time. + /// + /// The residuals. On return, the reconstructed bytes. + /// The first byte to reconstruct. It is the first byte of a pixel. + /// The byte count of one pixel. + /// The pixel to the left of the pixel at , in the low bytes. + private static void AddLeftScalar(Span values, nuint start, nuint bytesPerPixel, ulong left) + { + ref byte valuesRef = ref MemoryMarshal.GetReference(values); + nuint length = (uint)values.Length; + nuint i = start; + + // The first pixel adds the bytes of the left pixel. Each later byte adds the reconstructed byte one pixel before it. + for (nuint k = 0; k < bytesPerPixel && i < length; k++, i++) + { + ref byte value = ref Unsafe.Add(ref valuesRef, i); + value = (byte)(value + (byte)(left >> (int)(8 * k))); + } + + for (; i < length; i++) + { + ref byte value = ref Unsafe.Add(ref valuesRef, i); + value = (byte)(value + Unsafe.Add(ref valuesRef, i - bytesPerPixel)); + } + } + + /// + /// The pixel size operator of 1 byte for each pixel. + /// + private readonly struct AddLeft8Operator : IAddLeftOperator + { + /// + public static int BytesPerPixel => 1; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Broadcast(ulong left) => Vector128.Create((byte)left); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 BroadcastLast(Vector128 value) => Vector128.Shuffle(value, Vector128.Create((byte)15)); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PrefixSum(Vector128 value) + { + value += Vector128_.ShiftLeftBytesInVector(value, 1); + value += Vector128_.ShiftLeftBytesInVector(value, 2); + value += Vector128_.ShiftLeftBytesInVector(value, 4); + return value + Vector128_.ShiftLeftBytesInVector(value, 8); + } + } + + /// + /// The pixel size operator of 2 bytes for each pixel. + /// + private readonly struct AddLeft16Operator : IAddLeftOperator + { + /// + public static int BytesPerPixel => 2; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Broadcast(ulong left) => Vector128.Create((ushort)left).AsByte(); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 BroadcastLast(Vector128 value) => Vector128.Shuffle(value.AsUInt16(), Vector128.Create((ushort)7)).AsByte(); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PrefixSum(Vector128 value) + { + value += Vector128_.ShiftLeftBytesInVector(value, 2); + value += Vector128_.ShiftLeftBytesInVector(value, 4); + return value + Vector128_.ShiftLeftBytesInVector(value, 8); + } + } + + /// + /// The pixel size operator of 4 bytes for each pixel. + /// + private readonly struct AddLeft32Operator : IAddLeftOperator + { + /// + public static int BytesPerPixel => 4; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Broadcast(ulong left) => Vector128.Create((uint)left).AsByte(); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 BroadcastLast(Vector128 value) => Vector128.Shuffle(value.AsUInt32(), Vector128.Create(3u)).AsByte(); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PrefixSum(Vector128 value) + { + value += Vector128_.ShiftLeftBytesInVector(value, 4); + return value + Vector128_.ShiftLeftBytesInVector(value, 8); + } + } + + /// + /// The pixel size operator of 8 bytes for each pixel. + /// + private readonly struct AddLeft64Operator : IAddLeftOperator + { + /// + public static int BytesPerPixel => 8; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Broadcast(ulong left) => Vector128.Create(left).AsByte(); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 BroadcastLast(Vector128 value) => Vector128.Shuffle(value.AsUInt64(), Vector128.Create(1ul)).AsByte(); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PrefixSum(Vector128 value) => value + Vector128_.ShiftLeftBytesInVector(value, 8); + } +} diff --git a/src/ImageSharp/Common/Helpers/SimdUtils.Convert.cs b/src/ImageSharp/Common/Helpers/SimdUtils.Convert.cs index 8a513ca1b6..aa1d29896c 100644 --- a/src/ImageSharp/Common/Helpers/SimdUtils.Convert.cs +++ b/src/ImageSharp/Common/Helpers/SimdUtils.Convert.cs @@ -8,6 +8,9 @@ namespace SixLabors.ImageSharp; +/// +/// Converts spans of normalized and scaled floating-point components to and from 8-bit and 16-bit samples. +/// internal static partial class SimdUtils { /// @@ -262,7 +265,7 @@ public static void NormalizedFloatToByteSaturate(ReadOnlySpan sou } /// - /// Converts byte-magnitude floating-point values to bytes using saturating round-to-nearest with midpoint values away from zero. + /// Converts byte-magnitude floating-point values to bytes using saturating round-to-nearest with midpoint values to even. /// /// The source byte magnitudes. /// The destination bytes. @@ -272,7 +275,7 @@ public static void FloatToByteSaturate(ReadOnlySpan source, Span de /// /// Applies to each RGBA pixel, and converts the resulting byte magnitudes to bytes in the same - /// pass, with saturating round-to-nearest and midpoint values away from zero. The spans hold whole RGBA pixels, unless + /// pass, with saturating round-to-nearest and midpoint values to even. The spans hold whole RGBA pixels, unless /// is . /// /// The alpha step for each pixel. Its result is in byte magnitudes. @@ -381,12 +384,12 @@ private static void ConvertFloatToByteRemainder(ReadOnlySpan source, Span } /// - /// Scales a float, then rounds it to the nearest byte value. A value halfway between two bytes rounds up. + /// Scales a float, then rounds it to the nearest byte value. A value halfway between two bytes rounds to the even byte. /// A value outside the byte range clamps to 0 or 255. /// /// The float. /// The factor that multiplies the float. /// The byte. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static byte ConvertToByte(float value, float scale) => (byte)ColorNumerics.ClampToFinite((value * scale) + .5F, 0, byte.MaxValue); + private static byte ConvertToByte(float value, float scale) => (byte)MathF.Round(ColorNumerics.ClampToFinite(value * scale, 0, byte.MaxValue)); } diff --git a/src/ImageSharp/Common/Helpers/SimdUtils.ExtractBytes.cs b/src/ImageSharp/Common/Helpers/SimdUtils.ExtractBytes.cs new file mode 100644 index 0000000000..21de85a33a --- /dev/null +++ b/src/ImageSharp/Common/Helpers/SimdUtils.ExtractBytes.cs @@ -0,0 +1,108 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; + +namespace SixLabors.ImageSharp; + +/// +/// Extracts one byte of each packed 32-bit value. +/// +internal static partial class SimdUtils +{ + /// + /// Stores byte of each 32-bit value. Byte 0 is the least significant byte. + /// + /// + /// Each vector step loads four vectors of 32-bit values, shifts the selected byte down to bit 0, and narrows twice: 32-bit to 16-bit lanes and + /// 16-bit to byte lanes. Each narrow keeps the low half of each lane, in lane order, so the bytes keep the order of the values. The widths run from + /// the widest down, from the same offset, and the scalar form does the remainder. + /// + /// The values. + /// The destination. It has at least the length of . + /// The byte to extract, from 0 to 3. + public static void ExtractBytes(ReadOnlySpan source, Span destination, int byteIndex) + { + DebugGuard.MustBeGreaterThanOrEqualTo(destination.Length, source.Length, nameof(destination)); + DebugGuard.MustBeBetweenOrEqualTo(byteIndex, 0, 3, nameof(byteIndex)); + + ref uint sourceRef = ref MemoryMarshal.GetReference(source); + ref byte destinationRef = ref MemoryMarshal.GetReference(destination); + nuint length = (uint)source.Length; + int shift = 8 * byteIndex; + nuint i = 0; + + if (Vector512.IsHardwareAccelerated) + { + // One step fills one byte vector, so it reads four vectors of values. Vector k holds the values from k * quarter. + nuint step = (uint)Vector512.Count; + nuint quarter = (uint)Vector512.Count; + for (; i + step <= length; i += step) + { + // The shift moves the selected byte to bits 0 to 7 of each 32-bit lane. + Vector512 v0 = Vector512.LoadUnsafe(ref sourceRef, i) >>> shift; + Vector512 v1 = Vector512.LoadUnsafe(ref sourceRef, i + quarter) >>> shift; + Vector512 v2 = Vector512.LoadUnsafe(ref sourceRef, i + (2 * quarter)) >>> shift; + Vector512 v3 = Vector512.LoadUnsafe(ref sourceRef, i + (3 * quarter)) >>> shift; + + // A narrow keeps the low half of each lane, the lanes of its first argument first. Thus the 16-bit lanes of low hold the values + // of v0 then v1, and those of high the values of v2 then v3. The second narrow keeps the low byte of each 16-bit lane, which is + // the selected byte, so the bytes are in value order. + Vector512 low = Vector512.Narrow(v0, v1); + Vector512 high = Vector512.Narrow(v2, v3); + Vector512.Narrow(low, high).StoreUnsafe(ref destinationRef, i); + } + } + + if (Vector256.IsHardwareAccelerated) + { + // One step fills one byte vector, so it reads four vectors of values. Vector k holds the values from k * quarter. + nuint step = (uint)Vector256.Count; + nuint quarter = (uint)Vector256.Count; + for (; i + step <= length; i += step) + { + // The shift moves the selected byte to bits 0 to 7 of each 32-bit lane. + Vector256 v0 = Vector256.LoadUnsafe(ref sourceRef, i) >>> shift; + Vector256 v1 = Vector256.LoadUnsafe(ref sourceRef, i + quarter) >>> shift; + Vector256 v2 = Vector256.LoadUnsafe(ref sourceRef, i + (2 * quarter)) >>> shift; + Vector256 v3 = Vector256.LoadUnsafe(ref sourceRef, i + (3 * quarter)) >>> shift; + + // A narrow keeps the low half of each lane, the lanes of its first argument first. Thus the 16-bit lanes of low hold the values + // of v0 then v1, and those of high the values of v2 then v3. The second narrow keeps the low byte of each 16-bit lane, which is + // the selected byte, so the bytes are in value order. + Vector256 low = Vector256.Narrow(v0, v1); + Vector256 high = Vector256.Narrow(v2, v3); + Vector256.Narrow(low, high).StoreUnsafe(ref destinationRef, i); + } + } + + if (Vector128.IsHardwareAccelerated) + { + // One step fills one byte vector, so it reads four vectors of values. Vector k holds the values from k * quarter. + nuint step = (uint)Vector128.Count; + nuint quarter = (uint)Vector128.Count; + for (; i + step <= length; i += step) + { + // The shift moves the selected byte to bits 0 to 7 of each 32-bit lane. + Vector128 v0 = Vector128.LoadUnsafe(ref sourceRef, i) >>> shift; + Vector128 v1 = Vector128.LoadUnsafe(ref sourceRef, i + quarter) >>> shift; + Vector128 v2 = Vector128.LoadUnsafe(ref sourceRef, i + (2 * quarter)) >>> shift; + Vector128 v3 = Vector128.LoadUnsafe(ref sourceRef, i + (3 * quarter)) >>> shift; + + // A narrow keeps the low half of each lane, the lanes of its first argument first. Thus the 16-bit lanes of low hold the values + // of v0 then v1, and those of high the values of v2 then v3. The second narrow keeps the low byte of each 16-bit lane, which is + // the selected byte, so the bytes are in value order. + Vector128 low = Vector128.Narrow(v0, v1); + Vector128 high = Vector128.Narrow(v2, v3); + Vector128.Narrow(low, high).StoreUnsafe(ref destinationRef, i); + } + } + + for (; i < length; i++) + { + Unsafe.Add(ref destinationRef, i) = (byte)(Unsafe.Add(ref sourceRef, i) >> shift); + } + } +} diff --git a/src/ImageSharp/Common/Helpers/SimdUtils.HwIntrinsics.cs b/src/ImageSharp/Common/Helpers/SimdUtils.HwIntrinsics.cs index ec66ad50ca..ff1b4f507b 100644 --- a/src/ImageSharp/Common/Helpers/SimdUtils.HwIntrinsics.cs +++ b/src/ImageSharp/Common/Helpers/SimdUtils.HwIntrinsics.cs @@ -9,8 +9,14 @@ namespace SixLabors.ImageSharp; +/// +/// Contains the hardware-intrinsic byte and floating-point conversion kernels. +/// internal static partial class SimdUtils { + /// + /// Converts bytes to normalized floats and scaled floats to saturated bytes with explicit vector widths. + /// public static partial class HwIntrinsics { /// @@ -18,6 +24,7 @@ public static partial class HwIntrinsics /// Similar in behavior to the x86 instruction LZCNT. /// /// The value. + /// The number of leading zero bits, in the range 0 to 16. The result is 16 when the value is zero. public static ushort LeadingZeroCount(ushort value) => (ushort)(BitOperations.LeadingZeroCount(value) - 16); @@ -26,6 +33,7 @@ public static ushort LeadingZeroCount(ushort value) /// Similar in behavior to the x86 instruction TZCNT. /// /// The value. + /// The number of trailing zero bits, in the range 0 to 16. The result is 16 when the value is zero. public static ushort TrailingZeroCount(ushort value) => (ushort)(BitOperations.TrailingZeroCount(value << 16) - 16); @@ -150,9 +158,9 @@ public static void ByteToNormalizedFloat( // The alpha step runs in registers, so an associated conversion needs no second pass. d = TAlpha.Apply(f0); - Unsafe.Add(ref d, 1) = TAlpha.Apply(f1); - Unsafe.Add(ref d, 2) = TAlpha.Apply(f2); - Unsafe.Add(ref d, 3) = TAlpha.Apply(f3); + Unsafe.Add(ref d, 1U) = TAlpha.Apply(f1); + Unsafe.Add(ref d, 2U) = TAlpha.Apply(f2); + Unsafe.Add(ref d, 3U) = TAlpha.Apply(f3); } } else if (Vector256.IsHardwareAccelerated) @@ -190,9 +198,9 @@ public static void ByteToNormalizedFloat( // The alpha step runs in registers, so an associated conversion needs no second pass. d = TAlpha.Apply(f0); - Unsafe.Add(ref d, 1) = TAlpha.Apply(f1); - Unsafe.Add(ref d, 2) = TAlpha.Apply(f2); - Unsafe.Add(ref d, 3) = TAlpha.Apply(f3); + Unsafe.Add(ref d, 1U) = TAlpha.Apply(f1); + Unsafe.Add(ref d, 2U) = TAlpha.Apply(f2); + Unsafe.Add(ref d, 3U) = TAlpha.Apply(f3); } } else if (Vector128.IsHardwareAccelerated) @@ -233,9 +241,9 @@ public static void ByteToNormalizedFloat( // The alpha step runs in registers, so an associated conversion needs no second pass. d = TAlpha.Apply(f0); - Unsafe.Add(ref d, 1) = TAlpha.Apply(f1); - Unsafe.Add(ref d, 2) = TAlpha.Apply(f2); - Unsafe.Add(ref d, 3) = TAlpha.Apply(f3); + Unsafe.Add(ref d, 1U) = TAlpha.Apply(f1); + Unsafe.Add(ref d, 2U) = TAlpha.Apply(f2); + Unsafe.Add(ref d, 3U) = TAlpha.Apply(f3); } } } @@ -328,7 +336,7 @@ public static void NormalizedFloatToByteSaturate( /// /// Converts scaled floating-point values to bytes. - /// Each byte is the scaled value plus one half, truncated toward zero and saturated to [0, 255]. + /// Each byte is the scaled value rounded to the nearest integer, with ties to even, and saturated to [0, 255]. /// /// /// The source buffer. Its length is a multiple of the byte vector length of the widest accelerated width. @@ -343,7 +351,7 @@ public static void FloatToByteSaturate( /// /// Converts scaled floating-point values to bytes, and applies to the floats before the - /// scale. Each byte is the scaled value plus one half, truncated toward zero and saturated to [0, 255]. + /// scale. Each byte is the scaled value rounded to the nearest integer, with ties to even, and saturated to [0, 255]. /// /// /// Each float vector holds whole RGBA groups, because the vector widths are multiples of 4 floats and each step starts at @@ -381,9 +389,9 @@ public static void FloatToByteSaturate( ref Vector512 s = ref Unsafe.Add(ref sourceBase, i * 4); Unsafe.Add(ref destinationBase, i) = FloatToByteSaturate( ColorNumerics.ClampToFinite(TAlpha.Apply(s), Vector512.Zero, upperBound), - ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 1)), Vector512.Zero, upperBound), - ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 2)), Vector512.Zero, upperBound), - ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 3)), Vector512.Zero, upperBound), + ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 1U)), Vector512.Zero, upperBound), + ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 2U)), Vector512.Zero, upperBound), + ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 3U)), Vector512.Zero, upperBound), scale); } } @@ -405,9 +413,9 @@ public static void FloatToByteSaturate( ref Vector256 s = ref Unsafe.Add(ref sourceBase, i * 4); Unsafe.Add(ref destinationBase, i) = FloatToByteSaturate( ColorNumerics.ClampToFinite(TAlpha.Apply(s), Vector256.Zero, upperBound), - ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 1)), Vector256.Zero, upperBound), - ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 2)), Vector256.Zero, upperBound), - ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 3)), Vector256.Zero, upperBound), + ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 1U)), Vector256.Zero, upperBound), + ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 2U)), Vector256.Zero, upperBound), + ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 3U)), Vector256.Zero, upperBound), scale); } } @@ -429,9 +437,9 @@ public static void FloatToByteSaturate( ref Vector128 s = ref Unsafe.Add(ref sourceBase, i * 4); Unsafe.Add(ref destinationBase, i) = FloatToByteSaturate( ColorNumerics.ClampToFinite(TAlpha.Apply(s), Vector128.Zero, upperBound), - ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 1)), Vector128.Zero, upperBound), - ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 2)), Vector128.Zero, upperBound), - ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 3)), Vector128.Zero, upperBound), + ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 1U)), Vector128.Zero, upperBound), + ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 2U)), Vector128.Zero, upperBound), + ColorNumerics.ClampToFinite(TAlpha.Apply(Unsafe.Add(ref s, 3U)), Vector128.Zero, upperBound), scale); } } @@ -439,10 +447,10 @@ public static void FloatToByteSaturate( /// /// Converts four vectors of finite scaled floating-point values to one vector of bytes. - /// Each byte is the scaled value plus one half, truncated toward zero and saturated to [0, 255]. + /// Each byte is the scaled value rounded to the nearest integer, with ties to even, and saturated to [0, 255]. /// /// - /// Each value must be finite, and each scaled value plus one half must be in the range. + /// Each value must be finite, and each scaled value must be in the range. /// The span overload and the JPEG color converters meet this condition. A scaled value outside [0, 255] saturates to 0 or 255. /// /// The values for bytes 0 to 15. @@ -459,23 +467,22 @@ public static Vector512 FloatToByteSaturate( Vector512 f3, Vector512 scale) { - // Each lane is truncate(x * scale + 0.5), the rule of the scalar remainder in SimdUtils. The native - // conversion truncates toward zero on every platform, so all widths and platforms give the same bytes. + // Each lane is x * scale rounded to the nearest integer, with ties to even. This is the rule of the scalar + // remainder in SimdUtils and of the scalar pixel packers, so all widths and platforms give the same bytes. // The narrowing saturates negative results to 0 and results above 255 to 255. - Vector512 half = Vector512.Create(.5F); return Vector512_.NarrowToByteWithSaturation( - Vector512.ConvertToInt32Native((f0 * scale) + half), - Vector512.ConvertToInt32Native((f1 * scale) + half), - Vector512.ConvertToInt32Native((f2 * scale) + half), - Vector512.ConvertToInt32Native((f3 * scale) + half)); + Vector512_.ConvertToInt32RoundToEven(f0 * scale), + Vector512_.ConvertToInt32RoundToEven(f1 * scale), + Vector512_.ConvertToInt32RoundToEven(f2 * scale), + Vector512_.ConvertToInt32RoundToEven(f3 * scale)); } /// /// Converts four vectors of finite scaled floating-point values to one vector of bytes. - /// Each byte is the scaled value plus one half, truncated toward zero and saturated to [0, 255]. + /// Each byte is the scaled value rounded to the nearest integer, with ties to even, and saturated to [0, 255]. /// /// - /// Each value must be finite, and each scaled value plus one half must be in the range. + /// Each value must be finite, and each scaled value must be in the range. /// The span overload and the JPEG color converters meet this condition. A scaled value outside [0, 255] saturates to 0 or 255. /// /// The values for bytes 0 to 7. @@ -493,20 +500,19 @@ public static Vector256 FloatToByteSaturate( Vector256 scale) { // See the Vector512 overload. - Vector256 half = Vector256.Create(.5F); return Vector256_.NarrowToByteWithSaturation( - Vector256.ConvertToInt32Native((f0 * scale) + half), - Vector256.ConvertToInt32Native((f1 * scale) + half), - Vector256.ConvertToInt32Native((f2 * scale) + half), - Vector256.ConvertToInt32Native((f3 * scale) + half)); + Vector256_.ConvertToInt32RoundToEven(f0 * scale), + Vector256_.ConvertToInt32RoundToEven(f1 * scale), + Vector256_.ConvertToInt32RoundToEven(f2 * scale), + Vector256_.ConvertToInt32RoundToEven(f3 * scale)); } /// /// Converts four vectors of finite scaled floating-point values to one vector of bytes. - /// Each byte is the scaled value plus one half, truncated toward zero and saturated to [0, 255]. + /// Each byte is the scaled value rounded to the nearest integer, with ties to even, and saturated to [0, 255]. /// /// - /// Each value must be finite, and each scaled value plus one half must be in the range. + /// Each value must be finite, and each scaled value must be in the range. /// The span overload and the JPEG color converters meet this condition. A scaled value outside [0, 255] saturates to 0 or 255. /// /// The values for bytes 0 to 3. @@ -524,12 +530,11 @@ public static Vector128 FloatToByteSaturate( Vector128 scale) { // See the Vector512 overload. - Vector128 half = Vector128.Create(.5F); return Vector128_.NarrowToByteWithSaturation( - Vector128.ConvertToInt32Native((f0 * scale) + half), - Vector128.ConvertToInt32Native((f1 * scale) + half), - Vector128.ConvertToInt32Native((f2 * scale) + half), - Vector128.ConvertToInt32Native((f3 * scale) + half)); + Vector128_.ConvertToInt32RoundToEven(f0 * scale), + Vector128_.ConvertToInt32RoundToEven(f1 * scale), + Vector128_.ConvertToInt32RoundToEven(f2 * scale), + Vector128_.ConvertToInt32RoundToEven(f3 * scale)); } } } diff --git a/src/ImageSharp/Common/Helpers/SimdUtils.Pack.cs b/src/ImageSharp/Common/Helpers/SimdUtils.Pack.cs index de76f93ce2..504e001b55 100644 --- a/src/ImageSharp/Common/Helpers/SimdUtils.Pack.cs +++ b/src/ImageSharp/Common/Helpers/SimdUtils.Pack.cs @@ -10,6 +10,9 @@ namespace SixLabors.ImageSharp; +/// +/// Packs planar 8-bit color samples to pixels and unpacks pixels to planar samples. +/// internal static partial class SimdUtils { /// @@ -111,6 +114,119 @@ public static void PackFromRgbPlanes( PackFromRgbPlanesRemainder(redChannel, greenChannel, blueChannel, destination); } + /// + /// Packs four planes of 8-bit red, green, blue and alpha samples to pixels. + /// + /// The red samples. + /// The green samples. The length is the length of . + /// The blue samples. The length is the length of . + /// The alpha samples. The length is the length of . + /// The destination pixels. It holds at least one pixel for each red sample. + [MethodImpl(InliningOptions.ShortMethod)] + public static void PackFromRgbaPlanes( + ReadOnlySpan redChannel, + ReadOnlySpan greenChannel, + ReadOnlySpan blueChannel, + ReadOnlySpan alphaChannel, + Span destination) + { + DebugGuard.IsTrue(greenChannel.Length == redChannel.Length, nameof(greenChannel), "Channels must be of same size!"); + DebugGuard.IsTrue(blueChannel.Length == redChannel.Length, nameof(blueChannel), "Channels must be of same size!"); + DebugGuard.IsTrue(alphaChannel.Length == redChannel.Length, nameof(alphaChannel), "Channels must be of same size!"); + DebugGuard.IsTrue(destination.Length >= redChannel.Length, nameof(destination), "'destination' span should not be shorter than the source channels!"); + + // Rgba32 stores exactly one pixel per source sample, so caller padding + // must never extend the work performed by the remainder. + destination = destination[..redChannel.Length]; + + if (Vector512.IsHardwareAccelerated) + { + // One byte lane of each plane represents one pixel. Interleave4 writes the R, G, B, A bytes of each lane + // as one Rgba32 pixel, so each group writes 64 pixels. + nuint groups = redChannel.Vector512Count(); + ref byte red = ref MemoryMarshal.GetReference(redChannel); + ref byte green = ref MemoryMarshal.GetReference(greenChannel); + ref byte blue = ref MemoryMarshal.GetReference(blueChannel); + ref byte alpha = ref MemoryMarshal.GetReference(alphaChannel); + ref byte output = ref Unsafe.As(ref MemoryMarshal.GetReference(destination)); + + for (nuint group = 0; group < groups; group++) + { + nuint offset = group * (uint)Vector512.Count; + Vector512 r = Vector512.LoadUnsafe(ref red, offset); + Vector512 g = Vector512.LoadUnsafe(ref green, offset); + Vector512 b = Vector512.LoadUnsafe(ref blue, offset); + Vector512 a = Vector512.LoadUnsafe(ref alpha, offset); + Interleave4(r, g, b, a, ref Unsafe.Add(ref output, offset * 4)); + } + + int converted = (int)groups * Vector512.Count; + redChannel = redChannel[converted..]; + greenChannel = greenChannel[converted..]; + blueChannel = blueChannel[converted..]; + alphaChannel = alphaChannel[converted..]; + destination = destination[converted..]; + } + + if (Vector256.IsHardwareAccelerated) + { + // See the Vector512 stage. + nuint groups = redChannel.Vector256Count(); + ref byte red = ref MemoryMarshal.GetReference(redChannel); + ref byte green = ref MemoryMarshal.GetReference(greenChannel); + ref byte blue = ref MemoryMarshal.GetReference(blueChannel); + ref byte alpha = ref MemoryMarshal.GetReference(alphaChannel); + ref byte output = ref Unsafe.As(ref MemoryMarshal.GetReference(destination)); + + for (nuint group = 0; group < groups; group++) + { + nuint offset = group * (uint)Vector256.Count; + Vector256 r = Vector256.LoadUnsafe(ref red, offset); + Vector256 g = Vector256.LoadUnsafe(ref green, offset); + Vector256 b = Vector256.LoadUnsafe(ref blue, offset); + Vector256 a = Vector256.LoadUnsafe(ref alpha, offset); + Interleave4(r, g, b, a, ref Unsafe.Add(ref output, offset * 4)); + } + + int converted = (int)groups * Vector256.Count; + redChannel = redChannel[converted..]; + greenChannel = greenChannel[converted..]; + blueChannel = blueChannel[converted..]; + alphaChannel = alphaChannel[converted..]; + destination = destination[converted..]; + } + + if (Vector128.IsHardwareAccelerated) + { + // See the Vector512 stage. + nuint groups = redChannel.Vector128Count(); + ref byte red = ref MemoryMarshal.GetReference(redChannel); + ref byte green = ref MemoryMarshal.GetReference(greenChannel); + ref byte blue = ref MemoryMarshal.GetReference(blueChannel); + ref byte alpha = ref MemoryMarshal.GetReference(alphaChannel); + ref byte output = ref Unsafe.As(ref MemoryMarshal.GetReference(destination)); + + for (nuint group = 0; group < groups; group++) + { + nuint offset = group * (uint)Vector128.Count; + Vector128 r = Vector128.LoadUnsafe(ref red, offset); + Vector128 g = Vector128.LoadUnsafe(ref green, offset); + Vector128 b = Vector128.LoadUnsafe(ref blue, offset); + Vector128 a = Vector128.LoadUnsafe(ref alpha, offset); + Interleave4(r, g, b, a, ref Unsafe.Add(ref output, offset * 4)); + } + + int converted = (int)groups * Vector128.Count; + redChannel = redChannel[converted..]; + greenChannel = greenChannel[converted..]; + blueChannel = blueChannel[converted..]; + alphaChannel = alphaChannel[converted..]; + destination = destination[converted..]; + } + + PackFromRgbaPlanesRemainder(redChannel, greenChannel, blueChannel, alphaChannel, destination); + } + /// /// Unpacks pixels to three planes of red, green and blue values from 0 to 255. /// @@ -195,9 +311,9 @@ private static void PackFromRgbPlanesVector128Reduce( // exact stores avoid coupling the SIMD path to padding beyond the row or the next memory-group segment. ref byte destination0 = ref Unsafe.Add(ref destinationBase, i * 48); StoreRgb24Batch(Vector128.ShuffleNative(rgba0, removeAlpha), ref destination0); - StoreRgb24Batch(Vector128.ShuffleNative(rgba1, removeAlpha), ref Unsafe.Add(ref destination0, 12)); - StoreRgb24Batch(Vector128.ShuffleNative(rgba2, removeAlpha), ref Unsafe.Add(ref destination0, 24)); - StoreRgb24Batch(Vector128.ShuffleNative(rgba3, removeAlpha), ref Unsafe.Add(ref destination0, 36)); + StoreRgb24Batch(Vector128.ShuffleNative(rgba1, removeAlpha), ref Unsafe.Add(ref destination0, 12U)); + StoreRgb24Batch(Vector128.ShuffleNative(rgba2, removeAlpha), ref Unsafe.Add(ref destination0, 24U)); + StoreRgb24Batch(Vector128.ShuffleNative(rgba3, removeAlpha), ref Unsafe.Add(ref destination0, 36U)); } int convertedCount = (int)(batchCount * (uint)Vector128.Count); @@ -245,9 +361,9 @@ private static void PackFromRgbPlanesVector128Reduce( ref Vector128 destination0 = ref Unsafe.Add(ref destinationBase, i * 4); destination0 = rgba0; - Unsafe.Add(ref destination0, 1) = rgba1; - Unsafe.Add(ref destination0, 2) = rgba2; - Unsafe.Add(ref destination0, 3) = rgba3; + Unsafe.Add(ref destination0, 1U) = rgba1; + Unsafe.Add(ref destination0, 2U) = rgba2; + Unsafe.Add(ref destination0, 3U) = rgba3; } int convertedCount = (int)(batchCount * (uint)Vector128.Count); @@ -298,7 +414,7 @@ private static void InterleaveRgbPlanes( private static void StoreRgb24Batch(Vector128 value, ref byte destination) { Unsafe.WriteUnaligned(ref destination, value.AsUInt64().ToScalar()); - Unsafe.WriteUnaligned(ref Unsafe.Add(ref destination, 8), value.AsUInt32().GetElement(2)); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref destination, 8U), value.AsUInt32().GetElement(2)); } /// @@ -323,9 +439,9 @@ private static void PackFromRgbPlanesScalarBatchedReduce( for (nuint i = 0; i < batchCount; i++) { ref Rgb24 d0 = ref Unsafe.Add(ref rgb, i * 4); - ref Rgb24 d1 = ref Unsafe.Add(ref d0, 1); - ref Rgb24 d2 = ref Unsafe.Add(ref d0, 2); - ref Rgb24 d3 = ref Unsafe.Add(ref d0, 3); + ref Rgb24 d1 = ref Unsafe.Add(ref d0, 1U); + ref Rgb24 d2 = ref Unsafe.Add(ref d0, 2U); + ref Rgb24 d3 = ref Unsafe.Add(ref d0, 3U); ref ByteTuple4 rr = ref Unsafe.Add(ref r, i); ref ByteTuple4 gg = ref Unsafe.Add(ref g, i); @@ -378,9 +494,9 @@ private static void PackFromRgbPlanesScalarBatchedReduce( for (nuint i = 0; i < batchCount; i++) { ref Rgba32 d0 = ref Unsafe.Add(ref rgb, i * 4); - ref Rgba32 d1 = ref Unsafe.Add(ref d0, 1); - ref Rgba32 d2 = ref Unsafe.Add(ref d0, 2); - ref Rgba32 d3 = ref Unsafe.Add(ref d0, 3); + ref Rgba32 d1 = ref Unsafe.Add(ref d0, 1U); + ref Rgba32 d2 = ref Unsafe.Add(ref d0, 2U); + ref Rgba32 d3 = ref Unsafe.Add(ref d0, 3U); ref ByteTuple4 rr = ref Unsafe.Add(ref r, i); ref ByteTuple4 gg = ref Unsafe.Add(ref g, i); @@ -467,6 +583,37 @@ private static void PackFromRgbPlanesRemainder( } } + /// + /// Packs the samples that the vector paths leave to pixels, one pixel at a time. + /// + /// The red samples. + /// The green samples. + /// The blue samples. + /// The alpha samples. + /// The destination pixels. + private static void PackFromRgbaPlanesRemainder( + ReadOnlySpan redChannel, + ReadOnlySpan greenChannel, + ReadOnlySpan blueChannel, + ReadOnlySpan alphaChannel, + Span destination) + { + ref byte r = ref MemoryMarshal.GetReference(redChannel); + ref byte g = ref MemoryMarshal.GetReference(greenChannel); + ref byte b = ref MemoryMarshal.GetReference(blueChannel); + ref byte a = ref MemoryMarshal.GetReference(alphaChannel); + ref Rgba32 rgba = ref MemoryMarshal.GetReference(destination); + + for (nuint i = 0; i < (uint)redChannel.Length; i++) + { + ref Rgba32 d = ref Unsafe.Add(ref rgba, i); + d.R = Unsafe.Add(ref r, i); + d.G = Unsafe.Add(ref g, i); + d.B = Unsafe.Add(ref b, i); + d.A = Unsafe.Add(ref a, i); + } + } + /// /// Unpacks pixels to three planes of values from 0 to 255, one pixel at a time. /// @@ -557,9 +704,9 @@ public static void PackFromRgbPlanesReduce( out Vector256 rgb3); ref byte destination0 = ref Unsafe.Add(ref destinationBase, 96 * i); - ref byte destination1 = ref Unsafe.Add(ref destination0, 24); - ref byte destination2 = ref Unsafe.Add(ref destination1, 24); - ref byte destination3 = ref Unsafe.Add(ref destination2, 24); + ref byte destination1 = ref Unsafe.Add(ref destination0, 24U); + ref byte destination2 = ref Unsafe.Add(ref destination1, 24U); + ref byte destination3 = ref Unsafe.Add(ref destination2, 24U); Unsafe.As>(ref destination0) = rgb0; Unsafe.As>(ref destination1) = rgb1; @@ -583,9 +730,9 @@ public static void PackFromRgbPlanesReduce( out Vector256 rgb3); ref byte destination0 = ref Unsafe.Add(ref destinationBase, 96 * i); - ref byte destination1 = ref Unsafe.Add(ref destination0, 24); - ref byte destination2 = ref Unsafe.Add(ref destination1, 24); - ref byte destination3 = ref Unsafe.Add(ref destination2, 24); + ref byte destination1 = ref Unsafe.Add(ref destination0, 24U); + ref byte destination2 = ref Unsafe.Add(ref destination1, 24U); + ref byte destination3 = ref Unsafe.Add(ref destination2, 24U); Unsafe.As>(ref destination0) = rgb0; Unsafe.As>(ref destination1) = rgb1; @@ -600,7 +747,7 @@ public static void PackFromRgbPlanesReduce( // The final compacted vector contains 24 RGB bytes followed by eight unused bytes. Exact stores // retain all useful bytes without writing beyond an unpadded destination row. Unsafe.As>(ref destination3) = rgb3.GetLower(); - Unsafe.As(ref Unsafe.Add(ref destination3, 16)) = rgb3.GetUpper().AsUInt64().ToScalar(); + Unsafe.As(ref Unsafe.Add(ref destination3, 16U)) = rgb3.GetUpper().AsUInt64().ToScalar(); } } @@ -647,9 +794,9 @@ public static void PackFromRgbPlanesReduce( ref Vector256 destination0 = ref Unsafe.Add(ref destinationBase, i * 4); destination0 = rgba0; - Unsafe.Add(ref destination0, 1) = rgba1; - Unsafe.Add(ref destination0, 2) = rgba2; - Unsafe.Add(ref destination0, 3) = rgba3; + Unsafe.Add(ref destination0, 1U) = rgba1; + Unsafe.Add(ref destination0, 2U) = rgba2; + Unsafe.Add(ref destination0, 3U) = rgba3; } int convertedCount = (int)batchCount * Vector256.Count; diff --git a/src/ImageSharp/Common/Helpers/SimdUtils.Reduce.cs b/src/ImageSharp/Common/Helpers/SimdUtils.Reduce.cs new file mode 100644 index 0000000000..0eafb56675 --- /dev/null +++ b/src/ImageSharp/Common/Helpers/SimdUtils.Reduce.cs @@ -0,0 +1,113 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; + +namespace SixLabors.ImageSharp; + +/// +/// Reduces spans of packed values to one value with a bitwise operation. +/// +internal static partial class SimdUtils +{ + /// + /// Reduces packed 32-bit values to one value with a bitwise operation. + /// + /// The bitwise operation. + /// The values to reduce. + /// + /// The combination of all values. An empty span gives . + /// + public static uint Reduce(ReadOnlySpan source) + where TReduction : struct, IBitwiseReduction + { + ref uint sourceBase = ref MemoryMarshal.GetReference(source); + nuint length = (uint)source.Length; + nuint i = 0; + + // One running total flows down the widths. Each width folds its upper half into its lower half to give the + // next narrower total. Thus a span that is not a multiple of the widest register keeps a vectorized tail. + // The operation is associative and commutative, so the lane order of the folds does not change the result. + // Vector512 acceleration implies Vector256 acceleration, and Vector256 implies Vector128, so each fold + // result goes to a loop that runs. + uint total = TReduction.Identity; + Vector256 total256 = Vector256.Create(TReduction.Identity); + Vector128 total128 = Vector128.Create(TReduction.Identity); + + if (Vector512.IsHardwareAccelerated) + { + Vector512 total512 = Vector512.Create(TReduction.Identity); + nuint count = (uint)Vector512.Count; + + // Four loads combine in a tree before they reach the running total. The loop-carried chain thus has one + // operation for each four vectors, so the loads, not the operation latency, limit the loop. + for (; i + (count * 4) <= length; i += count * 4) + { + ref uint block = ref Unsafe.Add(ref sourceBase, i); + Vector512 first = TReduction.Invoke(Vector512.LoadUnsafe(ref block), Vector512.LoadUnsafe(ref block, count)); + Vector512 second = TReduction.Invoke(Vector512.LoadUnsafe(ref block, count * 2), Vector512.LoadUnsafe(ref block, count * 3)); + total512 = TReduction.Invoke(total512, TReduction.Invoke(first, second)); + } + + for (; i + count <= length; i += count) + { + total512 = TReduction.Invoke(total512, Vector512.LoadUnsafe(ref sourceBase, i)); + } + + total256 = TReduction.Invoke(total512.GetLower(), total512.GetUpper()); + } + + if (Vector256.IsHardwareAccelerated) + { + nuint count = (uint)Vector256.Count; + + // The same tree as the 512-bit loop. + for (; i + (count * 4) <= length; i += count * 4) + { + ref uint block = ref Unsafe.Add(ref sourceBase, i); + Vector256 first = TReduction.Invoke(Vector256.LoadUnsafe(ref block), Vector256.LoadUnsafe(ref block, count)); + Vector256 second = TReduction.Invoke(Vector256.LoadUnsafe(ref block, count * 2), Vector256.LoadUnsafe(ref block, count * 3)); + total256 = TReduction.Invoke(total256, TReduction.Invoke(first, second)); + } + + for (; i + count <= length; i += count) + { + total256 = TReduction.Invoke(total256, Vector256.LoadUnsafe(ref sourceBase, i)); + } + + total128 = TReduction.Invoke(total256.GetLower(), total256.GetUpper()); + } + + if (Vector128.IsHardwareAccelerated) + { + nuint count = (uint)Vector128.Count; + + // The same tree as the 512-bit loop. + for (; i + (count * 4) <= length; i += count * 4) + { + ref uint block = ref Unsafe.Add(ref sourceBase, i); + Vector128 first = TReduction.Invoke(Vector128.LoadUnsafe(ref block), Vector128.LoadUnsafe(ref block, count)); + Vector128 second = TReduction.Invoke(Vector128.LoadUnsafe(ref block, count * 2), Vector128.LoadUnsafe(ref block, count * 3)); + total128 = TReduction.Invoke(total128, TReduction.Invoke(first, second)); + } + + for (; i + count <= length; i += count) + { + total128 = TReduction.Invoke(total128, Vector128.LoadUnsafe(ref sourceBase, i)); + } + + // Lanes 0 and 1 combine with lanes 2 and 3, then the two remaining lanes combine. + Vector128 pairs = TReduction.Invoke(total128, Vector128.Shuffle(total128, Vector128.Create(2u, 3, 0, 1))); + total = TReduction.Invoke(pairs.ToScalar(), pairs.GetElement(1)); + } + + for (; i < length; i++) + { + total = TReduction.Invoke(total, Unsafe.Add(ref sourceBase, i)); + } + + return total; + } +} diff --git a/src/ImageSharp/Common/Helpers/Vector128Utilities.cs b/src/ImageSharp/Common/Helpers/Vector128Utilities.cs index 7d24f80368..05786a4b20 100644 --- a/src/ImageSharp/Common/Helpers/Vector128Utilities.cs +++ b/src/ImageSharp/Common/Helpers/Vector128Utilities.cs @@ -119,6 +119,7 @@ public static Vector128 Pow(Vector128 value, float exponent) Vector128 ordinary = Vector128.LessThan( value.AsUInt32() - Vector128.Create(SmallestNormalBits), Vector128.Create(InfinityBits - SmallestNormalBits)); + bool special = (ordinary | zero.AsUInt32()) != Vector128.AllBitsSet; Vector128 small = default; @@ -196,6 +197,39 @@ public static Vector128 Average(Vector128 left, Vector128 righ (Vector128.WidenUpper(left) + Vector128.WidenUpper(right) + Vector128.One) >> 1); } + /// + /// Average packed unsigned 8-bit integers in and , rounding down, and store the results. + /// + /// + /// The first vector containing packed unsigned 8-bit integers to average. + /// + /// + /// The second vector containing packed unsigned 8-bit integers to average. + /// + /// + /// A vector containing ( + ) >> 1 in each of its 16 lanes. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 AverageRoundDown(Vector128 left, Vector128 right) + { + if (Sse2.IsSupported) + { + // PAVGB rounds up. The complement of both inputs and of the result gives the average rounded down: + // 255 - ((255 - a) + (255 - b) + 1) / 2, rounded down, is (a + b) / 2, rounded down. + return ~Sse2.Average(~left, ~right); + } + + if (AdvSimd.IsSupported) + { + // The halving add of ARM rounds down. + return AdvSimd.FusedAddHalving(left, right); + } + + // (a & b) + ((a ^ b) >> 1) equals (a + b) >> 1 without the carry into a wider lane: + // a + b = 2 * (a & b) + (a ^ b), and the shift drops the low bit of the differing bits. + return (left & right) + ((left ^ right) >>> 1); + } + /// /// Average packed unsigned 16-bit integers in and , rounding up, and store the results. /// @@ -407,6 +441,73 @@ public static Vector128 ShiftRightLogicalVariable(Vector128 value, V value.GetElement(3) >> (int)count.GetElement(3)); } + /// + /// Shifts four unsigned 32-bit lanes left by their corresponding lane counts, inserting zero bits. + /// + /// The four unsigned words. + /// The per-lane shift counts. Each count must be from zero through 31. + /// The shifted unsigned words in the same lane order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftLeftLogicalVariable(Vector128 value, Vector128 count) + { + if (Avx2.IsSupported) + { + return Avx2.ShiftLeftLogicalVariable(value, count); + } + + if (AdvSimd.IsSupported) + { + // ARM logical shifts use signed counts: positive counts shift left. The 0..31 bound keeps the reinterpretation exact. + return AdvSimd.ShiftLogical(value, count.AsInt32()); + } + + if (Sse41.IsSupported) + { + // A left shift by n is a product with 2^n. The float with the biased exponent n + 127 is 2^n, and the truncating conversion + // gives it as an int lane. For n = 31 the conversion overflows to 0x80000000, which is 2^31 as an unsigned lane. + Vector128 power = Sse2.ConvertToVector128Int32WithTruncation(((count + Vector128.Create(127U)) << 23).AsSingle()); + return Sse41.MultiplyLow(value, power.AsUInt32()); + } + + return Vector128.Create( + value.GetElement(0) << (int)count.GetElement(0), + value.GetElement(1) << (int)count.GetElement(1), + value.GetElement(2) << (int)count.GetElement(2), + value.GetElement(3) << (int)count.GetElement(3)); + } + + /// + /// Shifts two unsigned 64-bit lanes left by their corresponding lane counts, inserting zero bits. + /// + /// The two unsigned 64-bit words. + /// The per-lane shift counts. Each count must be from zero through 63. + /// The shifted unsigned 64-bit words in the same lane order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftLeftLogicalVariable(Vector128 value, Vector128 count) + { + if (Avx2.IsSupported) + { + return Avx2.ShiftLeftLogicalVariable(value, count); + } + + if (AdvSimd.IsSupported) + { + // ARM logical shifts use signed counts: positive counts shift left. The 0..63 bound keeps the reinterpretation exact. + return AdvSimd.ShiftLogical(value, count.AsInt64()); + } + + if (Sse2.IsSupported) + { + // SSE2 shifts both lanes by the low count. Shift once by each count, then take the low lane of the first result and the + // high lane of the second. + Vector128 low = Sse2.ShiftLeftLogical(value, count); + Vector128 high = Sse2.ShiftLeftLogical(value, Sse2.UnpackHigh(count, count)); + return Sse2.Shuffle(low.AsDouble(), high.AsDouble(), 0b10).AsUInt64(); + } + + return Vector128.Create(value.GetElement(0) << (int)count.GetElement(0), value.GetElement(1) << (int)count.GetElement(1)); + } + /// /// Shifts a 128-bit value right by a specified number of bytes while shifting in zeros. /// @@ -595,6 +696,43 @@ public static Vector128 PackUnsignedSaturate(Vector128 left, Vector return Vector128.Narrow(lefClamped, rightClamped); } + /// + /// Gets the sum of the absolute differences of bytes 0 to 7 of and in 32-bit lane 0. + /// The other lanes are not defined. + /// + /// + /// The sum is at most 2040, so it also fits a signed 32-bit compare. On x64 the sum is one PSADBW, which gives the sum of each 8-byte half. On Arm64, + /// three widening pairwise adds fold the 8 differences into 64-bit lane 0. + /// + /// The first vector. + /// The second vector. + /// A vector with the sum in 32-bit lane 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SumAbsoluteDifferencesLow(Vector128 left, Vector128 right) + { + if (Sse2.IsSupported) + { + return Sse2.SumAbsoluteDifferences(left, right).AsUInt32(); + } + + if (AdvSimd.IsSupported) + { + Vector128 pairs = AdvSimd.AddPairwiseWidening(AdvSimd.AbsoluteDifference(left, right)); + return AdvSimd.AddPairwiseWidening(AdvSimd.AddPairwiseWidening(pairs)).AsUInt32(); + } + + // Unsigned lanes make the absolute difference the larger value minus the smaller one, so the subtraction cannot wrap. + Vector128 difference = Vector128.Max(left, right) - Vector128.Min(left, right); + ulong low = difference.AsUInt64().ToScalar(); + uint sum = 0; + for (int i = 0; i < 8; i++) + { + sum += (uint)(low >> (8 * i)) & 0xff; + } + + return Vector128.CreateScalar(sum); + } + /// /// Adds the absolute differences of packed unsigned 8-bit integers in and /// into . @@ -1124,7 +1262,7 @@ public static Vector128 UnpackHigh(Vector128 left, Vector128 r return Sse2.UnpackHigh(left, right); } - if (AdvSimd.IsSupported) + if (AdvSimd.Arm64.IsSupported) { return AdvSimd.Arm64.ZipHigh(left, right); } @@ -1194,7 +1332,7 @@ public static Vector128 UnpackLow(Vector128 left, Vector128 ri return Sse2.UnpackLow(left, right); } - if (AdvSimd.IsSupported) + if (AdvSimd.Arm64.IsSupported) { return AdvSimd.Arm64.ZipLow(left, right); } @@ -1224,7 +1362,7 @@ public static Vector128 UnpackHigh(Vector128 left, Vector128 righ return Sse2.UnpackHigh(left, right); } - if (AdvSimd.IsSupported) + if (AdvSimd.Arm64.IsSupported) { return AdvSimd.Arm64.ZipHigh(left, right); } @@ -1255,7 +1393,7 @@ public static Vector128 UnpackLow(Vector128 left, Vector128 right return Sse2.UnpackLow(left, right); } - if (AdvSimd.IsSupported) + if (AdvSimd.Arm64.IsSupported) { return AdvSimd.Arm64.ZipLow(left, right); } @@ -1286,7 +1424,7 @@ public static Vector128 UnpackHigh(Vector128 left, Vector128 UnpackLow(Vector128 left, Vector128 return Sse2.UnpackLow(left, right); } - if (AdvSimd.IsSupported) + if (AdvSimd.Arm64.IsSupported) { return AdvSimd.Arm64.ZipLow(left, right); } @@ -1348,7 +1486,7 @@ public static Vector128 UnpackHigh(Vector128 left, Vector128 r return Sse2.UnpackHigh(left, right); } - if (AdvSimd.IsSupported) + if (AdvSimd.Arm64.IsSupported) { return AdvSimd.Arm64.ZipHigh(left, right); } @@ -1379,7 +1517,7 @@ public static Vector128 UnpackLow(Vector128 left, Vector128 ri return Sse2.UnpackLow(left, right); } - if (AdvSimd.IsSupported) + if (AdvSimd.Arm64.IsSupported) { return AdvSimd.Arm64.ZipLow(left, right); } @@ -1410,7 +1548,7 @@ public static Vector128 UnpackHigh(Vector128 left, Vector128 UnpackLow(Vector128 left, Vector128 return Sse2.UnpackLow(left, right); } - if (AdvSimd.IsSupported) + if (AdvSimd.Arm64.IsSupported) { return AdvSimd.Arm64.ZipLow(left, right); } @@ -1584,9 +1722,9 @@ public static unsafe Vector128 Gather(ref int table, Vector128 indices } return Vector128.Create( - Unsafe.Add(ref table, Unsafe.Add(ref first, 0U)), - Unsafe.Add(ref table, Unsafe.Add(ref first, 1U)), - Unsafe.Add(ref table, Unsafe.Add(ref first, 2U)), - Unsafe.Add(ref table, Unsafe.Add(ref first, 3U))); + Unsafe.Add(ref table, (uint)Unsafe.Add(ref first, 0U)), + Unsafe.Add(ref table, (uint)Unsafe.Add(ref first, 1U)), + Unsafe.Add(ref table, (uint)Unsafe.Add(ref first, 2U)), + Unsafe.Add(ref table, (uint)Unsafe.Add(ref first, 3U))); } } diff --git a/src/ImageSharp/Common/Helpers/Vector256Utilities.cs b/src/ImageSharp/Common/Helpers/Vector256Utilities.cs index d689c1d51e..eceee18660 100644 --- a/src/ImageSharp/Common/Helpers/Vector256Utilities.cs +++ b/src/ImageSharp/Common/Helpers/Vector256Utilities.cs @@ -139,6 +139,7 @@ public static Vector256 Pow(Vector256 value, float exponent) Vector256 ordinary = Vector256.LessThan( value.AsUInt32() - Vector256.Create(SmallestNormalBits), Vector256.Create(InfinityBits - SmallestNormalBits)); + bool special = (ordinary | zero.AsUInt32()) != Vector256.AllBitsSet; Vector256 small = default; @@ -210,6 +211,61 @@ public static Vector256 Average(Vector256 left, Vector256 righ return (left | right) - ((left ^ right) >>> 1); } + /// + /// Average packed unsigned 8-bit integers in and , rounding down, and store the results. + /// + /// + /// The first vector containing packed unsigned 8-bit integers to average. + /// + /// + /// The second vector containing packed unsigned 8-bit integers to average. + /// + /// + /// A vector containing ( + ) >> 1 in each of its 32 lanes. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 AverageRoundDown(Vector256 left, Vector256 right) + { + if (Avx2.IsSupported) + { + // VPAVGB rounds up. The complement of both inputs and of the result gives the average rounded down: + // 255 - ((255 - a) + (255 - b) + 1) / 2, rounded down, is (a + b) / 2, rounded down. + return ~Avx2.Average(~left, ~right); + } + + // (a & b) + ((a ^ b) >> 1) equals (a + b) >> 1 without the carry into a wider lane: + // a + b = 2 * (a & b) + (a ^ b), and the shift drops the low bit of the differing bits. + return (left & right) + ((left ^ right) >>> 1); + } + + /// + /// Multiply the packed 16-bit unsigned integers in and , producing + /// intermediate unsigned 32-bit integers, and store the high 16 bits of the intermediate integers in the result. + /// + /// + /// The first vector containing packed 16-bit unsigned integers to multiply. + /// + /// + /// The second vector containing packed 16-bit unsigned integers to multiply. + /// + /// + /// A vector containing the high 16 bits of the products of the packed 16-bit unsigned integers + /// from and , in each of its 16 lanes. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 MultiplyHigh(Vector256 left, Vector256 right) + { + if (Avx2.IsSupported) + { + return Avx2.MultiplyHigh(left, right); + } + + // Each 32-bit lane holds the full product of two 16-bit values, so the shift gives the exact high half. + (Vector256 leftLow, Vector256 leftHigh) = Vector256.Widen(left); + (Vector256 rightLow, Vector256 rightHigh) = Vector256.Widen(right); + return Vector256.Narrow((leftLow * rightLow) >>> 16, (leftHigh * rightHigh) >>> 16); + } + /// /// Average packed unsigned 16-bit integers in and , rounding up, and store the results. /// @@ -809,6 +865,44 @@ public static unsafe Vector256 Gather(ref int table, Vector256 indices Vector128_.Gather(ref table, indices.GetUpper())); } + /// + /// Shifts eight unsigned 32-bit lanes left by their corresponding lane counts, inserting zero bits. + /// + /// The eight unsigned words. + /// The per-lane shift counts. Each count must be from zero through 31. + /// The shifted unsigned words in the same lane order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftLeftLogicalVariable(Vector256 value, Vector256 count) + { + if (Avx2.IsSupported) + { + return Avx2.ShiftLeftLogicalVariable(value, count); + } + + return Vector256.Create( + Vector128_.ShiftLeftLogicalVariable(value.GetLower(), count.GetLower()), + Vector128_.ShiftLeftLogicalVariable(value.GetUpper(), count.GetUpper())); + } + + /// + /// Shifts four unsigned 64-bit lanes left by their corresponding lane counts, inserting zero bits. + /// + /// The four unsigned 64-bit words. + /// The per-lane shift counts. Each count must be from zero through 63. + /// The shifted unsigned 64-bit words in the same lane order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftLeftLogicalVariable(Vector256 value, Vector256 count) + { + if (Avx2.IsSupported) + { + return Avx2.ShiftLeftLogicalVariable(value, count); + } + + return Vector256.Create( + Vector128_.ShiftLeftLogicalVariable(value.GetLower(), count.GetLower()), + Vector128_.ShiftLeftLogicalVariable(value.GetUpper(), count.GetUpper())); + } + /// /// Packs signed 32-bit integers to signed 16-bit integers and saturates. /// diff --git a/src/ImageSharp/Common/Helpers/Vector512Utilities.cs b/src/ImageSharp/Common/Helpers/Vector512Utilities.cs index c4c222dd5e..0e62c9a074 100644 --- a/src/ImageSharp/Common/Helpers/Vector512Utilities.cs +++ b/src/ImageSharp/Common/Helpers/Vector512Utilities.cs @@ -152,6 +152,7 @@ public static Vector512 Pow(Vector512 value, float exponent) Vector512 ordinary = Vector512.LessThan( value.AsUInt32() - Vector512.Create(SmallestNormalBits), Vector512.Create(InfinityBits - SmallestNormalBits)); + bool special = (ordinary | zero.AsUInt32()) != Vector512.AllBitsSet; Vector512 small = default; @@ -223,6 +224,90 @@ public static Vector512 Average(Vector512 left, Vector512 righ return (left | right) - ((left ^ right) >>> 1); } + /// + /// Average packed unsigned 8-bit integers in and , rounding down, and store the results. + /// + /// + /// The first vector containing packed unsigned 8-bit integers to average. + /// + /// + /// The second vector containing packed unsigned 8-bit integers to average. + /// + /// + /// A vector containing ( + ) >> 1 in each of its 64 lanes. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector512 AverageRoundDown(Vector512 left, Vector512 right) + { + if (Avx512BW.IsSupported) + { + // VPAVGB rounds up. The complement of both inputs and of the result gives the average rounded down: + // 255 - ((255 - a) + (255 - b) + 1) / 2, rounded down, is (a + b) / 2, rounded down. + return ~Avx512BW.Average(~left, ~right); + } + + // (a & b) + ((a ^ b) >> 1) equals (a + b) >> 1 without the carry into a wider lane: + // a + b = 2 * (a & b) + (a ^ b), and the shift drops the low bit of the differing bits. + return (left & right) + ((left ^ right) >>> 1); + } + + /// + /// Multiply the packed 16-bit unsigned integers in and , producing + /// intermediate unsigned 32-bit integers, and store the high 16 bits of the intermediate integers in the result. + /// + /// + /// The first vector containing packed 16-bit unsigned integers to multiply. + /// + /// + /// The second vector containing packed 16-bit unsigned integers to multiply. + /// + /// + /// A vector containing the high 16 bits of the products of the packed 16-bit unsigned integers + /// from and , in each of its 32 lanes. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector512 MultiplyHigh(Vector512 left, Vector512 right) + { + if (Avx512BW.IsSupported) + { + return Avx512BW.MultiplyHigh(left, right); + } + + // Each 32-bit lane holds the full product of two 16-bit values, so the shift gives the exact high half. + (Vector512 leftLow, Vector512 leftHigh) = Vector512.Widen(left); + (Vector512 rightLow, Vector512 rightHigh) = Vector512.Widen(right); + return Vector512.Narrow((leftLow * rightLow) >>> 16, (leftHigh * rightHigh) >>> 16); + } + + /// + /// Multiply the packed signed 16-bit integers in and , producing + /// intermediate signed 32-bit integers, and store the high 16 bits of the intermediate integers in the result. + /// + /// + /// The first vector containing packed 16-bit signed integers to multiply. + /// + /// + /// The second vector containing packed 16-bit signed integers to multiply. + /// + /// + /// A vector containing the high 16 bits of the products of the packed 16-bit signed integers + /// from and , in each of its 32 lanes. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector512 MultiplyHigh(Vector512 left, Vector512 right) + { + if (Avx512BW.IsSupported) + { + return Avx512BW.MultiplyHigh(left, right); + } + + // Each 32-bit lane holds the full signed product of two 16-bit values. The arithmetic shift gives the exact + // high half, which always fits in 16 bits, so the truncating narrow keeps it. + (Vector512 leftLow, Vector512 leftHigh) = Vector512.Widen(left); + (Vector512 rightLow, Vector512 rightHigh) = Vector512.Widen(right); + return Vector512.Narrow((leftLow * rightLow) >> 16, (leftHigh * rightHigh) >> 16); + } + /// /// Average packed unsigned 16-bit integers in and , rounding up, and store the results. /// @@ -896,6 +981,44 @@ public static unsafe Vector512 Gather(ref int table, Vector512 indices } } + /// + /// Shifts sixteen unsigned 32-bit lanes left by their corresponding lane counts, inserting zero bits. + /// + /// The sixteen unsigned words. + /// The per-lane shift counts. Each count must be from zero through 31. + /// The shifted unsigned words in the same lane order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector512 ShiftLeftLogicalVariable(Vector512 value, Vector512 count) + { + if (Avx512F.IsSupported) + { + return Avx512F.ShiftLeftLogicalVariable(value, count); + } + + return Vector512.Create( + Vector256_.ShiftLeftLogicalVariable(value.GetLower(), count.GetLower()), + Vector256_.ShiftLeftLogicalVariable(value.GetUpper(), count.GetUpper())); + } + + /// + /// Shifts eight unsigned 64-bit lanes left by their corresponding lane counts, inserting zero bits. + /// + /// The eight unsigned 64-bit words. + /// The per-lane shift counts. Each count must be from zero through 63. + /// The shifted unsigned 64-bit words in the same lane order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector512 ShiftLeftLogicalVariable(Vector512 value, Vector512 count) + { + if (Avx512F.IsSupported) + { + return Avx512F.ShiftLeftLogicalVariable(value, count); + } + + return Vector512.Create( + Vector256_.ShiftLeftLogicalVariable(value.GetLower(), count.GetLower()), + Vector256_.ShiftLeftLogicalVariable(value.GetUpper(), count.GetUpper())); + } + /// /// Reads 16 unaligned 32-bit words at byte offsets while the caller keeps the table pinned. /// diff --git a/src/ImageSharp/Common/InlineArray.cs b/src/ImageSharp/Common/InlineArray.cs index 4f73590d27..40efd2479d 100644 --- a/src/ImageSharp/Common/InlineArray.cs +++ b/src/ImageSharp/Common/InlineArray.cs @@ -89,6 +89,15 @@ internal struct InlineArray12 private T t; } +/// +/// Represents a safe, fixed sized buffer of 13 elements. +/// +[InlineArray(13)] +internal struct InlineArray13 +{ + private T t; +} + /// /// Represents a safe, fixed sized buffer of 14 elements. /// @@ -205,3 +214,12 @@ internal struct InlineArray256 { private T t; } + +/// +/// Represents a safe, fixed sized buffer of 264 elements. +/// +[InlineArray(264)] +internal struct InlineArray264 +{ + private T t; +} diff --git a/src/ImageSharp/Common/InlineArray.tt b/src/ImageSharp/Common/InlineArray.tt index 6d95ccb0b0..059c1cba51 100644 --- a/src/ImageSharp/Common/InlineArray.tt +++ b/src/ImageSharp/Common/InlineArray.tt @@ -12,17 +12,16 @@ using System; using System.Runtime.CompilerServices; namespace SixLabors.ImageSharp; - <#GenerateInlineArrays();#> - <#+ -private static int[] Lengths = [2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 19, 24, 25, 26, 32, 36, 64, 65, 128, 256]; +private static int[] Lengths = [2, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 16, 18, 19, 24, 25, 26, 32, 36, 64, 65, 128, 256, 264]; void GenerateInlineArrays() { foreach (int length in Lengths) { #> + /// /// Represents a safe, fixed sized buffer of <#=length#> elements. /// @@ -31,8 +30,7 @@ internal struct InlineArray<#=length#> { private T t; } - <#+ } } -#> +#> \ No newline at end of file diff --git a/src/ImageSharp/Compression/HuffmanCodeLengths.cs b/src/ImageSharp/Compression/HuffmanCodeLengths.cs new file mode 100644 index 0000000000..031e53b514 --- /dev/null +++ b/src/ImageSharp/Compression/HuffmanCodeLengths.cs @@ -0,0 +1,151 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.ImageSharp.Compression; + +/// +/// Builds length-limited Huffman code lengths from symbol counts. The WebP lossless and the JPEG XL encoders share it. +/// +internal static class HuffmanCodeLengths +{ + /// + /// Builds the code lengths of an optimal Huffman code whose lengths do not exceed a limit. + /// + /// + /// The method builds the Huffman tree of the counts. When the tree is deeper than the limit, it raises the small counts to a + /// minimum count, which doubles for each new try, and builds the tree again. The method writes only the lengths of the used + /// symbols, so the caller clears first. + /// + /// The node scratch, with room for 3 nodes for each used symbol. + /// The count of each symbol. + /// The number of symbols. + /// The largest code length. + /// Receives the code length of each used symbol. + public static void GenerateOptimalTree(Span tree, ReadOnlySpan histogram, int histogramSize, int treeDepthLimit, Span bitDepths) + { + uint countMin; + int treeSizeOrig = 0; + + for (int i = 0; i < histogramSize; i++) + { + if (histogram[i] != 0) + { + ++treeSizeOrig; + } + } + + if (treeSizeOrig == 0) + { + return; + } + + Span treePool = tree[treeSizeOrig..]; + + // For block sizes with less than 64k symbols we never need to do a + // second iteration of this loop. + for (countMin = 1; ; countMin *= 2) + { + int treeSize = treeSizeOrig; + + // We need to pack the Huffman tree in treeDepthLimit bits. + // So, we try by faking histogram entries to be at least 'countMin'. + int idx = 0; + for (int j = 0; j < histogramSize; j++) + { + if (histogram[j] != 0) + { + uint count = histogram[j] < countMin ? countMin : histogram[j]; + tree[idx].TotalCount = (int)count; + tree[idx].Value = j; + tree[idx].PoolIndexLeft = -1; + tree[idx].PoolIndexRight = -1; + idx++; + } + } + + // Build the Huffman tree. + Span treeSlice = tree[..treeSize]; + treeSlice.Sort(HuffmanTree.Compare); + + if (treeSize > 1) + { + // Normal case. + int treePoolSize = 0; + while (treeSize > 1) + { + // Finish when we have only one root. + treePool[treePoolSize++] = tree[treeSize - 1]; + treePool[treePoolSize++] = tree[treeSize - 2]; + int count = treePool[treePoolSize - 1].TotalCount + treePool[treePoolSize - 2].TotalCount; + treeSize -= 2; + + // Search for the insertion point. + int k; + for (k = 0; k < treeSize; k++) + { + if (tree[k].TotalCount <= count) + { + break; + } + } + + int endIdx = k + 1; + int num = treeSize - k; + int startIdx = endIdx + num - 1; + for (int i = startIdx; i >= endIdx; i--) + { + tree[i] = tree[i - 1]; + } + + tree[k].TotalCount = count; + tree[k].Value = -1; + tree[k].PoolIndexLeft = treePoolSize - 1; + tree[k].PoolIndexRight = treePoolSize - 2; + treeSize++; + } + + SetBitDepths(tree, treePool, bitDepths, 0); + } + else if (treeSize == 1) + { + // Trivial case: only one element. + bitDepths[tree[0].Value] = 1; + } + + // Test if this Huffman tree satisfies our 'treeDepthLimit' criteria. + int maxDepth = bitDepths[0]; + for (int j = 1; j < histogramSize; j++) + { + if (maxDepth < bitDepths[j]) + { + maxDepth = bitDepths[j]; + } + } + + if (maxDepth <= treeDepthLimit) + { + break; + } + } + } + + /// + /// Walks a Huffman tree and sets the code length of each leaf symbol to its depth. + /// + /// The tree. The first node is the root of the walk. + /// The pool that holds the child nodes. + /// Receives the code length of each symbol. + /// The depth of the root node. + private static void SetBitDepths(ReadOnlySpan tree, Span pool, Span bitDepths, int level) + { + if (tree[0].PoolIndexLeft >= 0) + { + SetBitDepths(pool[tree[0].PoolIndexLeft..], pool, bitDepths, level + 1); + SetBitDepths(pool[tree[0].PoolIndexRight..], pool, bitDepths, level + 1); + } + else + { + bitDepths[tree[0].Value] = (byte)level; + } + } +} diff --git a/src/ImageSharp/Formats/Webp/Lossless/HuffmanTree.cs b/src/ImageSharp/Compression/HuffmanTree.cs similarity index 89% rename from src/ImageSharp/Formats/Webp/Lossless/HuffmanTree.cs rename to src/ImageSharp/Compression/HuffmanTree.cs index 25af3e2d34..5caf1e0be6 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/HuffmanTree.cs +++ b/src/ImageSharp/Compression/HuffmanTree.cs @@ -3,10 +3,10 @@ using System.Diagnostics; -namespace SixLabors.ImageSharp.Formats.Webp.Lossless; +namespace SixLabors.ImageSharp.Compression; /// -/// Represents the Huffman tree. +/// A node of the Huffman tree that builds: a leaf with a symbol, or an inner node with two children. /// [DebuggerDisplay("TotalCount = {TotalCount}, Value = {Value}, Left = {PoolIndexLeft}, Right = {PoolIndexRight}")] internal struct HuffmanTree diff --git a/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs b/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs index 34b8b6f6df..9a4d6ed27d 100644 --- a/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs +++ b/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs @@ -8,7 +8,6 @@ using System.Numerics.Tensors; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Runtime.Intrinsics; using SixLabors.ImageSharp.ColorProfiles; using SixLabors.ImageSharp.ColorProfiles.Icc; using SixLabors.ImageSharp.Common.Helpers; @@ -1226,70 +1225,13 @@ private void ReadRgb32Slow(BufferedReadStream stream, Buffer2D p /// Gets a value indicating whether a row of B, G, R, A pixels has an alpha byte that is not 0. /// /// - /// Each pixel is one little-endian uint, with alpha in bits 24..31. The SIMD loops OR the pixels of the row into - /// one register, then test the alpha bits of all lanes one time. The narrower widths and the scalar loop take the - /// rest of the row. All forms give the same result as a test of each alpha byte. + /// Each pixel is one little-endian uint, with alpha in bits 24..31. The OR of all pixels has an alpha bit set + /// only when that bit is set in an alpha byte of the row. /// /// The pixel bytes of the row, 4 for each pixel. /// if an alpha byte is not 0. Else . private static bool HasNonZeroAlpha(ReadOnlySpan row) - { - const uint alphaMask = BmpConstants.Bgra32Masks.Alpha; - ReadOnlySpan pixels = MemoryMarshal.Cast(row); - ref uint pixelBase = ref MemoryMarshal.GetReference(pixels); - nuint length = (uint)pixels.Length; - nuint x = 0; - - if (Vector512.IsHardwareAccelerated && length >= (uint)Vector512.Count) - { - Vector512 any = Vector512.Zero; - for (; x + (uint)Vector512.Count <= length; x += (uint)Vector512.Count) - { - any |= Vector512.LoadUnsafe(ref pixelBase, x); - } - - if ((any & Vector512.Create(alphaMask)) != Vector512.Zero) - { - return true; - } - } - - if (Vector256.IsHardwareAccelerated && length - x >= (uint)Vector256.Count) - { - Vector256 any = Vector256.Zero; - for (; x + (uint)Vector256.Count <= length; x += (uint)Vector256.Count) - { - any |= Vector256.LoadUnsafe(ref pixelBase, x); - } - - if ((any & Vector256.Create(alphaMask)) != Vector256.Zero) - { - return true; - } - } - - if (Vector128.IsHardwareAccelerated && length - x >= (uint)Vector128.Count) - { - Vector128 any = Vector128.Zero; - for (; x + (uint)Vector128.Count <= length; x += (uint)Vector128.Count) - { - any |= Vector128.LoadUnsafe(ref pixelBase, x); - } - - if ((any & Vector128.Create(alphaMask)) != Vector128.Zero) - { - return true; - } - } - - uint rest = 0; - for (; x < length; x++) - { - rest |= Unsafe.Add(ref pixelBase, x); - } - - return (rest & alphaMask) != 0; - } + => (SimdUtils.Reduce(MemoryMarshal.Cast(row)) & BmpConstants.Bgra32Masks.Alpha) != 0; /// /// Reads one stored row of pixel data. @@ -1505,6 +1447,7 @@ private void ReadInfoHeader(BufferedReadStream stream) bool rgb555 = this.infoHeader.RedMask is BmpConstants.Bgr555Masks.Red && this.infoHeader.GreenMask is BmpConstants.Bgr555Masks.Green && this.infoHeader.BlueMask is BmpConstants.Bgr555Masks.Blue; + bool rgba5551 = rgb555 && this.infoHeader.AlphaMask is BmpConstants.Bgr555Masks.Alpha; (this.bmpMetadata.ColorType, BmpBitsPerPixel colorDepth) = bitsPerPixel switch @@ -1791,10 +1734,29 @@ private void ReadImageHeaders(BufferedReadStream stream, out bool inverted, out private readonly ref struct PaletteMaskOperator : IMaskOperator where TPixel : unmanaged, IPixel { + /// + /// The image row that receives the transparent pixels. + /// private readonly Span row; + + /// + /// The packed palette indices of the row. The first pixel is in the most significant bits. + /// private readonly ReadOnlySpan indices; + + /// + /// The transparent form of each palette entry, one for each index value. + /// private readonly ReadOnlySpan transparent; + + /// + /// The bit count of one index: 1, 2, 4 or 8. + /// private readonly int bitsPerPixel; + + /// + /// The mask of the low bits. + /// private readonly int indexMask; /// @@ -1834,6 +1796,9 @@ public void SetTransparent(int x) private readonly ref struct AlphaMaskOperator : IMaskOperator where TPixel : unmanaged, IPixel { + /// + /// The image row that receives the transparent pixels. + /// private readonly Span row; /// diff --git a/src/ImageSharp/Formats/Heif/Av1/Pipeline/Av1IntraSuperblockEncoder.TransformTypeModel.cs b/src/ImageSharp/Formats/Heif/Av1/Pipeline/Av1IntraSuperblockEncoder.TransformTypeModel.cs index 01a6f8610f..18e5a29e0a 100644 --- a/src/ImageSharp/Formats/Heif/Av1/Pipeline/Av1IntraSuperblockEncoder.TransformTypeModel.cs +++ b/src/ImageSharp/Formats/Heif/Av1/Pipeline/Av1IntraSuperblockEncoder.TransformTypeModel.cs @@ -14,6 +14,10 @@ namespace SixLabors.ImageSharp.Formats.Heif.Av1.Pipeline; /// internal static partial class Av1IntraSuperblockEncoder { + /// + /// Gets the hidden layer weights of the 4x4 transform type model of the horizontal axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType4x4HorizontalWeights0 => [ -1.64947F, -1.54497F, -1.62832F, -0.17774F, -2.89498F, -0.72498F, 0.72036F, 0.17996F, @@ -22,11 +26,19 @@ internal static partial class Av1IntraSuperblockEncoder 0.02194F, -0.26427F, 0.28049F, 0.21260F, 1.35792F, 0.27733F, 0.88660F, -0.68304F ]; + /// + /// Gets the hidden layer biases of the 4x4 transform type model of the horizontal axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType4x4HorizontalBias0 => [ 1.38742F, 0.59540F, -1.37622F, 1.92114F, 0.00000F, -0.38998F, -0.32726F, -0.15650F ]; + /// + /// Gets the output weights of the 4x4 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType4x4HorizontalWeights1 => [ 1.65254F, 1.00915F, -0.89318F, -2.05142F, -0.23235F, 0.96781F, -0.37145F, -0.21056F, @@ -35,11 +47,19 @@ internal static partial class Av1IntraSuperblockEncoder -1.49221F, -0.48349F, -0.64692F, 1.49297F, -0.26782F, -0.65416F, -0.10648F, 0.05568F ]; + /// + /// Gets the output biases of the 4x4 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType4x4HorizontalBias1 => [ 4.07177F, 3.26961F, 0.58083F, 1.21199F ]; + /// + /// Gets the hidden layer weights of the 4x4 transform type model of the vertical axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType4x4VerticalWeights0 => [ -0.02032F, 2.61610F, 0.02098F, -0.30217F, 0.12637F, 0.11017F, -3.01996F, 0.35144F, @@ -48,11 +68,19 @@ internal static partial class Av1IntraSuperblockEncoder -1.67358F, -1.67035F, -1.54623F, 0.16714F, -0.06589F, -0.28142F, -0.33118F, 1.72227F ]; + /// + /// Gets the hidden layer biases of the 4x4 transform type model of the vertical axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType4x4VerticalBias0 => [ -0.33685F, 0.22025F, 0.28140F, 0.56138F, 0.93489F, -1.77048F, 1.34989F, -0.93747F ]; + /// + /// Gets the output weights of the 4x4 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType4x4VerticalWeights1 => [ -1.39506F, -1.06271F, -1.10886F, -1.69719F, 0.19699F, -2.39850F, -1.26457F, 0.75328F, @@ -61,11 +89,19 @@ internal static partial class Av1IntraSuperblockEncoder 0.34776F, 0.58154F, -0.18217F, -0.29257F, -0.86315F, -0.53336F, 0.30320F, -1.32331F ]; + /// + /// Gets the output biases of the 4x4 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType4x4VerticalBias1 => [ -1.31519F, -3.26321F, 1.71794F, -1.90778F ]; + /// + /// Gets the hidden layer weights of the 4x8 transform type model of the horizontal axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType4x8HorizontalWeights0 => [ 0.00218F, -0.41880F, -0.61215F, -0.92588F, 0.54291F, -0.10898F, 0.70691F, 0.46819F, @@ -74,11 +110,19 @@ internal static partial class Av1IntraSuperblockEncoder -0.26732F, -0.48262F, -0.08682F, 2.44071F, -1.35896F, -1.17121F, 1.68866F, 0.10357F ]; + /// + /// Gets the hidden layer biases of the 4x8 transform type model of the horizontal axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType4x8HorizontalBias0 => [ 2.93391F, 0.66831F, -0.21419F, 0.00000F, -0.72878F, 0.15127F, -1.46755F, 0.16658F ]; + /// + /// Gets the output weights of the 4x8 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType4x8HorizontalWeights1 => [ -1.52077F, -1.06243F, 0.35319F, -0.49207F, 0.54524F, 0.44271F, 1.37117F, -0.38957F, @@ -87,11 +131,19 @@ internal static partial class Av1IntraSuperblockEncoder -1.41331F, -0.16453F, 0.05755F, 0.31405F, -0.50191F, 0.18219F, 1.83664F, -0.75276F ]; + /// + /// Gets the output biases of the 4x8 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType4x8HorizontalBias1 => [ -1.17455F, -2.26089F, -1.79863F, -2.26333F ]; + /// + /// Gets the hidden layer weights of the 4x8 transform type model of the vertical axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType4x8VerticalWeights0 => [ -0.00952F, -0.98858F, -0.93181F, 1.39594F, 0.96559F, 0.18162F, -0.76064F, -0.06066F, @@ -112,12 +164,20 @@ internal static partial class Av1IntraSuperblockEncoder 0.26514F, -0.84629F, -0.66343F, -2.10630F, 0.11017F, 2.18528F, -0.21958F, 0.05970F ]; + /// + /// Gets the hidden layer biases of the 4x8 transform type model of the vertical axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType4x8VerticalBias0 => [ 0.04205F, 0.22260F, -1.03870F, -1.19568F, 0.44283F, 0.01143F, 0.00235F, 4.26772F, 0.44364F, -0.33199F, -0.39076F, -0.35129F, 0.08288F, 0.18195F, -0.79890F, 0.10047F ]; + /// + /// Gets the output weights of the 4x8 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType4x8VerticalWeights1 => [ -0.38193F, -0.12095F, 1.57802F, 0.34932F, -0.47333F, -0.12304F, -0.01736F, -2.52445F, @@ -130,11 +190,19 @@ internal static partial class Av1IntraSuperblockEncoder -0.68736F, -0.37904F, -1.32371F, 0.47288F, 1.51904F, 0.78372F, -1.01830F, -1.01848F ]; + /// + /// Gets the output biases of the 4x8 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType4x8VerticalBias1 => [ -1.45955F, -2.08949F, -1.24813F, -1.55368F ]; + /// + /// Gets the hidden layer weights of the 8x4 transform type model of the horizontal axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType8x4HorizontalWeights0 => [ -0.22492F, 0.13341F, -4.03243F, -0.64015F, 0.02783F, 0.60466F, -0.13335F, 0.16828F, @@ -155,12 +223,20 @@ internal static partial class Av1IntraSuperblockEncoder -1.51234F, -1.13502F, -1.20470F, -1.02913F, -1.09182F, -0.93921F, -1.85523F, 0.92532F ]; + /// + /// Gets the hidden layer biases of the 8x4 transform type model of the horizontal axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType8x4HorizontalBias0 => [ 0.36631F, 0.02901F, 0.64305F, 1.53074F, -1.40229F, 0.03852F, -0.05043F, 0.89632F, -1.23312F, 0.07036F, 0.17070F, 0.56250F, -0.28958F, -0.32869F, -0.01704F, 0.68171F ]; + /// + /// Gets the output weights of the 8x4 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType8x4HorizontalWeights1 => [ -0.49441F, -0.31960F, -0.84946F, -0.85800F, -2.37767F, 0.81373F, -0.73172F, -0.69337F, @@ -173,11 +249,19 @@ internal static partial class Av1IntraSuperblockEncoder 0.09698F, 0.71888F, 0.60594F, 0.84103F, -0.50440F, -0.38825F, 0.15626F, -1.10654F ]; + /// + /// Gets the output biases of the 8x4 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType8x4HorizontalBias1 => [ -0.92861F, -1.45151F, -1.33588F, -4.33853F ]; + /// + /// Gets the hidden layer weights of the 8x4 transform type model of the vertical axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType8x4VerticalWeights0 => [ -1.10946F, 1.86574F, -1.59343F, 0.27018F, -1.70676F, -0.73982F, -0.19021F, -1.94208F, @@ -186,11 +270,19 @@ internal static partial class Av1IntraSuperblockEncoder 0.54407F, -0.45538F, 1.18262F, 2.28687F, 1.66212F, 1.70826F, 1.55182F, 0.12230F ]; + /// + /// Gets the hidden layer biases of the 8x4 transform type model of the vertical axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType8x4VerticalBias0 => [ 0.10943F, 2.09789F, 2.16578F, 0.15766F, -0.42461F, 0.00000F, 1.22090F, -1.28717F ]; + /// + /// Gets the output weights of the 8x4 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType8x4VerticalWeights1 => [ 1.20426F, -1.23237F, 2.41053F, -0.72488F, 1.25249F, 0.18018F, -0.09586F, 2.17901F, @@ -199,11 +291,19 @@ internal static partial class Av1IntraSuperblockEncoder -0.32338F, 2.68712F, -2.83483F, -0.27086F, -1.15005F, -0.39311F, 1.51236F, -1.68973F ]; + /// + /// Gets the output biases of the 8x4 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType8x4VerticalBias1 => [ 1.81013F, 1.10517F, 2.90059F, 0.95391F ]; + /// + /// Gets the hidden layer weights of the 8x8 transform type model of the horizontal axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType8x8HorizontalWeights0 => [ -0.85529F, 0.37619F, 0.12754F, 0.08622F, 0.45278F, 0.54929F, 1.60651F, -0.62654F, @@ -224,12 +324,20 @@ internal static partial class Av1IntraSuperblockEncoder -1.08197F, -1.08280F, -0.79489F, -1.12338F, -1.06795F, -0.87857F, -0.99892F, 1.09823F ]; + /// + /// Gets the hidden layer biases of the 8x8 transform type model of the horizontal axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType8x8HorizontalBias0 => [ -0.49232F, -0.29685F, -1.44020F, 1.10940F, 1.16452F, -0.34862F, -0.38761F, -0.36243F, 0.21776F, 0.28234F, 2.34269F, -0.04104F, -0.26319F, 2.65579F, -1.30137F, -0.01487F ]; + /// + /// Gets the output weights of the 8x8 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType8x8HorizontalWeights1 => [ -0.38058F, -0.41295F, -1.26884F, -0.75560F, -1.57450F, 0.56072F, -1.42322F, -0.29106F, @@ -242,11 +350,19 @@ internal static partial class Av1IntraSuperblockEncoder 0.49525F, 0.46839F, 1.32203F, 0.33923F, 0.97001F, 2.38584F, 1.58811F, 0.06161F ]; + /// + /// Gets the output biases of the 8x8 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType8x8HorizontalBias1 => [ 1.70385F, 1.82373F, 1.78496F, 1.80826F ]; + /// + /// Gets the hidden layer weights of the 8x8 transform type model of the vertical axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType8x8VerticalWeights0 => [ -0.67016F, -1.72366F, -1.86576F, -1.50962F, -1.70419F, -1.73964F, -1.84615F, 2.09681F, @@ -267,12 +383,20 @@ internal static partial class Av1IntraSuperblockEncoder -0.69806F, -1.00564F, -0.85995F, -0.90889F, -0.84412F, -0.85712F, -1.29848F, 0.39308F ]; + /// + /// Gets the hidden layer biases of the 8x8 transform type model of the vertical axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType8x8VerticalBias0 => [ -0.14868F, -0.48343F, 3.94416F, -0.78037F, -1.33789F, -0.60611F, 0.51793F, 0.44030F, -0.71563F, 0.22561F, -1.19083F, -0.46149F, 0.83015F, 0.06024F, 1.17180F, 0.65122F ]; + /// + /// Gets the output weights of the 8x8 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType8x8VerticalWeights1 => [ -1.42711F, -0.21683F, 2.12061F, 0.20489F, -0.50228F, -0.24770F, 0.23391F, 1.03470F, @@ -285,11 +409,19 @@ internal static partial class Av1IntraSuperblockEncoder -0.50406F, 0.63854F, 1.02340F, 0.49833F, 0.13671F, 0.26722F, 2.09516F, -0.41305F ]; + /// + /// Gets the output biases of the 8x8 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType8x8VerticalBias1 => [ 2.14067F, 2.76699F, 2.04233F, 1.34803F ]; + /// + /// Gets the hidden layer weights of the 8x16 transform type model of the horizontal axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType8x16HorizontalWeights0 => [ -1.61872F, -1.58520F, -1.41236F, -1.53255F, -1.59794F, -1.25769F, -1.90043F, 0.73431F, @@ -310,12 +442,20 @@ internal static partial class Av1IntraSuperblockEncoder -4.77119F, 0.13257F, -0.01704F, -0.23087F, -0.00825F, 0.07029F, -0.28136F, 0.42556F ]; + /// + /// Gets the hidden layer biases of the 8x16 transform type model of the horizontal axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType8x16HorizontalBias0 => [ 0.93617F, -0.24000F, -1.26821F, 0.78780F, 0.13690F, -0.21948F, -1.45162F, 0.44584F, -1.92582F, -0.23169F, 0.56004F, -1.19937F, 1.81560F, -1.02643F, -0.81690F, 0.08302F ]; + /// + /// Gets the output weights of the 8x16 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType8x16HorizontalWeights1 => [ 0.06696F, -0.11538F, -1.42029F, 0.32965F, 0.81046F, 0.01146F, 1.20945F, -0.16899F, @@ -328,11 +468,19 @@ internal static partial class Av1IntraSuperblockEncoder 1.53207F, 0.45634F, -1.48476F, 0.17489F, 0.71790F, -2.12086F, -1.21778F, -1.31243F ]; + /// + /// Gets the output biases of the 8x16 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType8x16HorizontalBias1 => [ 0.83359F, 1.06875F, 1.77645F, 1.49570F ]; + /// + /// Gets the hidden layer weights of the 8x16 transform type model of the vertical axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType8x16VerticalWeights0 => [ 0.32858F, -1.28887F, 0.25632F, -0.05262F, 2.69203F, -0.07004F, 1.37337F, -0.05725F, @@ -353,12 +501,20 @@ internal static partial class Av1IntraSuperblockEncoder -5.70858F, -0.14548F, -0.15745F, -0.11812F, -0.07605F, -0.07693F, -0.12236F, 0.16075F ]; + /// + /// Gets the hidden layer biases of the 8x16 transform type model of the vertical axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType8x16VerticalBias0 => [ -0.35385F, 0.30491F, -0.90011F, 0.42941F, 1.20928F, -0.88331F, -1.48818F, -0.34785F, -0.32668F, -0.22695F, 0.89188F, 0.65521F, 0.57598F, 0.99819F, 0.75175F, 0.17044F ]; + /// + /// Gets the output weights of the 8x16 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType8x16VerticalWeights1 => [ -0.62913F, -0.34304F, 0.42963F, -0.17440F, -1.44092F, 0.69142F, -1.36067F, 0.52211F, @@ -371,11 +527,19 @@ internal static partial class Av1IntraSuperblockEncoder 0.17251F, -0.35927F, 0.65631F, -0.26812F, 0.80128F, 0.85748F, 0.47404F, 2.20547F ]; + /// + /// Gets the output biases of the 8x16 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType8x16VerticalBias1 => [ -0.44080F, -1.67455F, -1.46332F, -6.13206F ]; + /// + /// Gets the hidden layer weights of the 16x8 transform type model of the horizontal axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType16x8HorizontalWeights0 => [ 0.02600F, 0.09786F, -1.05107F, -0.35594F, -0.15658F, 2.99828F, -0.07106F, -0.10101F, @@ -396,12 +560,20 @@ internal static partial class Av1IntraSuperblockEncoder 0.32394F, 0.52128F, 0.01013F, -0.28948F, -0.26293F, -0.44331F, -0.36570F, -0.50757F ]; + /// + /// Gets the hidden layer biases of the 16x8 transform type model of the horizontal axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType16x8HorizontalBias0 => [ -0.08696F, -0.22110F, -1.43604F, -1.00451F, -1.51029F, 0.63736F, 0.45260F, 0.16229F, 4.01393F, -0.21748F, 0.36411F, -0.08764F, -0.12329F, 0.08986F, 1.08117F, -0.00220F ]; + /// + /// Gets the output weights of the 16x8 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType16x8HorizontalWeights1 => [ 0.55824F, -0.14648F, 0.81947F, -0.45867F, -1.86078F, -0.17291F, 0.34849F, 0.15153F, @@ -414,11 +586,19 @@ internal static partial class Av1IntraSuperblockEncoder 2.00673F, -0.40189F, 0.95423F, 0.23234F, -0.80953F, 0.65814F, 0.49444F, -0.23347F ]; + /// + /// Gets the output biases of the 16x8 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType16x8HorizontalBias1 => [ 3.57175F, 2.42612F, 3.31259F, 2.08287F ]; + /// + /// Gets the hidden layer weights of the 16x8 transform type model of the vertical axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType16x8VerticalWeights0 => [ 0.46633F, 1.55328F, -0.11230F, -0.29571F, 0.18814F, -1.52430F, -2.34660F, 0.08644F, @@ -439,12 +619,20 @@ internal static partial class Av1IntraSuperblockEncoder -0.30039F, 0.25834F, 1.19944F, 1.22533F, 0.92330F, 0.75967F, -0.81945F, -0.41647F ]; + /// + /// Gets the hidden layer biases of the 16x8 transform type model of the vertical axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType16x8VerticalBias0 => [ 0.17841F, 0.67315F, -1.24450F, 3.13859F, 0.16203F, -0.14992F, 0.29553F, -1.15567F, -0.71421F, 1.15977F, 1.14585F, 3.02460F, -0.04510F, 0.48000F, -0.09354F, -0.42422F ]; + /// + /// Gets the output weights of the 16x8 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType16x8VerticalWeights1 => [ 0.29912F, -0.10009F, -1.11478F, 1.76812F, -0.27719F, 0.52148F, 0.17622F, -1.17116F, @@ -457,11 +645,19 @@ internal static partial class Av1IntraSuperblockEncoder 0.72422F, -1.24952F, 0.61653F, 2.04117F, -1.42406F, 0.52568F, -0.46180F, -0.00873F ]; + /// + /// Gets the output biases of the 16x8 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType16x8VerticalBias1 => [ 3.34981F, 3.74710F, 1.38339F, 0.45176F ]; + /// + /// Gets the hidden layer weights of the 16x16 transform type model. Both axes use this model. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType16x16Weights0 => [ 1.26592F, 1.36313F, 1.30956F, 1.29926F, 1.48816F, 1.68851F, 1.32000F, 0.13321F, @@ -482,12 +678,20 @@ internal static partial class Av1IntraSuperblockEncoder 0.35803F, -1.52676F, -0.89624F, 0.77665F, 0.19877F, 0.77175F, 0.50355F, 0.08592F ]; + /// + /// Gets the hidden layer biases of the 16x16 transform type model. Both axes use this model. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType16x16Bias0 => [ -1.31834F, 0.14346F, -0.10062F, 0.84489F, 0.95617F, -0.06720F, -0.68502F, -0.91442F, -0.31932F, 0.25276F, -0.15138F, -1.57661F, -0.14062F, -0.42120F, 0.94573F, -0.09287F ]; + /// + /// Gets the output weights of the 16x16 transform type model. Both axes use this model. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType16x16Weights1 => [ -1.80333F, -1.06353F, 0.55139F, 0.74644F, 0.13747F, -0.93018F, -0.10286F, 0.67133F, @@ -500,11 +704,19 @@ internal static partial class Av1IntraSuperblockEncoder -0.03718F, -0.35769F, 0.89651F, 0.63236F, 0.54215F, -0.07894F, 0.48274F, 1.08829F ]; + /// + /// Gets the output biases of the 16x16 transform type model. Both axes use this model. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType16x16Bias1 => [ 0.81986F, 1.26865F, 0.11118F, 2.48404F ]; + /// + /// Gets the hidden layer weights of the 4x16 transform type model of the horizontal axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType4x16HorizontalWeights0 => [ 0.36539F, 0.25667F, 0.01491F, -0.21959F, 2.55105F, 0.17615F, 1.79884F, 1.65936F, @@ -513,11 +725,19 @@ internal static partial class Av1IntraSuperblockEncoder 1.57855F, -0.51359F, 0.90553F, -1.67744F, -1.74563F, -0.88830F, -1.77603F, 2.15935F ]; + /// + /// Gets the hidden layer biases of the 4x16 transform type model of the horizontal axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType4x16HorizontalBias0 => [ -0.36435F, -2.22731F, -0.00837F, -1.34546F, 0.62806F, -0.20675F, 4.91940F, -0.56079F ]; + /// + /// Gets the output weights of the 4x16 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType4x16HorizontalWeights1 => [ -0.57191F, -1.46418F, 0.67331F, -1.15027F, 0.46288F, 0.81251F, 2.51768F, -0.27147F, @@ -526,11 +746,19 @@ internal static partial class Av1IntraSuperblockEncoder -0.17578F, -1.80034F, -0.32217F, 0.89519F, 1.28413F, -0.30326F, 2.45329F, -0.83335F ]; + /// + /// Gets the output biases of the 4x16 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType4x16HorizontalBias1 => [ 2.33198F, 3.36245F, 1.62603F, 2.91056F ]; + /// + /// Gets the hidden layer weights of the 4x16 transform type model of the vertical axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType4x16VerticalWeights0 => [ 1.61392F, 1.41239F, 1.47646F, 1.47325F, 1.46110F, 1.49208F, 1.49414F, 0.12835F, @@ -551,12 +779,20 @@ internal static partial class Av1IntraSuperblockEncoder -0.20426F, -1.51411F, -0.72293F, 0.64516F, 0.97638F, 0.32616F, -0.27975F, -0.01149F ]; + /// + /// Gets the hidden layer biases of the 4x16 transform type model of the vertical axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType4x16VerticalBias0 => [ -1.37863F, -0.05763F, -0.07041F, 0.15306F, 0.96026F, -1.42105F, -0.55822F, 1.04845F, -0.17662F, -1.25345F, -0.11927F, 0.49845F, -0.32530F, 0.73483F, 0.08322F, -0.23890F ]; + /// + /// Gets the output weights of the 4x16 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType4x16VerticalWeights1 => [ 0.27194F, 0.50607F, 0.49229F, -0.48192F, 0.15667F, -1.38891F, 0.38102F, -0.58825F, @@ -569,11 +805,19 @@ internal static partial class Av1IntraSuperblockEncoder -0.36631F, -0.56814F, 0.60410F, 0.53158F, 0.56389F, -0.70508F, 0.51009F, -0.56513F ]; + /// + /// Gets the output biases of the 4x16 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType4x16VerticalBias1 => [ 4.60896F, 4.53551F, 4.53124F, 4.27435F ]; + /// + /// Gets the hidden layer weights of the 16x4 transform type model of the horizontal axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType16x4HorizontalWeights0 => [ 1.45347F, -0.15743F, 0.44236F, 0.25808F, 0.33944F, 0.38678F, 0.24428F, 1.67287F, @@ -594,12 +838,20 @@ internal static partial class Av1IntraSuperblockEncoder 1.75440F, 0.49228F, -0.34858F, -0.17032F, 0.29288F, 0.47175F, 0.19055F, -1.56413F ]; + /// + /// Gets the hidden layer biases of the 16x4 transform type model of the horizontal axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType16x4HorizontalBias0 => [ -1.71227F, 0.47291F, -0.97536F, -0.66216F, 0.11729F, -0.21451F, 2.75281F, 0.04318F, 2.03965F, 0.14618F, -0.70483F, -0.24517F, 1.14048F, 0.33308F, -1.10886F, 0.41184F ]; + /// + /// Gets the output weights of the 16x4 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType16x4HorizontalWeights1 => [ -1.17079F, 0.19096F, -1.05753F, -0.30803F, -1.21680F, -0.67255F, 1.60115F, 0.05972F, @@ -612,11 +864,19 @@ internal static partial class Av1IntraSuperblockEncoder 1.62563F, 0.24787F, 0.31757F, 0.81751F, 1.57262F, 0.83214F, 1.04661F, -0.43819F ]; + /// + /// Gets the output biases of the 16x4 transform type model of the horizontal axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType16x4HorizontalBias1 => [ 2.32575F, 2.75703F, 1.12304F, 2.15567F ]; + /// + /// Gets the hidden layer weights of the 16x4 transform type model of the vertical axis. + /// Each hidden node has one row of input feature weights. + /// private static ReadOnlySpan TransformType16x4VerticalWeights0 => [ 0.26047F, 0.99930F, 1.16484F, -0.28196F, -2.67483F, -0.21456F, -0.16854F, 0.46375F, @@ -625,11 +885,19 @@ internal static partial class Av1IntraSuperblockEncoder -0.56305F, -0.02208F, -0.44517F, -0.00897F, -0.17967F, -0.96622F, 0.42635F, -1.04784F ]; + /// + /// Gets the hidden layer biases of the 16x4 transform type model of the vertical axis. + /// Each hidden node has one bias. + /// private static ReadOnlySpan TransformType16x4VerticalBias0 => [ -0.52088F, 0.52844F, -1.03655F, -0.30974F, 2.59952F, -1.93604F, 0.00000F, 2.51787F ]; + /// + /// Gets the output weights of the 16x4 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one row of hidden node weights. + /// private static ReadOnlySpan TransformType16x4VerticalWeights1 => [ 0.10916F, -0.21219F, -0.51340F, 0.69161F, 1.45988F, -1.36942F, -0.40899F, 1.05136F, @@ -638,17 +906,29 @@ internal static partial class Av1IntraSuperblockEncoder 0.26531F, 0.22378F, 0.15170F, 1.06965F, 1.26814F, -1.93873F, -0.00768F, 1.58309F ]; + /// + /// Gets the output biases of the 16x4 transform type model of the vertical axis. + /// Each of the four one-dimensional transform scores has one bias. + /// private static ReadOnlySpan TransformType16x4VerticalBias1 => [ 2.34713F, 1.68667F, 1.25488F, 1.69812F ]; + /// + /// Gets the compare/exchange network that sorts up to eight retained scores from largest to smallest. + /// Each two consecutive values are the score indices of one compare/exchange step. The steps apply in order. + /// private static ReadOnlySpan TransformTypeSort8 => [ 0, 1, 2, 3, 4, 5, 6, 7, 0, 2, 1, 3, 4, 6, 5, 7, 1, 2, 5, 6, 0, 4, 3, 7, 1, 5, 2, 6, 1, 4, 3, 6, 2, 4, 3, 5, 3, 4 ]; + /// + /// Gets the compare/exchange network that sorts up to sixteen retained scores from largest to smallest. + /// Each two consecutive values are the score indices of one compare/exchange step. The steps apply in order. + /// private static ReadOnlySpan TransformTypeSort16 => [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 2, 1, 3, 4, 6, 5, 7, @@ -871,6 +1151,12 @@ internal static void GetEnergyDistribution( Span horizontalFeatures, Span verticalFeatures) { + if (!Vector256.IsHardwareAccelerated) + { + GetEnergyDistributionScalar(residual, stride, width, height, horizontalFeatures, verticalFeatures); + return; + } + int heightShift = height <= 8 ? 0 : 1; int energyWidth = width <= 8 ? width : width >> 1; int energyHeight = height >> heightShift; @@ -954,6 +1240,88 @@ ref Unsafe.As, Vector256>(ref cellValues[6]), ((ReadOnlySpan)values)[..(energyHeight - 1)].CopyTo(verticalFeatures); } + /// + /// Computes the energy projections of one cell at a time, for hardware + /// without 256-bit vector acceleration. + /// + /// + /// The grid has the same integer cells as the vector form. Each feature adds the same values in the same order: + /// a horizontal feature adds its column top to bottom, and a vertical feature adds its row left to right. The + /// float results are thus the same as the vector form. + /// + /// The residual samples. + /// The residual row stride. + /// The block width: four, eight or sixteen. + /// The block height: four, eight or sixteen. + /// Receives the grid width minus one horizontal features. + /// Receives the grid height minus one vertical features. + private static void GetEnergyDistributionScalar( + ReadOnlySpan residual, + int stride, + int width, + int height, + Span horizontalFeatures, + Span verticalFeatures) + { + int widthShift = width <= 8 ? 0 : 1; + int heightShift = height <= 8 ? 0 : 1; + int energyWidth = width >> widthShift; + int energyHeight = height >> heightShift; + + // Cell (x, y) sums the squares of the samples that map to it. A cell holds at most four squared twelve-bit + // samples, so the 32-bit cells cannot overflow. + InlineArray8> grid = default; + for (int y = 0; y < height; y++) + { + ReadOnlySpan row = residual.Slice(y * stride, width); + ref InlineArray8 cells = ref grid[y >> heightShift]; + for (int x = 0; x < width; x++) + { + int sample = row[x]; + cells[x >> widthShift] += sample * sample; + } + } + + ulong totalEnergy = 0; + for (int y = 0; y < energyHeight; y++) + { + for (int x = 0; x < energyWidth; x++) + { + totalEnergy += (uint)grid[y][x]; + } + } + + if (totalEnergy == 0) + { + horizontalFeatures[..(energyWidth - 1)].Fill(1F / energyWidth); + verticalFeatures[..(energyHeight - 1)].Fill(1F / energyHeight); + return; + } + + float reciprocal = 1F / totalEnergy; + for (int x = 0; x < energyWidth - 1; x++) + { + float sum = 0F; + for (int y = 0; y < energyHeight; y++) + { + sum += grid[y][x]; + } + + horizontalFeatures[x] = sum * reciprocal; + } + + for (int y = 0; y < energyHeight - 1; y++) + { + float sum = 0F; + for (int x = 0; x < energyWidth; x++) + { + sum += grid[y][x]; + } + + verticalFeatures[y] = sum * reciprocal; + } + } + /// /// Evaluates the four one-dimensional transform scores for one axis. /// diff --git a/src/ImageSharp/Formats/Heif/Components/ColorConverters/HeifSampleConversion.cs b/src/ImageSharp/Formats/Heif/Components/ColorConverters/HeifSampleConversion.cs index 6f2c78dbb9..716330c279 100644 --- a/src/ImageSharp/Formats/Heif/Components/ColorConverters/HeifSampleConversion.cs +++ b/src/ImageSharp/Formats/Heif/Components/ColorConverters/HeifSampleConversion.cs @@ -671,7 +671,6 @@ public static void PackL16(ReadOnlySpan source, Span destination) Vector512 redWeight = Vector512.Create(0.2126F); Vector512 greenWeight = Vector512.Create(0.7152F); Vector512 blueWeight = Vector512.Create(0.0722F); - Vector512 roundingOffset = Vector512.Create(0.5F); int oneVectorFromEnd = length - Vector512.Count; for (; i <= oneVectorFromEnd; i += Vector512.Count) { @@ -681,9 +680,10 @@ public static void PackL16(ReadOnlySpan source, Span destination) Vector512.One) * maximum; // L16 uses its BT.709 luminance expression even when all three source components are equal. Preserve - // that exact arithmetic order so the SIMD path remains byte-identical to L16.FromScaledVector4. + // that exact arithmetic order, and its rounding to nearest with ties to even, so the SIMD path remains + // byte-identical to L16.FromScaledVector4. Vector512 luminance = ((value * redWeight) + (value * greenWeight)) + (value * blueWeight); - Vector512 samples = Vector512.ConvertToInt32(luminance + roundingOffset); + Vector512 samples = Vector512_.ConvertToInt32RoundToEven(luminance); Vector256 packed = Vector256.Narrow(samples.GetLower().AsUInt32(), samples.GetUpper().AsUInt32()); packed.StoreUnsafe(ref Unsafe.As(ref Unsafe.Add(ref destinationBase, i))); } @@ -695,7 +695,6 @@ public static void PackL16(ReadOnlySpan source, Span destination) Vector256 redWeight = Vector256.Create(0.2126F); Vector256 greenWeight = Vector256.Create(0.7152F); Vector256 blueWeight = Vector256.Create(0.0722F); - Vector256 roundingOffset = Vector256.Create(0.5F); int oneVectorFromEnd = length - Vector256.Count; for (; i <= oneVectorFromEnd; i += Vector256.Count) { @@ -705,7 +704,7 @@ public static void PackL16(ReadOnlySpan source, Span destination) Vector256.One) * maximum; Vector256 luminance = ((value * redWeight) + (value * greenWeight)) + (value * blueWeight); - Vector256 samples = Vector256.ConvertToInt32(luminance + roundingOffset); + Vector256 samples = Vector256_.ConvertToInt32RoundToEven(luminance); Vector128 packed = Vector128.Narrow(samples.GetLower().AsUInt32(), samples.GetUpper().AsUInt32()); packed.StoreUnsafe(ref Unsafe.As(ref Unsafe.Add(ref destinationBase, i))); } @@ -717,7 +716,6 @@ public static void PackL16(ReadOnlySpan source, Span destination) Vector128 redWeight = Vector128.Create(0.2126F); Vector128 greenWeight = Vector128.Create(0.7152F); Vector128 blueWeight = Vector128.Create(0.0722F); - Vector128 roundingOffset = Vector128.Create(0.5F); int oneVectorFromEnd = length - Vector128.Count; for (; i <= oneVectorFromEnd; i += Vector128.Count) { @@ -727,7 +725,7 @@ public static void PackL16(ReadOnlySpan source, Span destination) Vector128.One) * maximum; Vector128 luminance = ((value * redWeight) + (value * greenWeight)) + (value * blueWeight); - Vector128 samples = Vector128.ConvertToInt32(luminance + roundingOffset); + Vector128 samples = Vector128_.ConvertToInt32RoundToEven(luminance); Vector64 packed = Vector128.Narrow(samples.AsUInt32(), Vector128.Zero).GetLower(); packed.StoreUnsafe(ref Unsafe.As(ref Unsafe.Add(ref destinationBase, i))); } diff --git a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.CmykOperator.cs b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.CmykOperator.cs index a83bc6f0c3..7eb0f180d5 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.CmykOperator.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.CmykOperator.cs @@ -7,6 +7,9 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components; +/// +/// Contains the operator for inverted JPEG CMYK data. +/// internal abstract partial class JpegColorConverterBase { /// @@ -29,14 +32,13 @@ public static void ConvertToProfile( ref float c3, float maximumValue, float halfValue, - float scale, IccColorSpaceType profileSpace) { // Adobe stores inverted CMYK. Subtract before normalization to retain the existing operation order. - c0 = (maximumValue - c0) * scale; - c1 = (maximumValue - c1) * scale; - c2 = (maximumValue - c2) * scale; - c3 = (maximumValue - c3) * scale; + c0 = (maximumValue - c0) / maximumValue; + c1 = (maximumValue - c1) / maximumValue; + c2 = (maximumValue - c2) / maximumValue; + c3 = (maximumValue - c3) / maximumValue; } /// @@ -48,14 +50,13 @@ public static void ConvertToProfile( ref Vector128 c3, Vector128 maximumValue, Vector128 halfValue, - Vector128 scale, IccColorSpaceType profileSpace) { // Adobe stores inverted CMYK. Subtract before normalization to retain the existing operation order. - c0 = (maximumValue - c0) * scale; - c1 = (maximumValue - c1) * scale; - c2 = (maximumValue - c2) * scale; - c3 = (maximumValue - c3) * scale; + c0 = (maximumValue - c0) / maximumValue; + c1 = (maximumValue - c1) / maximumValue; + c2 = (maximumValue - c2) / maximumValue; + c3 = (maximumValue - c3) / maximumValue; } /// @@ -67,14 +68,13 @@ public static void ConvertToProfile( ref Vector256 c3, Vector256 maximumValue, Vector256 halfValue, - Vector256 scale, IccColorSpaceType profileSpace) { // Adobe stores inverted CMYK. Subtract before normalization to retain the existing operation order. - c0 = (maximumValue - c0) * scale; - c1 = (maximumValue - c1) * scale; - c2 = (maximumValue - c2) * scale; - c3 = (maximumValue - c3) * scale; + c0 = (maximumValue - c0) / maximumValue; + c1 = (maximumValue - c1) / maximumValue; + c2 = (maximumValue - c2) / maximumValue; + c3 = (maximumValue - c3) / maximumValue; } /// @@ -86,14 +86,13 @@ public static void ConvertToProfile( ref Vector512 c3, Vector512 maximumValue, Vector512 halfValue, - Vector512 scale, IccColorSpaceType profileSpace) { // Adobe stores inverted CMYK. Subtract before normalization to retain the existing operation order. - c0 = (maximumValue - c0) * scale; - c1 = (maximumValue - c1) * scale; - c2 = (maximumValue - c2) * scale; - c3 = (maximumValue - c3) * scale; + c0 = (maximumValue - c0) / maximumValue; + c1 = (maximumValue - c1) / maximumValue; + c2 = (maximumValue - c2) / maximumValue; + c3 = (maximumValue - c3) / maximumValue; } /// diff --git a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.GrayScaleOperator.cs b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.GrayScaleOperator.cs index 1ae969546d..29b281dbab 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.GrayScaleOperator.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.GrayScaleOperator.cs @@ -7,6 +7,9 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components; +/// +/// Contains the operator for JPEG grayscale data. +/// internal abstract partial class JpegColorConverterBase { /// @@ -29,10 +32,9 @@ public static void ConvertToProfile( ref float c3, float maximumValue, float halfValue, - float scale, IccColorSpaceType profileSpace) { - c0 *= scale; + c0 /= maximumValue; } /// @@ -44,10 +46,9 @@ public static void ConvertToProfile( ref Vector128 c3, Vector128 maximumValue, Vector128 halfValue, - Vector128 scale, IccColorSpaceType profileSpace) { - c0 *= scale; + c0 /= maximumValue; } /// @@ -59,10 +60,9 @@ public static void ConvertToProfile( ref Vector256 c3, Vector256 maximumValue, Vector256 halfValue, - Vector256 scale, IccColorSpaceType profileSpace) { - c0 *= scale; + c0 /= maximumValue; } /// @@ -74,10 +74,9 @@ public static void ConvertToProfile( ref Vector512 c3, Vector512 maximumValue, Vector512 halfValue, - Vector512 scale, IccColorSpaceType profileSpace) { - c0 *= scale; + c0 /= maximumValue; } /// diff --git a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.Icc.cs b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.Icc.cs index 90479041e5..b3e69260f0 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.Icc.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.Icc.cs @@ -11,8 +11,14 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components; +/// +/// Contains the ICC profile conversion of the operator-driven JPEG color converter. +/// internal abstract partial class JpegColorConverterBase { + /// + /// Converts JPEG component planes through an ICC profile, and packs and unpacks the profile samples. + /// internal sealed partial class JpegColorConverter { /// @@ -35,7 +41,6 @@ private void UnpackProfileComponents(in ComponentValues source, Span de ref float c2 = ref MemoryMarshal.GetReference(source.Component2); ref float c3 = ref MemoryMarshal.GetReference(source.Component3); ref float packed = ref Unsafe.As(ref MemoryMarshal.GetReference(destination)); - float scale = 1F / this.MaximumValue; float halfValue = this.HalfValue; int i = 0; @@ -46,7 +51,6 @@ private void UnpackProfileComponents(in ComponentValues source, Span de { Vector512 maximum = Vector512.Create(this.MaximumValue); Vector512 half = Vector512.Create(halfValue); - Vector512 reciprocal = Vector512.Create(scale); nuint vectorCount = source.Component0[i..].Vector512Count(); for (nuint block = 0; block < vectorCount; block++, i += Vector512.Count) @@ -55,7 +59,7 @@ private void UnpackProfileComponents(in ComponentValues source, Span de Vector512 y = channels >= 3 ? Vector512.LoadUnsafe(ref c1, (nuint)i) : default; Vector512 z = channels >= 3 ? Vector512.LoadUnsafe(ref c2, (nuint)i) : default; Vector512 k = channels == 4 ? Vector512.LoadUnsafe(ref c3, (nuint)i) : default; - TOperator.ConvertToProfile(ref x, ref y, ref z, ref k, maximum, half, reciprocal, profileSpace); + TOperator.ConvertToProfile(ref x, ref y, ref z, ref k, maximum, half, profileSpace); if (channels == 1) { @@ -71,7 +75,6 @@ private void UnpackProfileComponents(in ComponentValues source, Span de { Vector256 maximum = Vector256.Create(this.MaximumValue); Vector256 half = Vector256.Create(halfValue); - Vector256 reciprocal = Vector256.Create(scale); nuint vectorCount = source.Component0[i..].Vector256Count(); for (nuint block = 0; block < vectorCount; block++, i += Vector256.Count) @@ -80,7 +83,7 @@ private void UnpackProfileComponents(in ComponentValues source, Span de Vector256 y = channels >= 3 ? Vector256.LoadUnsafe(ref c1, (nuint)i) : default; Vector256 z = channels >= 3 ? Vector256.LoadUnsafe(ref c2, (nuint)i) : default; Vector256 k = channels == 4 ? Vector256.LoadUnsafe(ref c3, (nuint)i) : default; - TOperator.ConvertToProfile(ref x, ref y, ref z, ref k, maximum, half, reciprocal, profileSpace); + TOperator.ConvertToProfile(ref x, ref y, ref z, ref k, maximum, half, profileSpace); if (channels == 1) { @@ -96,7 +99,6 @@ private void UnpackProfileComponents(in ComponentValues source, Span de { Vector128 maximum = Vector128.Create(this.MaximumValue); Vector128 half = Vector128.Create(halfValue); - Vector128 reciprocal = Vector128.Create(scale); nuint vectorCount = source.Component0[i..].Vector128Count(); for (nuint block = 0; block < vectorCount; block++, i += Vector128.Count) @@ -105,7 +107,7 @@ private void UnpackProfileComponents(in ComponentValues source, Span de Vector128 y = channels >= 3 ? Vector128.LoadUnsafe(ref c1, (nuint)i) : default; Vector128 z = channels >= 3 ? Vector128.LoadUnsafe(ref c2, (nuint)i) : default; Vector128 k = channels == 4 ? Vector128.LoadUnsafe(ref c3, (nuint)i) : default; - TOperator.ConvertToProfile(ref x, ref y, ref z, ref k, maximum, half, reciprocal, profileSpace); + TOperator.ConvertToProfile(ref x, ref y, ref z, ref k, maximum, half, profileSpace); if (channels == 1) { @@ -147,7 +149,7 @@ private void UnpackProfileComponents(in ComponentValues source, Span de float y = channels >= 3 ? Unsafe.Add(ref c1, offset) : 0F; float z = channels >= 3 ? Unsafe.Add(ref c2, offset) : 0F; float k = channels == 4 ? Unsafe.Add(ref c3, offset) : 0F; - TOperator.ConvertToProfile(ref x, ref y, ref z, ref k, this.MaximumValue, halfValue, scale, profileSpace); + TOperator.ConvertToProfile(ref x, ref y, ref z, ref k, this.MaximumValue, halfValue, profileSpace); Unsafe.Add(ref vectors, offset) = channels switch { diff --git a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.Operator.cs b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.Operator.cs index 41f485671f..8c6b24a8a1 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.Operator.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.Operator.cs @@ -9,6 +9,9 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components; +/// +/// Contains the color operator contract and the generic converter that runs it. +/// internal abstract partial class JpegColorConverterBase { /// @@ -216,7 +219,6 @@ public static abstract void ConvertFromRgb( /// The fourth component, replaced in place when used. /// The maximum JPEG sample code. /// The integer JPEG chroma midpoint. - /// The reciprocal maximum JPEG sample code. /// The profile's device color space, used to select the required JPEG model transform. public static abstract void ConvertToProfile( ref float c0, @@ -225,7 +227,6 @@ public static abstract void ConvertToProfile( ref float c3, float maximumValue, float halfValue, - float scale, IccColorSpaceType profileSpace); /// @@ -237,7 +238,6 @@ public static abstract void ConvertToProfile( /// The fourth component lanes, replaced in place when used. /// The maximum JPEG sample code. /// The integer JPEG chroma midpoint. - /// The reciprocal maximum JPEG sample code. /// The profile's device color space, used to select the required JPEG model transform. public static abstract void ConvertToProfile( ref Vector128 c0, @@ -246,7 +246,6 @@ public static abstract void ConvertToProfile( ref Vector128 c3, Vector128 maximumValue, Vector128 halfValue, - Vector128 scale, IccColorSpaceType profileSpace); /// @@ -258,7 +257,6 @@ public static abstract void ConvertToProfile( /// The fourth component lanes, replaced in place when used. /// The maximum JPEG sample code. /// The integer JPEG chroma midpoint. - /// The reciprocal maximum JPEG sample code. /// The profile's device color space, used to select the required JPEG model transform. public static abstract void ConvertToProfile( ref Vector256 c0, @@ -267,7 +265,6 @@ public static abstract void ConvertToProfile( ref Vector256 c3, Vector256 maximumValue, Vector256 halfValue, - Vector256 scale, IccColorSpaceType profileSpace); /// @@ -279,7 +276,6 @@ public static abstract void ConvertToProfile( /// The fourth component lanes, replaced in place when used. /// The maximum JPEG sample code. /// The integer JPEG chroma midpoint. - /// The reciprocal maximum JPEG sample code. /// The profile's device color space, used to select the required JPEG model transform. public static abstract void ConvertToProfile( ref Vector512 c0, @@ -288,7 +284,6 @@ public static abstract void ConvertToProfile( ref Vector512 c3, Vector512 maximumValue, Vector512 halfValue, - Vector512 scale, IccColorSpaceType profileSpace); /// diff --git a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.RgbOperator.cs b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.RgbOperator.cs index 1bb04e1772..0136cc220b 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.RgbOperator.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.RgbOperator.cs @@ -7,6 +7,9 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components; +/// +/// Contains the operator for JPEG RGB data. +/// internal abstract partial class JpegColorConverterBase { /// @@ -29,12 +32,11 @@ public static void ConvertToProfile( ref float c3, float maximumValue, float halfValue, - float scale, IccColorSpaceType profileSpace) { - c0 *= scale; - c1 *= scale; - c2 *= scale; + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; } /// @@ -46,12 +48,11 @@ public static void ConvertToProfile( ref Vector128 c3, Vector128 maximumValue, Vector128 halfValue, - Vector128 scale, IccColorSpaceType profileSpace) { - c0 *= scale; - c1 *= scale; - c2 *= scale; + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; } /// @@ -63,12 +64,11 @@ public static void ConvertToProfile( ref Vector256 c3, Vector256 maximumValue, Vector256 halfValue, - Vector256 scale, IccColorSpaceType profileSpace) { - c0 *= scale; - c1 *= scale; - c2 *= scale; + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; } /// @@ -80,12 +80,11 @@ public static void ConvertToProfile( ref Vector512 c3, Vector512 maximumValue, Vector512 halfValue, - Vector512 scale, IccColorSpaceType profileSpace) { - c0 *= scale; - c1 *= scale; - c2 *= scale; + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; } /// diff --git a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.TiffCmykOperator.cs b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.TiffCmykOperator.cs index a9895db6bf..9e0e42c73b 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.TiffCmykOperator.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.TiffCmykOperator.cs @@ -7,6 +7,9 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components; +/// +/// Contains the operator for non-inverted TIFF JPEG CMYK data. +/// internal abstract partial class JpegColorConverterBase { /// @@ -29,13 +32,12 @@ public static void ConvertToProfile( ref float c3, float maximumValue, float halfValue, - float scale, IccColorSpaceType profileSpace) { - c0 *= scale; - c1 *= scale; - c2 *= scale; - c3 *= scale; + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; + c3 /= maximumValue; } /// @@ -47,13 +49,12 @@ public static void ConvertToProfile( ref Vector128 c3, Vector128 maximumValue, Vector128 halfValue, - Vector128 scale, IccColorSpaceType profileSpace) { - c0 *= scale; - c1 *= scale; - c2 *= scale; - c3 *= scale; + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; + c3 /= maximumValue; } /// @@ -65,13 +66,12 @@ public static void ConvertToProfile( ref Vector256 c3, Vector256 maximumValue, Vector256 halfValue, - Vector256 scale, IccColorSpaceType profileSpace) { - c0 *= scale; - c1 *= scale; - c2 *= scale; - c3 *= scale; + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; + c3 /= maximumValue; } /// @@ -83,13 +83,12 @@ public static void ConvertToProfile( ref Vector512 c3, Vector512 maximumValue, Vector512 halfValue, - Vector512 scale, IccColorSpaceType profileSpace) { - c0 *= scale; - c1 *= scale; - c2 *= scale; - c3 *= scale; + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; + c3 /= maximumValue; } /// diff --git a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.TiffYccKOperator.cs b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.TiffYccKOperator.cs index 41f140308c..c55fd5f0ab 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.TiffYccKOperator.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.TiffYccKOperator.cs @@ -10,6 +10,9 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components; +/// +/// Contains the operator for non-inverted TIFF JPEG YccK data. +/// internal abstract partial class JpegColorConverterBase { /// @@ -17,6 +20,9 @@ internal abstract partial class JpegColorConverterBase /// internal readonly struct TiffYccKOperator : IJpegColorConverterOperator { + /// + /// The factor that maps 8-bit RGB values to [0, 1]. + /// private const float SourceScale = 1F / 255F; /// @@ -41,15 +47,14 @@ public static void ConvertToProfile( ref float c3, float maximumValue, float halfValue, - float scale, IccColorSpaceType profileSpace) { // TIFF stores the matrix of CMY complements and an unchanged K sample. YCbCrOperator.ConvertToRgb(ref c0, ref c1, ref c2, halfValue); - c0 = 1F - (c0 * scale); - c1 = 1F - (c1 * scale); - c2 = 1F - (c2 * scale); - c3 = c3 * scale; + c0 = 1F - (c0 / maximumValue); + c1 = 1F - (c1 / maximumValue); + c2 = 1F - (c2 / maximumValue); + c3 = c3 / maximumValue; } /// @@ -61,15 +66,14 @@ public static void ConvertToProfile( ref Vector128 c3, Vector128 maximumValue, Vector128 halfValue, - Vector128 scale, IccColorSpaceType profileSpace) { // TIFF stores the matrix of CMY complements and an unchanged K sample. YCbCrOperator.ConvertToRgb(ref c0, ref c1, ref c2, halfValue); - c0 = Vector128.One - (c0 * scale); - c1 = Vector128.One - (c1 * scale); - c2 = Vector128.One - (c2 * scale); - c3 = c3 * scale; + c0 = Vector128.One - (c0 / maximumValue); + c1 = Vector128.One - (c1 / maximumValue); + c2 = Vector128.One - (c2 / maximumValue); + c3 = c3 / maximumValue; } /// @@ -81,15 +85,14 @@ public static void ConvertToProfile( ref Vector256 c3, Vector256 maximumValue, Vector256 halfValue, - Vector256 scale, IccColorSpaceType profileSpace) { // TIFF stores the matrix of CMY complements and an unchanged K sample. YCbCrOperator.ConvertToRgb(ref c0, ref c1, ref c2, halfValue); - c0 = Vector256.One - (c0 * scale); - c1 = Vector256.One - (c1 * scale); - c2 = Vector256.One - (c2 * scale); - c3 = c3 * scale; + c0 = Vector256.One - (c0 / maximumValue); + c1 = Vector256.One - (c1 / maximumValue); + c2 = Vector256.One - (c2 / maximumValue); + c3 = c3 / maximumValue; } /// @@ -101,15 +104,14 @@ public static void ConvertToProfile( ref Vector512 c3, Vector512 maximumValue, Vector512 halfValue, - Vector512 scale, IccColorSpaceType profileSpace) { // TIFF stores the matrix of CMY complements and an unchanged K sample. YCbCrOperator.ConvertToRgb(ref c0, ref c1, ref c2, halfValue); - c0 = Vector512.One - (c0 * scale); - c1 = Vector512.One - (c1 * scale); - c2 = Vector512.One - (c2 * scale); - c3 = c3 * scale; + c0 = Vector512.One - (c0 / maximumValue); + c1 = Vector512.One - (c1 / maximumValue); + c2 = Vector512.One - (c2 / maximumValue); + c3 = c3 / maximumValue; } /// diff --git a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.YCbCrOperator.cs b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.YCbCrOperator.cs index a70e3341b2..5dd0c91148 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.YCbCrOperator.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.YCbCrOperator.cs @@ -8,6 +8,9 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components; +/// +/// Contains the operator for JPEG YCbCr data. +/// internal abstract partial class JpegColorConverterBase { /// @@ -53,16 +56,15 @@ public static void ConvertToProfile( ref float c3, float maximumValue, float halfValue, - float scale, IccColorSpaceType profileSpace) { // An RGB profile reads RGB after the JPEG matrix. A native YCbCr profile reads the stored components. // Center chroma on the integer JPEG midpoint before normalization: 128/255 is not the model's 0.5. if (profileSpace == IccColorSpaceType.YCbCr) { - c0 *= scale; - c1 *= scale; - c2 *= scale; + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; } else { @@ -70,9 +72,9 @@ public static void ConvertToProfile( // The matrix can overshoot the integer JPEG device range. Bound RGB before ICC curves, // but retain its fractional precision until the destination pixel is packed. - c0 = ColorNumerics.ClampToFinite(c0 * scale, 0F, 1F); - c1 = ColorNumerics.ClampToFinite(c1 * scale, 0F, 1F); - c2 = ColorNumerics.ClampToFinite(c2 * scale, 0F, 1F); + c0 = ColorNumerics.ClampToFinite(c0 / maximumValue, 0F, 1F); + c1 = ColorNumerics.ClampToFinite(c1 / maximumValue, 0F, 1F); + c2 = ColorNumerics.ClampToFinite(c2 / maximumValue, 0F, 1F); } } @@ -85,16 +87,15 @@ public static void ConvertToProfile( ref Vector128 c3, Vector128 maximumValue, Vector128 halfValue, - Vector128 scale, IccColorSpaceType profileSpace) { // An RGB profile reads RGB after the JPEG matrix. A native YCbCr profile reads the stored components. // Center chroma on the integer JPEG midpoint before normalization: 128/255 is not the model's 0.5. if (profileSpace == IccColorSpaceType.YCbCr) { - c0 *= scale; - c1 *= scale; - c2 *= scale; + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; } else { @@ -102,9 +103,9 @@ public static void ConvertToProfile( // The matrix can overshoot the integer JPEG device range. Bound RGB before ICC curves, // but retain its fractional precision until the destination pixel is packed. - c0 = ColorNumerics.ClampToFinite(c0 * scale, Vector128.Zero, Vector128.One); - c1 = ColorNumerics.ClampToFinite(c1 * scale, Vector128.Zero, Vector128.One); - c2 = ColorNumerics.ClampToFinite(c2 * scale, Vector128.Zero, Vector128.One); + c0 = ColorNumerics.ClampToFinite(c0 / maximumValue, Vector128.Zero, Vector128.One); + c1 = ColorNumerics.ClampToFinite(c1 / maximumValue, Vector128.Zero, Vector128.One); + c2 = ColorNumerics.ClampToFinite(c2 / maximumValue, Vector128.Zero, Vector128.One); } } @@ -117,16 +118,15 @@ public static void ConvertToProfile( ref Vector256 c3, Vector256 maximumValue, Vector256 halfValue, - Vector256 scale, IccColorSpaceType profileSpace) { // An RGB profile reads RGB after the JPEG matrix. A native YCbCr profile reads the stored components. // Center chroma on the integer JPEG midpoint before normalization: 128/255 is not the model's 0.5. if (profileSpace == IccColorSpaceType.YCbCr) { - c0 *= scale; - c1 *= scale; - c2 *= scale; + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; } else { @@ -134,9 +134,9 @@ public static void ConvertToProfile( // The matrix can overshoot the integer JPEG device range. Bound RGB before ICC curves, // but retain its fractional precision until the destination pixel is packed. - c0 = ColorNumerics.ClampToFinite(c0 * scale, Vector256.Zero, Vector256.One); - c1 = ColorNumerics.ClampToFinite(c1 * scale, Vector256.Zero, Vector256.One); - c2 = ColorNumerics.ClampToFinite(c2 * scale, Vector256.Zero, Vector256.One); + c0 = ColorNumerics.ClampToFinite(c0 / maximumValue, Vector256.Zero, Vector256.One); + c1 = ColorNumerics.ClampToFinite(c1 / maximumValue, Vector256.Zero, Vector256.One); + c2 = ColorNumerics.ClampToFinite(c2 / maximumValue, Vector256.Zero, Vector256.One); } } @@ -149,16 +149,15 @@ public static void ConvertToProfile( ref Vector512 c3, Vector512 maximumValue, Vector512 halfValue, - Vector512 scale, IccColorSpaceType profileSpace) { // An RGB profile reads RGB after the JPEG matrix. A native YCbCr profile reads the stored components. // Center chroma on the integer JPEG midpoint before normalization: 128/255 is not the model's 0.5. if (profileSpace == IccColorSpaceType.YCbCr) { - c0 *= scale; - c1 *= scale; - c2 *= scale; + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; } else { @@ -166,9 +165,9 @@ public static void ConvertToProfile( // The matrix can overshoot the integer JPEG device range. Bound RGB before ICC curves, // but retain its fractional precision until the destination pixel is packed. - c0 = ColorNumerics.ClampToFinite(c0 * scale, Vector512.Zero, Vector512.One); - c1 = ColorNumerics.ClampToFinite(c1 * scale, Vector512.Zero, Vector512.One); - c2 = ColorNumerics.ClampToFinite(c2 * scale, Vector512.Zero, Vector512.One); + c0 = ColorNumerics.ClampToFinite(c0 / maximumValue, Vector512.Zero, Vector512.One); + c1 = ColorNumerics.ClampToFinite(c1 / maximumValue, Vector512.Zero, Vector512.One); + c2 = ColorNumerics.ClampToFinite(c2 / maximumValue, Vector512.Zero, Vector512.One); } } diff --git a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.YccKOperator.cs b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.YccKOperator.cs index 9de383e1ba..f0f5f16d1f 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.YccKOperator.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverter.YccKOperator.cs @@ -7,6 +7,9 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components; +/// +/// Contains the operator for inverted JPEG YccK data. +/// internal abstract partial class JpegColorConverterBase { /// @@ -36,15 +39,14 @@ public static void ConvertToProfile( ref float c3, float maximumValue, float halfValue, - float scale, IccColorSpaceType profileSpace) { // Adobe stores the matrix of CMY ink values and the complement of K. YCbCrOperator.ConvertToRgb(ref c0, ref c1, ref c2, halfValue); - c0 *= scale; - c1 *= scale; - c2 *= scale; - c3 = 1F - (c3 * scale); + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; + c3 = 1F - (c3 / maximumValue); } /// @@ -56,15 +58,14 @@ public static void ConvertToProfile( ref Vector128 c3, Vector128 maximumValue, Vector128 halfValue, - Vector128 scale, IccColorSpaceType profileSpace) { // Adobe stores the matrix of CMY ink values and the complement of K. YCbCrOperator.ConvertToRgb(ref c0, ref c1, ref c2, halfValue); - c0 *= scale; - c1 *= scale; - c2 *= scale; - c3 = Vector128.One - (c3 * scale); + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; + c3 = Vector128.One - (c3 / maximumValue); } /// @@ -76,15 +77,14 @@ public static void ConvertToProfile( ref Vector256 c3, Vector256 maximumValue, Vector256 halfValue, - Vector256 scale, IccColorSpaceType profileSpace) { // Adobe stores the matrix of CMY ink values and the complement of K. YCbCrOperator.ConvertToRgb(ref c0, ref c1, ref c2, halfValue); - c0 *= scale; - c1 *= scale; - c2 *= scale; - c3 = Vector256.One - (c3 * scale); + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; + c3 = Vector256.One - (c3 / maximumValue); } /// @@ -96,15 +96,14 @@ public static void ConvertToProfile( ref Vector512 c3, Vector512 maximumValue, Vector512 halfValue, - Vector512 scale, IccColorSpaceType profileSpace) { // Adobe stores the matrix of CMY ink values and the complement of K. YCbCrOperator.ConvertToRgb(ref c0, ref c1, ref c2, halfValue); - c0 *= scale; - c1 *= scale; - c2 *= scale; - c3 = Vector512.One - (c3 * scale); + c0 /= maximumValue; + c1 /= maximumValue; + c2 /= maximumValue; + c3 = Vector512.One - (c3 / maximumValue); } /// diff --git a/src/ImageSharp/Formats/Jxl/Components/ColorConverters/JxlSampleConverter.cs b/src/ImageSharp/Formats/Jxl/Components/ColorConverters/JxlSampleConverter.cs index 52e11d32e3..b27ef21fe3 100644 --- a/src/ImageSharp/Formats/Jxl/Components/ColorConverters/JxlSampleConverter.cs +++ b/src/ImageSharp/Formats/Jxl/Components/ColorConverters/JxlSampleConverter.cs @@ -533,40 +533,40 @@ public Vector512 Invoke(Vector512 value) /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int Invoke(float value) => (int)((ColorNumerics.ClampToFinite(value, 0F, 1F) * this.factor) + .5F); + public int Invoke(float value) => (int)MathF.Round(ColorNumerics.ClampToFinite(value, 0F, 1F) * this.factor); /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector128 Invoke(Vector128 value) { // Integer samples use the unsigned interval [0,1]. Bound extended RGB before scaling so all carriers - // fit the declared precision. Add before truncation to retain the scalar midpoint rule. + // fit the declared precision. Round to nearest with ties to even, as the scalar operation does. value = ColorNumerics.ClampToFinite(value, Vector128.Zero, Vector128.One); Vector128 scaled = value * Vector128.Create(this.factor); - return Vector128.ConvertToInt32(scaled + Vector128.Create(.5F)); + return Vector128_.ConvertToInt32RoundToEven(scaled); } /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector256 Invoke(Vector256 value) { - // The bounds and add-before-truncation rule match the scalar and four-lane operations. + // The bounds and the rounding rule match the scalar and four-lane operations. value = ColorNumerics.ClampToFinite(value, Vector256.Zero, Vector256.One); Vector256 scaled = value * Vector256.Create(this.factor); - return Vector256.ConvertToInt32(scaled + Vector256.Create(.5F)); + return Vector256_.ConvertToInt32RoundToEven(scaled); } /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector512 Invoke(Vector512 value) { - // The bounds and add-before-truncation rule match the scalar and narrower operations. + // The bounds and the rounding rule match the scalar and narrower operations. value = ColorNumerics.ClampToFinite(value, Vector512.Zero, Vector512.One); Vector512 scaled = value * Vector512.Create(this.factor); - return Vector512.ConvertToInt32(scaled + Vector512.Create(.5F)); + return Vector512_.ConvertToInt32RoundToEven(scaled); } } @@ -588,7 +588,7 @@ public Vector512 Invoke(Vector512 value) /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int Invoke(float value) => (int)((ColorNumerics.ClampToFinite(value, 0F, 1F) * this.factor) + .5D); + public int Invoke(float value) => (int)Math.Round(ColorNumerics.ClampToFinite(value, 0F, 1F) * this.factor); /// [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -599,14 +599,11 @@ public Vector128 Invoke(Vector128 value) value = ColorNumerics.ClampToFinite(value, Vector128.Zero, Vector128.One); (Vector128 lower, Vector128 upper) = Vector128.Widen(value); Vector128 multiplier = Vector128.Create(this.factor); - lower *= multiplier; - upper *= multiplier; - Vector128 half = Vector128.Create(.5D); - - // Bounded inputs produce unsigned sample codes. Int64 conversion holds the maximum plus one half; - // truncation removes the fraction before narrowing rejoins the original lane order. - lower += half; - upper += half; + lower = Vector128.Round(lower * multiplier); + upper = Vector128.Round(upper * multiplier); + + // Round rounds to nearest with ties to even, as the scalar operation does. Bounded inputs give whole unsigned + // sample codes, so the Int64 conversion is exact, and narrowing rejoins the original lane order. return Vector128.Narrow(Vector128.ConvertToInt64(lower), Vector128.ConvertToInt64(upper)); } @@ -619,13 +616,10 @@ public Vector256 Invoke(Vector256 value) value = ColorNumerics.ClampToFinite(value, Vector256.Zero, Vector256.One); (Vector256 lower, Vector256 upper) = Vector256.Widen(value); Vector256 multiplier = Vector256.Create(this.factor); - lower *= multiplier; - upper *= multiplier; - Vector256 half = Vector256.Create(.5D); + lower = Vector256.Round(lower * multiplier); + upper = Vector256.Round(upper * multiplier); - // Bounded inputs keep the truncated codes in int range. Narrowing retains the original lane order. - lower += half; - upper += half; + // Bounded inputs keep the rounded codes in int range. Narrowing retains the original lane order. return Vector256.Narrow(Vector256.ConvertToInt64(lower), Vector256.ConvertToInt64(upper)); } @@ -638,13 +632,10 @@ public Vector512 Invoke(Vector512 value) value = ColorNumerics.ClampToFinite(value, Vector512.Zero, Vector512.One); (Vector512 lower, Vector512 upper) = Vector512.Widen(value); Vector512 multiplier = Vector512.Create(this.factor); - lower *= multiplier; - upper *= multiplier; - Vector512 half = Vector512.Create(.5D); + lower = Vector512.Round(lower * multiplier); + upper = Vector512.Round(upper * multiplier); - // Bounded inputs keep the truncated codes in int range. Narrowing retains the original lane order. - lower += half; - upper += half; + // Bounded inputs keep the rounded codes in int range. Narrowing retains the original lane order. return Vector512.Narrow(Vector512.ConvertToInt64(lower), Vector512.ConvertToInt64(upper)); } } @@ -1039,6 +1030,9 @@ public Vector512 Invoke(Vector512 value) public readonly struct Int16Operator : IConversionOperator where TOperator : struct, IConversionOperator { + /// + /// The prepared operation over signed 32-bit carriers. + /// private readonly TOperator operation; /// @@ -1091,6 +1085,9 @@ public Vector512 Invoke(Vector512 value) /// public readonly struct IntegerOperator : IConversionOperator { + /// + /// The single-precision reciprocal of the largest unsigned sample code at the declared precision. + /// private readonly float factor; /// @@ -1121,6 +1118,9 @@ public Vector512 Invoke(Vector512 value) /// public readonly struct AccurateIntegerOperator : IConversionOperator { + /// + /// The double-precision reciprocal of the largest unsigned sample code at the declared precision. + /// private readonly double factor; /// @@ -1210,7 +1210,14 @@ public Vector512 Invoke(Vector512 value) /// public readonly struct Exponent8Operator : IConversionOperator { + /// + /// The exponent and mantissa bits of the declared layout. A carrier above this mask has a negative sign. + /// private readonly uint magnitudeMask; + + /// + /// The number of low binary32 mantissa bits omitted by the declared layout. + /// private readonly int mantissaShift; /// @@ -1276,11 +1283,35 @@ public Vector512 Invoke(Vector512 value) /// public readonly struct CustomFloatOperator : IConversionOperator { + /// + /// The exponent and mantissa bits of the declared layout. A carrier above this mask has a negative sign. + /// private readonly uint magnitudeMask; + + /// + /// The mantissa bits of the declared layout. + /// private readonly uint mantissaMask; + + /// + /// The exponent bits of the declared layout, at their declared position. + /// private readonly uint exponentMask; + + /// + /// The difference between the binary32 bias and the declared bias, at the binary32 exponent position. + /// Adding it to a shifted normal magnitude gives the binary32 exponent. + /// private readonly uint exponentOffset; + + /// + /// The number of low binary32 mantissa bits omitted by the declared layout. + /// private readonly int mantissaShift; + + /// + /// The power of two that scales an integer subnormal mantissa to its binary32 value. + /// private readonly float subnormalScale; /// diff --git a/src/ImageSharp/Formats/Jxl/Components/Decoder/JxlIccReader.cs b/src/ImageSharp/Formats/Jxl/Components/Decoder/JxlIccReader.cs index 95b8f66905..ccafb10c8c 100644 --- a/src/ImageSharp/Formats/Jxl/Components/Decoder/JxlIccReader.cs +++ b/src/ImageSharp/Formats/Jxl/Components/Decoder/JxlIccReader.cs @@ -25,11 +25,6 @@ internal static class JxlIccReader /// private const int HeaderSize = JxlIccPrediction.HeaderSize; - /// - /// The first-byte context plus eight preceding-byte classes times five second-byte classes in native ICC prediction. - /// - private const int ContextCount = 41; - // libjxl rejects a prediction stream more than 65536 bytes larger than its reconstructed profile, so this decoder rejects it too. // Combine that bound with the shared profile-size limit before allocating scratch. private const int MaximumPredictionOverhead = 65536; @@ -71,7 +66,7 @@ internal static class JxlIccReader throw new InvalidImageContentException("The JPEG XL encoded ICC length is invalid."); } - using JxlEntropyDecoder codes = JxlEntropyDecoder.Read(ref reader, allocator, ContextCount, true); + using JxlEntropyDecoder codes = JxlEntropyDecoder.Read(ref reader, allocator, JxlConstants.IccContextCount, true); JxlEntropyDecoder.Reader symbols = codes.CreateReader(ref reader); // The declared prediction length is bounded above before renting. Retain the bytes as LZ77 history diff --git a/src/ImageSharp/Formats/Jxl/Components/Entropy/JxlHybridUint.cs b/src/ImageSharp/Formats/Jxl/Components/Entropy/JxlHybridUint.cs index bf83f35538..5af75e199a 100644 --- a/src/ImageSharp/Formats/Jxl/Components/Entropy/JxlHybridUint.cs +++ b/src/ImageSharp/Formats/Jxl/Components/Entropy/JxlHybridUint.cs @@ -3,6 +3,8 @@ using System.Numerics; using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Common.Helpers; using SixLabors.ImageSharp.Formats.Jxl.Components.Decoder; namespace SixLabors.ImageSharp.Formats.Jxl.Components.Entropy; @@ -43,11 +45,197 @@ private JxlHybridUint(int splitExponent, int highBits, int lowBits) /// public static JxlHybridUint Zero { get; } = new(0, 0, 0); + /// + /// Gets the configuration that stores the values below 16 directly and splits larger values at their leading bit, with no value bits + /// in the token: the configuration 4/0/0. + /// + public static JxlHybridUint Split400 { get; } = new(4, 0, 0); + /// /// Gets a value indicating whether this configuration uses a four-bit split, two leading token bits and no trailing token bits. /// public bool Is420 => this.splitExponent == 4 && this.highBits == 2 && this.lowBits == 0; + /// + /// Splits one value with the configuration 4/2/0: a four-bit split, two leading token bits and no trailing token bits. It is the + /// libjxl default. The constant configuration gives the encoder loops a short path for the values below 16. + /// + /// The unsigned value to encode. + /// The entropy-coded token, less than 128. + /// The number of following literal bits. + /// The literal bits below the two leading bits, with all higher bits clear. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Encode420(uint value, out uint token, out int bitCount, out uint extraBits) + { + if (value < 16) + { + token = value; + bitCount = 0; + extraBits = 0; + return; + } + + // The token holds the position of the leading one after the split and the two bits below it. The rest follow the token. + int exponent = BitOperations.Log2(value); + token = 16 + ((uint)(exponent - 4) << 2) + ((value >> (exponent - 2)) & 3); + bitCount = exponent - 2; + extraBits = value & ((1U << bitCount) - 1); + } + + /// + /// Splits four values with the configuration 4/2/0, one value in each lane. Each lane gives the same result as the scalar overload. + /// + /// The unsigned values to encode. + /// The entropy-coded tokens, each less than 128. + /// The numbers of following literal bits. + /// The literal bits below the two leading bits, with all higher bits clear. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Encode420(Vector128 value, out Vector128 token, out Vector128 bitCount, out Vector128 extraBits) + { + // The float conversion gives the position of the leading one and the bits below it without a lane-wise bit scan. Half of the + // value fits a signed lane. A positive int below 2^24 converts exactly. From 2^24, half has its leading one at bit 24 to 30, so + // clearing the low 7 bits leaves at most 24 significant bits. Then the conversion is exact and keeps the leading three bits. + Vector128 half = (value >>> 1).AsInt32(); + Vector128 exact = Vector128.AndNot(half, Vector128.GreaterThan(half, Vector128.Create(0xFFFFFF)) & Vector128.Create(0x7F)); + Vector128 floatBits = Vector128.ConvertToSingle(exact).AsUInt32(); + + // For a value of 16 or more with the leading one at bit e, the float of half has the biased exponent e - 1 + 127 and the two + // mantissa bits below the leading one. So floatBits >> 21 is 4 * (e + 126) plus those two bits, and the token + // 16 + 4 * (e - 4) plus the two bits is that minus 504. The bit count e - 2 is the biased exponent minus 128. + Vector128 small = Vector128.LessThan(half, Vector128.Create(8)).AsUInt32(); + token = Vector128.ConditionalSelect(small, value, (floatBits >>> 21) - Vector128.Create(504U)); + bitCount = Vector128.AndNot((floatBits >>> 23) - Vector128.Create(128U), small); + + // The float 2^(e - 2) has the biased exponent of half minus 1. It converts exactly to an int because e - 2 is at most 29. + // Minus one, it is the mask of the extra bits. + Vector128 power = Vector128.ConvertToInt32Native(((floatBits & Vector128.Create(0x7F800000U)) - Vector128.Create(0x00800000U)).AsSingle()); + extraBits = Vector128.AndNot(value & (power - Vector128.One).AsUInt32(), small); + } + + /// + /// Splits eight values with the configuration 4/2/0, one value in each lane. Each lane gives the same result as the scalar overload. + /// + /// The unsigned values to encode. + /// The entropy-coded tokens, each less than 128. + /// The numbers of following literal bits. + /// The literal bits below the two leading bits, with all higher bits clear. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Encode420(Vector256 value, out Vector256 token, out Vector256 bitCount, out Vector256 extraBits) + { + // The float conversion gives the position of the leading one and the bits below it without a lane-wise bit scan. Half of the + // value fits a signed lane. A positive int below 2^24 converts exactly. From 2^24, half has its leading one at bit 24 to 30, so + // clearing the low 7 bits leaves at most 24 significant bits. Then the conversion is exact and keeps the leading three bits. + Vector256 half = (value >>> 1).AsInt32(); + Vector256 exact = Vector256.AndNot(half, Vector256.GreaterThan(half, Vector256.Create(0xFFFFFF)) & Vector256.Create(0x7F)); + Vector256 floatBits = Vector256.ConvertToSingle(exact).AsUInt32(); + + // For a value of 16 or more with the leading one at bit e, the float of half has the biased exponent e - 1 + 127 and the two + // mantissa bits below the leading one. So floatBits >> 21 is 4 * (e + 126) plus those two bits, and the token + // 16 + 4 * (e - 4) plus the two bits is that minus 504. The bit count e - 2 is the biased exponent minus 128. + Vector256 small = Vector256.LessThan(half, Vector256.Create(8)).AsUInt32(); + token = Vector256.ConditionalSelect(small, value, (floatBits >>> 21) - Vector256.Create(504U)); + bitCount = Vector256.AndNot((floatBits >>> 23) - Vector256.Create(128U), small); + + // The float 2^(e - 2) has the biased exponent of half minus 1. It converts exactly to an int because e - 2 is at most 29. + // Minus one, it is the mask of the extra bits. + Vector256 power = Vector256.ConvertToInt32Native(((floatBits & Vector256.Create(0x7F800000U)) - Vector256.Create(0x00800000U)).AsSingle()); + extraBits = Vector256.AndNot(value & (power - Vector256.One).AsUInt32(), small); + } + + /// + /// Splits sixteen values with the configuration 4/2/0, one value in each lane. Each lane gives the same result as the scalar overload. + /// + /// The unsigned values to encode. + /// The entropy-coded tokens, each less than 128. + /// The numbers of following literal bits. + /// The literal bits below the two leading bits, with all higher bits clear. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Encode420(Vector512 value, out Vector512 token, out Vector512 bitCount, out Vector512 extraBits) + { + // The float conversion gives the position of the leading one and the bits below it without a lane-wise bit scan. Half of the + // value fits a signed lane. A positive int below 2^24 converts exactly. From 2^24, half has its leading one at bit 24 to 30, so + // clearing the low 7 bits leaves at most 24 significant bits. Then the conversion is exact and keeps the leading three bits. + Vector512 half = (value >>> 1).AsInt32(); + Vector512 exact = Vector512.AndNot(half, Vector512.GreaterThan(half, Vector512.Create(0xFFFFFF)) & Vector512.Create(0x7F)); + Vector512 floatBits = Vector512.ConvertToSingle(exact).AsUInt32(); + + // For a value of 16 or more with the leading one at bit e, the float of half has the biased exponent e - 1 + 127 and the two + // mantissa bits below the leading one. So floatBits >> 21 is 4 * (e + 126) plus those two bits, and the token + // 16 + 4 * (e - 4) plus the two bits is that minus 504. The bit count e - 2 is the biased exponent minus 128. + Vector512 small = Vector512.LessThan(half, Vector512.Create(8)).AsUInt32(); + token = Vector512.ConditionalSelect(small, value, (floatBits >>> 21) - Vector512.Create(504U)); + bitCount = Vector512.AndNot((floatBits >>> 23) - Vector512.Create(128U), small); + + // The float 2^(e - 2) has the biased exponent of half minus 1. It converts exactly to an int because e - 2 is at most 29. + // Minus one, it is the mask of the extra bits. + Vector512 power = Vector512.ConvertToInt32Native(((floatBits & Vector512.Create(0x7F800000U)) - Vector512.Create(0x00800000U)).AsSingle()); + extraBits = Vector512.AndNot(value & (power - Vector512.One).AsUInt32(), small); + } + + /// + /// Splits four values with the configuration 0/0/0, one value in each lane. Each lane gives the result of . + /// + /// The unsigned values to encode. + /// The entropy-coded tokens: 0 for 0, else the bit length of the value. + /// The numbers of following literal bits: the bit length minus one, and 0 for 0. + /// The literal bits below the leading one, with all higher bits clear. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Encode000(Vector128 value, out Vector128 token, out Vector128 bitCount, out Vector128 extraBits) + { + // The float conversion gives the position of the leading one without a lane-wise bit scan, as in Encode420. Half of the value + // fits a signed lane, and the low bits that a conversion from 2^24 can round are clear, so the exponent is exact. + Vector128 half = (value >>> 1).AsInt32(); + Vector128 exact = Vector128.AndNot(half, Vector128.GreaterThan(half, Vector128.Create(0xFFFFFF)) & Vector128.Create(0x7F)); + Vector128 exponent = Vector128.ConvertToSingle(exact).AsUInt32() >>> 23; + + // For a value of 2 or more with the leading one at bit e, half has the biased exponent e - 1 + 127. The token e + 1 is that + // minus 125, and the bit count e is that minus 126. The values 0 and 1 are their own tokens and have no extra bits. + Vector128 small = Vector128.Equals(half, Vector128.Zero).AsUInt32(); + token = Vector128.ConditionalSelect(small, value, exponent - Vector128.Create(125U)); + bitCount = Vector128.AndNot(exponent - Vector128.Create(126U), small); + extraBits = value & (Vector128_.ShiftLeftLogicalVariable(Vector128.One, bitCount) - Vector128.One); + } + + /// + /// Splits eight values with the configuration 0/0/0, one value in each lane. Each lane gives the result of . + /// + /// The unsigned values to encode. + /// The entropy-coded tokens: 0 for 0, else the bit length of the value. + /// The numbers of following literal bits: the bit length minus one, and 0 for 0. + /// The literal bits below the leading one, with all higher bits clear. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Encode000(Vector256 value, out Vector256 token, out Vector256 bitCount, out Vector256 extraBits) + { + // The steps are the same as in the 128-bit overload. + Vector256 half = (value >>> 1).AsInt32(); + Vector256 exact = Vector256.AndNot(half, Vector256.GreaterThan(half, Vector256.Create(0xFFFFFF)) & Vector256.Create(0x7F)); + Vector256 exponent = Vector256.ConvertToSingle(exact).AsUInt32() >>> 23; + Vector256 small = Vector256.Equals(half, Vector256.Zero).AsUInt32(); + token = Vector256.ConditionalSelect(small, value, exponent - Vector256.Create(125U)); + bitCount = Vector256.AndNot(exponent - Vector256.Create(126U), small); + extraBits = value & (Vector256_.ShiftLeftLogicalVariable(Vector256.One, bitCount) - Vector256.One); + } + + /// + /// Splits sixteen values with the configuration 0/0/0, one value in each lane. Each lane gives the result of . + /// + /// The unsigned values to encode. + /// The entropy-coded tokens: 0 for 0, else the bit length of the value. + /// The numbers of following literal bits: the bit length minus one, and 0 for 0. + /// The literal bits below the leading one, with all higher bits clear. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Encode000(Vector512 value, out Vector512 token, out Vector512 bitCount, out Vector512 extraBits) + { + // The steps are the same as in the 128-bit overload. + Vector512 half = (value >>> 1).AsInt32(); + Vector512 exact = Vector512.AndNot(half, Vector512.GreaterThan(half, Vector512.Create(0xFFFFFF)) & Vector512.Create(0x7F)); + Vector512 exponent = Vector512.ConvertToSingle(exact).AsUInt32() >>> 23; + Vector512 small = Vector512.Equals(half, Vector512.Zero).AsUInt32(); + token = Vector512.ConditionalSelect(small, value, exponent - Vector512.Create(125U)); + bitCount = Vector512.AndNot(exponent - Vector512.Create(126U), small); + extraBits = value & (Vector512_.ShiftLeftLogicalVariable(Vector512.One, bitCount) - Vector512.One); + } + /// /// Gets the conservative output width represented by an entropy token without consuming its middle bits. /// diff --git a/src/ImageSharp/Formats/Jxl/Components/Modular/JxlModularColorTransform.cs b/src/ImageSharp/Formats/Jxl/Components/Modular/JxlModularColorTransform.cs index de1f47871e..cb7e8e76c4 100644 --- a/src/ImageSharp/Formats/Jxl/Components/Modular/JxlModularColorTransform.cs +++ b/src/ImageSharp/Formats/Jxl/Components/Modular/JxlModularColorTransform.cs @@ -8,7 +8,8 @@ namespace SixLabors.ImageSharp.Formats.Jxl.Components.Modular; /// -/// Reverses modular color arithmetic on three planar integer rows. +/// Applies modular color arithmetic to three planar integer rows: the inverse transforms of the decoder, and the forward YCoCg transform +/// of the encoder. /// /// /// The frame owner validates operation codes and matching channel dimensions before calling this kernel. @@ -17,12 +18,12 @@ namespace SixLabors.ImageSharp.Formats.Jxl.Components.Modular; internal static class JxlModularColorTransform { /// - /// Defines inverse modular color arithmetic independently of row traversal. + /// Defines modular color arithmetic independently of row traversal. /// private interface IColorTransformOperator { /// - /// Restores one column's three channel values. + /// Transforms one column's three channel values. /// /// The first input and output component. /// The second input and output component. @@ -30,7 +31,7 @@ private interface IColorTransformOperator static abstract void Apply(ref int first, ref int second, ref int third); /// - /// Restores four independent columns, one column per signed integer lane. + /// Transforms four independent columns, one column per signed integer lane. /// /// The first channel's input and output lanes. /// The second channel's input and output lanes. @@ -38,7 +39,7 @@ private interface IColorTransformOperator static abstract void Apply(ref Vector128 first, ref Vector128 second, ref Vector128 third); /// - /// Restores eight independent columns, one column per signed integer lane. + /// Transforms eight independent columns, one column per signed integer lane. /// /// The first channel's input and output lanes. /// The second channel's input and output lanes. @@ -46,7 +47,7 @@ private interface IColorTransformOperator static abstract void Apply(ref Vector256 first, ref Vector256 second, ref Vector256 third); /// - /// Restores sixteen independent columns, one column per signed integer lane. + /// Transforms sixteen independent columns, one column per signed integer lane. /// /// The first channel's input and output lanes. /// The second channel's input and output lanes. @@ -64,6 +65,16 @@ private interface IColorTransformOperator public static void Apply(int operation, Span first, Span second, Span third) => Apply(operation, first, second, third); + /// + /// Applies the forward YCoCg transform in place: RGB becomes Y, Co and Cg. The inverse transform with operation 6 restores RGB + /// exactly. + /// + /// The red row. It receives Y. + /// The green row, with the same length as the first. It receives Co. + /// The blue row, with the same length as the first. It receives Cg. + public static void ApplyRgbToYCoCg(Span first, Span second, Span third) + => Apply(first, second, third); + /// /// Applies one inverse reversible color transform using the stream's signed sample storage. /// @@ -451,4 +462,64 @@ public static void Apply(ref Vector512 first, ref Vector512 second, re third = blue; } } + + /// + /// Converts RGB to reversible YCoCg components. + /// + private readonly struct RgbToYCoCgOperator : IColorTransformOperator + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Apply(ref int first, ref int second, ref int third) + { + // Inputs are R, G and B. Co is R - B. Cg is G minus the center B + Co / 2, and Y is the center plus Cg / 2. The signed shifts + // give the same rounding as the inverse transform, so the inverse restores each input exactly. + int co = first - third; + int center = third + (co >> 1); + int cg = second - center; + + first = center + (cg >> 1); + second = co; + third = cg; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Apply(ref Vector128 first, ref Vector128 second, ref Vector128 third) + { + Vector128 co = first - third; + Vector128 center = third + (co >> 1); + Vector128 cg = second - center; + + first = center + (cg >> 1); + second = co; + third = cg; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Apply(ref Vector256 first, ref Vector256 second, ref Vector256 third) + { + Vector256 co = first - third; + Vector256 center = third + (co >> 1); + Vector256 cg = second - center; + + first = center + (cg >> 1); + second = co; + third = cg; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Apply(ref Vector512 first, ref Vector512 second, ref Vector512 third) + { + Vector512 co = first - third; + Vector512 center = third + (co >> 1); + Vector512 cg = second - center; + + first = center + (cg >> 1); + second = co; + third = cg; + } + } } diff --git a/src/ImageSharp/Formats/Jxl/Components/Modular/JxlModularTree.cs b/src/ImageSharp/Formats/Jxl/Components/Modular/JxlModularTree.cs index 7f67474fef..72146c504b 100644 --- a/src/ImageSharp/Formats/Jxl/Components/Modular/JxlModularTree.cs +++ b/src/ImageSharp/Formats/Jxl/Components/Modular/JxlModularTree.cs @@ -17,11 +17,6 @@ namespace SixLabors.ImageSharp.Formats.Jxl.Components.Modular; /// internal sealed class JxlModularTree : IDisposable { - /// - /// The six entropy contexts encode split values, properties, predictors, offsets and two multiplier fields. - /// - private const int TreeContextCount = 6; - /// /// The entropy context for signed split thresholds. /// @@ -175,7 +170,7 @@ public static JxlModularTree Read(ref JxlBitReader reader, MemoryAllocator alloc int leaves = 0; int propertyCount = 0; Span nodes = nodeOwner.Memory.Span; - using (JxlEntropyDecoder treeCodes = JxlEntropyDecoder.Read(ref reader, allocator, TreeContextCount, true)) + using (JxlEntropyDecoder treeCodes = JxlEntropyDecoder.Read(ref reader, allocator, JxlConstants.TreeContextCount, true)) { // A leaf uses five values and a split uses two. This bounds the complete history before parsing begins. // Tree distances are linear, unlike modular sample distances. Retain a ring only when LZ77 is enabled. diff --git a/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlAcContexts.cs b/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlAcContexts.cs new file mode 100644 index 0000000000..b83b73b892 --- /dev/null +++ b/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlAcContexts.cs @@ -0,0 +1,58 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.ImageSharp.Formats.Jxl.Components.VarDct; + +/// +/// Contains the fixed context tables of the VarDCT AC coefficient entropy coding, shared by the decoder and the encoder. +/// +/// +/// The AC contexts of one histogram set are the nonzero-count contexts, predictionBucket * blockContextCount + blockContext, then +/// the coefficient-density contexts of each block context, blockContextCount * 37 + blockContext * 458 + density. +/// +internal static class JxlAcContexts +{ + /// + /// Gets the format's default block map. The large coefficient-order families share the same context. + /// + /// + /// The map index is component * 13 + orderFamily, with the components in Y, X, B order. + /// + public static ReadOnlySpan DefaultBlockContextMap => + [ + 0, 1, 2, 2, 3, 3, 4, 5, 6, 6, 6, 6, 6, + 7, 8, 9, 9, 10, 11, 12, 13, 14, 14, 14, 14, 14, + 7, 8, 9, 9, 10, 11, 12, 13, 14, 14, 14, 14, 14 + ]; + + /// + /// Gets the format's frequency-position buckets, already multiplied by two for the previous-symbol context bit. + /// + public static ReadOnlySpan CoefficientFrequencyContexts => + [ + + // These are the coefficient-frequency context buckets. Index zero is unused: AC scanning starts after the LLF prefix. + 0, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, + 30, 30, 32, 32, 34, 34, 36, 36, 38, 38, 40, 40, 42, 42, 44, 44, + 46, 46, 46, 46, 48, 48, 48, 48, 50, 50, 50, 50, 52, 52, 52, 52, + 54, 54, 54, 54, 56, 56, 56, 56, 58, 58, 58, 58, 60, 60, 60, 60 + ]; + + /// + /// Gets the format's remaining-nonzero buckets, already multiplied by two for the previous-symbol context bit. + /// + public static ReadOnlySpan CoefficientNonzeroContexts => + [ + 0, 0, 62, 124, 124, 186, 186, 186, 186, 246, 246, 246, 246, 304, 304, 304, + 304, 304, 304, 304, 304, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, + 360, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, + 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412 + ]; + + /// + /// Gets the nonzero-count bucket of a predicted nonzero count: the count itself below 8, then one bucket for each two counts. + /// + /// The predicted nonzero count, from 0 to 64. + /// The bucket, from 0 to 36. + public static int GetPredictionBucket(int predicted) => predicted < 8 ? predicted : 4 + (predicted / 2); +} diff --git a/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.Coefficients.cs b/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.Coefficients.cs index d4c11768c4..878c7363eb 100644 --- a/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.Coefficients.cs +++ b/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.Coefficients.cs @@ -28,30 +28,6 @@ internal sealed partial class JxlVarDctDecoder private InlineArray4 coefficientCounts; private int acGroupColumns; - /// - /// Gets the format's frequency-position buckets, already multiplied by two for the previous-symbol context bit. - /// - private static ReadOnlySpan CoefficientFrequencyContexts => - [ - - // These are the coefficient-frequency context buckets. Index zero is unused: AC scanning starts after the LLF prefix. - 0, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, - 30, 30, 32, 32, 34, 34, 36, 36, 38, 38, 40, 40, 42, 42, 44, 44, - 46, 46, 46, 46, 48, 48, 48, 48, 50, 50, 50, 50, 52, 52, 52, 52, - 54, 54, 54, 54, 56, 56, 56, 56, 58, 58, 58, 58, 60, 60, 60, 60 - ]; - - /// - /// Gets the format's remaining-nonzero buckets, already multiplied by two for the previous-symbol context bit. - /// - private static ReadOnlySpan CoefficientNonzeroContexts => - [ - 0, 0, 62, 124, 124, 186, 186, 186, 186, 246, 246, 246, 246, 304, 304, 304, - 304, 304, 304, 304, 304, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, - 360, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, - 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412 - ]; - /// /// Borrows the current group's packed sixteen-bit coefficients for one component. /// @@ -366,7 +342,7 @@ private void ReadAcGroup( int mapComponent = component < 2 ? component ^ 1 : component; int mapIndex = (((mapComponent * JxlCoefficientOrder.OrderCount) + orderFamily) * (quantizerThresholds.Length + 1)) + quantizerBucket; int blockContext = blockContexts[(mapIndex * dcContextCount) + dcRow[x]]; - int predictionBucket = predicted < 8 ? predicted : 4 + (predicted / 2); + int predictionBucket = JxlAcContexts.GetPredictionBucket(predicted); int countContext = histogramOffset + (predictionBucket * blockContextCount) + blockContext; uint count = symbols.ReadUInt32(ref reader, countContext, history, decodedCount++, 0); if (count > size - coveredBlocks) @@ -484,8 +460,8 @@ private static void ReadAcCoefficients( { int size = block.Length; int previous = remaining > size / 16 ? 0 : 1; - ref byte frequencyContexts = ref MemoryMarshal.GetReference(CoefficientFrequencyContexts); - ref ushort nonzeroContexts = ref MemoryMarshal.GetReference(CoefficientNonzeroContexts); + ref byte frequencyContexts = ref MemoryMarshal.GetReference(JxlAcContexts.CoefficientFrequencyContexts); + ref ushort nonzeroContexts = ref MemoryMarshal.GetReference(JxlAcContexts.CoefficientNonzeroContexts); ref uint firstOrder = ref MemoryMarshal.GetReference(order); ref TCoefficient firstCoefficient = ref MemoryMarshal.GetReference(block); diff --git a/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.cs b/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.cs index 8b52a574f2..eac3697534 100644 --- a/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.cs +++ b/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.cs @@ -120,7 +120,7 @@ private JxlVarDctDecoder(Vector3 dcFactors, int sampleBitDepth) /// The index groups component, coefficient order, quantization bucket and DC bucket, from outermost to innermost. /// Component indices exchange X and Y because the encoded modular channel order is Y, X, B. /// - public ReadOnlySpan BlockContextMap => this.blockContextMap is null ? DefaultBlockContextMap : this.blockContextMap.Memory.Span; + public ReadOnlySpan BlockContextMap => this.blockContextMap is null ? JxlAcContexts.DefaultBlockContextMap : this.blockContextMap.Memory.Span; /// /// Gets the AC quantization thresholds in encoded order. A sample enters the next bucket only when it exceeds a threshold. @@ -152,16 +152,6 @@ private JxlVarDctDecoder(Vector3 dcFactors, int sampleBitDepth) /// public float DcCorrelationB { get; private set; } - /// - /// Gets the format's default block map. The large coefficient-order families share the same context. - /// - private static ReadOnlySpan DefaultBlockContextMap => - [ - 0, 1, 2, 2, 3, 3, 4, 5, 6, 6, 6, 6, 6, - 7, 8, 9, 9, 10, 11, 12, 13, 14, 14, 14, 14, 14, - 7, 8, 9, 9, 10, 11, 12, 13, 14, 14, 14, 14, 14 - ]; - /// /// Reads the VarDCT fields between the frame's DC matrix factors and its global modular tree. /// diff --git a/src/ImageSharp/Formats/Jxl/JxlConstants.cs b/src/ImageSharp/Formats/Jxl/JxlConstants.cs index ea13bce81b..b62c43e668 100644 --- a/src/ImageSharp/Formats/Jxl/JxlConstants.cs +++ b/src/ImageSharp/Formats/Jxl/JxlConstants.cs @@ -13,6 +13,17 @@ internal static class JxlConstants /// public const int QuantizationTableCount = 17; + /// + /// The six entropy contexts of a modular tree stream: split values, properties, predictors, offsets and two multiplier fields. + /// + public const int TreeContextCount = 6; + + /// + /// The entropy contexts of an ICC profile stream: the first-byte context plus eight preceding-byte classes times five + /// second-byte classes in native ICC prediction. + /// + public const int IccContextCount = 41; + /// /// The fifteen block contexts selected by the default VarDCT block map. /// diff --git a/src/ImageSharp/Formats/Jxl/JxlEncoderCore.Ac.cs b/src/ImageSharp/Formats/Jxl/JxlEncoderCore.Ac.cs new file mode 100644 index 0000000000..c5181dcfd2 --- /dev/null +++ b/src/ImageSharp/Formats/Jxl/JxlEncoderCore.Ac.cs @@ -0,0 +1,395 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using SixLabors.ImageSharp.Formats.Jxl.Components.Entropy; +using SixLabors.ImageSharp.Formats.Jxl.Components.Modular; +using SixLabors.ImageSharp.Formats.Jxl.Components.VarDct; + +namespace SixLabors.ImageSharp.Formats.Jxl; + +/// +/// Writes the VarDCT AC coefficients with the contexts of the format and prefix codes built from their histograms. +/// +/// +/// The design follows libjxl at effort 7: the tokens of all AC groups of a pass give the histograms of the pass, the fast clustering +/// groups the histograms, and each cluster has a prefix code with the 4/2/0 hybrid integer configuration and no copies. +/// The contexts are those of the VarDCT AC coefficient coding of ISO/IEC 18181-1 (JPEG XL core coding system): the nonzero count of a +/// block uses the count predicted from the blocks above and to the left, and each coefficient uses the remaining nonzero count, its scan +/// position and whether the coefficient before it is zero. +/// +internal sealed partial class JxlEncoderCore +{ + /// + /// The number of AC contexts of one block context: the nonzero-count contexts, then the coefficient-density contexts. + /// + private const int AcBlockContextSize = JxlConstants.NonzeroContextCount + JxlConstants.ZeroDensityContextCount; + + /// + /// The number of AC contexts of one histogram set with the default block context map. + /// + private const int AcContextCount = JxlConstants.DefaultBlockContextCount * AcBlockContextSize; + + /// + /// The number of block contexts that DCT8 blocks use with the default map: Y uses one, and X and B share another. + /// The encoder counts histograms only for the AC contexts of these block contexts. + /// + private const int AcHistogramBlockContexts = 2; + + /// + /// The number of counted AC histograms of one pass. + /// + private const int AcHistogramCount = AcHistogramBlockContexts * AcBlockContextSize; + + /// + /// The number of blocks of one AC group, the area of the nonzero-count prediction of one component. + /// + private const int AcGroupBlocks = (GroupDimension / 8) * (GroupDimension / 8); + + /// + /// Selects whether the AC tokenizer counts the tokens or writes them. + /// + private interface IAcTokenOperation + { + /// + /// Gets a value indicating whether the operation writes the tokens. Otherwise it counts them in the histograms. + /// + public static abstract bool Writes { get; } + } + + /// + /// Counts or writes the AC tokens of one pass of one AC group in block-row and Y, X, B order, with the contexts that the decoder uses. + /// + /// Counts the tokens, or writes them. + /// The retained quantized coefficients. + /// The group in block coordinates. + /// The spectral pass index. + /// One full pass or three spectral passes. + /// The natural DCT8 coefficient order. + /// The nonzero count of each block of the group, for the prediction. It has one region for each component. + /// The counted histograms of the pass, with counts each. It is empty to write. + /// The cluster of each counted histogram. It is empty to count. + /// The code lengths of the clusters, with entries each. It is empty to count. + /// The codes of the clusters, with entries each. It is empty to count. + /// The retained byte buffer. + /// The token checked between block rows. + private void TokenizeAcGroup( + JxlVarDctEncoder varDct, + Rectangle rectangle, + int pass, + int passes, + ReadOnlySpan order, + Span nonzeros, + Span histograms, + ReadOnlySpan clusterOf, + ReadOnlySpan lengths, + ReadOnlySpan codes, + Span output, + CancellationToken cancellationToken) + where TOperation : struct, IAcTokenOperation + { + InlineArray64 scanStorage = default; + Span scan = scanStorage; + InlineArray64 packedStorage = default; + Span packedValues = packedStorage; + InlineArray64 positionStorage = default; + Span positions = positionStorage; + InlineArray64 indexStorage = default; + Span indices = indexStorage; + int selectedCount = 0; + ReadOnlySpan frequencyContexts = JxlAcContexts.CoefficientFrequencyContexts; + ReadOnlySpan nonzeroContexts = JxlAcContexts.CoefficientNonzeroContexts; + + // Select each pass's frequencies once. The three spectral regions contain 3, 5 and 55 AC + // coefficients. Their scan positions retain the natural order, including gaps for earlier passes. + // Unselected scan entries start at zero and are never changed. Every selected entry is overwritten + // for every block, so scans need neither another coefficient pass nor a per-block clear. + for (int k = 1; k < 64; k++) + { + int index = (int)order[k]; + int fx = index / 8; + int fy = index & 7; + int stage = fx < 2 && fy < 2 ? 0 : fx < 3 && fy < 3 ? 1 : 2; + + if (passes == 1 || pass == stage) + { + positions[selectedCount] = k; + indices[selectedCount++] = index; + } + } + + // The bit state stays in locals. Each block checks the buffer capacity once: its three components write at most 3 * 64 tokens, + // fewer than one batch of the stream writer. + ulong bits = this.bits; + int pendingBits = this.pendingBits; + int bufferedBytes = this.bufferedBytes; + const int stride = GroupDimension / 8; + for (int y = rectangle.Y; y < rectangle.Bottom; y++) + { + cancellationToken.ThrowIfCancellationRequested(); + _ = varDct.TryGetCoefficientRow(0, rectangle.X, y, rectangle.Width, out Span rowX); + _ = varDct.TryGetCoefficientRow(1, rectangle.X, y, rectangle.Width, out Span rowY); + _ = varDct.TryGetCoefficientRow(2, rectangle.X, y, rectangle.Width, out Span rowB); + int blockY = y - rectangle.Y; + + for (int x = rectangle.X; x < rectangle.Right; x++) + { + int blockX = x - rectangle.X; + int offset = (blockY * stride) + blockX; + if (TOperation.Writes && bufferedBytes > output.Length - SymbolBatchBytes) + { + this.outputStream.Write(output[..bufferedBytes]); + bufferedBytes = 0; + } + + for (int encodedComponent = 0; encodedComponent < 3; encodedComponent++) + { + int component = encodedComponent < 2 ? encodedComponent ^ 1 : encodedComponent; + ReadOnlySpan row = component switch + { + 0 => rowX, + 1 => rowY, + _ => rowB + }; + + // A normal allocator exposes this group row as one contiguous footprint. Small + // segments borrow individual blocks instead; both paths visit the same 64-value layout. + ReadOnlySpan coefficients = row.IsEmpty + ? varDct.GetCoefficientBlock(component, x, y) + : row.Slice((x - rectangle.X) * 64, 64); + + int count = 0; + int last = 0; + + // DC never appears in this scan. Selected positions increase in wire order, so + // the final nonzero position also bounds the coefficient symbols that must be emitted. + for (int i = 0; i < selectedCount; i++) + { + int k = positions[i]; + int value = coefficients[indices[i]]; + scan[k] = value; + + if (value != 0) + { + count++; + last = k; + } + } + + // The count prediction: 32 for the first block, the block above in the first column, the block to the left in the + // first row, else the rounded mean of both. The counts of the earlier blocks of the group are already stored. + Span componentNonzeros = nonzeros.Slice(component * AcGroupBlocks, AcGroupBlocks); + int predicted = blockX == 0 + ? blockY == 0 ? 32 : componentNonzeros[offset - stride] + : blockY == 0 + ? componentNonzeros[offset - 1] + : (componentNonzeros[offset - stride] + componentNonzeros[offset - 1] + 1) / 2; + + componentNonzeros[offset] = (byte)count; + + // The counted histograms of the Y block context come first, then those of the shared X and B block context. + int histogramOffset = component == 1 ? 0 : AcBlockContextSize; + AddAcToken( + histogramOffset + JxlAcContexts.GetPredictionBucket(predicted), + (uint)count, + histograms, + clusterOf, + lengths, + codes, + ref bits, + ref pendingBits, + ref bufferedBytes, + output); + + if (last == 0) + { + continue; + } + + // The coefficient tokens end at the last nonzero coefficient, where the remaining count becomes zero. The first + // coefficient uses the zero-before context when the block has few nonzero coefficients, as in the decoder. + Span packed = packedValues[..last]; + JxlModularPredictor.PackZeroResiduals(scan.Slice(1, last), packed); + int densityOffset = histogramOffset + JxlConstants.NonzeroContextCount; + int remaining = count; + int previous = remaining > 64 / 16 ? 0 : 1; + + for (int k = 1; k <= last; k++) + { + uint value = packed[k - 1]; + int context = densityOffset + nonzeroContexts[remaining] + frequencyContexts[k] + previous; + AddAcToken( + context, + value, + histograms, + clusterOf, + lengths, + codes, + ref bits, + ref pendingBits, + ref bufferedBytes, + output); + + previous = value != 0 ? 1 : 0; + remaining -= previous; + } + } + } + } + + this.bits = bits; + this.pendingBits = pendingBits; + this.bufferedBytes = bufferedBytes; + } + + /// + /// Counts one AC token in its histogram, or writes it with the prefix code of its cluster. + /// + /// Counts the token, or writes it. + /// The counted histogram of the context. + /// The unsigned value. + /// The counted histograms. It is empty to write. + /// The cluster of each counted histogram. It is empty to count. + /// The code lengths of the clusters. It is empty to count. + /// The codes of the clusters. It is empty to count. + /// The bit reservoir of the writer. + /// The number of pending bits of the writer. + /// The number of bytes in the output buffer. + /// The retained byte buffer. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AddAcToken( + int histogram, + uint value, + Span histograms, + ReadOnlySpan clusterOf, + ReadOnlySpan lengths, + ReadOnlySpan codes, + ref ulong bits, + ref int pendingBits, + ref int bufferedBytes, + Span output) + where TOperation : struct, IAcTokenOperation + { + JxlHybridUint.Encode420(value, out uint token, out int bitCount, out uint extraBits); + if (TOperation.Writes) + { + int index = (clusterOf[histogram] * TokenAlphabetSize) + (int)token; + AppendSymbol(codes[index], lengths[index], extraBits, bitCount, ref bits, ref pendingBits, ref bufferedBytes, output); + } + else + { + histograms[(histogram * TokenAlphabetSize) + (int)token]++; + } + } + + /// + /// Counts the AC tokens of one pass of all AC groups, groups their histograms in clusters, and writes the entropy code of the pass. + /// + /// The retained quantized coefficients. + /// The block grid size of the frame. + /// The spectral pass index. + /// One full pass or three spectral passes. + /// The natural DCT8 coefficient order. + /// + /// Scratch for the histograms, the clusters, the totals and the context map values. The layout is the counted histograms, the + /// clusters, the totals and the used token lengths, then twice the context count. + /// + /// Scratch for the context map, the cluster numbers and the count prediction. + /// Scratch for the clustering. The length is twice the counted histogram count plus the cluster limit. + /// Receives the cluster of each counted histogram of the pass. + /// Receives the code lengths of the clusters of the pass. + /// Receives the codes of the clusters of the pass. + /// The retained byte buffer. + /// The token checked between block rows. + private void WriteAcHistograms( + JxlVarDctEncoder varDct, + Size blocks, + int pass, + int passes, + ReadOnlySpan order, + Span counts, + Span bytes, + Span floats, + Span clusterOf, + Span lengths, + Span codes, + Span output, + CancellationToken cancellationToken) + { + Span histograms = counts[..(AcHistogramCount * TokenAlphabetSize)]; + Span clusters = counts.Slice(histograms.Length, MaximumClusterCount * TokenAlphabetSize); + Span totals = counts.Slice(histograms.Length + clusters.Length, 2 * (AcHistogramCount + MaximumClusterCount)); + Span values = counts.Slice(histograms.Length + clusters.Length + totals.Length, 2 * AcContextCount); + Span contextMap = bytes[..AcContextCount]; + Span renumber = bytes.Slice(AcContextCount, 2 * MaximumClusterCount); + Span nonzeros = bytes.Slice(AcContextCount + renumber.Length, 3 * AcGroupBlocks); + + histograms.Clear(); + for (int group = 0; group < this.groupCount; group++) + { + Rectangle rectangle = this.GetAcGroupBlocks(group, blocks); + this.TokenizeAcGroup(varDct, rectangle, pass, passes, order, nonzeros, histograms, [], [], [], output, cancellationToken); + } + + int clusterCount = ClusterHistograms(histograms, clusterOf, clusters, totals, floats); + + // The full context map. The AC contexts of the block contexts that DCT8 blocks do not use have no tokens. They use cluster 0, like + // the empty histograms. + ReadOnlySpan blockContextMap = JxlAcContexts.DefaultBlockContextMap; + int yBlockContext = blockContextMap[0]; + int xbBlockContext = blockContextMap[JxlCoefficientOrder.OrderCount]; + const int countContexts = JxlConstants.DefaultBlockContextCount * JxlConstants.NonzeroContextCount; + for (int context = 0; context < AcContextCount; context++) + { + int blockContext = context < countContexts + ? context % JxlConstants.DefaultBlockContextCount + : (context - countContexts) / JxlConstants.ZeroDensityContextCount; + + int local = context < countContexts + ? context / JxlConstants.DefaultBlockContextCount + : JxlConstants.NonzeroContextCount + ((context - countContexts) % JxlConstants.ZeroDensityContextCount); + + int histogram = blockContext == yBlockContext ? local : blockContext == xbBlockContext ? AcBlockContextSize + local : -1; + contextMap[context] = histogram < 0 ? (byte)0 : clusterOf[histogram]; + } + + this.WriteHistogramCodes(contextMap, clusters, clusterCount, renumber, values, lengths, codes, output); + + // The AC groups write with the new cluster numbers. + foreach (ref byte cluster in clusterOf) + { + cluster = renumber[cluster]; + } + } + + /// + /// Gets the block rectangle of one AC group. + /// + /// The AC group index. + /// The block grid size of the frame. + /// The group in block coordinates. + private Rectangle GetAcGroupBlocks(int group, Size blocks) + { + int x = (group % this.groupColumns) * (GroupDimension / 8); + int y = (group / this.groupColumns) * (GroupDimension / 8); + return new Rectangle(x, y, Math.Min(GroupDimension / 8, blocks.Width - x), Math.Min(GroupDimension / 8, blocks.Height - y)); + } + + /// + /// Counts the AC tokens in the histograms. + /// + private readonly struct AcTokenCount : IAcTokenOperation + { + /// + public static bool Writes => false; + } + + /// + /// Writes the AC tokens with the prefix codes of their clusters. + /// + private readonly struct AcTokenWrite : IAcTokenOperation + { + /// + public static bool Writes => true; + } +} diff --git a/src/ImageSharp/Formats/Jxl/JxlEncoderCore.Entropy.cs b/src/ImageSharp/Formats/Jxl/JxlEncoderCore.Entropy.cs new file mode 100644 index 0000000000..e059d3f61c --- /dev/null +++ b/src/ImageSharp/Formats/Jxl/JxlEncoderCore.Entropy.cs @@ -0,0 +1,1596 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Buffers; +using System.Buffers.Binary; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Compression; +using SixLabors.ImageSharp.Formats.Jxl.Components.Entropy; +using SixLabors.ImageSharp.Memory; + +namespace SixLabors.ImageSharp.Formats.Jxl; + +/// +/// Writes entropy-coded sample streams with prefix codes built from the stream histogram, and with run-length copies. +/// +/// +/// The stream format is the entropy coding of ISO/IEC 18181-1 (JPEG XL core coding system), annex C: the LZ77 parameters, the +/// context map, the hybrid integer configurations, and the prefix codes in the Brotli format of RFC 7932, section 3. +/// The streams use prefix codes with at most 4 clusters, as libjxl does at effort 1 and 2 outside its fast lossless mode. They use the +/// 4/2/0 hybrid integer configuration, and LZ77 as run-length copies of the previous value when the copies save bits. The fast lossless +/// mode has its own streams. +/// +internal sealed partial class JxlEncoderCore +{ + /// + /// The first copy-length symbol. Literal tokens are below it. The U32 field of the stream header encodes this value with 2 bits. + /// + private const int CopySymbolStart = 224; + + /// + /// The shortest copy. The U32 field of the stream header encodes this value with 2 bits. + /// + private const int CopyMinimumLength = 3; + + /// + /// The number of values that the stream writer writes between two checks of the output buffer capacity. + /// + private const int SymbolBatchSize = 256; + + /// + /// The largest number of bytes that one batch of the stream writer writes. A value writes at most one symbol of 15 bits with + /// 29 extra bits. A copy of at least 3 values writes a length symbol of 15 bits with at most 30 extra bits and a distance symbol of + /// at most 15 bits. So each value of a batch writes at most 64 bits. The 64-bit field writer also stores the 8 bytes of its buffer past the written bytes. + /// + private const int SymbolBatchBytes = (SymbolBatchSize * sizeof(ulong)) + sizeof(ulong); + + /// + /// The longest prefix code of the format. + /// + private const int MaximumPrefixCodeLength = 15; + + /// + /// The number of symbols of the code-length code: the lengths 0 to 15, and the repeat codes 16 and 17. + /// + private const int CodeLengthCodeCount = 18; + + /// + /// The number of 4/2/0 tokens of 32-bit values. The largest token is 16 + (27 * 4) + 3 = 127. + /// + private const int TokenAlphabetSize = 128; + + /// + /// The largest number of clusters of one histogram set: 4, as the fastest clustering of libjxl at effort 1 and 2. + /// + private const int MaximumClusterCount = 4; + + /// + /// The smallest distance of a histogram from all clusters at which the fast clustering starts another cluster, as in libjxl. + /// + private const float MinimumDistinctClusterDistance = 48F; + + /// + /// Gets the order in which the format stores the lengths of the code-length code (RFC 7932, section 3.5). + /// + private static ReadOnlySpan CodeLengthCodeOrder => [1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + + /// + /// Gets the fixed codes that store the lengths 0 to 5 of the code-length code, least-significant bit first (RFC 7932, section 3.5). + /// + private static ReadOnlySpan CodeLengthLengthCodes => [0, 7, 3, 2, 1, 15]; + + /// + /// Gets the bit counts of . + /// + private static ReadOnlySpan CodeLengthLengthBits => [2, 4, 3, 2, 2, 4]; + + /// + /// Writes one entropy-coded stream of values with one cluster for all its contexts: the stream header and the values. + /// + /// + /// The method counts the 4/2/0 tokens of the values. A run of values equal to the value before it becomes a copy with distance 1 + /// when the copy costs fewer bits than the literals, by the token costs of the count. The copies are used only when they save more + /// than 0.2 bits for each value plus 16 bits, as in libjxl. Then the method builds one length-limited prefix code for the literals and + /// the copy lengths, and one for the copy distances. + /// + /// + /// The unsigned values, in stream order. The stream has at least one value: the callers write no stream for an empty modular channel, + /// and the other streams always have values. + /// + /// The number of contexts of the stream syntax. All contexts use the one cluster of the values. + /// + /// The distance symbol of a copy from the value before: 1 for a stream with a row width, where symbol 1 is the short distance (1, 0); + /// 0 for a stream without one. + /// + /// The retained output buffer. + private void WriteSampleStream(ReadOnlySpan values, int contextCount, uint distanceSymbol, Span output) + { + // One pass gives the token counts and the runs of values equal to the value before them. A run has at least 3 values, and a + // different value ends it, so the stream has fewer than n / 4 + 1 runs. + using IMemoryOwner copyOwner = this.memoryAllocator.Allocate(2 * ((values.Length / (CopyMinimumLength + 1)) + 1)); + using IMemoryOwner histogramOwner = this.memoryAllocator.Allocate(4 * TokenAlphabetSize, AllocationOptions.Clean); + Span copies = copyOwner.GetSpan(); + Span histograms = histogramOwner.GetSpan(); + int runCount = CountTokens(values, histograms, copies); + + // The four partial histograms give the token counts. + InlineArray256 literalCountStorage = default; + Span literalCounts = literalCountStorage; + for (int token = 0; token < TokenAlphabetSize; token++) + { + literalCounts[token] = histograms[token] + + histograms[TokenAlphabetSize + token] + + histograms[(2 * TokenAlphabetSize) + token] + + histograms[(3 * TokenAlphabetSize) + token]; + } + + // The cost of a token is -log2 of its share of the count. A copy costs about the bits of its length plus one bit. + InlineArray256 tokenBitsStorage = default; + Span tokenBits = tokenBitsStorage; + float totalInverse = 1F / values.Length; + for (int token = 0; token < literalCounts.Length; token++) + { + uint count = literalCounts[token]; + tokenBits[token] = count == 0 || count == (uint)values.Length ? 0F : -MathF.Log2(count * totalInverse); + } + + // A run becomes a copy with distance 1 when the copy costs fewer bits than its literals. The copies keep the run order. + int copyCount = 0; + float saving = 0; + for (int r = 0; r < runCount; r++) + { + int start = copies[2 * r]; + int run = copies[(2 * r) + 1]; + JxlHybridUint.Encode420(values[start - 1], out uint token, out int bitCount, out _); + float literalCost = run * (tokenBits[(int)token] + bitCount); + float copyCost = (32 - BitOperations.LeadingZeroCount((uint)(run - CopyMinimumLength))) + 1; + if (literalCost > copyCost) + { + copies[2 * copyCount] = start; + copies[(2 * copyCount) + 1] = run; + copyCount++; + saving += literalCost - copyCost; + } + } + + bool useCopies = saving > (values.Length * 0.2F) + 16; + copyCount = useCopies ? copyCount : 0; + copies = copies[..(2 * copyCount)]; + + // The counts of the coded symbols. The copied values are not literals. Each copy adds a length symbol and a distance symbol. + // The 4/2/0 tokens of 32-bit values are less than 128. A copy of fewer than 2^31 values has a length token of at most 32, so + // the last symbol is at most 256 and 264 counts hold all symbols. + InlineArray264 symbolCountStorage = default; + Span symbolCounts = symbolCountStorage; + literalCounts.CopyTo(symbolCounts); + uint distanceCount = 0; + for (int c = 0; c < copyCount; c++) + { + int start = copies[2 * c]; + int run = copies[(2 * c) + 1]; + JxlHybridUint.Encode420(values[start - 1], out uint token, out _, out _); + symbolCounts[(int)token] -= (uint)run; + JxlHybridUint.Zero.Encode((uint)(run - CopyMinimumLength), out uint lengthToken, out _, out _); + symbolCounts[CopySymbolStart + (int)lengthToken]++; + distanceCount++; + } + + // The stream header. With copies, the distances have one more context after the contexts of the syntax. The context map gives + // the distances cluster 1 and all other contexts cluster 0. + this.WriteBits(1, useCopies ? 1U : 0U, output); + if (useCopies) + { + this.WriteBits(2, 0, output); // The first copy symbol is 224. + this.WriteBits(2, 0, output); // The shortest copy is 3. + this.WriteBits(4, 0, output); // The copy lengths use the hybrid integer configuration 0/0/0 (an 8-bit alphabet). + this.WriteBits(1, 1, output); // Simple context map. + this.WriteBits(2, 1, output); // One bit for each entry. + for (int c = 0; c < contextCount; c++) + { + this.WriteBits(1, 0, output); // The values use cluster 0. + } + + this.WriteBits(1, 1, output); // The distances use cluster 1. + } + else if (contextCount > 1) + { + this.WriteBits(1, 1, output); // Simple context map. + this.WriteBits(2, 0, output); // Zero bits for each entry: every context uses cluster 0. + } + + InlineArray2 distanceCountStorage = default; + Span distanceCounts = distanceCountStorage; + JxlHybridUint.Zero.Encode(distanceSymbol, out uint distanceToken, out _, out _); + distanceCounts[(int)distanceToken] = distanceCount; + + this.WriteBits(1, 1, output); // Prefix codes. + + // The hybrid integer configuration of each cluster, with the 15-bit prefix alphabet. The copy distances use the configuration + // 0/0/0: a split of zero with 4 bits. + this.WriteSplit420Configuration(MaximumPrefixCodeLength, output); + if (useCopies) + { + this.WriteBits(4, 0, output); + } + + // The alphabet size of each cluster, then its code lengths. The codes are least-significant bit first. + int symbolAlphabet = GetAlphabetSize(symbolCounts); + int distanceAlphabet = GetAlphabetSize(distanceCounts); + this.WriteAlphabetSize(symbolAlphabet, output); + if (useCopies) + { + this.WriteAlphabetSize(distanceAlphabet, output); + } + + InlineArray264 symbolLengthStorage = default; + InlineArray264 symbolCodeStorage = default; + Span symbolLengths = symbolLengthStorage[..symbolAlphabet]; + Span symbolCodes = symbolCodeStorage[..symbolAlphabet]; + this.WritePrefixCode(symbolCounts[..symbolAlphabet], symbolLengths, symbolCodes, output); + + InlineArray2 distanceLengthStorage = default; + InlineArray2 distanceCodeStorage = default; + Span distanceLengths = distanceLengthStorage[..distanceAlphabet]; + Span distanceCodes = distanceCodeStorage[..distanceAlphabet]; + if (useCopies) + { + this.WritePrefixCode(distanceCounts[..distanceAlphabet], distanceLengths, distanceCodes, output); + } + + // The symbol table of the field operator: the code in the low 16 bits and the code length in the high 16 bits. + for (int symbol = 0; symbol < symbolAlphabet; symbol++) + { + symbolCodes[symbol] |= (uint)symbolLengths[symbol] << 16; + } + + // The values. A copy writes its length symbol and its distance symbol in place of its run. The literals between the copies go + // through the field operator. The bit state stays in locals as a 64-bit buffer, and each batch checks the buffer capacity once. + ulong buffer = this.bits; + int bufferBits = this.pendingBits; + int bufferedBytes = this.bufferedBytes; + ref int table = ref Unsafe.As(ref MemoryMarshal.GetReference(symbolCodes)); + int nextCopy = 0; + int nextCopyStart = copyCount > 0 ? copies[0] : int.MaxValue; + + // A stream without copies has no distance code. + uint distanceCode = useCopies ? distanceCodes[(int)distanceToken] : 0; + int distanceLength = useCopies ? distanceLengths[(int)distanceToken] : 0; + for (int i = 0; i < values.Length;) + { + if (bufferedBytes > output.Length - SymbolBatchBytes) + { + this.outputStream.Write(output[..bufferedBytes]); + bufferedBytes = 0; + } + + // A copy can end after the batch. The batch still has at most one copy or literal for each of its values. + int end = Math.Min(values.Length, i + SymbolBatchSize); + while (i < end) + { + if (i == nextCopyStart) + { + int run = copies[(2 * nextCopy) + 1]; + JxlHybridUint.Zero.Encode((uint)(run - CopyMinimumLength), out uint lengthToken, out int lengthBitCount, out uint lengthBits); + int lengthEntry = Unsafe.Add(ref table, CopySymbolStart + lengthToken); + int lengthCodeLength = lengthEntry >> 16; + ulong lengthField = (uint)(lengthEntry & 0xFFFF) | ((ulong)lengthBits << lengthCodeLength); + AppendField(lengthField, lengthCodeLength + lengthBitCount, ref buffer, ref bufferBits, ref bufferedBytes, output); + AppendField(distanceCode, distanceLength, ref buffer, ref bufferBits, ref bufferedBytes, output); + i += run; + nextCopy++; + nextCopyStart = nextCopy < copyCount ? copies[2 * nextCopy] : int.MaxValue; + continue; + } + + // A short literal segment between copies has no complete vector block, so it skips the vector traversal. + int literalEnd = Math.Min(end, nextCopyStart); + if (literalEnd - i < Vector128.Count) + { + for (; i < literalEnd; i++) + { + ulong field = PrefixFieldOperator.GetField(values[i], ref table, out int fieldBits); + AppendField(field, fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + } + + continue; + } + + // The traversal is not inlined, and a local that a call takes by reference stays in memory for the whole method. So the + // traversal takes copies of the bit state, and the bit state of this loop stays in registers. + ulong segmentBuffer = buffer; + int segmentBufferBits = bufferBits; + int segmentBufferedBytes = bufferedBytes; + AppendLiterals(values[i..literalEnd], ref table, ref segmentBuffer, ref segmentBufferBits, ref segmentBufferedBytes, output); + buffer = segmentBuffer; + bufferBits = segmentBufferBits; + bufferedBytes = segmentBufferedBytes; + i = literalEnd; + } + } + + // The other writers keep fewer than 32 pending bits. The buffer bytes are already stored, so a complete low word only moves on. + BinaryPrimitives.WriteUInt64LittleEndian(output[bufferedBytes..], buffer); + if (bufferBits >= 32) + { + bufferedBytes += sizeof(uint); + buffer >>= 32; + bufferBits -= 32; + } + + this.bits = buffer; + this.pendingBits = bufferBits; + this.bufferedBytes = bufferedBytes; + } + + /// + /// Counts the 4/2/0 tokens of the values and finds the runs of values equal to the value before them. + /// + /// + /// The vector blocks compare each value with the value before it. A change of that equality starts or ends a run. The token counts + /// go to four partial histograms by lane, so that equal tokens of adjacent values do not wait for the same counter. + /// + /// The values, in stream order. The stream has at least one value. + /// Four cleared histograms of counts each. Their sums are the token counts. + /// The runs of at least values: the start, then the length of each run, in order. + /// The number of runs. + private static int CountTokens(ReadOnlySpan values, Span histograms, Span runs) + { + ref uint source = ref MemoryMarshal.GetReference(values); + ref uint histogram = ref MemoryMarshal.GetReference(histograms); + InlineArray16 tokenStorage = default; + ref uint tokens = ref Unsafe.As, uint>(ref tokenStorage); + int runCount = 0; + int runStart = -1; + + // The first value has no value before it, so it does not continue a run. The blocks start after it. + JxlHybridUint.Encode420(source, out uint firstToken, out _, out _); + Unsafe.Add(ref histogram, firstToken)++; + int position = 1; + + if (Vector512.IsHardwareAccelerated) + { + while (position <= values.Length - Vector512.Count) + { + Vector512 lanes = Vector512.LoadUnsafe(ref source, (nuint)position); + Vector512 previous = Vector512.LoadUnsafe(ref source, (nuint)(position - 1)); + uint equal = (uint)Vector512.Equals(lanes, previous).ExtractMostSignificantBits(); + if (equal == (1U << Vector512.Count) - 1) + { + SkipRun(values, ref histogram, ref position, ref runStart); + continue; + } + + JxlHybridUint.Encode420(lanes, out Vector512 token, out _, out _); + token.StoreUnsafe(ref tokens); + AddTokens(ref histogram, ref tokens, Vector512.Count); + AddRuns(equal, Vector512.Count, position, runs, ref runCount, ref runStart); + position += Vector512.Count; + } + } + + if (Vector256.IsHardwareAccelerated) + { + while (position <= values.Length - Vector256.Count) + { + Vector256 lanes = Vector256.LoadUnsafe(ref source, (nuint)position); + Vector256 previous = Vector256.LoadUnsafe(ref source, (nuint)(position - 1)); + uint equal = Vector256.Equals(lanes, previous).ExtractMostSignificantBits(); + if (equal == (1U << Vector256.Count) - 1) + { + SkipRun(values, ref histogram, ref position, ref runStart); + continue; + } + + JxlHybridUint.Encode420(lanes, out Vector256 token, out _, out _); + token.StoreUnsafe(ref tokens); + AddTokens(ref histogram, ref tokens, Vector256.Count); + AddRuns(equal, Vector256.Count, position, runs, ref runCount, ref runStart); + position += Vector256.Count; + } + } + + if (Vector128.IsHardwareAccelerated) + { + while (position <= values.Length - Vector128.Count) + { + Vector128 lanes = Vector128.LoadUnsafe(ref source, (nuint)position); + Vector128 previous = Vector128.LoadUnsafe(ref source, (nuint)(position - 1)); + uint equal = Vector128.Equals(lanes, previous).ExtractMostSignificantBits(); + if (equal == (1U << Vector128.Count) - 1) + { + SkipRun(values, ref histogram, ref position, ref runStart); + continue; + } + + JxlHybridUint.Encode420(lanes, out Vector128 token, out _, out _); + token.StoreUnsafe(ref tokens); + AddTokens(ref histogram, ref tokens, Vector128.Count); + AddRuns(equal, Vector128.Count, position, runs, ref runCount, ref runStart); + position += Vector128.Count; + } + } + + for (; position < values.Length; position++) + { + uint value = Unsafe.Add(ref source, (nuint)position); + JxlHybridUint.Encode420(value, out uint token, out _, out _); + Unsafe.Add(ref histogram, token)++; + AddRuns(value == Unsafe.Add(ref source, (nuint)(position - 1)) ? 1U : 0U, 1, position, runs, ref runCount, ref runStart); + } + + // The last run ends with the stream. + if (runStart >= 0) + { + AddRun(runs, ref runCount, runStart, values.Length - runStart); + } + + return runCount; + } + + /// + /// Counts a run that continues for at least one complete vector block, and moves past it. All values of the block are equal to the + /// value before the block, so the run is open after the call. The span search finds the end of the run, and all its values have + /// the token of that value, so the run adds its count in one step. + /// + /// The values, in stream order. + /// The first count of the four partial histograms. + /// The stream index of the block. It moves to the first value after the run, or to the end of the stream. + /// The stream index of the first value of the open run, or -1 when no run is open. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void SkipRun(ReadOnlySpan values, ref uint histogram, ref int position, ref int runStart) + { + uint value = values[position - 1]; + int run = values[position..].IndexOfAnyExcept(value); + run = run < 0 ? values.Length - position : run; + JxlHybridUint.Encode420(value, out uint token, out _, out _); + Unsafe.Add(ref histogram, token) += (uint)run; + + // The equality of the block opens a run at the block when no run is open. The first value after the run closes it. + if (runStart < 0) + { + runStart = position; + } + + position += run; + } + + /// + /// Adds the tokens of one vector block to the four partial histograms. Lane i goes to histogram i mod 4. + /// + /// The first count of the four histograms. + /// The first token of the block. Each token is less than . + /// The number of tokens. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AddTokens(ref uint histogram, ref uint tokens, int count) + { + for (nuint lane = 0; lane < (uint)count; lane++) + { + Unsafe.Add(ref histogram, ((lane & 3) * TokenAlphabetSize) + Unsafe.Add(ref tokens, lane))++; + } + } + + /// + /// Starts and ends the runs of one block from its equality mask. Bit i is set when value i of the block is equal to the value before it. + /// + /// The equality mask of the block. + /// The number of values of the block, at most 16. + /// The stream index of the first value of the block. + /// The runs of at least values. + /// The number of runs. + /// The stream index of the first value of the open run, or -1 when no run is open. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AddRuns(uint equal, int count, int position, Span runs, ref int runCount, ref int runStart) + { + // An open run means that the value before the block was equal to its previous value. Each bit of the transitions is a change of + // the equality from the value before: a run starts at a set bit of the mask and ends at a clear bit. Starts and ends alternate. + uint before = (equal << 1) | (runStart >= 0 ? 1U : 0U); + uint transitions = (equal ^ before) & ((1U << count) - 1); + while (transitions != 0) + { + int index = position + BitOperations.TrailingZeroCount(transitions); + if (runStart < 0) + { + runStart = index; + } + else + { + AddRun(runs, ref runCount, runStart, index - runStart); + runStart = -1; + } + + transitions &= transitions - 1; + } + } + + /// + /// Adds a run to the run list when it is long enough for a copy. + /// + /// The runs: the start, then the length of each run. + /// The number of runs. + /// The stream index of the first value of the run. + /// The number of values of the run. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AddRun(Span runs, ref int runCount, int start, int length) + { + if (length >= CopyMinimumLength) + { + runs[2 * runCount] = start; + runs[(2 * runCount) + 1] = length; + runCount++; + } + } + + /// + /// Appends the fields of literal values to the 64-bit field buffer. The caller makes sure that the output buffer has space for + /// 8 bytes for each value plus 8 bytes. + /// + /// The literal values, in stream order. + /// The first entry of the symbol table of . + /// The field buffer. Fewer than 64 bits are pending before and after the call. + /// The number of pending bits. + /// The number of bytes in the output buffer. + /// The output buffer. + private static void AppendLiterals( + ReadOnlySpan values, + ref int table, + ref ulong buffer, + ref int bufferBits, + ref int bufferedBytes, + Span output) + { + // The writes use locals, because writes through the reference parameters would go to memory at each field. The callees are + // inlined, so the locals stay in registers. + ulong bits = buffer; + int pending = bufferBits; + int written = bufferedBytes; + ref uint source = ref MemoryMarshal.GetReference(values); + InlineArray8 fieldStorage = default; + InlineArray8 fieldBitStorage = default; + ref ulong fields = ref Unsafe.As, ulong>(ref fieldStorage); + ref ulong fieldBits = ref Unsafe.As, ulong>(ref fieldBitStorage); + int position = 0; + + // Each block gives one joined field for each pair of values. A block with a field wider than 32 bits writes its values one by one. + if (Vector512.IsHardwareAccelerated) + { + nuint count = values.Vector512Count(); + for (nuint block = 0; block < count; block++, position += Vector512.Count) + { + Vector512 lanes = Vector512.LoadUnsafe(ref source, (nuint)position); + if (PrefixFieldOperator.TryGetFields(lanes, ref table, out Vector512 blockFields, out Vector512 blockBits)) + { + blockFields.StoreUnsafe(ref fields); + blockBits.StoreUnsafe(ref fieldBits); + AppendFields(ref fields, ref fieldBits, Vector512.Count, ref bits, ref pending, ref written, output); + } + else + { + AppendLiteralFields(values.Slice(position, Vector512.Count), ref table, ref bits, ref pending, ref written, output); + } + } + } + + if (Vector256.IsHardwareAccelerated) + { + nuint count = values[position..].Vector256Count(); + for (nuint block = 0; block < count; block++, position += Vector256.Count) + { + Vector256 lanes = Vector256.LoadUnsafe(ref source, (nuint)position); + if (PrefixFieldOperator.TryGetFields(lanes, ref table, out Vector256 blockFields, out Vector256 blockBits)) + { + blockFields.StoreUnsafe(ref fields); + blockBits.StoreUnsafe(ref fieldBits); + AppendFields(ref fields, ref fieldBits, Vector256.Count, ref bits, ref pending, ref written, output); + } + else + { + AppendLiteralFields(values.Slice(position, Vector256.Count), ref table, ref bits, ref pending, ref written, output); + } + } + } + + if (Vector128.IsHardwareAccelerated) + { + nuint count = values[position..].Vector128Count(); + for (nuint block = 0; block < count; block++, position += Vector128.Count) + { + Vector128 lanes = Vector128.LoadUnsafe(ref source, (nuint)position); + if (PrefixFieldOperator.TryGetFields(lanes, ref table, out Vector128 blockFields, out Vector128 blockBits)) + { + blockFields.StoreUnsafe(ref fields); + blockBits.StoreUnsafe(ref fieldBits); + AppendFields(ref fields, ref fieldBits, Vector128.Count, ref bits, ref pending, ref written, output); + } + else + { + AppendLiteralFields(values.Slice(position, Vector128.Count), ref table, ref bits, ref pending, ref written, output); + } + } + } + + AppendLiteralFields(values[position..], ref table, ref bits, ref pending, ref written, output); + buffer = bits; + bufferBits = pending; + bufferedBytes = written; + } + + /// + /// Appends the fields of literal values one by one to the 64-bit field buffer. + /// + /// The literal values, in stream order. + /// The first entry of the symbol table of . + /// The field buffer. Fewer than 64 bits are pending before and after the call. + /// The number of pending bits. + /// The number of bytes in the output buffer. + /// The output buffer. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AppendLiteralFields( + ReadOnlySpan values, + ref int table, + ref ulong buffer, + ref int bufferBits, + ref int bufferedBytes, + Span output) + { + foreach (uint value in values) + { + ulong field = PrefixFieldOperator.GetField(value, ref table, out int fieldBits); + AppendField(field, fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + } + } + + /// + /// Appends the stored joined fields of one vector block to the 64-bit field buffer. + /// + /// The first stored field. + /// The first stored bit count. + /// The number of fields. + /// The field buffer. Fewer than 64 bits are pending before and after the call. + /// The number of pending bits. + /// The number of bytes in the output buffer. + /// The output buffer. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AppendFields( + ref ulong fields, + ref ulong fieldBits, + int count, + ref ulong buffer, + ref int bufferBits, + ref int bufferedBytes, + Span output) + { + for (nuint field = 0; field < (uint)count; field++) + { + AppendField(Unsafe.Add(ref fields, field), (int)Unsafe.Add(ref fieldBits, field), ref buffer, ref bufferBits, ref bufferedBytes, output); + } + } + + /// + /// Appends one field of at most 64 bits to the 64-bit field buffer, least-significant bit first. The caller makes sure that the + /// output buffer has space for 8 bytes past the written bytes. + /// + /// The field, with all bits above clear. + /// The number of bits of the field, from 0 to 64. + /// The field buffer. Fewer than 64 bits are pending before and after the call. + /// The number of pending bits. + /// The number of bytes in the output buffer. + /// The output buffer. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AppendField(ulong field, int fieldBits, ref ulong buffer, ref int bufferBits, ref int bufferedBytes, Span output) + { + // The buffer bytes are stored at each field, so a full buffer only moves on by 8 bytes. The bits of the field that did not fit + // start the next buffer. The shift is in two steps because a shift of a ulong by 64 bits does not clear it. + buffer |= field << bufferBits; + BinaryPrimitives.WriteUInt64LittleEndian(output[bufferedBytes..], buffer); + int shift = 64 - bufferBits; + bufferBits += fieldBits; + if (bufferBits >= 64) + { + buffer = (field >> (shift - 1)) >> 1; + bufferBits -= 64; + bufferedBytes += sizeof(ulong); + } + } + + /// + /// Appends one coded symbol and the extra bits of its value to a bit reservoir held in locals. The caller makes sure that the output + /// buffer has space for the complete words. + /// + /// The prefix code of the symbol, least-significant bit first. + /// The code length. It is 0 for the only symbol of a code. + /// The extra bits of the value. + /// The number of extra bits. + /// The bit reservoir. Fewer than 32 bits are pending before and after the call. + /// The number of pending bits. + /// The number of bytes in the output buffer. + /// The output buffer. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AppendSymbol( + uint code, + int codeLength, + uint extraBits, + int extraBitCount, + ref ulong bits, + ref int pendingBits, + ref int bufferedBytes, + Span output) + { + // A field of at most 32 bits is one append. A code has at most 15 bits and a value at most 31 extra bits, so a wider field + // appends the code first. Then fewer than 32 pending bits and the extra bits fit the 64-bit reservoir. + if (codeLength + extraBitCount > 32) + { + bits |= (ulong)code << pendingBits; + pendingBits += codeLength; + if (pendingBits >= 32) + { + BinaryPrimitives.WriteUInt32LittleEndian(output[bufferedBytes..], (uint)bits); + bufferedBytes += sizeof(uint); + bits >>= 32; + pendingBits -= 32; + } + + code = extraBits; + codeLength = extraBitCount; + } + else + { + code |= extraBits << codeLength; + codeLength += extraBitCount; + } + + bits |= (ulong)code << pendingBits; + pendingBits += codeLength; + if (pendingBits >= 32) + { + BinaryPrimitives.WriteUInt32LittleEndian(output[bufferedBytes..], (uint)bits); + bufferedBytes += sizeof(uint); + bits >>= 32; + pendingBits -= 32; + } + } + + /// + /// Writes the hybrid integer configuration 4/2/0 for an alphabet of 2^logAlphabetSize symbols: the split exponent, then the + /// leading and the trailing token bit counts, each with the bits that the remaining width needs. + /// + /// The base-2 logarithm of the alphabet size: 15 for prefix codes. + /// The retained output buffer. + private void WriteSplit420Configuration(int logAlphabetSize, Span output) + { + this.WriteBits(32 - BitOperations.LeadingZeroCount((uint)logAlphabetSize), 4, output); + this.WriteBits(3, 2, output); + this.WriteBits(2, 0, output); + } + + /// + /// Gets the alphabet size of a cluster: one more than its last used symbol, and at least 1. + /// + /// The symbol counts. + /// The alphabet size. + private static int GetAlphabetSize(ReadOnlySpan counts) + { + int last = counts.LastIndexOfAnyExcept(0U); + return last < 0 ? 1 : last + 1; + } + + /// + /// Writes an alphabet size in the variable-length 16-bit format: 0 as one bit, else one bit, 4 bits of the exponent and the bits + /// below the leading one of the size minus one. + /// + /// The alphabet size, from 1 to 2^15. + /// The retained output buffer. + private void WriteAlphabetSize(int alphabetSize, Span output) + { + uint value = (uint)(alphabetSize - 1); + if (value == 0) + { + this.WriteBits(1, 0, output); + return; + } + + int exponent = BitOperations.Log2(value); + this.WriteBits(1, 1, output); + this.WriteBits(4, (uint)exponent, output); + this.WriteBits(exponent, value - (1U << exponent), output); + } + + /// + /// Builds the length-limited prefix code of a histogram and writes it in the Brotli format (RFC 7932, section 3.4 and 3.5). + /// + /// + /// An alphabet of one symbol has no stored code. A histogram with at most 4 used symbols uses the simple form: the symbols in order of + /// their code length. Other histograms store the code lengths with the code-length code, whose lengths use a fixed code. + /// + /// The symbol counts. The length is the alphabet size. + /// Receives the code length of each symbol. The only used symbol of a code gets length 0. + /// + /// Receives the code of each used symbol, least-significant bit first. The only used symbol of a code gets code 0, so the symbol + /// writes no bits. + /// + /// The retained output buffer. + private void WritePrefixCode(ReadOnlySpan counts, Span lengths, Span codes, Span output) + { + // The writers add each code to the bit reservoir without a mask, so a code without bits must be 0. The callers reuse the code + // buffers between streams. + lengths.Clear(); + codes.Clear(); + if (counts.Length == 1) + { + // The decoder reads no code for a one-symbol alphabet. The symbol has no code bits. + return; + } + + InlineArray4 usedStorage = default; + Span used = usedStorage; + int usedCount = 0; + for (int i = 0; i < counts.Length && usedCount <= 4; i++) + { + if (counts[i] != 0) + { + if (usedCount < 4) + { + used[usedCount] = i; + } + + usedCount++; + } + } + + // The simple form stores each symbol with the bits of the largest symbol index. + int symbolBits = 32 - BitOperations.LeadingZeroCount((uint)(counts.Length - 1)); + if (usedCount <= 1) + { + // One used symbol in a larger alphabet: the simple form with one symbol. The symbol has no code bits. + this.WriteBits(2, 1, output); + this.WriteBits(2, 0, output); + this.WriteBits(symbolBits, (uint)(usedCount == 0 ? 0 : used[0]), output); + return; + } + + this.BuildCodeLengths(counts, MaximumPrefixCodeLength, lengths); + BuildCodes(lengths, codes); + + if (usedCount <= 4) + { + // The decoder gives the code lengths by position: 2 symbols get 1 bit; 3 symbols get 1, 2, 2; 4 symbols get 2 bits each, or + // 1, 2, 3, 3 when the tree-select bit is set. So the symbols go in order of their code length. + Span symbols = used[..usedCount]; + for (int i = 1; i < symbols.Length; i++) + { + int symbol = symbols[i]; + int j = i - 1; + for (; j >= 0 && lengths[symbols[j]] > lengths[symbol]; j--) + { + symbols[j + 1] = symbols[j]; + } + + symbols[j + 1] = symbol; + } + + this.WriteBits(2, 1, output); + this.WriteBits(2, (uint)(usedCount - 1), output); + foreach (int symbol in symbols) + { + this.WriteBits(symbolBits, (uint)symbol, output); + } + + if (usedCount == 4) + { + this.WriteBits(1, lengths[symbols[0]] == 1 ? 1U : 0U, output); + } + + return; + } + + this.WriteCodeLengths(lengths, output); + } + + /// + /// Writes the code lengths of a prefix code with the code-length code (RFC 7932, section 3.5). A run of equal nonzero lengths uses + /// symbol 16 and a run of zeros uses symbol 17, as libjxl does. + /// + /// The code lengths. The code is complete. + /// The retained output buffer. + private void WriteCodeLengths(ReadOnlySpan lengths, Span output) + { + // A code with many symbols has at most one token for each length, so the token buffer has the alphabet size. + using IMemoryOwner tokenOwner = this.memoryAllocator.Allocate(2 * lengths.Length); + Span tokens = tokenOwner.GetSpan()[..lengths.Length]; + Span extraBits = tokenOwner.GetSpan().Slice(lengths.Length, lengths.Length); + int tokenCount = GetCodeLengthTokens(lengths, tokens, extraBits); + tokens = tokens[..tokenCount]; + extraBits = extraBits[..tokenCount]; + + InlineArray18 histogramStorage = default; + Span histogram = histogramStorage; + foreach (byte token in tokens) + { + histogram[token]++; + } + + int usedTokens = 0; + int onlyToken = 0; + for (int i = 0; i < CodeLengthCodeCount; i++) + { + if (histogram[i] != 0) + { + usedTokens++; + onlyToken = i; + } + } + + // The code-length code is limited to 5 bits. + InlineArray18 tokenLengthStorage = default; + InlineArray18 tokenCodeStorage = default; + Span tokenLengths = tokenLengthStorage; + Span tokenCodes = tokenCodeStorage; + this.BuildCodeLengths(histogram, 5, tokenLengths); + BuildCodes(tokenLengths, tokenCodes); + + // Skip the trailing unused entries in the storage order, and 2 or 3 leading unused entries. + ReadOnlySpan order = CodeLengthCodeOrder; + int stored = CodeLengthCodeCount; + if (usedTokens > 1) + { + while (stored > 0 && tokenLengths[order[stored - 1]] == 0) + { + stored--; + } + } + + int skip = 0; + if (tokenLengths[order[0]] == 0 && tokenLengths[order[1]] == 0) + { + skip = tokenLengths[order[2]] == 0 ? 3 : 2; + } + + this.WriteBits(2, (uint)skip, output); + for (int i = skip; i < stored; i++) + { + int length = tokenLengths[order[i]]; + this.WriteBits(CodeLengthLengthBits[length], CodeLengthLengthCodes[length], output); + } + + // A code-length code with one used token has no code bits for it. + if (usedTokens == 1) + { + tokenLengths[onlyToken] = 0; + } + + for (int i = 0; i < tokens.Length; i++) + { + int token = tokens[i]; + this.WriteBits(tokenLengths[token], tokenCodes[token], output); + if (token == 16) + { + this.WriteBits(2, extraBits[i], output); + } + else if (token == 17) + { + this.WriteBits(3, extraBits[i], output); + } + } + } + + /// + /// Converts code lengths to the tokens of the code-length code. The trailing zero lengths are not stored. A run uses the repeat + /// symbols only when the runs of the code are long enough, as libjxl decides it. + /// + /// The code lengths. + /// Receives the tokens. + /// Receives the extra bits of each token. + /// The number of tokens. + private static int GetCodeLengthTokens(ReadOnlySpan lengths, Span tokens, Span extraBits) + { + int length = lengths.LastIndexOfAnyExcept((byte)0) + 1; + lengths = lengths[..length]; + + // Runs are worth their repeat symbols only when the code has many of them. + bool repeatNonZero = false; + bool repeatZero = false; + if (lengths.Length > 50) + { + int totalZero = 0; + int totalNonZero = 0; + int runsZero = 1; + int runsNonZero = 1; + for (int i = 0; i < lengths.Length;) + { + byte value = lengths[i]; + int run = lengths[i..].IndexOfAnyExcept(value); + run = run < 0 ? lengths.Length - i : run; + if (run >= 3 && value == 0) + { + totalZero += run; + runsZero++; + } + + if (run >= 4 && value != 0) + { + totalNonZero += run; + runsNonZero++; + } + + i += run; + } + + repeatNonZero = totalNonZero > runsNonZero * 2; + repeatZero = totalZero > runsZero * 2; + } + + int count = 0; + byte previous = 8; + for (int i = 0; i < lengths.Length;) + { + byte value = lengths[i]; + int run = 1; + if ((value != 0 && repeatNonZero) || (value == 0 && repeatZero)) + { + run = lengths[i..].IndexOfAnyExcept(value); + run = run < 0 ? lengths.Length - i : run; + } + + count = value == 0 + ? AddZeroRun(run, tokens, extraBits, count) + : AddLengthRun(previous, value, run, tokens, extraBits, count); + + if (value != 0) + { + previous = value; + } + + i += run; + } + + return count; + } + + /// + /// Adds the tokens of a run of one nonzero code length. Symbol 16 repeats the previous length 3 to 6 times, and a sequence of + /// symbols 16 multiplies the counts, so the run is written as base-4 digits, the most significant first. + /// + /// The previous nonzero length. + /// The length of the run. + /// The number of lengths in the run. + /// The tokens. + /// The extra bits of the tokens. + /// The number of tokens before the run. + /// The number of tokens after the run. + private static int AddLengthRun(byte previous, byte value, int run, Span tokens, Span extraBits, int count) + { + if (previous != value) + { + tokens[count] = value; + extraBits[count++] = 0; + run--; + } + + if (run == 7) + { + tokens[count] = value; + extraBits[count++] = 0; + run--; + } + + if (run < 3) + { + for (int i = 0; i < run; i++) + { + tokens[count] = value; + extraBits[count++] = 0; + } + + return count; + } + + run -= 3; + int start = count; + while (true) + { + tokens[count] = 16; + extraBits[count++] = (byte)(run & 3); + run >>= 2; + if (run == 0) + { + break; + } + + run--; + } + + tokens[start..count].Reverse(); + extraBits[start..count].Reverse(); + return count; + } + + /// + /// Adds the tokens of a run of zero code lengths. Symbol 17 repeats zero 3 to 10 times, and a sequence of symbols 17 multiplies the + /// counts, so the run is written as base-8 digits, the most significant first. + /// + /// The number of zeros. + /// The tokens. + /// The extra bits of the tokens. + /// The number of tokens before the run. + /// The number of tokens after the run. + private static int AddZeroRun(int run, Span tokens, Span extraBits, int count) + { + if (run == 11) + { + tokens[count] = 0; + extraBits[count++] = 0; + run--; + } + + if (run < 3) + { + for (int i = 0; i < run; i++) + { + tokens[count] = 0; + extraBits[count++] = 0; + } + + return count; + } + + run -= 3; + int start = count; + while (true) + { + tokens[count] = 17; + extraBits[count++] = (byte)(run & 7); + run >>= 3; + if (run == 0) + { + break; + } + + run--; + } + + tokens[start..count].Reverse(); + extraBits[start..count].Reverse(); + return count; + } + + /// + /// Builds the length-limited Huffman code lengths of a histogram with the shared owner. + /// + /// The symbol counts. + /// The largest code length. + /// Receives the code length of each symbol, 0 for an unused symbol. + private void BuildCodeLengths(ReadOnlySpan counts, int limit, Span lengths) + { + // The tree needs 3 nodes for each used symbol. + using IMemoryOwner treeOwner = this.memoryAllocator.Allocate(3 * counts.Length); + lengths.Clear(); + HuffmanCodeLengths.GenerateOptimalTree(treeOwner.GetSpan(), counts, counts.Length, limit, lengths); + } + + /// + /// Builds the canonical codes of code lengths, least-significant bit first, with the shared table builder that the decoder uses. + /// + /// The code lengths. The code is complete. + /// Receives the code of each used symbol. + private static void BuildCodes(ReadOnlySpan lengths, Span codes) + { + InlineArray264 lengthStorage = default; + InlineArray264 sortedStorage = default; + Span intLengths = lengthStorage[..lengths.Length]; + for (int i = 0; i < lengths.Length; i++) + { + intLengths[i] = lengths[i]; + } + + _ = HuffmanTableBuilder.Build([], 8, intLengths, sortedStorage[..lengths.Length], codes); + } + + /// + /// Groups histograms into clusters with the fast clustering of libjxl for prefix codes. The histogram with the largest count starts + /// the first cluster. Then the histogram farthest from all clusters starts the next cluster, until all histograms are near a cluster. + /// Each other histogram then joins its nearest cluster. + /// + /// The histograms, with counts each. + /// Receives the cluster of each histogram. An empty histogram gets cluster 0. The length is the histogram count. + /// Receives the counts of each cluster, with counts each. + /// + /// Scratch for the totals and the used token lengths of the histograms and of the clusters. The length is twice the histogram count + /// plus the cluster limit. + /// + /// Scratch for the entropies and the distances. The length is twice the histogram count plus the cluster limit. + /// The number of clusters. + private static int ClusterHistograms( + ReadOnlySpan histograms, + Span clusterOf, + Span clusters, + Span totals, + Span scratch) + { + const byte unassigned = byte.MaxValue; + int count = clusterOf.Length; + Span clusterTotals = totals.Slice(count, MaximumClusterCount); + Span entropies = scratch[..count]; + Span distances = scratch.Slice(count, count); + Span clusterEntropies = scratch.Slice(2 * count, MaximumClusterCount); + int maximum = Math.Min(MaximumClusterCount, count); + + // Each histogram and cluster keeps the length of its used tokens: one more than its last used token. The distance loops stop + // there, because most contexts use few tokens. + Span lengths = MemoryMarshal.Cast(totals.Slice(count + MaximumClusterCount, count + MaximumClusterCount)); + Span clusterLengths = lengths.Slice(count, MaximumClusterCount); + int largest = 0; + for (int i = 0; i < count; i++) + { + ReadOnlySpan histogram = histograms.Slice(i * TokenAlphabetSize, TokenAlphabetSize); + lengths[i] = histogram.LastIndexOfAnyExcept(0U) + 1; + histogram = histogram[..lengths[i]]; + uint total = 0; + foreach (uint value in histogram) + { + total += value; + } + + totals[i] = total; + entropies[i] = GetEntropy(histogram, total); + + // A distance of zero marks a histogram that needs no cluster search: an empty histogram, or a cluster seed. + distances[i] = total == 0 ? 0F : float.MaxValue; + clusterOf[i] = total == 0 ? (byte)0 : unassigned; + if (total > totals[largest]) + { + largest = i; + } + } + + int clusterCount = 0; + while (clusterCount < maximum) + { + Span cluster = clusters.Slice(clusterCount * TokenAlphabetSize, TokenAlphabetSize); + histograms.Slice(largest * TokenAlphabetSize, TokenAlphabetSize).CopyTo(cluster); + clusterLengths[clusterCount] = lengths[largest]; + clusterTotals[clusterCount] = totals[largest]; + clusterEntropies[clusterCount] = entropies[largest]; + clusterOf[largest] = (byte)clusterCount; + distances[largest] = 0F; + + // Each distance is the distance to the nearest cluster. Only the new cluster can make it smaller. + largest = 0; + for (int i = 0; i < count; i++) + { + if (distances[i] == 0F) + { + continue; + } + + int length = Math.Max(lengths[i], clusterLengths[clusterCount]); + float distance = GetClusterDistance( + histograms.Slice(i * TokenAlphabetSize, length), + totals[i], + entropies[i], + cluster[..length], + clusterTotals[clusterCount], + clusterEntropies[clusterCount]); + + distances[i] = Math.Min(distance, distances[i]); + if (distances[i] > distances[largest]) + { + largest = i; + } + } + + clusterCount++; + if (distances[largest] < MinimumDistinctClusterDistance) + { + break; + } + } + + for (int i = 0; i < count; i++) + { + if (clusterOf[i] != unassigned) + { + continue; + } + + ReadOnlySpan histogram = histograms.Slice(i * TokenAlphabetSize, TokenAlphabetSize); + int best = 0; + float bestDistance = float.MaxValue; + for (int j = 0; j < clusterCount; j++) + { + int length = Math.Max(lengths[i], clusterLengths[j]); + float distance = GetClusterDistance( + histogram[..length], + totals[i], + entropies[i], + clusters.Slice(j * TokenAlphabetSize, length), + clusterTotals[j], + clusterEntropies[j]); + + if (distance < bestDistance) + { + best = j; + bestDistance = distance; + } + } + + Span cluster = clusters.Slice(best * TokenAlphabetSize, TokenAlphabetSize); + for (int k = 0; k < lengths[i]; k++) + { + cluster[k] += histogram[k]; + } + + clusterLengths[best] = Math.Max(clusterLengths[best], lengths[i]); + clusterTotals[best] += totals[i]; + clusterEntropies[best] = GetEntropy(cluster[..clusterLengths[best]], clusterTotals[best]); + clusterOf[i] = (byte)best; + } + + return clusterCount; + } + + /// + /// Gets the Shannon entropy of a histogram in bits: the sum of -count * log2(count / total). A histogram with one used symbol has + /// zero entropy. + /// + /// The counts. + /// The sum of the counts. + /// The entropy. + private static float GetEntropy(ReadOnlySpan histogram, uint total) + { + float entropy = 0F; + float inverseTotal = 1F / total; + foreach (uint count in histogram) + { + if (count != 0 && count != total) + { + entropy -= count * MathF.Log2(count * inverseTotal); + } + } + + return entropy; + } + + /// + /// Gets the cost in bits of the merge of two histograms, as libjxl measures it for prefix codes: the entropy of the merged histogram + /// minus the entropies of the two histograms. A prefix code gives a symbol at least one bit when it has two or more symbols, so the + /// merge costs at least one bit for each value of a histogram with one used symbol. + /// + /// The counts of the first histogram. + /// The total of the first histogram. + /// The entropy of the first histogram. + /// The counts of the second histogram. + /// The total of the second histogram. + /// The entropy of the second histogram. + /// The merge cost. + private static float GetClusterDistance( + ReadOnlySpan a, + uint totalA, + float entropyA, + ReadOnlySpan b, + uint totalB, + float entropyB) + { + if (totalA == 0 || totalB == 0) + { + return 0F; + } + + uint total = totalA + totalB; + float inverseTotal = 1F / total; + float entropy = 0F; + int symbolsA = 0; + int symbolsB = 0; + int symbols = 0; + for (int k = 0; k < a.Length; k++) + { + uint count = a[k] + b[k]; + if (count == 0) + { + continue; + } + + symbols++; + symbolsA += a[k] != 0 ? 1 : 0; + symbolsB += b[k] != 0 ? 1 : 0; + if (count != total) + { + entropy -= count * MathF.Log2(count * inverseTotal); + } + } + + float distance = entropy - entropyA - entropyB; + if (symbols <= 1) + { + return distance; + } + + float single = (symbolsA <= 1 ? totalA : 0F) + (symbolsB <= 1 ? totalB : 0F); + return Math.Max(distance, single); + } + + /// + /// Writes the entropy code of a histogram set with prefix codes and without copies: the stream header with the context map, then the + /// 4/2/0 hybrid integer configuration, the alphabet size and the prefix code of each cluster. + /// + /// + /// The method numbers the clusters in the order of their first context, as libjxl does. Then the context map is dense from zero. + /// + /// The cluster of each context. The method renumbers the clusters in place. + /// The counts of each cluster, with counts each. + /// The number of clusters. + /// Receives the new number of each old cluster. The length is twice the cluster limit. + /// Scratch for the context map streams. The length is twice the context count. + /// Receives the code lengths of each cluster in the new order, with entries each. + /// Receives the codes of each cluster in the new order, with entries each. + /// The retained output buffer. + private void WriteHistogramCodes( + Span contextMap, + ReadOnlySpan clusters, + int clusterCount, + Span renumber, + Span values, + Span lengths, + Span codes, + Span output) + { + renumber[..clusterCount].Fill(byte.MaxValue); + int next = 0; + for (int i = 0; i < contextMap.Length; i++) + { + byte cluster = contextMap[i]; + if (renumber[cluster] == byte.MaxValue) + { + renumber[cluster] = (byte)next++; + } + + contextMap[i] = renumber[cluster]; + } + + this.WriteBits(1, 0, output); // No copies. + this.WriteContextMap(contextMap, clusterCount, values, output); + + // The old number of each new number. Each cluster has a context, so each old number has a new number. + Span inverse = renumber.Slice(MaximumClusterCount, clusterCount); + for (int c = 0; c < clusterCount; c++) + { + inverse[renumber[c]] = (byte)c; + } + + this.WriteBits(1, 1, output); // Prefix codes. + for (int c = 0; c < clusterCount; c++) + { + this.WriteSplit420Configuration(MaximumPrefixCodeLength, output); + } + + // The alphabet sizes come before all codes, so each size is kept for the code of its cluster. + InlineArray4 alphabetSizeStorage = default; + Span alphabetSizes = alphabetSizeStorage; + for (int c = 0; c < clusterCount; c++) + { + alphabetSizes[c] = GetAlphabetSize(clusters.Slice(inverse[c] * TokenAlphabetSize, TokenAlphabetSize)); + this.WriteAlphabetSize(alphabetSizes[c], output); + } + + for (int c = 0; c < clusterCount; c++) + { + ReadOnlySpan cluster = clusters.Slice(inverse[c] * TokenAlphabetSize, TokenAlphabetSize); + int alphabetSize = alphabetSizes[c]; + this.WritePrefixCode( + cluster[..alphabetSize], + lengths.Slice(c * TokenAlphabetSize, alphabetSize), + codes.Slice(c * TokenAlphabetSize, alphabetSize), + output); + } + } + + /// + /// Writes a context map in the smallest of its forms, as libjxl selects it: the simple form with fixed-width entries when the entries + /// need fewer than 4 bits, or an entropy-coded stream of the entries, with or without the move-to-front transform. + /// + /// The cluster of each context, dense from zero. + /// The number of clusters. + /// Scratch for the two entropy-coded forms. The length is twice the context count. + /// The retained output buffer. + private void WriteContextMap(ReadOnlySpan contextMap, int clusterCount, Span values, Span output) + { + if (clusterCount == 1) + { + this.WriteBits(1, 1, output); // Simple context map. + this.WriteBits(2, 0, output); // Zero bits for each entry: every context uses cluster 0. + return; + } + + // The plain entries, then their move-to-front ranks: the rank of each cluster in the list of the clusters by last use. + Span plain = values[..contextMap.Length]; + Span moved = values.Slice(contextMap.Length, contextMap.Length); + InlineArray256 orderStorage = default; + Span order = orderStorage; + for (int i = 0; i < order.Length; i++) + { + order[i] = (byte)i; + } + + for (int i = 0; i < contextMap.Length; i++) + { + byte cluster = contextMap[i]; + int rank = order.IndexOf(cluster); + plain[i] = cluster; + moved[i] = (uint)rank; + order[..rank].CopyTo(order[1..]); + order[0] = cluster; + } + + // Measure each entropy-coded form by writing it. The whole buffered bytes go to the stream first, so the stream position and + // the bit reservoir restore the writer. + this.outputStream.Write(output[..this.bufferedBytes]); + this.bufferedBytes = 0; + long position = this.outputStream.Position; + ulong bits = this.bits; + int pendingBits = this.pendingBits; + + this.WriteContextMapStream(plain, false, output); + long plainBits = this.GetWrittenBits(position, pendingBits); + this.RestoreBits(position, bits, pendingBits); + + this.WriteContextMapStream(moved, true, output); + long movedBits = this.GetWrittenBits(position, pendingBits); + this.RestoreBits(position, bits, pendingBits); + + int entryBits = 32 - BitOperations.LeadingZeroCount((uint)(clusterCount - 1)); + long simpleBits = (long)entryBits * contextMap.Length; + if (entryBits < 4 && simpleBits < plainBits && simpleBits < movedBits) + { + this.WriteBits(1, 1, output); // Simple context map. + this.WriteBits(2, (uint)entryBits, output); + foreach (byte cluster in contextMap) + { + this.WriteBits(entryBits, cluster, output); + } + + return; + } + + bool useMoveToFront = movedBits < plainBits; + this.WriteContextMapStream(useMoveToFront ? moved : plain, useMoveToFront, output); + } + + /// + /// Writes the entropy-coded form of a context map: the form bit, the move-to-front bit, and the entries as a stream with one context. + /// + /// The entries, plain or as move-to-front ranks. + /// Whether the entries are move-to-front ranks. + /// The retained output buffer. + private void WriteContextMapStream(ReadOnlySpan entries, bool moveToFront, Span output) + { + this.WriteBits(1, 0, output); // Entropy-coded context map. + this.WriteBits(1, moveToFront ? 1U : 0U, output); + + // The entries have one context and no row width, so a copy from the entry before uses distance symbol 0. + this.WriteSampleStream(entries, 1, 0, output); + } + + /// + /// Gets the number of bits written since a stream position and a pending bit count. + /// + /// The stream position at the start. The buffered byte count was zero at the start. + /// The pending bit count at the start. + /// The number of bits. + private long GetWrittenBits(long position, int pendingBits) + => ((this.outputStream.Position - position + this.bufferedBytes) * 8) + this.pendingBits - pendingBits; + + /// + /// Restores the writer to a stream position and a bit reservoir. The buffered byte count was zero at that position. + /// + /// The stream position. + /// The bit reservoir. + /// The pending bit count. + private void RestoreBits(long position, ulong bits, int pendingBits) + { + this.outputStream.Position = position; + this.bits = bits; + this.pendingBits = pendingBits; + this.bufferedBytes = 0; + } +} diff --git a/src/ImageSharp/Formats/Jxl/JxlEncoderCore.FastLossless.cs b/src/ImageSharp/Formats/Jxl/JxlEncoderCore.FastLossless.cs new file mode 100644 index 0000000000..3eb595e064 --- /dev/null +++ b/src/ImageSharp/Formats/Jxl/JxlEncoderCore.FastLossless.cs @@ -0,0 +1,1671 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Buffers; +using System.Buffers.Binary; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Formats.Jxl.Components.ColorConverters; +using SixLabors.ImageSharp.Formats.Jxl.Components.Entropy; +using SixLabors.ImageSharp.Formats.Jxl.Components.Modular; +using SixLabors.ImageSharp.Memory; +using SixLabors.ImageSharp.PixelFormats; + +namespace SixLabors.ImageSharp.Formats.Jxl; + +/// +/// Contains the fast lossless mode, the lossless mode of libjxl at effort 1. +/// +/// +/// The frame has one global tree with one leaf for each channel, so each channel has its own prefix code, and all groups share the +/// codes. Three color channels use the YCoCg color transform. All leaves use the clamped gradient predictor. The residuals use the +/// hybrid integer configuration 0/0/0. A run of zero residuals becomes one zero literal and a copy of distance 1. The codes come from +/// the residuals of a few rows in the center of each group, added to a fixed base histogram. The code lengths of the literals are +/// limited, as libjxl limits them, so that a literal field is short. +/// +internal sealed partial class JxlEncoderCore +{ + /// + /// The number of residuals that the run decision of the fast lossless mode looks at together. A run starts or ends only at the + /// borders of these chunks. libjxl uses 32 with AVX-512. The size is fixed here, so all instruction sets give the same output. + /// + private const int FastChunkSize = 32; + + /// + /// The shortest copy of the fast lossless mode. A run of zeros is one zero literal and a copy, so a run has at least 8 zeros. + /// + private const int FastCopyMinimumLength = 7; + + /// + /// The number of literal symbols of a fast lossless code: the 0/0/0 tokens of residuals below 2^18. + /// + private const int FastRawSymbolCount = 19; + + /// + /// The number of copy-length symbols of a fast lossless code: the 4/0/0 tokens of the lengths. + /// + private const int FastCopySymbolCount = 33; + + /// + /// The number of short runs whose complete field each code keeps. + /// + private const int FastRunCacheSize = 32; + + /// + /// The largest number of bytes that one row of a channel writes, with the copy that ends the channel and the 8 bytes that the field + /// writer stores past the written bytes. A chunk writes at most one run field of 39 bits (8 bits of the zero literal, 15 code bits + /// and 16 extra bits for a run of at most 2^16 values) and 32 literals of at most 26 bits (8 code bits and 18 extra bits). The + /// longest row is a palette row of at most 512 values, with 16 chunks: 13936 bits, or 1742 bytes. + /// + private const int FastRowBytes = 2048; + + /// + /// The number of entries of the color hash table of the palette detection. + /// + private const int FastPaletteHashSize = 1 << 16; + + /// + /// The largest number of palette colors, with the color 0. A palette index is then at most 511, so its gradient residual has at most + /// 10 bits, as a sample of 8 bits with YCoCg. + /// + private const int FastMaximumPaletteColors = 512; + + /// + /// Gets the base literal counts of libjxl. They are added to the sampled counts times 256. + /// + private static ReadOnlySpan FastBaseRawCounts => [3843, 852, 1270, 1214, 1014, 727, 481, 300, 159, 51, 5, 1, 1, 1, 1, 1, 1, 1, 1]; + + /// + /// Gets the base copy-length counts of libjxl. They are added to the sampled counts times 256. + /// + private static ReadOnlySpan FastBaseCopyCounts => + [29, 27, 25, 23, 21, 21, 19, 18, 21, 17, 16, 15, 15, 14, 13, 13, 137, 98, 61, 34, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]; + + /// + /// Gets the shortest code lengths of the literal symbols and the copy symbol of samples of at most 8 bits: no limit. + /// + private static ReadOnlySpan FastMinimumLengths8 => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + + /// + /// Gets the longest code lengths of the literal symbols and the copy symbol of samples of at most 8 bits. A literal field then has + /// at most 16 bits. + /// + private static ReadOnlySpan FastMaximumLengths8 => [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 10]; + + /// + /// Gets the shortest code lengths of the literal symbols and the copy symbol of samples of 9 to 13 bits: no limit. + /// + private static ReadOnlySpan FastMinimumLengths13 => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + + /// + /// Gets the longest code lengths of the literal symbols and the copy symbol of samples of 9 to 13 bits. + /// + private static ReadOnlySpan FastMaximumLengths13 => [8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10]; + + /// + /// Gets the shortest code lengths of the literal symbols and the copy symbol of samples of 14 bits. + /// + private static ReadOnlySpan FastMinimumLengths14 => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 7]; + + /// + /// Gets the longest code lengths of the literal symbols and the copy symbol of samples of 14 bits. + /// + private static ReadOnlySpan FastMaximumLengths14 => [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 10]; + + /// + /// Gets the shortest code lengths of the literal symbols and the copy symbol of samples of 15 and 16 bits. + /// + private static ReadOnlySpan FastMinimumLengths16 => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 7]; + + /// + /// Gets the longest code lengths of the literal symbols and the copy symbol of samples of 15 and 16 bits. + /// + private static ReadOnlySpan FastMaximumLengths16 => [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 10]; + + /// + /// Gets the token values of the global tree: one split on the channel property for each of the three inner nodes, then the four + /// leaves. A split is the property plus one and the packed split value: channel greater than 1, then greater than 2 and greater + /// than 0. A leaf is 0, the gradient predictor 5, no offset, multiplier exponent 0 and multiplier 1 stored as 0. So the leaves hold + /// channels 3, 2, 1 and 0, in this order. + /// + private static ReadOnlySpan FastTreeValues => [1, 2, 1, 4, 1, 0, 0, 5, 0, 0, 0, 0, 5, 0, 0, 0, 0, 5, 0, 0, 0, 0, 5, 0, 0, 0]; + + /// + /// Gets the fields of the tree values 0 to 5: the 2-bit code of the 0/0/0 token, least-significant bit first, then the extra bits. + /// + private static ReadOnlySpan FastTreeFields => [0b00, 0b10, 0b001, 0b101, 0b0011, 0b0111]; + + /// + /// Gets the bit counts of . + /// + private static ReadOnlySpan FastTreeFieldBits => [2, 2, 3, 3, 4, 4]; + + /// + /// Writes one frame with the fast lossless mode: the global section with the tree and the codes, then the groups. + /// + /// + /// libjxl at effort 1 runs this mode with effort 2, and the sampling and the palette rules below use that effort. An 8-bit frame + /// with few colors codes palette indices instead of the color channels. + /// + /// The source pixel type. + /// The closed color packing operator. + /// The closed alpha packing operator. + /// The closed black packing operator. + /// The closed alpha reconstruction operator. + /// The source frame. + /// Whether the frame has one section, which holds the global data and the only group. + /// Whether conversion clears hidden transparent colors. + /// The reusable working pixel row. + /// The reusable conversion rows. + /// The retained section lengths. + /// The retained output buffer. + /// The selected color sample operation. + /// The selected alpha sample operation. + /// The selected black sample operation. + /// The selected alpha reconstruction. + /// The token checked between groups and rows. + private void WriteFastLosslessFrame( + ImageFrame image, + bool combined, + bool clearTransparent, + Span pixelRow, + Span floatRows, + Span sectionSizes, + Span output, + TColor colorOperation, + TAlpha alphaOperation, + TBlack blackOperation, + TAlphaDecode alphaDecodeOperation, + CancellationToken cancellationToken) + where TPixel : unmanaged, IPixel + where TColor : struct, JxlSampleConverter.IConversionOperator + where TAlpha : struct, JxlSampleConverter.IConversionOperator + where TBlack : struct, JxlSampleConverter.IConversionOperator + where TAlphaDecode : struct, JxlSampleConverter.IConversionOperator + { + // Only 8-bit integer samples can use a palette. The color hash table holds each color at the hash of its packed components, and + // the lookup table holds the palette index at the same hash. + int depth = this.bitDepth.BitsPerSample; + bool paletteDepth = depth == 8 && this.bitDepth.ExponentBits == 0; + using IMemoryOwner? paletteOwner = paletteDepth ? this.memoryAllocator.Allocate(FastPaletteHashSize, AllocationOptions.Clean) : null; + using IMemoryOwner? lookupOwner = paletteDepth ? this.memoryAllocator.Allocate(FastPaletteHashSize, AllocationOptions.Clean) : null; + Span palette = paletteOwner is null ? [] : paletteOwner.GetSpan(); + Span lookup = lookupOwner is null ? [] : lookupOwner.GetSpan(); + + // The residual row holds complete chunks of the longest row: a group row or a palette row. So a chunk at the end of a row reads + // inside the buffer. The palette code also uses it for the packed colors of a row. + using IMemoryOwner residualOwner = this.memoryAllocator.Allocate( + ((Math.Max(this.groupWidth, FastMaximumPaletteColors) + FastChunkSize - 1) / FastChunkSize) * FastChunkSize, + AllocationOptions.Clean); + + Span residuals = residualOwner.GetSpan(); + int paletteColors = 0; + if (paletteDepth) + { + paletteColors = this.DetectFastLosslessPalette( + image, + clearTransparent, + pixelRow, + floatRows, + palette, + lookup, + residuals, + colorOperation, + alphaOperation, + blackOperation, + alphaDecodeOperation, + cancellationToken); + } + + // The counts of the four channel codes: the literal counts of all channels, then the copy-length counts of all channels. + using IMemoryOwner countOwner = this.memoryAllocator.Allocate(4 * (FastRawSymbolCount + FastCopySymbolCount), AllocationOptions.Clean); + using IMemoryOwner codeOwner = this.memoryAllocator.Allocate(4); + Span rawCounts = countOwner.GetSpan()[..(4 * FastRawSymbolCount)]; + Span copyCounts = countOwner.GetSpan().Slice(4 * FastRawSymbolCount, 4 * FastCopySymbolCount); + Span codes = codeOwner.GetSpan()[..4]; + + // The palette indices of a frame with one section use the second code, because the global section holds the palette before + // them. Otherwise the groups hold only the indices, which use the first code. + int indexCode = combined ? 1 : 0; + + // The sampling reads 4 rows of each full group: the rows in the center of the group, after one row that only gives the + // predictions. It reads complete chunks of each row only. + for (int index = 0; index < this.groupCount; index++) + { + cancellationToken.ThrowIfCancellationRequested(); + Rectangle bounds = this.GetGroupBounds(image, index); + int sampleRows = 4 * bounds.Height / GroupDimension; + int sampleStart = Math.Max(0, bounds.Height - sampleRows) / 2; + int sampleCount = Math.Max(0, Math.Min(sampleRows, bounds.Height - sampleStart - 1)); + int sampleWidth = bounds.Width / FastChunkSize * FastChunkSize; + if (sampleCount == 0 || sampleWidth == 0) + { + continue; + } + + Rectangle sampleBounds = new(bounds.X, bounds.Y + sampleStart, sampleWidth, sampleCount + 1); + this.ConvertRows( + image, + sampleBounds, + clearTransparent, + pixelRow, + floatRows, + colorOperation, + alphaOperation, + blackOperation, + alphaDecodeOperation, + cancellationToken); + + if (paletteColors != 0) + { + this.ApplyFastLosslessPalette(sampleBounds.Size, lookup, residuals); + CollectFastLosslessChannel( + this.GetComponentRegion(0), + sampleBounds.Size, + residuals, + rawCounts.Slice(indexCode * FastRawSymbolCount, FastRawSymbolCount), + copyCounts.Slice(indexCode * FastCopySymbolCount, FastCopySymbolCount)); + + continue; + } + + this.ApplyFastLosslessColorTransform(sampleBounds.Size); + for (int component = 0; component < this.componentCount; component++) + { + CollectFastLosslessChannel( + this.GetComponentRegion(component), + sampleBounds.Size, + residuals, + rawCounts.Slice(component * FastRawSymbolCount, FastRawSymbolCount), + copyCounts.Slice(component * FastCopySymbolCount, FastCopySymbolCount)); + } + } + + // The literal symbols above the largest token of the samples get no base count. YCoCg adds one bit to the chroma channels, and + // the gradient residual adds one more bit. A palette index has at most 9 bits. + int symbolCount = depth <= 13 ? depth + (this.colorComponents == 3 || paletteColors != 0 ? 3 : 2) : depth == 14 ? 17 : 19; + for (int c = 0; c < 4; c++) + { + Span raw = rawCounts.Slice(c * FastRawSymbolCount, FastRawSymbolCount); + Span copy = copyCounts.Slice(c * FastCopySymbolCount, FastCopySymbolCount); + for (int i = 0; i < raw.Length; i++) + { + raw[i] = (raw[i] << 8) + (i < symbolCount ? FastBaseRawCounts[i] : 0U); + } + + for (int i = 0; i < copy.Length; i++) + { + copy[i] = (copy[i] << 8) + FastBaseCopyCounts[i]; + } + } + + if (paletteColors != 0) + { + // The first code also codes the palette. Each token up to the token of the largest index residual gets a code, and the + // tokens above it up to 9, which only the palette can use, get the count 1. + JxlHybridUint.Zero.Encode((uint)(2 * (paletteColors - 1)), out uint paletteToken, out _, out _); + for (int i = 0; i <= paletteToken; i++) + { + rawCounts[i] = Math.Max(rawCounts[i], 1UL); + } + + for (int i = (int)paletteToken + 1; i < 10; i++) + { + rawCounts[i] = 1; + } + } + + ReadOnlySpan minimum = depth <= 8 ? FastMinimumLengths8 + : depth <= 13 ? FastMinimumLengths13 : depth == 14 ? FastMinimumLengths14 : FastMinimumLengths16; + + ReadOnlySpan maximum = depth <= 8 ? FastMaximumLengths8 + : depth <= 13 ? FastMaximumLengths13 : depth == 14 ? FastMaximumLengths14 : FastMaximumLengths16; + + for (int c = 0; c < 4; c++) + { + this.BuildFastLosslessCode( + rawCounts.Slice(c * FastRawSymbolCount, FastRawSymbolCount), + copyCounts.Slice(c * FastCopySymbolCount, FastCopySymbolCount), + minimum, + maximum, + ref codes[c]); + } + + // A literal of a sample of at most 8 bits has at most 16 bits, so four literals fit one field. + bool narrow = depth <= 8; + this.WriteFastLosslessGlobal(codes, paletteColors, output); + if (paletteColors != 0) + { + this.WriteFastLosslessPalette(palette, paletteColors, ref codes[0], residuals, output, cancellationToken); + } + + if (!combined) + { + // The global section has no samples, because each channel is larger than one group. The DC sections and the AC-global + // section are empty. + this.FlushBits(output); + sectionSizes[0] = GetSectionSize(this.payload.Position); + } + + for (int index = 0; index < this.groupCount; index++) + { + cancellationToken.ThrowIfCancellationRequested(); + Rectangle bounds = this.GetGroupBounds(image, index); + long sectionStart = combined ? 0 : this.payload.Position; + this.ConvertRows( + image, bounds, clearTransparent, pixelRow, floatRows, colorOperation, alphaOperation, blackOperation, alphaDecodeOperation, cancellationToken); + + if (!combined) + { + // The group stream header: the global tree, the default weighted predictor and no transforms. + this.WriteBits(1, 1, output); + this.WriteBits(1, 1, output); + this.WriteBits(2, 0, output); + } + + if (paletteColors != 0) + { + this.ApplyFastLosslessPalette(bounds.Size, lookup, residuals); + this.WriteFastLosslessChannel(this.GetComponentRegion(0), bounds.Size, ref codes[indexCode], residuals, narrow, output, cancellationToken); + } + else + { + // The decoder reads the channels one after the other, so each channel writes all its rows. + this.ApplyFastLosslessColorTransform(bounds.Size); + for (int component = 0; component < this.componentCount; component++) + { + this.WriteFastLosslessChannel( + this.GetComponentRegion(component), bounds.Size, ref codes[component], residuals, narrow, output, cancellationToken); + } + } + + this.FlushBits(output); + sectionSizes[combined ? 0 : 2 + this.dcGroupCount + index] = GetSectionSize(this.payload.Position - sectionStart); + } + } + + /// + /// Finds the palette of an 8-bit frame as libjxl finds it, and fills the index lookup table. + /// + /// + /// Each color goes to the slot of its hash in the color table. A slot that already holds a different color is a collision, and the + /// frame then has no palette. The color 0 is always index 0. A palette needs at most colors, + /// and a gray frame needs few colors for its range of levels. The other colors get indices in the order of their luma, times alpha + /// with four channels. Equal keys keep the order of the packed colors. + /// + /// The source pixel type. + /// The closed color packing operator. + /// The closed alpha packing operator. + /// The closed black packing operator. + /// The closed alpha reconstruction operator. + /// The source frame. + /// Whether conversion clears hidden transparent colors. + /// The reusable working pixel row. + /// The reusable conversion rows. + /// The cleared color hash table. It receives the palette colors without the color 0, in index order. + /// The cleared lookup table. It receives the index of each palette color at the hash of the color. + /// The scratch for the packed colors of one row, at least one group row long. + /// The selected color sample operation. + /// The selected alpha sample operation. + /// The selected black sample operation. + /// The selected alpha reconstruction. + /// The token checked before each row. + /// The number of palette colors with the color 0, or 0 when the frame has no palette. + private int DetectFastLosslessPalette( + ImageFrame image, + bool clearTransparent, + Span pixelRow, + Span floatRows, + Span palette, + Span lookup, + Span colors, + TColor colorOperation, + TAlpha alphaOperation, + TBlack blackOperation, + TAlphaDecode alphaDecodeOperation, + CancellationToken cancellationToken) + where TPixel : unmanaged, IPixel + where TColor : struct, JxlSampleConverter.IConversionOperator + where TAlpha : struct, JxlSampleConverter.IConversionOperator + where TBlack : struct, JxlSampleConverter.IConversionOperator + where TAlphaDecode : struct, JxlSampleConverter.IConversionOperator + { + // The rows are converted one at a time, so the detection stops at the first row with a collision. The first color is never + // equal to the previous color, because a packed color has at most 32 bits and the previous color starts above them. + ulong previous = ulong.MaxValue; + for (int index = 0; index < this.groupCount; index++) + { + Rectangle bounds = this.GetGroupBounds(image, index); + for (int y = 0; y < bounds.Height; y++) + { + this.ConvertRows( + image, + new Rectangle(bounds.X, bounds.Y + y, bounds.Width, 1), + clearTransparent, + pixelRow, + floatRows, + colorOperation, + alphaOperation, + blackOperation, + alphaDecodeOperation, + cancellationToken); + + // A color equal to the color before it finds its own slot with itself, so it changes nothing and is skipped. + bool collided = false; + Span rowColors = colors[..bounds.Width]; + this.PackFastPaletteRow(0, rowColors); + foreach (uint color in rowColors) + { + if (color == previous) + { + continue; + } + + previous = color; + ref uint slot = ref palette[GetFastPaletteHash(color)]; + collided |= slot != 0 && slot != color; + slot = color; + } + + if (collided) + { + return 0; + } + } + } + + // Move the colors to the front of the table, in table order. The color 0 is always a palette color. + int paletteColors = 1; + int entries = 0; + bool hasColor = false; + int minimumGreen = 255; + int maximumGreen = 0; + for (int k = 0; k < palette.Length; k++) + { + uint color = palette[k]; + if (color == 0) + { + continue; + } + + palette[entries++] = color; + int red = (int)(color & 0xFF); + int green = (int)((color >> 8) & 0xFF); + int blue = (int)((color >> 16) & 0xFF); + hasColor |= red != green || red != blue; + minimumGreen = Math.Min(minimumGreen, green); + maximumGreen = Math.Max(maximumGreen, green); + if (entries + paletteColors > FastMaximumPaletteColors) + { + return 0; + } + } + + // A gray frame with nearly all levels of its range codes better without a palette. + if (!hasColor && maximumGreen - minimumGreen < entries * 1.4F) + { + return 0; + } + + Span entryColors = palette[..entries]; + entryColors.Sort(new FastPaletteComparer(this.componentCount == 4)); + foreach (uint color in entryColors) + { + lookup[GetFastPaletteHash(color)] = (short)paletteColors++; + } + + return paletteColors; + } + + /// + /// Packs the components of one converted row into palette colors: component c in byte c. + /// + /// The row in the group. + /// Receives the packed colors. The length is the row width. + private void PackFastPaletteRow(int y, Span colors) + { + // The first component sets the colors, and each other component adds its byte. The components are 8-bit, so the bytes do not + // overlap. + for (int c = 0; c < this.componentCount; c++) + { + ReadOnlySpan row = MemoryMarshal.Cast(this.GetComponentRow(c, y)[..colors.Length]); + ref uint source = ref MemoryMarshal.GetReference(row); + ref uint destination = ref MemoryMarshal.GetReference(colors); + int shift = 8 * c; + nuint x = 0; + nuint length = (uint)colors.Length; + if (Vector512.IsHardwareAccelerated) + { + for (; x + (uint)Vector512.Count <= length; x += (uint)Vector512.Count) + { + Vector512 value = Vector512.LoadUnsafe(ref source, x) << shift; + (c == 0 ? value : value | Vector512.LoadUnsafe(ref destination, x)).StoreUnsafe(ref destination, x); + } + } + + if (Vector256.IsHardwareAccelerated) + { + for (; x + (uint)Vector256.Count <= length; x += (uint)Vector256.Count) + { + Vector256 value = Vector256.LoadUnsafe(ref source, x) << shift; + (c == 0 ? value : value | Vector256.LoadUnsafe(ref destination, x)).StoreUnsafe(ref destination, x); + } + } + + if (Vector128.IsHardwareAccelerated) + { + for (; x + (uint)Vector128.Count <= length; x += (uint)Vector128.Count) + { + Vector128 value = Vector128.LoadUnsafe(ref source, x) << shift; + (c == 0 ? value : value | Vector128.LoadUnsafe(ref destination, x)).StoreUnsafe(ref destination, x); + } + } + + for (; x < length; x++) + { + uint value = Unsafe.Add(ref source, x) << shift; + Unsafe.Add(ref destination, x) = c == 0 ? value : value | Unsafe.Add(ref destination, x); + } + } + } + + /// + /// Gets the slot of a packed color in the color hash table: the top 16 bits of the color times a large odd constant. The color 0 + /// has the slot 0. + /// + /// The packed color. + /// The slot. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int GetFastPaletteHash(uint color) => (int)((color * 2654435761U) >> 16); + + /// + /// Replaces the first component row of each converted row with the palette index of each sample. + /// + /// The size of the converted rows. + /// The lookup table of the palette indices. + /// The scratch for the packed colors of one row, at least one group row long. + private void ApplyFastLosslessPalette(Size size, ReadOnlySpan lookup, Span colors) + { + Span rowColors = colors[..size.Width]; + for (int y = 0; y < size.Height; y++) + { + // The colors are packed before the first component row receives the indices. + // A color equal to the color before it has the same index. + this.PackFastPaletteRow(y, rowColors); + Span indices = this.GetComponentRow(0, y)[..size.Width]; + ulong previous = ulong.MaxValue; + int index = 0; + for (int x = 0; x < indices.Length; x++) + { + uint color = rowColors[x]; + if (color != previous) + { + previous = color; + index = lookup[GetFastPaletteHash(color)]; + } + + indices[x] = index; + } + } + } + + /// + /// Writes the palette channel of the global section: one row for each component, and one column for each palette color. The first + /// column is the color 0. + /// + /// The palette colors without the color 0, in index order. + /// The number of palette colors with the color 0. + /// The code of the palette channel. + /// The residual row buffer. + /// The retained output buffer. + /// The token checked before each row. + private void WriteFastLosslessPalette( + ReadOnlySpan palette, + int colors, + ref FastLosslessCode code, + Span residuals, + Span output, + CancellationToken cancellationToken) + { + using Buffer2D channel = this.memoryAllocator.Allocate2D(colors, this.componentCount); + for (int c = 0; c < this.componentCount; c++) + { + Span row = channel.DangerousGetRowSpan(c); + row[0] = 0; + for (int i = 1; i < colors; i++) + { + row[i] = (int)((palette[i - 1] >> (8 * c)) & 0xFF); + } + } + + this.WriteFastLosslessChannel(channel.GetRegion(), new Size(colors, this.componentCount), ref code, residuals, true, output, cancellationToken); + } + + /// + /// Gets the rows of one converted component of the group. + /// + /// The component. + /// The component rows. + private Buffer2DRegion GetComponentRegion(int component) + => this.sampleRegion.GetSubRegion(0, component * this.groupHeight, this.groupWidth, this.groupHeight); + + /// + /// Converts the RGB rows of the converted group to YCoCg in place. One color channel has no color transform. + /// + /// The size of the converted rows. + private void ApplyFastLosslessColorTransform(Size size) + { + if (this.colorComponents != 3) + { + return; + } + + for (int y = 0; y < size.Height; y++) + { + JxlModularColorTransform.ApplyRgbToYCoCg( + this.GetComponentRow(0, y)[..size.Width], + this.GetComponentRow(1, y)[..size.Width], + this.GetComponentRow(2, y)[..size.Width]); + } + } + + /// + /// Counts the literal and copy-length tokens of the sampled rows of one channel. The first row only gives the predictions of the + /// second row. The run that is open at the end is not counted, as libjxl does, because its length is not known. + /// + /// The rows of the channel. + /// The size of the converted rows. The width is a multiple of . + /// The residual row buffer. + /// The literal counts of the channel. + /// The copy-length counts of the channel. + private static void CollectFastLosslessChannel( + Buffer2DRegion channel, + Size size, + Span residuals, + Span rawCounts, + Span copyCounts) + { + ref uint source = ref MemoryMarshal.GetReference(residuals); + int run = 0; + for (int y = 1; y < size.Height; y++) + { + JxlModularPredictor.PackGradientResiduals( + channel.DangerousGetRowSpan(y)[..size.Width], + channel.DangerousGetRowSpan(y - 1)[..size.Width], + residuals[..size.Width]); + + for (int x = 0; x < size.Width; x += FastChunkSize) + { + ref uint chunk = ref Unsafe.Add(ref source, (uint)x); + int count = Math.Min(FastChunkSize, size.Width - x); + int prefix = Math.Min(count, BitOperations.TrailingZeroCount(~FastLosslessFieldOperator.GetZeroMask(ref chunk))); + if (ContinueFastRun(ref run, prefix, count, out int completed, out int skip)) + { + continue; + } + + // A run is one zero literal and one copy. + if (completed != 0) + { + rawCounts[0]++; + JxlHybridUint.Split400.Encode((uint)(completed - FastCopyMinimumLength - 1), out uint copyToken, out _, out _); + copyCounts[(int)copyToken]++; + } + + for (int i = skip; i < count; i++) + { + JxlHybridUint.Zero.Encode(Unsafe.Add(ref chunk, (uint)i), out uint token, out _, out _); + rawCounts[(int)token]++; + } + } + } + } + + /// + /// Applies the run rule of libjxl to one chunk. A chunk that is all zeros continues an open run, or opens a run when it is longer + /// than . Otherwise an open run, with the leading zeros of the chunk, ends when it is longer than + /// , and the rest of the chunk is literals. Shorter runs are literals. + /// + /// The length of the open run: 0, or more than . + /// The number of leading zero residuals of the chunk. + /// The number of residuals of the chunk. + /// The length of the run that ends before the literals, or 0 when no run ends. + /// The number of leading residuals of the chunk that the completed run holds. + /// when the chunk only continues the run, so it has no literals. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool ContinueFastRun(ref int run, int prefix, int count, out int completed, out int skip) + { + if (prefix == count && (run > 0 || prefix > FastCopyMinimumLength)) + { + run += prefix; + completed = 0; + skip = 0; + return true; + } + + if (run + prefix > FastCopyMinimumLength) + { + completed = run + prefix; + skip = prefix; + } + else + { + // The run is 0 here, because an open run is longer than the minimum. + completed = 0; + skip = 0; + } + + run = 0; + return false; + } + + /// + /// Writes the residuals of one channel with its fast lossless code. + /// + /// The rows of the channel. + /// The channel size. + /// The code of the channel. + /// The residual row buffer. + /// Whether each literal field has at most 16 bits, so four literals fit one field. + /// The retained output buffer. + /// The token checked before each row. + private void WriteFastLosslessChannel( + Buffer2DRegion channel, + Size size, + ref FastLosslessCode code, + Span residuals, + bool narrow, + Span output, + CancellationToken cancellationToken) + { + // The bit state stays in locals, as in WriteSampleStream. The helpers that take it by reference are inlined. + ulong buffer = this.bits; + int bufferBits = this.pendingBits; + int bufferedBytes = this.bufferedBytes; + ref uint source = ref MemoryMarshal.GetReference(residuals); + ref int table = ref Unsafe.As, int>(ref code.Raw); + InlineArray8 fieldStorage = default; + InlineArray8 fieldBitStorage = default; + ref ulong fields = ref Unsafe.As, ulong>(ref fieldStorage); + ref ulong fieldBits = ref Unsafe.As, ulong>(ref fieldBitStorage); + int run = 0; + + for (int y = 0; y < size.Height; y++) + { + cancellationToken.ThrowIfCancellationRequested(); + if (bufferedBytes > output.Length - FastRowBytes) + { + this.outputStream.Write(output[..bufferedBytes]); + bufferedBytes = 0; + } + + JxlModularPredictor.PackGradientResiduals( + channel.DangerousGetRowSpan(y)[..size.Width], + y == 0 ? [] : channel.DangerousGetRowSpan(y - 1)[..size.Width], + residuals[..size.Width]); + + for (int x = 0; x < size.Width; x += FastChunkSize) + { + // Each chunk is loaded once. The zero mask of the loaded lanes decides the run, then the same lanes give the literal + // fields. The lanes outside the literals of the chunk give empty fields. + ref uint chunk = ref Unsafe.Add(ref source, (uint)x); + int count = Math.Min(FastChunkSize, size.Width - x); + if (Vector512.IsHardwareAccelerated) + { + Vector512 v0 = Vector512.LoadUnsafe(ref chunk); + Vector512 v1 = Vector512.LoadUnsafe(ref chunk, 16); + uint zeros = FastLosslessFieldOperator.GetZeroMask(v0) | (FastLosslessFieldOperator.GetZeroMask(v1) << 16); + if (!BeginFastChunk(zeros, count, ref run, ref code, out int skip, ref buffer, ref bufferBits, ref bufferedBytes, output)) + { + continue; + } + + AppendFastBlock(v0, 0, skip, count, narrow, ref table, ref fields, ref fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + AppendFastBlock(v1, 16, skip, count, narrow, ref table, ref fields, ref fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + } + else if (Vector256.IsHardwareAccelerated) + { + Vector256 v0 = Vector256.LoadUnsafe(ref chunk); + Vector256 v1 = Vector256.LoadUnsafe(ref chunk, 8); + Vector256 v2 = Vector256.LoadUnsafe(ref chunk, 16); + Vector256 v3 = Vector256.LoadUnsafe(ref chunk, 24); + uint zeros = FastLosslessFieldOperator.GetZeroMask(v0) | (FastLosslessFieldOperator.GetZeroMask(v1) << 8) + | (FastLosslessFieldOperator.GetZeroMask(v2) << 16) | (FastLosslessFieldOperator.GetZeroMask(v3) << 24); + + if (!BeginFastChunk(zeros, count, ref run, ref code, out int skip, ref buffer, ref bufferBits, ref bufferedBytes, output)) + { + continue; + } + + AppendFastBlock(v0, 0, skip, count, narrow, ref table, ref fields, ref fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + AppendFastBlock(v1, 8, skip, count, narrow, ref table, ref fields, ref fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + AppendFastBlock(v2, 16, skip, count, narrow, ref table, ref fields, ref fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + AppendFastBlock(v3, 24, skip, count, narrow, ref table, ref fields, ref fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + } + else if (Vector128.IsHardwareAccelerated) + { + Vector128 v0 = Vector128.LoadUnsafe(ref chunk); + Vector128 v1 = Vector128.LoadUnsafe(ref chunk, 4); + Vector128 v2 = Vector128.LoadUnsafe(ref chunk, 8); + Vector128 v3 = Vector128.LoadUnsafe(ref chunk, 12); + Vector128 v4 = Vector128.LoadUnsafe(ref chunk, 16); + Vector128 v5 = Vector128.LoadUnsafe(ref chunk, 20); + Vector128 v6 = Vector128.LoadUnsafe(ref chunk, 24); + Vector128 v7 = Vector128.LoadUnsafe(ref chunk, 28); + uint zeros = FastLosslessFieldOperator.GetZeroMask(v0) | (FastLosslessFieldOperator.GetZeroMask(v1) << 4) + | (FastLosslessFieldOperator.GetZeroMask(v2) << 8) | (FastLosslessFieldOperator.GetZeroMask(v3) << 12) + | (FastLosslessFieldOperator.GetZeroMask(v4) << 16) | (FastLosslessFieldOperator.GetZeroMask(v5) << 20) + | (FastLosslessFieldOperator.GetZeroMask(v6) << 24) | (FastLosslessFieldOperator.GetZeroMask(v7) << 28); + + if (!BeginFastChunk(zeros, count, ref run, ref code, out int skip, ref buffer, ref bufferBits, ref bufferedBytes, output)) + { + continue; + } + + AppendFastBlock(v0, 0, skip, count, narrow, ref table, ref fields, ref fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + AppendFastBlock(v1, 4, skip, count, narrow, ref table, ref fields, ref fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + AppendFastBlock(v2, 8, skip, count, narrow, ref table, ref fields, ref fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + AppendFastBlock(v3, 12, skip, count, narrow, ref table, ref fields, ref fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + AppendFastBlock(v4, 16, skip, count, narrow, ref table, ref fields, ref fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + AppendFastBlock(v5, 20, skip, count, narrow, ref table, ref fields, ref fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + AppendFastBlock(v6, 24, skip, count, narrow, ref table, ref fields, ref fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + AppendFastBlock(v7, 28, skip, count, narrow, ref table, ref fields, ref fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + } + else + { + uint zeros = FastLosslessFieldOperator.GetZeroMask(ref chunk); + if (!BeginFastChunk(zeros, count, ref run, ref code, out int skip, ref buffer, ref bufferBits, ref bufferedBytes, output)) + { + continue; + } + + for (int i = skip; i < count; i++) + { + ulong field = FastLosslessFieldOperator.GetField(Unsafe.Add(ref chunk, (uint)i), ref table, out int literalBits); + AppendField(field, literalBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + } + } + } + } + + // The run that is open at the end of the channel ends with it. + if (run != 0) + { + AppendFastRun(ref code, run, ref buffer, ref bufferBits, ref bufferedBytes, output); + } + + // The other writers keep fewer than 32 pending bits. The buffer bytes are already stored, so a complete low word only moves on. + BinaryPrimitives.WriteUInt64LittleEndian(output[bufferedBytes..], buffer); + if (bufferBits >= 32) + { + bufferedBytes += sizeof(uint); + buffer >>= 32; + bufferBits -= 32; + } + + this.bits = buffer; + this.pendingBits = bufferBits; + this.bufferedBytes = bufferedBytes; + } + + /// + /// Appends the literal fields of one vector block of a chunk. A narrow block joins the fields once more, so each written field + /// holds four literals. + /// + /// The residuals of the block. + /// The index of the first lane of the block in the chunk. + /// The index of the first literal of the chunk. + /// The number of residuals of the chunk. The literals end there. + /// Whether each literal field has at most 16 bits. + /// The first entry of the literal table of the code. + /// The first element of the field stage. + /// The first element of the bit-count stage. + /// The field buffer. + /// The number of pending bits. + /// The number of bytes in the output buffer. + /// The output buffer. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AppendFastBlock( + Vector512 lanes, + int offset, + int skip, + int count, + bool narrow, + ref int table, + ref ulong fields, + ref ulong fieldBits, + ref ulong buffer, + ref int bufferBits, + ref int bufferedBytes, + Span output) + { + // A lane is a literal when its chunk index is from skip to count. The unsigned compare also rejects the lanes below skip. + Vector512 keep = Vector512.LessThan( + Vector512.Indices + Vector512.Create((uint)(offset - skip)), + Vector512.Create((uint)(count - skip))); + + FastLosslessFieldOperator.GetFields(lanes, keep, ref table, out Vector512 blockFields, out Vector512 blockBits); + if (narrow) + { + FastLosslessFieldOperator.JoinPairs(ref blockFields, ref blockBits); + } + + blockFields.StoreUnsafe(ref fields); + blockBits.StoreUnsafe(ref fieldBits); + AppendFastStage(ref fields, ref fieldBits, Vector512.Count, narrow, ref buffer, ref bufferBits, ref bufferedBytes, output); + } + + /// + /// Appends the literal fields of one vector block of a chunk. A narrow block joins the fields once more, so each written field + /// holds four literals. + /// + /// The residuals of the block. + /// The index of the first lane of the block in the chunk. + /// The index of the first literal of the chunk. + /// The number of residuals of the chunk. The literals end there. + /// Whether each literal field has at most 16 bits. + /// The first entry of the literal table of the code. + /// The first element of the field stage. + /// The first element of the bit-count stage. + /// The field buffer. + /// The number of pending bits. + /// The number of bytes in the output buffer. + /// The output buffer. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AppendFastBlock( + Vector256 lanes, + int offset, + int skip, + int count, + bool narrow, + ref int table, + ref ulong fields, + ref ulong fieldBits, + ref ulong buffer, + ref int bufferBits, + ref int bufferedBytes, + Span output) + { + // A lane is a literal when its chunk index is from skip to count. The unsigned compare also rejects the lanes below skip. + Vector256 keep = Vector256.LessThan( + Vector256.Indices + Vector256.Create((uint)(offset - skip)), + Vector256.Create((uint)(count - skip))); + + FastLosslessFieldOperator.GetFields(lanes, keep, ref table, out Vector256 blockFields, out Vector256 blockBits); + if (narrow) + { + FastLosslessFieldOperator.JoinPairs(ref blockFields, ref blockBits); + } + + blockFields.StoreUnsafe(ref fields); + blockBits.StoreUnsafe(ref fieldBits); + AppendFastStage(ref fields, ref fieldBits, Vector256.Count, narrow, ref buffer, ref bufferBits, ref bufferedBytes, output); + } + + /// + /// Appends the literal fields of one vector block of a chunk. A narrow block joins the fields once more, so each written field + /// holds four literals. + /// + /// The residuals of the block. + /// The index of the first lane of the block in the chunk. + /// The index of the first literal of the chunk. + /// The number of residuals of the chunk. The literals end there. + /// Whether each literal field has at most 16 bits. + /// The first entry of the literal table of the code. + /// The first element of the field stage. + /// The first element of the bit-count stage. + /// The field buffer. + /// The number of pending bits. + /// The number of bytes in the output buffer. + /// The output buffer. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AppendFastBlock( + Vector128 lanes, + int offset, + int skip, + int count, + bool narrow, + ref int table, + ref ulong fields, + ref ulong fieldBits, + ref ulong buffer, + ref int bufferBits, + ref int bufferedBytes, + Span output) + { + // A lane is a literal when its chunk index is from skip to count. The unsigned compare also rejects the lanes below skip. + Vector128 keep = Vector128.LessThan( + Vector128.Indices + Vector128.Create((uint)(offset - skip)), + Vector128.Create((uint)(count - skip))); + + FastLosslessFieldOperator.GetFields(lanes, keep, ref table, out Vector128 blockFields, out Vector128 blockBits); + if (narrow) + { + FastLosslessFieldOperator.JoinPairs(ref blockFields, ref blockBits); + } + + blockFields.StoreUnsafe(ref fields); + blockBits.StoreUnsafe(ref fieldBits); + AppendFastStage(ref fields, ref fieldBits, Vector128.Count, narrow, ref buffer, ref bufferBits, ref bufferedBytes, output); + } + + /// + /// Appends the stored fields of one vector block. After a narrow join, only the even elements hold fields. + /// + /// The first stored field. + /// The first stored bit count. + /// The number of stored elements. + /// Whether the fields were joined once more, so that only the even elements are fields. + /// The field buffer. + /// The number of pending bits. + /// The number of bytes in the output buffer. + /// The output buffer. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AppendFastStage( + ref ulong fields, + ref ulong fieldBits, + int count, + bool narrow, + ref ulong buffer, + ref int bufferBits, + ref int bufferedBytes, + Span output) + { + nuint step = narrow ? 2U : 1U; + for (nuint field = 0; field < (uint)count; field += step) + { + AppendField(Unsafe.Add(ref fields, field), (int)Unsafe.Add(ref fieldBits, field), ref buffer, ref bufferBits, ref bufferedBytes, output); + } + } + + /// + /// Applies the run rule to one chunk from its zero mask, and appends the run that the chunk ends. + /// + /// The zero mask of the chunk. Bit i is set when residual i is zero. + /// The number of residuals of the chunk. + /// The length of the open run. + /// The code of the channel. + /// The index of the first literal of the chunk. + /// The field buffer. + /// The number of pending bits. + /// The number of bytes in the output buffer. + /// The output buffer. + /// when the chunk has literals; when it only continues the run. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool BeginFastChunk( + uint zeros, + int count, + ref int run, + ref FastLosslessCode code, + out int skip, + ref ulong buffer, + ref int bufferBits, + ref int bufferedBytes, + Span output) + { + int prefix = Math.Min(count, BitOperations.TrailingZeroCount(~zeros)); + if (ContinueFastRun(ref run, prefix, count, out int completed, out skip)) + { + return false; + } + + if (completed != 0) + { + AppendFastRun(ref code, completed, ref buffer, ref bufferBits, ref bufferedBytes, output); + } + + return true; + } + + /// + /// Appends a run of zeros: one zero literal, then a copy of the rest with distance 1. The distance code has one symbol, so the + /// distance has no bits. + /// + /// The code of the channel. + /// The length of the run, more than . + /// The field buffer. + /// The number of pending bits. + /// The number of bytes in the output buffer. + /// The output buffer. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AppendFastRun(ref FastLosslessCode code, int run, ref ulong buffer, ref int bufferBits, ref int bufferedBytes, Span output) + { + // The copy has the length run - 1, and the stream header gives the shortest copy 7, so the length symbol holds run - 8. + int length = run - FastCopyMinimumLength - 1; + if (length < FastRunCacheSize) + { + AppendField(code.RunFields[length], code.RunBits[length], ref buffer, ref bufferBits, ref bufferedBytes, output); + return; + } + + ulong field = GetFastRunField(ref code, length, out int fieldBits); + AppendField(field, fieldBits, ref buffer, ref bufferBits, ref bufferedBytes, output); + } + + /// + /// Gets the field of a run of zeros: the zero literal, the copy-length code, then the extra bits of the length. + /// + /// The code of the channel. + /// The value of the copy length: the run length minus 8. + /// The number of bits of the field: at most 8 + 15 + 16. + /// The field, with all bits above clear. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static ulong GetFastRunField(ref FastLosslessCode code, int length, out int fieldBits) + { + JxlHybridUint.Split400.Encode((uint)length, out uint token, out int bitCount, out uint extraBits); + int zero = code.Raw[0]; + int copy = code.Copy[(int)token]; + int zeroLength = zero >> 16; + int copyLength = copy >> 16; + fieldBits = zeroLength + copyLength + bitCount; + return ((((ulong)extraBits << copyLength) | (uint)(copy & 0xFFFF)) << zeroLength) | (uint)(zero & 0xFFFF); + } + + /// + /// Builds the prefix code of one channel as libjxl builds it. The first level codes the literal symbols and one symbol that stands + /// for all copy-length symbols, with the length limits of the sample depth. The second level codes the copy-length symbols below + /// that symbol, so a copy-length code is the code of that symbol, then its own bits. + /// + /// The literal counts. + /// The copy-length counts. + /// The shortest code lengths of the first level, by symbol. + /// The longest code lengths of the first level, by symbol. + /// Receives the code. + private void BuildFastLosslessCode( + ReadOnlySpan rawCounts, + ReadOnlySpan copyCounts, + ReadOnlySpan minimum, + ReadOnlySpan maximum, + ref FastLosslessCode code) + { + code = default; + + // The first level: the used literal symbols, then the copy symbol with the sum of the copy-length counts. + int rawCount = rawCounts.LastIndexOfAnyExcept(0UL) + 1; + InlineArray24 levelStorage = default; + Span level = levelStorage[..(rawCount + 1)]; + rawCounts[..rawCount].CopyTo(level); + foreach (ulong count in copyCounts) + { + level[rawCount] += count; + } + + InlineArray24 levelLengthStorage = default; + Span levelLengths = levelLengthStorage[..(rawCount + 1)]; + this.BuildBoundedCodeLengths(level, minimum, maximum, levelLengths); + + // The second level fills the subtree of the copy symbol, so a copy-length code has at most 15 bits in total. + int copyCount = copyCounts.LastIndexOfAnyExcept(0UL) + 1; + InlineArray36 copyMinimumStorage = default; + InlineArray36 copyMaximumStorage = default; + InlineArray36 copyLengthStorage = default; + Span copyMaximum = copyMaximumStorage[..copyCount]; + Span copyLengths = copyLengthStorage[..copyCount]; + copyMaximum.Fill((byte)(MaximumPrefixCodeLength - levelLengths[rawCount])); + this.BuildBoundedCodeLengths(copyCounts[..copyCount], copyMinimumStorage[..copyCount], copyMaximum, copyLengths); + + // The codes are canonical over the symbol order of the stream: the literal symbols, then the copy-length symbols from 224. + InlineArray64 lengthStorage = default; + InlineArray64 bitStorage = default; + Span lengths = lengthStorage[..(FastRawSymbolCount + FastCopySymbolCount)]; + Span codeBits = bitStorage[..(FastRawSymbolCount + FastCopySymbolCount)]; + levelLengths[..rawCount].CopyTo(lengths); + for (int i = 0; i < copyCount; i++) + { + lengths[FastRawSymbolCount + i] = copyLengths[i] == 0 ? (byte)0 : (byte)(levelLengths[rawCount] + copyLengths[i]); + } + + BuildCodes(lengths, codeBits); + for (int i = 0; i < FastRawSymbolCount; i++) + { + code.Raw[i] = (int)(codeBits[i] | ((uint)lengths[i] << 16)); + } + + for (int i = 0; i < FastCopySymbolCount; i++) + { + code.Copy[i] = (int)(codeBits[FastRawSymbolCount + i] | ((uint)lengths[FastRawSymbolCount + i] << 16)); + } + + // The complete fields of the short runs. + for (int length = 0; length < FastRunCacheSize; length++) + { + code.RunFields[length] = GetFastRunField(ref code, length, out int fieldBits); + code.RunBits[length] = fieldBits; + } + } + + /// + /// Builds the code lengths with the least total cost under a shortest and a longest length for each symbol, as libjxl builds them. + /// The symbols without counts get no code. + /// + /// + /// The method finds the lengths by dynamic programming over the symbols and the used code space. The space is counted in units of + /// the longest length, so a code of length n uses 2^(longest - n) units, and a complete code uses all units. Entry (s, u) is the + /// least cost of the first s symbols that use u units. The last entry gives the least cost, and the path back gives the lengths. + /// + /// The symbol counts. + /// The shortest code length of each symbol. A limit below 1 is 1. + /// The longest code length of each symbol. + /// Receives the code length of each symbol. + private void BuildBoundedCodeLengths(ReadOnlySpan counts, ReadOnlySpan minimum, ReadOnlySpan maximum, Span lengths) + { + InlineArray36 frequencyStorage = default; + InlineArray36 lowStorage = default; + InlineArray36 highStorage = default; + InlineArray36 resultStorage = default; + int used = 0; + int precision = 0; + int shortest = 255; + ulong total = 0; + for (int i = 0; i < counts.Length; i++) + { + if (counts[i] == 0) + { + continue; + } + + frequencyStorage[used] = counts[i]; + lowStorage[used] = Math.Max(minimum[i], (byte)1); + highStorage[used] = maximum[i]; + precision = Math.Max(precision, highStorage[used]); + shortest = Math.Min(shortest, lowStorage[used]); + total += counts[i]; + used++; + } + + // When all shortest lengths are above 1, the space is counted as if the shortest were 1. + precision -= shortest - 1; + ulong infinity = total * (ulong)precision; + ReadOnlySpan frequencies = frequencyStorage[..used]; + Span result = resultStorage[..used]; + if (infinity < uint.MaxValue / 2) + { + this.SolveBoundedCodeLengths(frequencies, lowStorage[..used], highStorage[..used], precision, (uint)infinity, result); + } + else + { + this.SolveBoundedCodeLengths(frequencies, lowStorage[..used], highStorage[..used], precision, infinity, result); + } + + int next = 0; + for (int i = 0; i < counts.Length; i++) + { + lengths[i] = counts[i] == 0 ? (byte)0 : result[next++]; + } + } + + /// + /// Solves the length problem of for used symbols. + /// + /// The cost type: when twice the largest cost fits it, else . + /// The counts of the used symbols. + /// The shortest code length of each used symbol, at least 1. + /// The longest code length of each used symbol. + /// The base-2 logarithm of the number of space units. + /// A cost above all reachable costs. Twice this value fits . + /// Receives the code length of each used symbol. + private void SolveBoundedCodeLengths( + ReadOnlySpan frequencies, + ReadOnlySpan minimum, + ReadOnlySpan maximum, + int precision, + T infinity, + Span lengths) + where T : unmanaged, IBinaryInteger, IUnsignedNumber + { + int units = 1 << precision; + int stride = units + 1; + using IMemoryOwner tableOwner = this.memoryAllocator.Allocate(stride * (frequencies.Length + 1)); + Span table = tableOwner.GetSpan(); + table.Fill(infinity); + table[0] = T.Zero; + + // A symbol of length n moves each reachable entry of the previous row by 2^(precision - n) units. The rows are disjoint, so each + // move is one vector pass. + for (int symbol = 0; symbol < frequencies.Length; symbol++) + { + ReadOnlySpan previous = table.Slice(symbol * stride, stride); + Span current = table.Slice((symbol + 1) * stride, stride); + T frequency = T.CreateTruncating(frequencies[symbol]); + for (int length = minimum[symbol]; length <= maximum[symbol]; length++) + { + int step = 1 << (precision - length); + AddMinimum(previous[..(stride - step)], current[step..], frequency * T.CreateTruncating(length)); + } + } + + // The path back from the complete code gives the length of each symbol. + int unit = units; + for (int symbol = frequencies.Length - 1; symbol >= 0; symbol--) + { + T frequency = T.CreateTruncating(frequencies[symbol]); + T cost = table[((symbol + 1) * stride) + unit]; + for (int length = minimum[symbol]; length <= maximum[symbol]; length++) + { + int step = 1 << (precision - length); + if (step <= unit && cost == table[(symbol * stride) + unit - step] + (frequency * T.CreateTruncating(length))) + { + unit -= step; + lengths[symbol] = (byte)length; + break; + } + } + } + } + + /// + /// Sets each destination element to the smaller of itself and the source element plus a cost. + /// + /// The unsigned cost type. + /// The source row. + /// The destination row, with the length of the source. + /// The cost to add. + private static void AddMinimum(ReadOnlySpan source, Span destination, T cost) + where T : unmanaged, IBinaryInteger, IUnsignedNumber + { + ref T sourceStart = ref MemoryMarshal.GetReference(source); + ref T destinationStart = ref MemoryMarshal.GetReference(destination); + nuint i = 0; + nuint length = (uint)source.Length; + if (Vector512.IsHardwareAccelerated && length >= (uint)Vector512.Count) + { + Vector512 add = Vector512.Create(cost); + for (; i <= length - (uint)Vector512.Count; i += (uint)Vector512.Count) + { + Vector512 value = Vector512.LoadUnsafe(ref sourceStart, i) + add; + Vector512.Min(value, Vector512.LoadUnsafe(ref destinationStart, i)).StoreUnsafe(ref destinationStart, i); + } + } + + if (Vector256.IsHardwareAccelerated && length - i >= (uint)Vector256.Count) + { + Vector256 add = Vector256.Create(cost); + for (; i <= length - (uint)Vector256.Count; i += (uint)Vector256.Count) + { + Vector256 value = Vector256.LoadUnsafe(ref sourceStart, i) + add; + Vector256.Min(value, Vector256.LoadUnsafe(ref destinationStart, i)).StoreUnsafe(ref destinationStart, i); + } + } + + if (Vector128.IsHardwareAccelerated && length - i >= (uint)Vector128.Count) + { + Vector128 add = Vector128.Create(cost); + for (; i <= length - (uint)Vector128.Count; i += (uint)Vector128.Count) + { + Vector128 value = Vector128.LoadUnsafe(ref sourceStart, i) + add; + Vector128.Min(value, Vector128.LoadUnsafe(ref destinationStart, i)).StoreUnsafe(ref destinationStart, i); + } + } + + for (; i < length; i++) + { + T value = Unsafe.Add(ref sourceStart, i) + cost; + ref T target = ref Unsafe.Add(ref destinationStart, i); + target = T.Min(value, target); + } + } + + /// + /// Writes the global section of the fast lossless mode, as libjxl writes it: the global tree, the stream header with copies, the + /// context map, the five codes, and the stream header of the global modular image with the color transform. + /// + /// The four channel codes. + /// The number of palette colors with the color 0, or 0 when the frame has no palette. + /// The retained output buffer. + private void WriteFastLosslessGlobal(ReadOnlySpan codes, int paletteColors, Span output) + { + this.WriteBits(1, 1, output); // Default DC dequantization factors. + this.WriteBits(1, 1, output); // A global tree. + + // The tree stream: no copies, a simple context map with one cluster, and a prefix code with the configuration 0/0/0 and an + // alphabet of 4 symbols, as a simple code of 4 symbols with 2 bits each. + this.WriteBits(1, 0, output); + this.WriteBits(1, 1, output); + this.WriteBits(2, 0, output); + this.WriteBits(1, 1, output); + this.WriteBits(4, 0, output); + this.WriteAlphabetSize(4, output); + this.WriteBits(2, 1, output); + this.WriteBits(2, 3, output); + this.WriteBits(2, 0, output); + this.WriteBits(2, 1, output); + this.WriteBits(2, 2, output); + this.WriteBits(2, 3, output); + this.WriteBits(1, 0, output); + foreach (byte value in FastTreeValues) + { + this.WriteBits(FastTreeFieldBits[value], FastTreeFields[value], output); + } + + // The sample stream header: copies from symbol 224 with the shortest copy 7 and the length configuration 4/0/0. + this.WriteBits(1, 1, output); + this.WriteBits(2, 0, output); + this.WriteBits(2, 2, output); + this.WriteBits(2, 2, output); + this.WriteBits(4, 4, output); + this.WriteBits(3, 0, output); + this.WriteBits(3, 0, output); + + // A simple context map with 3 bits for each entry. The four leaf contexts hold channels 3 to 0 and use clusters 4 to 1. The + // distance context uses cluster 0. + this.WriteBits(1, 1, output); + this.WriteBits(2, 3, output); + this.WriteBits(3, 4, output); + this.WriteBits(3, 3, output); + this.WriteBits(3, 2, output); + this.WriteBits(3, 1, output); + this.WriteBits(3, 0, output); + + // Prefix codes with the configuration 0/0/0 for all clusters. The distance alphabet has 2 symbols, and each channel alphabet has + // the literal symbols and the copy-length symbols from 224. + this.WriteBits(1, 1, output); + for (int c = 0; c < 5; c++) + { + this.WriteBits(4, 0, output); + } + + this.WriteAlphabetSize(2, output); + for (int c = 0; c < 4; c++) + { + this.WriteAlphabetSize(224 + FastCopySymbolCount, output); + } + + // The distance code is a simple code with symbol 1, the distance (1, 0) of a modular stream. It has no bits. + this.WriteBits(2, 1, output); + this.WriteBits(2, 0, output); + this.WriteBits(1, 1, output); + for (int c = 0; c < codes.Length; c++) + { + this.WriteFastLosslessCode(in codes[c], output); + } + + // The stream header of the global modular image: the global tree, the default weighted predictor, then the transforms. + this.WriteBits(1, 1, output); + this.WriteBits(1, 1, output); + if (paletteColors != 0) + { + this.WriteBits(2, 1, output); // One transform. + this.WriteBits(2, 1, output); // The palette. + this.WriteBits(5, 0, output); // From channel 0. + + // The number of palette channels: 1, 3 and 4 have their own selectors. Other counts store the count minus one in 13 bits. + if (this.componentCount is 1 or 3 or 4) + { + this.WriteBits(2, this.componentCount == 1 ? 0U : this.componentCount == 3 ? 1U : 2U, output); + } + else + { + this.WriteBits(2, 3, output); + this.WriteBits(13, (uint)(this.componentCount - 1), output); + } + + // The number of colors: below 256 in 8 bits, else the count minus 256 in 10 bits. + if (paletteColors < 256) + { + this.WriteBits(2, 0, output); + this.WriteBits(8, (uint)paletteColors, output); + } + else + { + this.WriteBits(2, 1, output); + this.WriteBits(10, (uint)(paletteColors - 256), output); + } + + this.WriteBits(2, 0, output); // No delta colors. + this.WriteBits(4, 0, output); // The zero predictor for delta colors. + } + else if (this.colorComponents == 3) + { + this.WriteBits(2, 1, output); // One transform. + this.WriteBits(2, 0, output); // The reversible color transform. + this.WriteBits(5, 0, output); // From channel 0. + this.WriteBits(2, 0, output); // Type 6: YCoCg. + } + else + { + this.WriteBits(2, 0, output); // No transforms. + } + } + + /// + /// Writes the code lengths of one channel code with the code-length code, as libjxl writes them: the 19 literal lengths, three + /// repeat symbols for the 205 unused symbols before 224, and the copy-length lengths. + /// + /// The channel code. + /// The retained output buffer. + private void WriteFastLosslessCode(in FastLosslessCode code, Span output) + { + // The counts of the code-length symbols. libjxl counts the repeat symbol 17 as 67, a fixed estimate. + InlineArray18 countStorage = default; + Span counts = countStorage; + counts[17] = 3 + (2 * (FastCopySymbolCount - 1)); + for (int i = 0; i < FastRawSymbolCount; i++) + { + counts[code.Raw[i] >> 16]++; + } + + for (int i = 0; i < FastCopySymbolCount; i++) + { + counts[code.Copy[i] >> 16]++; + } + + InlineArray18 minimumStorage = default; + InlineArray18 maximumStorage = default; + InlineArray18 lengthStorage = default; + InlineArray18 codeStorage = default; + Span maximum = maximumStorage; + Span lengths = lengthStorage; + Span codes = codeStorage; + maximum.Fill(5); + this.BuildBoundedCodeLengths(counts, minimumStorage, maximum, lengths); + BuildCodes(lengths, codes); + + // No skipped lengths. The trailing unused lengths in the storage order are not stored. + ReadOnlySpan order = CodeLengthCodeOrder; + int stored = CodeLengthCodeCount; + while (lengths[order[stored - 1]] == 0) + { + stored--; + } + + this.WriteBits(2, 0, output); + for (int i = 0; i < stored; i++) + { + int length = lengths[order[i]]; + this.WriteBits(CodeLengthLengthBits[length], CodeLengthLengthCodes[length], output); + } + + for (int i = 0; i < FastRawSymbolCount; i++) + { + int length = code.Raw[i] >> 16; + this.WriteBits(lengths[length], codes[length], output); + } + + // Symbol 17 repeats zero 3 + extra times, and a following 17 multiplies the previous count: 5, then 8 * 3 + 3 = 27, then + // 8 * 25 + 5 = 205 zeros. + this.WriteBits(lengths[17], codes[17], output); + this.WriteBits(3, 2, output); + this.WriteBits(lengths[17], codes[17], output); + this.WriteBits(3, 0, output); + this.WriteBits(lengths[17], codes[17], output); + this.WriteBits(3, 2, output); + + // The decoder stops after the last length that completes the code. + int copyCount = FastCopySymbolCount; + while (code.Copy[copyCount - 1] >> 16 == 0) + { + copyCount--; + } + + for (int i = 0; i < copyCount; i++) + { + int length = code.Copy[i] >> 16; + this.WriteBits(lengths[length], codes[length], output); + } + } + + /// + /// Holds the prefix code of one channel of the fast lossless mode. + /// + private struct FastLosslessCode + { + /// + /// The entry of each literal symbol: the code, least-significant bit first, in the low 16 bits and the length in the high 16 + /// bits. The entries above the used symbols are 0. + /// + public InlineArray32 Raw; + + /// + /// The entry of each copy-length symbol, in the layout of . + /// + public InlineArray36 Copy; + + /// + /// The complete field of each short run, by the length symbol value: the zero literal, the copy-length code and its extra bits. + /// + public InlineArray32 RunFields; + + /// + /// The bit counts of . + /// + public InlineArray32 RunBits; + } + + /// + /// Orders palette colors by their luma, as libjxl orders them: 0.299 R + 0.587 G + 0.114 B + 0.01, times alpha with four channels. + /// Equal keys order by the packed color, so the order is the same on all runs. + /// + private readonly struct FastPaletteComparer : IComparer + { + /// + /// Whether the colors have four channels, so the alpha multiplies the luma. + /// + private readonly bool hasAlpha; + + /// + /// Initializes a new instance of the struct. + /// + /// Whether the colors have four channels. + public FastPaletteComparer(bool hasAlpha) => this.hasAlpha = hasAlpha; + + /// + public int Compare(uint x, uint y) + { + int order = this.GetKey(x).CompareTo(this.GetKey(y)); + return order != 0 ? order : x.CompareTo(y); + } + + /// + /// Gets the order key of one packed color. + /// + /// The packed color: component c in byte c. + /// The key. + private float GetKey(uint color) + { + float luma = (0.299F * (color & 0xFF)) + (0.587F * ((color >> 8) & 0xFF)) + (0.114F * ((color >> 16) & 0xFF)) + 0.01F; + return this.hasAlpha ? luma * (color >> 24) : luma; + } + } +} diff --git a/src/ImageSharp/Formats/Jxl/JxlEncoderCore.FastLosslessFieldOperator.cs b/src/ImageSharp/Formats/Jxl/JxlEncoderCore.FastLosslessFieldOperator.cs new file mode 100644 index 0000000000..7184276c53 --- /dev/null +++ b/src/ImageSharp/Formats/Jxl/JxlEncoderCore.FastLosslessFieldOperator.cs @@ -0,0 +1,231 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Common.Helpers; +using SixLabors.ImageSharp.Formats.Jxl.Components.Entropy; + +namespace SixLabors.ImageSharp.Formats.Jxl; + +/// +/// Contains the lane arithmetic that turns fast lossless residuals into prefix-coded bit fields. +/// +internal sealed partial class JxlEncoderCore +{ + /// + /// Builds the bit fields of fast lossless literals: the prefix code of the 0/0/0 token of each residual, then the extra bits. + /// + /// + /// The symbol table holds one entry for each literal symbol: the code, least-significant bit first, in the low 16 bits and the code + /// length in the high 16 bits. A literal field has at most 26 bits: 8 code bits and 18 extra bits. The vector overloads join the + /// fields of two adjacent residuals into one 64-bit field, the earlier residual in the low bits, because the stream is + /// least-significant bit first. + /// + private static class FastLosslessFieldOperator + { + /// + /// Gets the bit field of one literal. + /// + /// The residual. + /// The first entry of the symbol table. + /// The number of bits of the field. + /// The field, with all bits above clear. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong GetField(uint value, ref int table, out int fieldBits) + { + JxlHybridUint.Zero.Encode(value, out uint token, out int bitCount, out uint extraBits); + int entry = Unsafe.Add(ref table, token); + int codeLength = entry >> 16; + fieldBits = codeLength + bitCount; + return (uint)(entry & 0xFFFF) | ((ulong)extraBits << codeLength); + } + + /// + /// Gets the mask of the zero residuals of one chunk. Bit i is set when residual i is zero. + /// + /// The first residual of the chunk of residuals. + /// The zero mask. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint GetZeroMask(ref uint chunk) + { + if (Vector512.IsHardwareAccelerated) + { + return GetZeroMask(Vector512.LoadUnsafe(ref chunk)) | (GetZeroMask(Vector512.LoadUnsafe(ref chunk, 16)) << 16); + } + + if (Vector256.IsHardwareAccelerated) + { + uint mask = 0; + for (nuint i = 0; i < FastChunkSize; i += (uint)Vector256.Count) + { + mask |= GetZeroMask(Vector256.LoadUnsafe(ref chunk, i)) << (int)i; + } + + return mask; + } + + if (Vector128.IsHardwareAccelerated) + { + uint mask = 0; + for (nuint i = 0; i < FastChunkSize; i += (uint)Vector128.Count) + { + mask |= GetZeroMask(Vector128.LoadUnsafe(ref chunk, i)) << (int)i; + } + + return mask; + } + + uint scalarMask = 0; + for (nuint i = 0; i < FastChunkSize; i++) + { + scalarMask |= (Unsafe.Add(ref chunk, i) == 0 ? 1U : 0U) << (int)i; + } + + return scalarMask; + } + + /// + /// Gets the mask of the zero lanes of four residuals. Bit i is set when lane i is zero. + /// + /// The residuals. + /// The zero mask. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint GetZeroMask(Vector128 values) => Vector128.Equals(values, Vector128.Zero).ExtractMostSignificantBits(); + + /// + /// Gets the mask of the zero lanes of eight residuals. Bit i is set when lane i is zero. + /// + /// The residuals. + /// The zero mask. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint GetZeroMask(Vector256 values) => Vector256.Equals(values, Vector256.Zero).ExtractMostSignificantBits(); + + /// + /// Gets the mask of the zero lanes of sixteen residuals. Bit i is set when lane i is zero. + /// + /// The residuals. + /// The zero mask. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint GetZeroMask(Vector512 values) => (uint)Vector512.Equals(values, Vector512.Zero).ExtractMostSignificantBits(); + + /// + /// Gets the bit fields of four literals as two joined 64-bit fields. + /// + /// The residuals. + /// All bits set in the lanes that are literals. The other lanes give empty fields. + /// The first entry of the symbol table. Each token of the residuals must be inside the table. + /// The joined fields of residuals 0 and 1, and of residuals 2 and 3. + /// The number of bits of each joined field, at most 52. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void GetFields(Vector128 values, Vector128 keep, ref int table, out Vector128 fields, out Vector128 fieldBits) + { + JxlHybridUint.Encode000(values, out Vector128 token, out Vector128 bitCount, out Vector128 extraBits); + Vector128 entry = Vector128_.Gather(ref table, token.AsInt32()).AsUInt32(); + Vector128 codeLength = entry >>> 16; + + // Lane field: the code, then the extra bits above it. A field has at most 26 bits, so the shift does not overflow. + Vector128 laneBits = (codeLength + bitCount) & keep; + Vector128 laneFields = ((entry & Vector128.Create(0xFFFFU)) | Vector128_.ShiftLeftLogicalVariable(extraBits, codeLength)) & keep; + + // Each 64-bit lane holds the fields of an even residual in its low half and of the next odd residual in its high half. The odd + // field moves up by the bit count of the even field, so the two fields become one field in stream order. + Vector128 pairs = laneFields.AsUInt64(); + Vector128 pairBits = laneBits.AsUInt64(); + Vector128 lowBits = pairBits & Vector128.Create((ulong)uint.MaxValue); + fields = (pairs & Vector128.Create((ulong)uint.MaxValue)) | Vector128_.ShiftLeftLogicalVariable(pairs >>> 32, lowBits); + fieldBits = lowBits + (pairBits >>> 32); + } + + /// + /// Gets the bit fields of eight literals as four joined 64-bit fields. + /// + /// The residuals. + /// All bits set in the lanes that are literals. The other lanes give empty fields. + /// The first entry of the symbol table. Each token of the residuals must be inside the table. + /// The joined fields of the residual pairs, in stream order. + /// The number of bits of each joined field, at most 52. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void GetFields(Vector256 values, Vector256 keep, ref int table, out Vector256 fields, out Vector256 fieldBits) + { + // The steps are the same as in the 128-bit overload. + JxlHybridUint.Encode000(values, out Vector256 token, out Vector256 bitCount, out Vector256 extraBits); + Vector256 entry = Vector256_.Gather(ref table, token.AsInt32()).AsUInt32(); + Vector256 codeLength = entry >>> 16; + Vector256 laneBits = (codeLength + bitCount) & keep; + Vector256 laneFields = ((entry & Vector256.Create(0xFFFFU)) | Vector256_.ShiftLeftLogicalVariable(extraBits, codeLength)) & keep; + Vector256 pairs = laneFields.AsUInt64(); + Vector256 pairBits = laneBits.AsUInt64(); + Vector256 lowBits = pairBits & Vector256.Create((ulong)uint.MaxValue); + fields = (pairs & Vector256.Create((ulong)uint.MaxValue)) | Vector256_.ShiftLeftLogicalVariable(pairs >>> 32, lowBits); + fieldBits = lowBits + (pairBits >>> 32); + } + + /// + /// Gets the bit fields of sixteen literals as eight joined 64-bit fields. + /// + /// The residuals. + /// All bits set in the lanes that are literals. The other lanes give empty fields. + /// The first entry of the symbol table. Each token of the residuals must be inside the table. + /// The joined fields of the residual pairs, in stream order. + /// The number of bits of each joined field, at most 52. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void GetFields(Vector512 values, Vector512 keep, ref int table, out Vector512 fields, out Vector512 fieldBits) + { + // The steps are the same as in the 128-bit overload. + JxlHybridUint.Encode000(values, out Vector512 token, out Vector512 bitCount, out Vector512 extraBits); + Vector512 entry = Vector512_.Gather(ref table, token.AsInt32()).AsUInt32(); + Vector512 codeLength = entry >>> 16; + Vector512 laneBits = (codeLength + bitCount) & keep; + Vector512 laneFields = ((entry & Vector512.Create(0xFFFFU)) | Vector512_.ShiftLeftLogicalVariable(extraBits, codeLength)) & keep; + Vector512 pairs = laneFields.AsUInt64(); + Vector512 pairBits = laneBits.AsUInt64(); + Vector512 lowBits = pairBits & Vector512.Create((ulong)uint.MaxValue); + fields = (pairs & Vector512.Create((ulong)uint.MaxValue)) | Vector512_.ShiftLeftLogicalVariable(pairs >>> 32, lowBits); + fieldBits = lowBits + (pairBits >>> 32); + } + + /// + /// Joins the 64-bit fields of each even lane and the next odd lane into the even lane, the odd field above the even field. The odd + /// lanes keep their values, and the caller ignores them. + /// + /// The fields. Each pair of lanes has at most 64 bits in total. + /// The bit counts of the fields. Each count is at most 32. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void JoinPairs(ref Vector128 fields, ref Vector128 fieldBits) + { + // The shuffle moves each odd lane to the even lane below it. + Vector128 swap = Vector128.Create(1UL, 0UL); + fields |= Vector128_.ShiftLeftLogicalVariable(Vector128.Shuffle(fields, swap), fieldBits); + fieldBits += Vector128.Shuffle(fieldBits, swap); + } + + /// + /// Joins the 64-bit fields of each even lane and the next odd lane into the even lane, the odd field above the even field. The odd + /// lanes keep their values, and the caller ignores them. + /// + /// The fields. Each pair of lanes has at most 64 bits in total. + /// The bit counts of the fields. Each count is at most 32. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void JoinPairs(ref Vector256 fields, ref Vector256 fieldBits) + { + Vector256 swap = Vector256.Create(1UL, 0UL, 3UL, 2UL); + fields |= Vector256_.ShiftLeftLogicalVariable(Vector256.Shuffle(fields, swap), fieldBits); + fieldBits += Vector256.Shuffle(fieldBits, swap); + } + + /// + /// Joins the 64-bit fields of each even lane and the next odd lane into the even lane, the odd field above the even field. The odd + /// lanes keep their values, and the caller ignores them. + /// + /// The fields. Each pair of lanes has at most 64 bits in total. + /// The bit counts of the fields. Each count is at most 32. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void JoinPairs(ref Vector512 fields, ref Vector512 fieldBits) + { + Vector512 swap = Vector512.Create(1UL, 0UL, 3UL, 2UL, 5UL, 4UL, 7UL, 6UL); + fields |= Vector512_.ShiftLeftLogicalVariable(Vector512.Shuffle(fields, swap), fieldBits); + fieldBits += Vector512.Shuffle(fieldBits, swap); + } + } +} diff --git a/src/ImageSharp/Formats/Jxl/JxlEncoderCore.PrefixFieldOperator.cs b/src/ImageSharp/Formats/Jxl/JxlEncoderCore.PrefixFieldOperator.cs new file mode 100644 index 0000000000..201e4b2688 --- /dev/null +++ b/src/ImageSharp/Formats/Jxl/JxlEncoderCore.PrefixFieldOperator.cs @@ -0,0 +1,151 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Common.Helpers; +using SixLabors.ImageSharp.Formats.Jxl.Components.Entropy; + +namespace SixLabors.ImageSharp.Formats.Jxl; + +/// +/// Contains the lane arithmetic that turns stream values into prefix-coded bit fields. +/// +internal sealed partial class JxlEncoderCore +{ + /// + /// Builds the bit fields of literal values: the prefix code of the 4/2/0 token of each value, then the extra bits of the value. + /// + /// + /// The symbol table holds one entry for each symbol: the code, least-significant bit first, in the low 16 bits and the code length + /// in the high 16 bits. The vector overloads give the same bits as the scalar overload. They join the fields of two adjacent values + /// into one 64-bit field, the earlier value in the low bits, because the stream is least-significant bit first. + /// + private static class PrefixFieldOperator + { + /// + /// The longest field of one value that the vector overloads join. Two such fields fill one 64-bit lane. + /// + private const int MaximumLaneBits = 32; + + /// + /// Gets the bit field of one literal value. + /// + /// The value. + /// The first entry of the symbol table. + /// The number of bits of the field: at most 15 code bits and 29 extra bits. + /// The field, with all bits above clear. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong GetField(uint value, ref int table, out int fieldBits) + { + JxlHybridUint.Encode420(value, out uint token, out int bitCount, out uint extraBits); + int entry = Unsafe.Add(ref table, token); + int codeLength = entry >> 16; + fieldBits = codeLength + bitCount; + return (uint)(entry & 0xFFFF) | ((ulong)extraBits << codeLength); + } + + /// + /// Gets the bit fields of four literal values as two joined 64-bit fields. + /// + /// The values. + /// The first entry of the symbol table. Each token of the values must be inside the table. + /// The joined fields of values 0 and 1, and of values 2 and 3. + /// The number of bits of each joined field. + /// when the field of each value has at most 32 bits; otherwise with zero outputs. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryGetFields(Vector128 values, ref int table, out Vector128 fields, out Vector128 fieldBits) + { + JxlHybridUint.Encode420(values, out Vector128 token, out Vector128 bitCount, out Vector128 extraBits); + Vector128 entry = Vector128_.Gather(ref table, token.AsInt32()).AsUInt32(); + Vector128 codeLength = entry >>> 16; + Vector128 laneBits = codeLength + bitCount; + + // A value of 2^20 or more has at least 18 extra bits and can need more than 32 bits. Then the caller writes the values one by one. + if (Vector128.GreaterThanAny(laneBits.AsInt32(), Vector128.Create(MaximumLaneBits))) + { + fields = default; + fieldBits = default; + return false; + } + + // Lane field: the code, then the extra bits above it. Each field has at most 32 bits, so the shift does not overflow. + Vector128 laneFields = (entry & Vector128.Create(0xFFFFU)) | Vector128_.ShiftLeftLogicalVariable(extraBits, codeLength); + + // Each 64-bit lane holds the fields of an even value in its low half and of the next odd value in its high half. The odd field + // moves up by the bit count of the even field, so the two fields become one field of at most 64 bits in stream order. + Vector128 pairs = laneFields.AsUInt64(); + Vector128 pairBits = laneBits.AsUInt64(); + Vector128 lowBits = pairBits & Vector128.Create((ulong)uint.MaxValue); + fields = (pairs & Vector128.Create((ulong)uint.MaxValue)) | Vector128_.ShiftLeftLogicalVariable(pairs >>> 32, lowBits); + fieldBits = lowBits + (pairBits >>> 32); + return true; + } + + /// + /// Gets the bit fields of eight literal values as four joined 64-bit fields. + /// + /// The values. + /// The first entry of the symbol table. Each token of the values must be inside the table. + /// The joined fields of the value pairs, in stream order. + /// The number of bits of each joined field. + /// when the field of each value has at most 32 bits; otherwise with zero outputs. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryGetFields(Vector256 values, ref int table, out Vector256 fields, out Vector256 fieldBits) + { + JxlHybridUint.Encode420(values, out Vector256 token, out Vector256 bitCount, out Vector256 extraBits); + Vector256 entry = Vector256_.Gather(ref table, token.AsInt32()).AsUInt32(); + Vector256 codeLength = entry >>> 16; + Vector256 laneBits = codeLength + bitCount; + + // The steps are the same as in the 128-bit overload. + if (Vector256.GreaterThanAny(laneBits.AsInt32(), Vector256.Create(MaximumLaneBits))) + { + fields = default; + fieldBits = default; + return false; + } + + Vector256 laneFields = (entry & Vector256.Create(0xFFFFU)) | Vector256_.ShiftLeftLogicalVariable(extraBits, codeLength); + Vector256 pairs = laneFields.AsUInt64(); + Vector256 pairBits = laneBits.AsUInt64(); + Vector256 lowBits = pairBits & Vector256.Create((ulong)uint.MaxValue); + fields = (pairs & Vector256.Create((ulong)uint.MaxValue)) | Vector256_.ShiftLeftLogicalVariable(pairs >>> 32, lowBits); + fieldBits = lowBits + (pairBits >>> 32); + return true; + } + + /// + /// Gets the bit fields of sixteen literal values as eight joined 64-bit fields. + /// + /// The values. + /// The first entry of the symbol table. Each token of the values must be inside the table. + /// The joined fields of the value pairs, in stream order. + /// The number of bits of each joined field. + /// when the field of each value has at most 32 bits; otherwise with zero outputs. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryGetFields(Vector512 values, ref int table, out Vector512 fields, out Vector512 fieldBits) + { + JxlHybridUint.Encode420(values, out Vector512 token, out Vector512 bitCount, out Vector512 extraBits); + Vector512 entry = Vector512_.Gather(ref table, token.AsInt32()).AsUInt32(); + Vector512 codeLength = entry >>> 16; + Vector512 laneBits = codeLength + bitCount; + + // The steps are the same as in the 128-bit overload. + if (Vector512.GreaterThanAny(laneBits.AsInt32(), Vector512.Create(MaximumLaneBits))) + { + fields = default; + fieldBits = default; + return false; + } + + Vector512 laneFields = (entry & Vector512.Create(0xFFFFU)) | Vector512_.ShiftLeftLogicalVariable(extraBits, codeLength); + Vector512 pairs = laneFields.AsUInt64(); + Vector512 pairBits = laneBits.AsUInt64(); + Vector512 lowBits = pairBits & Vector512.Create((ulong)uint.MaxValue); + fields = (pairs & Vector512.Create((ulong)uint.MaxValue)) | Vector512_.ShiftLeftLogicalVariable(pairs >>> 32, lowBits); + fieldBits = lowBits + (pairBits >>> 32); + return true; + } + } +} diff --git a/src/ImageSharp/Formats/Jxl/JxlEncoderCore.cs b/src/ImageSharp/Formats/Jxl/JxlEncoderCore.cs index 59552e8f90..ece0bc80e9 100644 --- a/src/ImageSharp/Formats/Jxl/JxlEncoderCore.cs +++ b/src/ImageSharp/Formats/Jxl/JxlEncoderCore.cs @@ -27,7 +27,7 @@ namespace SixLabors.ImageSharp.Formats.Jxl; /// /// Coordinates modular and VarDCT frame encoding and writes the image and frame headers. /// -internal sealed class JxlEncoderCore : IDisposable +internal sealed partial class JxlEncoderCore : IDisposable { /// /// The width and height of a coding group for the default modular group shift. @@ -79,6 +79,17 @@ internal sealed class JxlEncoderCore : IDisposable /// private readonly IMemoryOwner floatRows; + /// + /// The allocator of the scratch buffers of the entropy streams. + /// + private readonly MemoryAllocator memoryAllocator; + + /// + /// The packed residuals of all components of one modular group, in stream order, or null when the frame has no plain groups. + /// The group writes its entropy code after it has all its residuals, because the code comes from their histogram. + /// + private readonly IMemoryOwner? groupValues; + /// /// The ordered byte lengths of the completed frame sections. /// @@ -249,6 +260,13 @@ internal sealed class JxlEncoderCore : IDisposable /// private readonly bool narrowSamples; + /// + /// Whether the frames use the fast lossless mode: lossless, not progressive, and only color and alpha channels of the same depth: + /// integers of at most 16 bits, or binary16 floats as their 16-bit patterns. libjxl uses its fast lossless mode at effort 1 for these + /// frames, except for animation frames. An animation frame replaces the full canvas, so the mode is valid for it too. + /// + private readonly bool fastLossless; + /// /// Whether image features or displayed frame rates require a Level 10 container declaration. /// @@ -521,6 +539,9 @@ public JxlEncoderCore(JxlEncoder encoder, Image image, Stream stream) // Unsqueezed integers need one sign bit. Squeeze reserves two further arithmetic bits. // The libjxl limit of bit depth + 2 < 16 includes that original sign bit. this.narrowSamples = !this.usesXyb && bitDepth.ExponentBits == 0 && bitDepth.BitsPerSample <= (encoder.Progressive ? 12 : 14); + this.fastLossless = !this.usesXyb && !encoder.Progressive && !this.hasBlack && encoder.ExtraChannels.Count == 0 + && ((bitDepth.ExponentBits == 0 && bitDepth.BitsPerSample <= 16) || (bitDepth.ExponentBits == 5 && bitDepth.BitsPerSample == 16)) + && this.alphaBitDepth == bitDepth; bool hasBlackChannel = false; foreach (JxlExtraChannelMetadata channel in this.extraChannels) @@ -550,6 +571,7 @@ public JxlEncoderCore(JxlEncoder encoder, Image image, Stream stream) { PixelColorType sampleColorType = this.hasBlack ? PixelColorType.CMYK : this.colorType == JxlColorType.Luminance ? PixelColorType.Luminance : PixelColorType.RGB; + this.profile = IccProfile.GetCompatibleProfileForEncoding( sourceProfile, sampleColorType, configuration.MemoryAllocator, out profileConverter); } @@ -595,15 +617,18 @@ public JxlEncoderCore(JxlEncoder encoder, Image image, Stream stream) // Named coordinates have exact format constants. Custom coordinates use signed millionths. this.whitePoint = whitePoint == KnownIlluminants.D65Chromaticity || whitePoint == KnownIlluminants.EChromaticity || whitePoint == KnownIlluminants.DciP3Chromaticity ? whitePoint : QuantizeChromaticity(whitePoint); + this.primaries = primaries.Equals(srgbPrimaries) || primaries.Equals(KnownRgbWorkingSpaces.Rec2020.ChromaticityCoordinates) || primaries.Equals(KnownRgbWorkingSpaces.DisplayP3.ChromaticityCoordinates) ? primaries : new(QuantizeChromaticity(primaries.R), QuantizeChromaticity(primaries.G), QuantizeChromaticity(primaries.B)); + this.transferCharacteristics = useWorkingRgb ? CicpTransferCharacteristics.Iec61966_2_1 : metadata.TransferCharacteristics ?? (byte)transfer switch { 1 or 6 or 14 or 15 => CicpTransferCharacteristics.ItuRBt709_6, 8 or 13 or 16 or 17 or 18 => transfer, _ => CicpTransferCharacteristics.Iec61966_2_1 }; + this.gamma = useWorkingRgb ? null : metadata.Gamma is Rational gamma ? (uint)Math.Round(gamma.ToDouble() * 10_000_000D) : metadata.TransferCharacteristics is null && (byte)transfer is 4 or 5 ? (uint)Math.Round(10_000_000D * 5D / ((byte)transfer == 4 ? 11D : 14D)) : null; @@ -661,6 +686,8 @@ public JxlEncoderCore(JxlEncoder encoder, Image image, Stream stream) Buffer2D? expandedAlpha = null; JxlUpsampler? alphaUpsampler = null; JxlVarDctEncoder? varDct = null; + IMemoryOwner? groupValues = null; + this.memoryAllocator = allocator; try { @@ -681,6 +708,14 @@ public JxlEncoderCore(JxlEncoder encoder, Image image, Stream stream) floatRows = allocator.Allocate( this.groupWidth * (this.hasBlack ? 12 : this.profileConverter is null ? 4 : 7)); + // A plain modular group keeps the residuals of all its components, because its entropy code comes from their histogram. + // A progressive frame allocates its buffer after the squeeze layout below. The fast lossless mode writes each row as it + // predicts it. + if (!this.usesXyb && !encoder.Progressive && !this.fastLossless) + { + groupValues = allocator.Allocate(this.groupWidth * this.groupHeight * this.componentCount); + } + if (this.suppliedAlphaIndex >= 0 && this.extraChannels[this.suppliedAlphaIndex].DimensionShift != 0 && (this.alphaAssociated || encoder.TransparentColorMode == TransparentColorMode.Clear)) { @@ -716,6 +751,11 @@ public JxlEncoderCore(JxlEncoder encoder, Image image, Stream stream) this.globalPrefixCount++; } + + // Each modular stream of a VarDCT frame holds at most one group region of each of its channels. The DC group stream has + // three DC channels, and the AC metadata stream has five channels. Each extra-channel stream has at most all extra channels. + int regionSamples = Math.Min(size.Width, GroupDimension) * Math.Min(size.Height, GroupDimension); + groupValues = allocator.Allocate(regionSamples * Math.Max(5, 3 + extraCount)); } else if (encoder.Progressive) { @@ -750,6 +790,11 @@ public JxlEncoderCore(JxlEncoder encoder, Image image, Stream stream) { squeezeRows = allocator.Allocate2D(halfWidth, 5 * colors); } + + // Each progressive stream holds at most one group region of each channel: the global channels fit one group, and the + // DC and AC group streams select one group region of each channel. + int regionSamples = Math.Min(size.Width, GroupDimension) * Math.Min(size.Height, GroupDimension); + groupValues = allocator.Allocate(regionSamples * progressiveChannels.Length); } // Sections with no selected samples emit no header. Clean lengths keep those TOC entries at zero. @@ -768,6 +813,7 @@ public JxlEncoderCore(JxlEncoder encoder, Image image, Stream stream) } // The core owns its buffers only after construction succeeds. A failed rent returns the local owners. + groupValues?.Dispose(); floatRows?.Dispose(); pixelRow?.Dispose(); samples?.Dispose(); @@ -778,6 +824,7 @@ public JxlEncoderCore(JxlEncoder encoder, Image image, Stream stream) this.samples = samples; this.pixelRow = pixelRow; this.floatRows = floatRows; + this.groupValues = groupValues; this.progressiveChannels = progressiveChannels; this.squeezeRows = squeezeRows; this.expandedAlpha = expandedAlpha; @@ -846,6 +893,7 @@ public void Dispose() } this.sectionSizes.Dispose(); + this.groupValues?.Dispose(); this.floatRows.Dispose(); this.pixelRow.Dispose(); this.samples?.Dispose(); @@ -972,6 +1020,7 @@ private uint GetFrameDuration(LongRational delay, bool last) ulong denominator = (ulong)Int128.Abs(delay.Denominator); UInt128 ticks = (UInt128)numerator * this.ticksPerSecondNumerator / ((UInt128)denominator * this.ticksPerSecondDenominator); + uint duration = (uint)UInt128.Min(ticks, uint.MaxValue); // A non-final zero duration denotes a hidden reference frame. Source image frames are displayed. @@ -1263,31 +1312,10 @@ private void EncodeFrame( { Configuration configuration = source.Configuration; MemoryAllocator allocator = configuration.MemoryAllocator; - int maximumBits = this.usesXyb || this.encoder.Progressive ? 32 : this.bitDepth.BitsPerSample; - foreach (JxlExtraChannelMetadata channel in this.extraChannels) - { - maximumBits = Math.Max(maximumBits, channel.BitDepth.BitsPerSample); - } - - // Zigzag values can use every uint bit. Hybrid configuration zero therefore needs tokens through 32. - // The alphabet is a complete power of two selected from declared precision, independently of int carrier storage. - int codeLength = Math.Max(4, BitOperations.Log2((uint)maximumBits + 1) + 1); - int alphabetSize = 1 << codeLength; - - // Each residual has one prefix and at most 31 literal bits. Reserve space for every complete - // word emitted by a 256-value batch, including up to 31 bits retained from the preceding batch. - int batchBytes = (((GroupDimension * (codeLength + 31)) + 31) / 32) * sizeof(uint); - using IMemoryOwner outputOwner = allocator.Allocate(Math.Max(batchBytes, configuration.StreamProcessingBufferSize)); - using IMemoryOwner lengthOwner = allocator.Allocate(alphabetSize); - using IMemoryOwner sortedOwner = allocator.Allocate(alphabetSize); - using IMemoryOwner codeOwner = allocator.Allocate(alphabetSize); + // The output buffer holds at least one complete batch of the stream writer. + using IMemoryOwner outputOwner = allocator.Allocate(Math.Max(SymbolBatchBytes, configuration.StreamProcessingBufferSize)); Span output = outputOwner.Memory.Span; - Span lengths = lengthOwner.Memory.Span[..alphabetSize]; - Span sorted = sortedOwner.Memory.Span[..alphabetSize]; - Span prefixCodes = codeOwner.Memory.Span[..alphabetSize]; - lengths.Fill(codeLength); - _ = HuffmanTableBuilder.Build([], codeLength, lengths, sorted, prefixCodes); bool combined = this.groupCount == 1 && !this.encoder.Progressive; bool useGradient = this.usesXyb || this.bitDepth.ExponentBits == 0; @@ -1300,11 +1328,12 @@ private void EncodeFrame( bool clearTransparent = this.suppliedAlphaIndex >= 0 ? this.encoder.TransparentColorMode == TransparentColorMode.Clear : EncodingUtilities.ShouldReplaceTransparentPixels(this.encoder.TransparentColorMode); + Span pixelRow = this.pixelRow.Memory.Span[..this.groupWidth]; Span floatRows = this.floatRows.Memory.Span; Span sectionSizes = this.sectionSizes.Memory.Span[..this.sectionCount]; ChunkedMemoryStream payload = this.payload; - this.WriteImageHeader(codeLength, prefixCodes, output); + this.WriteImageHeader(output); if (this.varDct is JxlVarDctEncoder varDct) { @@ -1314,8 +1343,6 @@ private void EncodeFrame( varDct, useGradient, clearTransparent, - codeLength, - prefixCodes, pixelRow, floatRows, sectionSizes, @@ -1341,83 +1368,80 @@ private void EncodeFrame( payload.Position = 0; this.outputStream = payload; - // LF-global starts with DC factors. The global tree has one leaf and no LZ77 or ANS state. - // Floating carriers use the zero predictor: their raw signed bit patterns need no overflowing subtraction. - this.WriteBits(1, 1, output); - this.WriteGlobalTree(useGradient, codeLength, prefixCodes, output); - this.WriteBits(1, 1, output); // Use the global tree. - this.WriteBits(1, 1, output); // Default weighted-predictor parameters. - - if (this.squeezedComponents != 0) - { - this.WriteBits(2, 1, output); // One channel transform. - this.WriteBits(2, 2, output); // Squeeze transform. - this.WriteU32(2, (0, 0), (4, 1), (6, 9), (8, 41), output); - - for (int direction = 0; direction < 2; direction++) - { - this.WriteBits(1, direction == 0 ? 1U : 0U, output); // Horizontal, then vertical. - this.WriteBits(1, 1, output); // Insert residuals after the selected colors. - this.WriteU32(0, (3, 0), (6, 8), (10, 72), (13, 1096), output); - this.WriteU32((uint)this.squeezedComponents, (0, 1), (0, 2), (0, 3), (4, 4), output); - } - } - else - { - this.WriteBits(2, 0, output); // No channel transforms. - } - - if (this.encoder.Progressive) - { - this.PrepareProgressiveSamples( - image, clearTransparent, pixelRow, floatRows, colorOperation, alphaOperation, blackOperation, alphaDecodeOperation, cancellationToken); - this.WriteProgressiveSections(useGradient, codeLength, prefixCodes, floatRows, sectionSizes, output, cancellationToken); + // The fast lossless mode writes its own LF-global with a global tree. + if (this.fastLossless) + { + this.WriteFastLosslessFrame( + image, + combined, + clearTransparent, + pixelRow, + floatRows, + sectionSizes, + output, + colorOperation, + alphaOperation, + blackOperation, + alphaDecodeOperation, + cancellationToken); } else { + // LF-global starts with DC factors. Each modular stream of the frame has its own tree with one leaf and the entropy code + // of its histogram, so the frame has no global tree. Floating carriers use the zero predictor: their raw signed bit + // patterns need no overflowing subtraction. A single plain group is the global modular stream itself, and the group writes + // the stream header. Otherwise the global stream header has a local tree, the default weighted predictor and the global + // transforms. + this.WriteBits(1, 1, output); + this.WriteBits(1, 0, output); // No global tree. if (!combined) { - // A leading full-resolution channel larger than one coding group ends the global prefix. - // Reduced channels then use DC or AC groups; HF-global has no data in this modular frame. - this.FlushBits(output); - sectionSizes[0] = GetSectionSize(payload.Position); - this.WritePlainDcSections(useGradient, codeLength, prefixCodes, floatRows, sectionSizes, output, cancellationToken); + this.WriteBits(1, 0, output); + this.WriteBits(1, 1, output); + this.WriteGlobalTransforms(output); } - for (int index = 0; index < this.groupCount; index++) + if (this.encoder.Progressive) { - cancellationToken.ThrowIfCancellationRequested(); - int x = (index % this.groupColumns) * GroupDimension; - int y = (index / this.groupColumns) * GroupDimension; - Rectangle bounds = new(x, y, Math.Min(GroupDimension, image.Width - x), Math.Min(GroupDimension, image.Height - y)); - long sectionStart = combined ? 0 : payload.Position; + this.PrepareProgressiveSamples( + image, clearTransparent, pixelRow, floatRows, colorOperation, alphaOperation, blackOperation, alphaDecodeOperation, cancellationToken); + this.WriteProgressiveSections(useGradient, sectionSizes, output, cancellationToken); + } + else + { if (!combined) { - // Each AC group reuses the global tree and has no local channel transforms. - this.WriteBits(1, 1, output); - this.WriteBits(1, 1, output); - this.WriteBits(2, 0, output); + // A leading full-resolution channel larger than one coding group ends the global prefix. + // Reduced channels then use DC or AC groups; HF-global has no data in this modular frame. + this.FlushBits(output); + sectionSizes[0] = GetSectionSize(payload.Position); + this.WritePlainDcSections(useGradient, sectionSizes, output, cancellationToken); } - this.WriteGroup( - image, - bounds, - useGradient, - clearTransparent, - codeLength, - prefixCodes, - pixelRow, - floatRows, - output, - colorOperation, - alphaOperation, - blackOperation, - alphaDecodeOperation, - cancellationToken); - - this.FlushBits(output); - sectionSizes[combined ? 0 : 2 + this.dcGroupCount + index] = GetSectionSize(payload.Position - sectionStart); + for (int index = 0; index < this.groupCount; index++) + { + cancellationToken.ThrowIfCancellationRequested(); + Rectangle bounds = this.GetGroupBounds(image, index); + long sectionStart = combined ? 0 : payload.Position; + + this.WriteGroup( + image, + bounds, + useGradient, + clearTransparent, + pixelRow, + floatRows, + output, + colorOperation, + alphaOperation, + blackOperation, + alphaDecodeOperation, + cancellationToken); + + this.FlushBits(output); + sectionSizes[combined ? 0 : 2 + this.dcGroupCount + index] = GetSectionSize(payload.Position - sectionStart); + } } } @@ -1452,10 +1476,8 @@ private void EncodeFrame( /// The retained forward-transform and coefficient owner. /// Whether the shared modular tree uses the gradient predictor. /// Whether conversion clears hidden transparent colors. - /// The prepared prefix width. - /// The prepared LSB-first codes. /// The reusable working pixel row. - /// The reusable conversion rows and residual scratch. + /// The reusable conversion rows and DC prediction rows. /// The retained section lengths. /// The retained byte buffer. /// The selected color sample operation. @@ -1469,8 +1491,6 @@ private void EncodeVarDctFrame( JxlVarDctEncoder varDct, bool gradient, bool clearTransparent, - int codeLength, - ReadOnlySpan prefixCodes, Span pixelRow, Span floatRows, Span sectionSizes, @@ -1490,12 +1510,26 @@ private void EncodeVarDctFrame( int passes = this.encoder.Progressive ? 3 : 1; int dcColumns = ((this.groupColumns - 1) / 8) + 1; Size blocks = new(((this.size.Width - 1) / 8) + 1, ((this.size.Height - 1) / 8) + 1); - Span residuals = MemoryMarshal.Cast(floatRows[..this.groupWidth]); InlineArray64 orderStorage = default; Span order = orderStorage; JxlCoefficientOrder.WriteNaturalCoefficientOrder(0, order, cancellationToken); int frameIndex = 0; + // The AC entropy work buffers: the histograms and clusters of one pass, and the cluster codes of every pass. The AC global + // section writes the codes of all passes before the first AC group, so the groups keep them. + int countLength = ((AcHistogramCount + MaximumClusterCount) * (TokenAlphabetSize + 2)) + (2 * AcContextCount); + int codeCount = passes * MaximumClusterCount * TokenAlphabetSize; + using IMemoryOwner acCountOwner = this.memoryAllocator.Allocate(countLength); + using IMemoryOwner acCodeOwner = this.memoryAllocator.Allocate(codeCount); + using IMemoryOwner acByteOwner = this.memoryAllocator.Allocate( + codeCount + (passes * AcHistogramCount) + AcContextCount + (2 * MaximumClusterCount) + (3 * AcGroupBlocks)); + + using IMemoryOwner acFloatOwner = this.memoryAllocator.Allocate((2 * AcHistogramCount) + MaximumClusterCount); + Span acCodes = acCodeOwner.GetSpan(); + Span acLengths = acByteOwner.GetSpan()[..codeCount]; + Span acClusters = acByteOwner.GetSpan().Slice(codeCount, passes * AcHistogramCount); + Span acBytes = acByteOwner.GetSpan()[(codeCount + acClusters.Length)..]; + foreach (ImageFrame image in source.Frames) { this.sourceFrameIndex = frameIndex; @@ -1537,26 +1571,25 @@ private void EncodeVarDctFrame( this.WriteU32((uint)varDct.DcQuantizer, (0, 16), (5, 1), (8, 1), (16, 1), output); this.WriteBits(1, 1, output); // Default block contexts: no DC or quantizer thresholds. this.WriteBits(1, 1, output); // Default color correlation: X=0, B=1. - this.WriteGlobalTree(gradient, codeLength, prefixCodes, output); + this.WriteBits(1, 0, output); // No global tree: each modular stream has its own tree and entropy code. + Span values = this.groupValues!.GetSpan(); if (this.extraChannels.Length != 0) { - this.WriteModularHeader(output); + // The global stream has a header when the frame has extra channels, also when no channel fits one group. + this.WriteBits(1, 0, output); // A local tree. + this.WriteBits(1, 1, output); // Default weighted-predictor parameters. + this.WriteBits(2, 0, output); // No channel transforms. + int count = 0; for (int c = 0; c < this.globalPrefixCount; c++) { JxlModularChannelLayout layout = this.GetExtraChannelLayout(c); - this.WriteVarDctExtraChannel( - varDct, - c, - new Rectangle(0, 0, layout.Width, layout.Height), - gradient, - residuals, - codeLength, - prefixCodes, - output, - cancellationToken); + count += this.PackVarDctExtraChannel( + varDct, c, new Rectangle(0, 0, layout.Width, layout.Height), gradient, values[count..], cancellationToken); } + + this.WriteLocalStream(values[..count], gradient, false, output); } if (!combined) @@ -1572,59 +1605,57 @@ private void EncodeVarDctFrame( int y = (group / dcColumns) * GroupDimension; Rectangle rectangle = new(x, y, Math.Min(GroupDimension, blocks.Width - x), Math.Min(GroupDimension, blocks.Height - y)); this.WriteBits(2, 0, output); // Linear DC quantization needs no extra precision bits. - this.WriteModularHeader(output); + int count = 0; // DC modular streams visit Y, X, B. Each substream resets its predictor at its own edges. for (int encodedComponent = 0; encodedComponent < 3; encodedComponent++) { int component = encodedComponent < 2 ? encodedComponent ^ 1 : encodedComponent; - // Pixel conversion has finished. Reuse two of its component rows for DC prediction; - // the disjoint first row still holds packed residuals for entropy emission. - Span values = MemoryMarshal.Cast(floatRows.Slice(this.groupWidth, rectangle.Width)); + // Pixel conversion has finished. Reuse two of its float rows as the DC rows of the prediction. + Span current = MemoryMarshal.Cast(floatRows.Slice(this.groupWidth, rectangle.Width)); Span previous = MemoryMarshal.Cast(floatRows.Slice(2 * this.groupWidth, rectangle.Width)); for (int row = 0; row < rectangle.Height; row++) { cancellationToken.ThrowIfCancellationRequested(); - varDct.CopyDcRow(component, rectangle.X, rectangle.Y + row, values); - Span packed = residuals[..rectangle.Width]; + varDct.CopyDcRow(component, rectangle.X, rectangle.Y + row, current); + Span packed = values.Slice(count, rectangle.Width); if (gradient) { - JxlModularPredictor.PackGradientResiduals(values, row == 0 ? [] : previous, packed); + JxlModularPredictor.PackGradientResiduals(current, row == 0 ? [] : previous, packed); } else { - JxlModularPredictor.PackZeroResiduals(values, packed); + JxlModularPredictor.PackZeroResiduals(current, packed); } - this.WriteValues(packed, codeLength, prefixCodes, output); + count += packed.Length; // Retain the previous row by swapping scratch spans. Each component and DC // group starts with an empty predictor row, so old scratch values are never read. Span next = previous; - previous = values; - values = next; + previous = current; + current = next; } } + this.WriteLocalStream(values[..count], gradient, true, output); Rectangle pixels = new(rectangle.X * 8, rectangle.Y * 8, 8 * GroupDimension, 8 * GroupDimension); - this.WriteVarDctExtras(varDct, pixels, 3, 1000, gradient, residuals, codeLength, prefixCodes, output, cancellationToken); + this.WriteVarDctExtras(varDct, pixels, 3, 1000, gradient, values, output, cancellationToken); // DCT8 has one transform record per block. The two correlation planes retain the native // fast-path defaults. Sharpness four selects the native fast-path restoration strength. int area = rectangle.Width * rectangle.Height; this.WriteBits(32 - BitOperations.LeadingZeroCount((uint)(area - 1)), (uint)area - 1, output); - this.WriteModularHeader(output); Size correlation = new(((rectangle.Width - 1) / 8) + 1, ((rectangle.Height - 1) / 8) + 1); - this.WriteConstantChannel(correlation, 0, gradient, residuals, codeLength, prefixCodes, output, cancellationToken); - this.WriteConstantChannel(correlation, 0, gradient, residuals, codeLength, prefixCodes, output, cancellationToken); - this.WriteConstantChannel(new Size(area, 1), 0, gradient, residuals, codeLength, prefixCodes, output, cancellationToken); - this.WriteConstantChannel( - new Size(area, 1), varDct.AcQuantizer - 1, gradient, residuals, codeLength, prefixCodes, output, cancellationToken); - - this.WriteConstantChannel(rectangle.Size, 4, gradient, residuals, codeLength, prefixCodes, output, cancellationToken); + count = PackConstantChannel(correlation, 0, gradient, values); + count += PackConstantChannel(correlation, 0, gradient, values[count..]); + count += PackConstantChannel(new Size(area, 1), 0, gradient, values[count..]); + count += PackConstantChannel(new Size(area, 1), varDct.AcQuantizer - 1, gradient, values[count..]); + count += PackConstantChannel(rectangle.Size, 4, gradient, values[count..]); + this.WriteLocalStream(values[..count], gradient, true, output); if (!combined) { @@ -1640,10 +1671,22 @@ private void EncodeVarDctFrame( for (int pass = 0; pass < passes; pass++) { this.WriteU32(0, (0, 0x5F), (0, 0x13), (0, 0), (13, 0), output); // Natural coefficient orders. - this.WritePrefixHeader( - JxlConstants.DefaultBlockContextCount * (JxlConstants.NonzeroContextCount + JxlConstants.ZeroDensityContextCount), - codeLength, - output); + int codeOffset = pass * MaximumClusterCount * TokenAlphabetSize; + + this.WriteAcHistograms( + varDct, + blocks, + pass, + passes, + order, + acCountOwner.GetSpan(), + acBytes, + acFloatOwner.GetSpan(), + acClusters.Slice(pass * AcHistogramCount, AcHistogramCount), + acLengths.Slice(codeOffset, MaximumClusterCount * TokenAlphabetSize), + acCodes.Slice(codeOffset, MaximumClusterCount * TokenAlphabetSize), + output, + cancellationToken); } if (!combined) @@ -1659,17 +1702,23 @@ private void EncodeVarDctFrame( int minimumShift = passes == 1 ? 0 : 2 - pass; int maximumShift = passes == 1 ? 2 : minimumShift; + int codeOffset = pass * MaximumClusterCount * TokenAlphabetSize; + ReadOnlySpan passClusters = acClusters.Slice(pass * AcHistogramCount, AcHistogramCount); + ReadOnlySpan passLengths = acLengths.Slice(codeOffset, MaximumClusterCount * TokenAlphabetSize); + ReadOnlySpan passCodes = acCodes.Slice(codeOffset, MaximumClusterCount * TokenAlphabetSize); + Span nonzeros = acBytes.Slice(AcContextCount + (2 * MaximumClusterCount), 3 * AcGroupBlocks); + for (int group = 0; group < this.groupCount; group++) { cancellationToken.ThrowIfCancellationRequested(); long start = combined ? 0 : this.payload.Position; - int x = (group % this.groupColumns) * (GroupDimension / 8); - int y = (group / this.groupColumns) * (GroupDimension / 8); - Rectangle rectangle = new(x, y, Math.Min(GroupDimension / 8, blocks.Width - x), Math.Min(GroupDimension / 8, blocks.Height - y)); - this.WriteAcGroup(varDct, rectangle, pass, passes, order, codeLength, prefixCodes, output, cancellationToken); - Rectangle pixels = new(x * 8, y * 8, GroupDimension, GroupDimension); + Rectangle rectangle = this.GetAcGroupBlocks(group, blocks); + this.TokenizeAcGroup( + varDct, rectangle, pass, passes, order, nonzeros, [], passClusters, passLengths, passCodes, output, cancellationToken); + + Rectangle pixels = new(rectangle.X * 8, rectangle.Y * 8, GroupDimension, GroupDimension); this.WriteVarDctExtras( - varDct, pixels, minimumShift, maximumShift, gradient, residuals, codeLength, prefixCodes, output, cancellationToken); + varDct, pixels, minimumShift, maximumShift, gradient, values, output, cancellationToken); this.FlushBits(output); sectionSizes[combined ? 0 : 2 + this.dcGroupCount + (pass * this.groupCount) + group] = GetSectionSize(this.payload.Position - start); @@ -1685,113 +1734,6 @@ private void EncodeVarDctFrame( } } - /// - /// Writes one spectral contribution in block-row and Y, X, B order through the shared prefix writer. - /// - /// The retained quantized coefficients. - /// The group in block coordinates. - /// The spectral pass index. - /// One full pass or three spectral passes. - /// The natural DCT8 coefficient order. - /// The prepared prefix width. - /// The prepared LSB-first codes. - /// The retained byte buffer. - /// The token checked between block rows. - private void WriteAcGroup( - JxlVarDctEncoder varDct, - Rectangle rectangle, - int pass, - int passes, - ReadOnlySpan order, - int codeLength, - ReadOnlySpan prefixCodes, - Span output, - CancellationToken cancellationToken) - { - InlineArray64 scanStorage = default; - Span scan = scanStorage; - InlineArray64 packedStorage = default; - Span packedValues = packedStorage; - InlineArray64 positionStorage = default; - Span positions = positionStorage; - InlineArray64 indexStorage = default; - Span indices = indexStorage; - int selectedCount = 0; - - // Select each pass's frequencies once. The three spectral regions contain 3, 5 and 55 AC - // coefficients. Their scan positions retain the natural order, including gaps for earlier passes. - // Unselected scan entries start at zero and are never changed. Every selected entry is overwritten - // for every block, so scans need neither another coefficient pass nor a per-block clear. - for (int k = 1; k < 64; k++) - { - int index = (int)order[k]; - int fx = index / 8; - int fy = index & 7; - int stage = fx < 2 && fy < 2 ? 0 : fx < 3 && fy < 3 ? 1 : 2; - - if (passes == 1 || pass == stage) - { - positions[selectedCount] = k; - indices[selectedCount++] = index; - } - } - - for (int y = rectangle.Y; y < rectangle.Bottom; y++) - { - cancellationToken.ThrowIfCancellationRequested(); - _ = varDct.TryGetCoefficientRow(0, rectangle.X, y, rectangle.Width, out Span rowX); - _ = varDct.TryGetCoefficientRow(1, rectangle.X, y, rectangle.Width, out Span rowY); - _ = varDct.TryGetCoefficientRow(2, rectangle.X, y, rectangle.Width, out Span rowB); - - for (int x = rectangle.X; x < rectangle.Right; x++) - { - for (int encodedComponent = 0; encodedComponent < 3; encodedComponent++) - { - int component = encodedComponent < 2 ? encodedComponent ^ 1 : encodedComponent; - ReadOnlySpan row = component switch - { - 0 => rowX, - 1 => rowY, - _ => rowB - }; - - // A normal allocator exposes this group row as one contiguous footprint. Small - // segments borrow individual blocks instead; both paths visit the same 64-value layout. - ReadOnlySpan coefficients = row.IsEmpty - ? varDct.GetCoefficientBlock(component, x, y) - : row.Slice((x - rectangle.X) * 64, 64); - - int count = 0; - int last = 0; - - // DC never appears in this scan. Selected positions increase in wire order, so - // the final nonzero position also bounds the coefficient symbols that must be emitted. - for (int i = 0; i < selectedCount; i++) - { - int k = positions[i]; - int value = coefficients[indices[i]]; - scan[k] = value; - - if (value != 0) - { - count++; - last = k; - } - } - - this.WriteValue((uint)count, codeLength, prefixCodes, output); - - if (last != 0) - { - Span packed = packedValues[..last]; - JxlModularPredictor.PackZeroResiduals(scan.Slice(1, last), packed); - this.WriteValues(packed, codeLength, prefixCodes, output); - } - } - } - } - } - /// /// Writes the extra channels assigned to one DC or progressive AC section. /// @@ -1799,10 +1741,8 @@ private void WriteAcGroup( /// The uncropped section rectangle in full-resolution pixels. /// The inclusive minimum channel reduction. /// The inclusive maximum channel reduction. - /// Whether the global tree uses gradient prediction. - /// The reusable residual row. - /// The prepared prefix width. - /// The prepared LSB-first codes. + /// Whether the stream tree uses gradient prediction. + /// Receives the packed residuals of the stream. It holds one group region of each extra channel. /// The retained byte buffer. /// The token checked between channels and rows. private void WriteVarDctExtras( @@ -1811,13 +1751,11 @@ private void WriteVarDctExtras( int minimumShift, int maximumShift, bool gradient, - Span residuals, - int codeLength, - ReadOnlySpan prefixCodes, + Span values, Span output, CancellationToken cancellationToken) { - bool hasSamples = false; + int count = 0; for (int c = this.globalPrefixCount; c < this.extraChannels.Length; c++) { @@ -1835,155 +1773,132 @@ private void WriteVarDctExtras( continue; } - if (!hasSamples) - { - this.WriteModularHeader(output); - hasSamples = true; - } - - this.WriteVarDctExtraChannel(varDct, c, region, gradient, residuals, codeLength, prefixCodes, output, cancellationToken); + count += this.PackVarDctExtraChannel(varDct, c, region, gradient, values[count..], cancellationToken); } + + // A stream without selected channel samples has no header and occupies zero bytes. + this.WriteLocalStream(values[..count], gradient, true, output); } /// - /// Writes supplied extra samples or retained pixel-derived alpha without another color conversion. + /// Packs the residuals of supplied extra samples or retained pixel-derived alpha without another color conversion. /// /// The retained derived-alpha owner. /// The encoded extra-channel index. /// The clipped channel region in its own reduced coordinates. - /// Whether the global tree uses gradient prediction. - /// The reusable residual row. - /// The prepared prefix width. - /// The prepared LSB-first codes. - /// The retained byte buffer. + /// Whether the stream tree uses gradient prediction. + /// Receives the packed unsigned residuals, row by row. /// The token checked between rows. - private void WriteVarDctExtraChannel( + /// The number of residuals. + private int PackVarDctExtraChannel( JxlVarDctEncoder varDct, int index, Rectangle region, bool gradient, - Span residuals, - int codeLength, - ReadOnlySpan prefixCodes, - Span output, + Span destination, CancellationToken cancellationToken) { + Span packed = destination[..(region.Width * region.Height)]; + if (index < this.encoder.ExtraChannels.Count) { this.CopySuppliedSamples(index, region, cancellationToken); if (gradient) { - this.WriteGradientComponent(this.colorComponents + index, region.Size, residuals, codeLength, prefixCodes, output, cancellationToken); + this.PackGradientComponent(this.colorComponents + index, region.Size, packed, cancellationToken); } else { - this.WriteZeroComponent(this.colorComponents + index, region.Size, residuals, codeLength, prefixCodes, output, cancellationToken); + this.PackZeroComponent(this.colorComponents + index, region.Size, packed, cancellationToken); } - return; + return packed.Length; } - Span packed = residuals[..region.Width]; - for (int y = 0; y < region.Height; y++) { cancellationToken.ThrowIfCancellationRequested(); - ReadOnlySpan values = varDct.GetAlphaRow(region.X, region.Y + y)[..region.Width]; + ReadOnlySpan row = varDct.GetAlphaRow(region.X, region.Y + y)[..region.Width]; ReadOnlySpan previous = y == 0 ? [] : varDct.GetAlphaRow(region.X, region.Y + y - 1)[..region.Width]; + Span residuals = packed.Slice(y * region.Width, region.Width); if (gradient) { - JxlModularPredictor.PackGradientResiduals(values, previous, packed); + JxlModularPredictor.PackGradientResiduals(row, previous, residuals); } else { - JxlModularPredictor.PackZeroResiduals(values, packed); + JxlModularPredictor.PackZeroResiduals(row, residuals); } - - this.WriteValues(packed, codeLength, prefixCodes, output); } + + return packed.Length; } /// - /// Emits a constant metadata plane in bounded batches without allocating its full sample grid. + /// Packs the residuals of a constant metadata plane. /// /// The metadata plane dimensions. /// The actual transform, quantizer, correlation or sharpness value. - /// Whether the global tree uses gradient prediction. - /// The reusable packed-value scratch. - /// The prepared prefix width. - /// The prepared LSB-first codes. - /// The retained byte buffer. - /// The token checked between rows and batches. - private void WriteConstantChannel( - Size size, - int value, - bool gradient, - Span residuals, - int codeLength, - ReadOnlySpan prefixCodes, - Span output, - CancellationToken cancellationToken) + /// Whether the stream tree uses gradient prediction. + /// Receives the packed unsigned residuals, row by row. + /// The number of residuals. + private static int PackConstantChannel(Size size, int value, bool gradient, Span destination) { - Span carriers = MemoryMarshal.Cast(residuals); - - // A constant gradient-predicted plane has only one nonzero residual, at its first sample. - // The zero predictor stores the same value at every position. Pack through the existing SIMD worker. - carriers.Fill(gradient ? 0 : value); - JxlModularPredictor.PackZeroResiduals(carriers, residuals); - - for (int y = 0; y < size.Height; y++) - { - for (int x = 0; x < size.Width; x += residuals.Length) - { - cancellationToken.ThrowIfCancellationRequested(); - int count = Math.Min(residuals.Length, size.Width - x); - - if (gradient && y == 0 && x == 0) - { - carriers[0] = value; - JxlModularPredictor.PackZeroResiduals(carriers[..1], residuals[..1]); - } - - this.WriteValues(residuals[..count], codeLength, prefixCodes, output); - - if (gradient) - { - residuals[0] = 0; - } - } - } + Span packed = destination[..(size.Width * size.Height)]; + + // The packed value comes from the shared signed packing. A constant gradient-predicted plane has only one nonzero + // residual, at its first sample: every other prediction is the constant itself. The zero predictor stores the value + // at every position. + int carrier = value; + uint residual = 0; + JxlModularPredictor.PackZeroResiduals(new ReadOnlySpan(ref carrier), new Span(ref residual)); + packed.Fill(gradient ? 0 : residual); + packed[0] = residual; + return packed.Length; } /// - /// Writes the single-leaf shared modular tree and its residual entropy description. + /// Writes the channel transforms of the global modular stream: the horizontal and vertical squeeze of the colors in progressive mode, + /// or no transform. /// - /// Whether integer channels use the clamped gradient instead of the zero predictor. - /// The prepared prefix width. - /// The prepared LSB-first codes. /// The retained byte buffer. - private void WriteGlobalTree(bool gradient, int codeLength, ReadOnlySpan prefixCodes, Span output) + private void WriteGlobalTransforms(Span output) { - this.WriteBits(1, 1, output); - this.WritePrefixHeader(6, codeLength, output); - this.WriteValue(0, codeLength, prefixCodes, output); // Property zero marks a leaf. - this.WriteValue(gradient ? 5U : 0U, codeLength, prefixCodes, output); - this.WriteValue(0, codeLength, prefixCodes, output); // No signed prediction offset. - this.WriteValue(0, codeLength, prefixCodes, output); // Multiplier exponent zero. - this.WriteValue(0, codeLength, prefixCodes, output); // Unit residual multiplier, stored minus one. - this.WritePrefixHeader(1, codeLength, output); + if (this.squeezedComponents != 0) + { + this.WriteBits(2, 1, output); // One channel transform. + this.WriteBits(2, 2, output); // Squeeze transform. + this.WriteU32(2, (0, 0), (4, 1), (6, 9), (8, 41), output); + + for (int direction = 0; direction < 2; direction++) + { + this.WriteBits(1, direction == 0 ? 1U : 0U, output); // Horizontal, then vertical. + this.WriteBits(1, 1, output); // Insert residuals after the selected colors. + this.WriteU32(0, (3, 0), (6, 8), (10, 72), (13, 1096), output); + this.WriteU32((uint)this.squeezedComponents, (0, 1), (0, 2), (0, 3), (4, 4), output); + } + } + else + { + this.WriteBits(2, 0, output); // No channel transforms. + } } /// - /// Writes a modular substream header that reuses the global tree and has no local transforms. + /// Writes the tree stream of a modular tree with one leaf. The sample stream header that follows the tree is not part of it. /// + /// Whether the leaf uses the clamped gradient predictor instead of the zero predictor. /// The retained byte buffer. - private void WriteModularHeader(Span output) + private void WriteSingleLeafTree(bool gradient, Span output) { - this.WriteBits(1, 1, output); // Reuse the global tree. - this.WriteBits(1, 1, output); // Default weighted-predictor parameters. - this.WriteBits(2, 0, output); // No local channel transforms. + // The tree tokens of one leaf: property zero marks a leaf, then the predictor, no signed prediction offset, multiplier exponent + // zero, and the unit residual multiplier, stored minus one. The tree stream has 6 contexts and no row width. + InlineArray5 treeStorage = default; + Span tree = treeStorage; + tree[1] = gradient ? 5U : 0U; + this.WriteSampleStream(tree, JxlConstants.TreeContextCount, 0, output); } /// @@ -1998,8 +1913,6 @@ private void WriteModularHeader(Span output) /// The clipped coding group in source coordinates. /// Whether integer samples use the bounded gradient predictor. /// Whether the output conversion clears colors at zero alpha. - /// The common prefix-code width. - /// The prepared least-significant-bit-first codes. /// The retained converted vector row. /// Four retained component rows with this.groupWidth elements each. /// The retained output byte buffer. @@ -2013,8 +1926,6 @@ private void WriteGroup( Rectangle bounds, bool useGradient, bool clearTransparent, - int codeLength, - ReadOnlySpan prefixCodes, Span pixelRow, Span floatRows, Span output, @@ -2041,9 +1952,9 @@ private void WriteGroup( alphaDecodeOperation, cancellationToken); - // Conversion is complete for the group. Reuse its first float scratch row as packed uint residuals; - // the next group overwrites that row before any float sample reads it. No additional row owner is needed. - Span residuals = MemoryMarshal.Cast(floatRows[..bounds.Width]); + // The residuals of all components go to the group buffer in stream order: each component, row by row. + Span values = this.groupValues!.GetSpan(); + int count = 0; // Select the predictor outside sample traversal. Both workers borrow the same completed component planes. for (int component = 0; component < this.componentCount; component++) @@ -2066,15 +1977,35 @@ private void WriteGroup( this.CopySuppliedSamples(extraIndex, region, cancellationToken); } + Span destination = values.Slice(count, componentSize.Width * componentSize.Height); if (useGradient) { - this.WriteGradientComponent(component, componentSize, residuals, codeLength, prefixCodes, output, cancellationToken); + this.PackGradientComponent(component, componentSize, destination, cancellationToken); } else { - this.WriteZeroComponent(component, componentSize, residuals, codeLength, prefixCodes, output, cancellationToken); + this.PackZeroComponent(component, componentSize, destination, cancellationToken); } + + count += destination.Length; } + + this.WriteLocalStream(values[..count], useGradient, true, output); + } + + /// + /// Gets the bounds of one coding group in source coordinates, clipped to the frame. + /// + /// The source pixel type. + /// The source frame. + /// The group index, in raster order. + /// The group bounds. + private Rectangle GetGroupBounds(ImageFrame image, int index) + where TPixel : unmanaged, IPixel + { + int x = (index % this.groupColumns) * GroupDimension; + int y = (index / this.groupColumns) * GroupDimension; + return new(x, y, Math.Min(GroupDimension, image.Width - x), Math.Min(GroupDimension, image.Height - y)); } /// @@ -2223,29 +2154,25 @@ private void PrepareExpandedAlpha(TAlpha operation, TAlpha /// /// Writes eightfold-reduced supplied channels into their DC-group streams in a plain modular frame. /// - /// Whether the shared tree uses gradient prediction. - /// The prepared prefix-code width. - /// The prepared prefix codes. - /// Conversion scratch reused for unsigned residuals. + /// Whether the trees use the clamped gradient predictor. /// The frame section table. /// The retained output byte workspace. /// The token checked between groups and rows. private void WritePlainDcSections( bool gradient, - int codeLength, - ReadOnlySpan prefixCodes, - Span floatRows, Span sectionSizes, Span output, CancellationToken cancellationToken) { int columns = ((this.groupColumns - 1) / 8) + 1; - Span residuals = MemoryMarshal.Cast(floatRows[..this.groupWidth]); for (int group = 0; group < this.dcGroupCount; group++) { long start = this.payload.Position; - bool hasSamples = false; + + // The residuals of all reduced channels go to the group buffer in stream order. A reduced region fits the buffer of a group. + Span values = this.groupValues!.GetSpan(); + int count = 0; for (int c = 0; c < this.encoder.ExtraChannels.Count; c++) { @@ -2265,26 +2192,23 @@ private void WritePlainDcSections( continue; } - if (!hasSamples) - { - this.WriteBits(1, 1, output); // Reuse the global tree. - this.WriteBits(1, 1, output); // Default weighted predictor. - this.WriteBits(2, 0, output); // No local transforms. - hasSamples = true; - } - + // The scratch plane holds one supplied channel at a time, so the residuals are packed before the next copy. this.CopySuppliedSamples(c, region, cancellationToken); - + Span destination = values.Slice(count, region.Width * region.Height); if (gradient) { - this.WriteGradientComponent(this.colorComponents + c, region.Size, residuals, codeLength, prefixCodes, output, cancellationToken); + this.PackGradientComponent(this.colorComponents + c, region.Size, destination, cancellationToken); } else { - this.WriteZeroComponent(this.colorComponents + c, region.Size, residuals, codeLength, prefixCodes, output, cancellationToken); + this.PackZeroComponent(this.colorComponents + c, region.Size, destination, cancellationToken); } + + count += destination.Length; } + this.WriteLocalStream(values[..count], gradient, true, output); + this.FlushBits(output); sectionSizes[1 + group] = GetSectionSize(this.payload.Position - start); } @@ -2538,24 +2462,20 @@ private void SqueezeVerticalPair(Buffer2D rows, int y) /// /// Writes global progressive samples and two ordered passes over the remaining channel regions. /// - /// Whether the global tree selects clamped gradient prediction. - /// The common symbol width. - /// The prepared prefix codes. - /// Conversion scratch reused as unsigned residuals after conversion ends. + /// Whether the trees select clamped gradient prediction. /// The retained frame section table. /// The output byte workspace. /// The token checked between groups and rows. private void WriteProgressiveSections( bool gradient, - int codeLength, - ReadOnlySpan prefixCodes, - Span floatRows, Span sectionSizes, Span output, CancellationToken cancellationToken) { - Span residuals = MemoryMarshal.Cast(floatRows[..this.groupWidth]); - + // Each stream packs the residuals of its channel regions in stream order, then writes them with the entropy code of their + // histogram. LF-global wrote the header of the global stream, so its tree follows directly. + Span values = this.groupValues!.GetSpan(); + int count = 0; for (int c = 0; c < this.globalPrefixCount; c++) { JxlModularChannel channel = this.progressiveChannels[c]; @@ -2566,10 +2486,10 @@ private void WriteProgressiveSections( continue; } - this.WriteProgressiveChannel( - channel, new Rectangle(Point.Empty, channel.Size), gradient, residuals, codeLength, prefixCodes, output, cancellationToken); + count += PackProgressiveChannel(channel, new Rectangle(Point.Empty, channel.Size), gradient, values[count..], cancellationToken); } + this.WriteLocalStream(values[..count], gradient, false, output); this.FlushBits(output); sectionSizes[0] = GetSectionSize(this.payload.Position); @@ -2578,7 +2498,7 @@ private void WriteProgressiveSections( for (int group = 0; group < this.dcGroupCount; group++) { long start = this.payload.Position; - bool hasSamples = false; + count = 0; int groupX = (group % dcColumns) * (8 * GroupDimension); int groupY = (group / dcColumns) * (8 * GroupDimension); @@ -2602,18 +2522,10 @@ private void WriteProgressiveSections( continue; } - if (!hasSamples) - { - this.WriteBits(1, 1, output); // Reuse the global tree. - this.WriteBits(1, 1, output); // Default weighted predictor. - this.WriteBits(2, 0, output); // No local transforms. - hasSamples = true; - } - - this.WriteProgressiveChannel( - channel, new Rectangle(x, y, width, height), gradient, residuals, codeLength, prefixCodes, output, cancellationToken); + count += PackProgressiveChannel(channel, new Rectangle(x, y, width, height), gradient, values[count..], cancellationToken); } + this.WriteLocalStream(values[..count], gradient, true, output); this.FlushBits(output); sectionSizes[1 + group] = GetSectionSize(this.payload.Position - start); } @@ -2624,7 +2536,7 @@ private void WriteProgressiveSections( { cancellationToken.ThrowIfCancellationRequested(); long start = this.payload.Position; - bool hasSamples = false; + count = 0; int groupX = (group % this.groupColumns) * GroupDimension; int groupY = (group / this.groupColumns) * GroupDimension; @@ -2650,19 +2562,11 @@ private void WriteProgressiveSections( continue; } - if (!hasSamples) - { - this.WriteBits(1, 1, output); // Reuse the global tree. - this.WriteBits(1, 1, output); // Default weighted predictor. - this.WriteBits(2, 0, output); // No local transforms. - hasSamples = true; - } - - this.WriteProgressiveChannel( - channel, new Rectangle(x, y, width, height), gradient, residuals, codeLength, prefixCodes, output, cancellationToken); + count += PackProgressiveChannel(channel, new Rectangle(x, y, width, height), gradient, values[count..], cancellationToken); } // A stream without selected channel samples has no header and occupies zero bytes. + this.WriteLocalStream(values[..count], gradient, true, output); this.FlushBits(output); sectionSizes[2 + this.dcGroupCount + (pass * this.groupCount) + group] = GetSectionSize(this.payload.Position - start); } @@ -2670,32 +2574,60 @@ private void WriteProgressiveSections( } /// - /// Emits a channel region with prediction restarted at its modular stream boundary. + /// Writes a modular stream with its own tree with one leaf and the entropy code of the histogram of its residuals. A stream without + /// samples writes nothing, because the decoder reads no tree and no samples for it. + /// + /// The packed residuals of the stream, in stream order. + /// Whether the leaf uses the clamped gradient predictor instead of the zero predictor. + /// + /// Whether to write the stream header first: a local tree, the default weighted predictor and no local transforms. The global stream + /// header comes from LF-global. + /// + /// The output byte workspace. + private void WriteLocalStream( + ReadOnlySpan values, + bool gradient, + bool writeHeader, + Span output) + { + if (values.IsEmpty) + { + return; + } + + if (writeHeader) + { + this.WriteBits(1, 0, output); + this.WriteBits(1, 1, output); + this.WriteBits(2, 0, output); + } + + // A modular stream has a row width, so a copy from the value before uses the short distance symbol 1. + this.WriteSingleLeafTree(gradient, output); + this.WriteSampleStream(values, 1, 1, output); + } + + /// + /// Packs the residuals of a channel region, with prediction restarted at its modular stream boundary. /// /// The retained transformed plane. /// The selected region in channel coordinates. - /// Whether to use the clamped-gradient tree leaf. - /// The reusable unsigned residual row. - /// The prefix-code width. - /// The prepared prefix codes. - /// The output byte workspace. + /// Whether to use the clamped-gradient prediction. + /// Receives the packed unsigned residuals, row by row. /// The token checked before each row. - private void WriteProgressiveChannel( + /// The number of residuals. + private static int PackProgressiveChannel( JxlModularChannel channel, Rectangle bounds, bool gradient, - Span workspace, - int codeLength, - ReadOnlySpan prefixCodes, - Span output, + Span destination, CancellationToken cancellationToken) { - Span residuals = workspace[..bounds.Width]; - for (int y = 0; y < bounds.Height; y++) { cancellationToken.ThrowIfCancellationRequested(); ReadOnlySpan row = channel.GetRow(bounds.Y + y).Slice(bounds.X, bounds.Width); + Span residuals = destination.Slice(y * bounds.Width, bounds.Width); if (gradient) { @@ -2706,83 +2638,53 @@ private void WriteProgressiveChannel( { JxlModularPredictor.PackZeroResiduals(row, residuals); } - - this.WriteValues(residuals, codeLength, prefixCodes, output); } + + return bounds.Width * bounds.Height; } /// - /// Encodes one integer component with the shared clamped-gradient predictor. + /// Packs the clamped-gradient residuals of one component, row by row. /// /// The selected component index. - /// The clipped group size. - /// The reused row scratch for packed unsigned residuals. - /// The common symbol width. - /// The prepared symbol codes. - /// The retained output buffer. + /// The clipped group size of the component. + /// Receives the packed unsigned residuals. Its length is the sample count of the component. /// The token checked before rows. - private void WriteGradientComponent( - int component, - Size size, - Span residuals, - int codeLength, - ReadOnlySpan prefixCodes, - Span output, - CancellationToken cancellationToken) + private void PackGradientComponent(int component, Size size, Span destination, CancellationToken cancellationToken) { - residuals = residuals[..size.Width]; - for (int y = 0; y < size.Height; y++) { cancellationToken.ThrowIfCancellationRequested(); ReadOnlySpan row = this.GetComponentRow(component, y)[..size.Width]; ReadOnlySpan previous = y == 0 ? [] : this.GetComponentRow(component, y - 1)[..size.Width]; - JxlModularPredictor.PackGradientResiduals(row, previous, residuals); - // Prediction and signed packing use independent SIMD lanes. Entropy emission retains one ordered bit reservoir. - this.WriteValues(residuals, codeLength, prefixCodes, output); + // Prediction and signed packing use independent SIMD lanes. + JxlModularPredictor.PackGradientResiduals(row, previous, destination.Slice(y * size.Width, size.Width)); } } /// - /// Encodes raw floating-point carrier bits without prediction subtraction. + /// Packs the raw floating-point carrier bits of one component, without prediction subtraction, row by row. /// /// The selected component index. - /// The clipped group size. - /// The reused row scratch for packed unsigned residuals. - /// The common symbol width. - /// The prepared symbol codes. - /// The retained output buffer. + /// The clipped group size of the component. + /// Receives the packed unsigned residuals. Its length is the sample count of the component. /// The token checked before rows. - private void WriteZeroComponent( - int component, - Size size, - Span residuals, - int codeLength, - ReadOnlySpan prefixCodes, - Span output, - CancellationToken cancellationToken) + private void PackZeroComponent(int component, Size size, Span destination, CancellationToken cancellationToken) { - residuals = residuals[..size.Width]; - for (int y = 0; y < size.Height; y++) { cancellationToken.ThrowIfCancellationRequested(); ReadOnlySpan row = this.GetComponentRow(component, y)[..size.Width]; - - JxlModularPredictor.PackZeroResiduals(row, residuals); - - this.WriteValues(residuals, codeLength, prefixCodes, output); + JxlModularPredictor.PackZeroResiduals(row, destination.Slice(y * size.Width, size.Width)); } } /// /// Writes the image dimensions, color model and declared component precision. /// - /// The prepared entropy symbol width, also sufficient for profile bytes. - /// The prepared canonical symbol codes. /// The retained output buffer. - private void WriteImageHeader(int codeLength, ReadOnlySpan prefixCodes, Span output) + private void WriteImageHeader(Span output) { this.WriteBits(16, 0x0AFF, output); this.WriteBits(1, 0, output); // General dimensions, including sizes that are not multiples of eight. @@ -2844,6 +2746,7 @@ private void WriteImageHeader(int codeLength, ReadOnlySpan prefixCodes, Sp uint white = this.whitePoint == KnownIlluminants.D65Chromaticity ? 1U : this.whitePoint == KnownIlluminants.EChromaticity ? 10U : this.whitePoint == KnownIlluminants.DciP3Chromaticity ? 11U : 2U; + this.WriteU32(white, (0, 0), (0, 1), (4, 2), (6, 18), output); if (white == 2) @@ -2856,6 +2759,7 @@ private void WriteImageHeader(int codeLength, ReadOnlySpan prefixCodes, Sp uint primaries = this.primaries.Equals(KnownRgbWorkingSpaces.SRgb.ChromaticityCoordinates) ? 1U : this.primaries.Equals(KnownRgbWorkingSpaces.Rec2020.ChromaticityCoordinates) ? 9U : this.primaries.Equals(KnownRgbWorkingSpaces.DisplayP3.ChromaticityCoordinates) ? 11U : 2U; + this.WriteU32(primaries, (0, 0), (0, 1), (4, 2), (6, 18), output); if (primaries == 2) @@ -2899,7 +2803,7 @@ private void WriteImageHeader(int codeLength, ReadOnlySpan prefixCodes, Sp if (this.profile is not null) { - this.WriteIccProfile(this.profileData.Span, codeLength, prefixCodes, output); + this.WriteIccProfile(this.profileData.Span, output); } this.FlushBits(output); @@ -2975,14 +2879,16 @@ private void WriteExtraChannel(JxlExtraChannelMetadata channel, Span outpu /// Writes ICC prediction bytes directly into their entropy stream without a second profile-sized buffer. /// /// The unchanged original profile bytes. - /// The prepared entropy symbol width. - /// The canonical symbol codes. /// The borrowed output byte buffer. - private void WriteIccProfile(ReadOnlySpan data, int codeLength, ReadOnlySpan prefixCodes, Span output) + private void WriteIccProfile(ReadOnlySpan data, Span output) { + // The preamble and the commands each fit their 12-byte buffer, so the stream has at most 24 more bytes than the profile. + using IMemoryOwner valueOwner = this.memoryAllocator.Allocate(data.Length + 24); + // A zero tag-list command followed by one literal insertion represents every valid profile tail. - // Header residuals still use the shared previous-byte predictions. All byte contexts share one prefix table. - Span commands = stackalloc byte[12]; + // Header residuals still use the shared previous-byte predictions. All byte contexts share one cluster. + InlineArray12 commandStorage = default; + Span commands = commandStorage; int commandLength = 0; if (data.Length > JxlIccPrediction.HeaderSize) @@ -2992,32 +2898,38 @@ private void WriteIccProfile(ReadOnlySpan data, int codeLength, ReadOnlySp commandLength += WriteVarUInt((uint)(data.Length - JxlIccPrediction.HeaderSize), commands[commandLength..]); } - Span preamble = stackalloc byte[12]; + InlineArray12 preambleStorage = default; + Span preamble = preambleStorage; int preambleLength = WriteVarUInt((uint)data.Length, preamble); preambleLength += WriteVarUInt((uint)commandLength, preamble[preambleLength..]); this.WriteU64((ulong)(data.Length + commandLength + preambleLength), output); - this.WritePrefixHeader(41, codeLength, output); + // The stream bytes in order: the preamble, the commands, the header residuals and the profile tail. + Span values = valueOwner.GetSpan()[..(data.Length + commandLength + preambleLength)]; + int count = 0; foreach (byte value in preamble[..preambleLength]) { - this.WriteValue(value, codeLength, prefixCodes, output); + values[count++] = value; } foreach (byte value in commands[..commandLength]) { - this.WriteValue(value, codeLength, prefixCodes, output); + values[count++] = value; } for (int i = 0; i < JxlIccPrediction.HeaderSize; i++) { byte prediction = JxlIccPrediction.GetHeaderPrediction(data, data.Length, i); - this.WriteValue((byte)(data[i] - prediction), codeLength, prefixCodes, output); + values[count++] = (byte)(data[i] - prediction); } foreach (byte value in data[JxlIccPrediction.HeaderSize..]) { - this.WriteValue(value, codeLength, prefixCodes, output); + values[count++] = value; } + + // The ICC stream has 41 contexts and no row width. + this.WriteSampleStream(values, JxlConstants.IccContextCount, 0, output); } /// @@ -3231,171 +3143,6 @@ private void WriteFrameHeader(ReadOnlySpan sectionSizes, uint duration, bo this.FlushBits(output); } - /// - /// Writes one no-LZ77 prefix description with a complete fixed-length alphabet and hybrid integer configuration zero. - /// - /// The syntax-defined context count, all assigned to one cluster. - /// The fixed code width selected from the declared sample precision. - /// The retained output buffer. - private void WritePrefixHeader(int contexts, int codeLength, Span output) - { - this.WriteBits(1, 0, output); // No LZ77 copy symbols or history. - - if (contexts > 1) - { - this.WriteBits(1, 1, output); // Simple context map. - this.WriteBits(2, 0, output); // Zero bits per entry assigns every context to cluster zero. - } - - this.WriteBits(1, 1, output); // Prefix entropy coding. - this.WriteBits(4, 0, output); // Hybrid split zero; leading and trailing configuration widths are also zero. - this.WriteBits(1, 1, output); // Alphabet size is greater than one. - this.WriteBits(4, (uint)(codeLength - 1), output); - this.WriteBits(codeLength - 1, (1U << (codeLength - 1)) - 1, output); - - // A complete fixed-length alphabet needs only one code-length symbol. - // Skip the first three zero entries. Give only the selected length a one-bit meta-code; its sole symbol - // then consumes zero bits until the complete fixed-length alphabet fills the prefix space. - this.WriteBits(2, 3, output); - ReadOnlySpan order = [4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15]; - - foreach (byte length in order) - { - this.WriteBits(length == codeLength ? 4 : 2, length == codeLength ? 7U : 0U, output); - } - } - - /// - /// Emits a residual row in bounded batches with reservoir state retained in local variables. - /// - /// The unsigned residuals in sample order. - /// The common entropy-symbol width. - /// The prepared code for each symbol. - /// The retained buffer, large enough for one complete batch. - private void WriteValues(ReadOnlySpan values, int codeLength, ReadOnlySpan prefixCodes, Span output) - { - // Like JPEG's coding-unit reserve, the batch bound moves stream-capacity checks outside sample emission. - // Only complete uint words leave the reservoir. Partial words remain unaligned between rows and batches. - ulong bits = this.bits; - int pendingBits = this.pendingBits; - int bufferedBytes = this.bufferedBytes; - - while (!values.IsEmpty) - { - int count = Math.Min(values.Length, GroupDimension); - int maximumBytes = (((count * (codeLength + 31)) + 31) / 32) * sizeof(uint); - - if (bufferedBytes > output.Length - maximumBytes) - { - this.outputStream.Write(output[..bufferedBytes]); - bufferedBytes = 0; - } - - ReadOnlySpan batch = values[..count]; - - // The complete equal-length canonical table assigns prefix zero to symbol zero, which has no literals. - // The shared span search checks whole SIMD registers and handles scalar tails. An all-zero batch can - // therefore append its prefix bits together instead of splitting and emitting every residual separately. - if (!batch.ContainsAnyExcept(0U)) - { - int totalBits = pendingBits + (count * codeLength); - int completeBytes = (totalBits / 32) * sizeof(uint); - - if (completeBytes != 0) - { - // Existing pending bits occupy only the first word. Subsequent complete words and the retained - // partial word contain zeros. A short batch that emits no word must retain the existing bits. - BinaryPrimitives.WriteUInt32LittleEndian(output[bufferedBytes..], (uint)bits); - output.Slice(bufferedBytes + sizeof(uint), completeBytes - sizeof(uint)).Clear(); - bufferedBytes += completeBytes; - bits = 0; - } - - pendingBits = totalBits & 31; - values = values[count..]; - continue; - } - - foreach (uint value in batch) - { - JxlHybridUint.Zero.Encode(value, out uint token, out int extraBitCount, out uint extraBits); - uint field = prefixCodes[(int)token]; - int fieldBits = codeLength + extraBitCount; - - if (fieldBits > 32) - { - // A wide residual can have 31 literal bits after its prefix. Drain the prefix first - // when needed so the next field plus fewer than 32 pending bits fits one ulong. - bits |= (ulong)field << pendingBits; - pendingBits += codeLength; - - if (pendingBits >= 32) - { - BinaryPrimitives.WriteUInt32LittleEndian(output[bufferedBytes..], (uint)bits); - bufferedBytes += sizeof(uint); - bits >>= 32; - pendingBits -= 32; - } - - field = extraBits; - fieldBits = extraBitCount; - } - else - { - field |= extraBits << codeLength; - } - - bits |= (ulong)field << pendingBits; - pendingBits += fieldBits; - - if (pendingBits >= 32) - { - // Byte-based writes support unaligned output on every target. No partial word is exposed. - BinaryPrimitives.WriteUInt32LittleEndian(output[bufferedBytes..], (uint)bits); - bufferedBytes += sizeof(uint); - bits >>= 32; - pendingBits -= 32; - } - } - - values = values[count..]; - } - - // Header fields and section padding resume through WriteBits after the completed row. - this.bits = bits; - this.pendingBits = pendingBits; - this.bufferedBytes = bufferedBytes; - } - - /// - /// Emits one unsigned value through hybrid integer configuration zero and prepared canonical prefix codes. - /// - /// The tree value or packed sample residual. - /// The common entropy-symbol width. - /// The prepared code for each symbol. - /// The retained output buffer. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void WriteValue(uint value, int codeLength, ReadOnlySpan prefixCodes, Span output) - { - // The shared hybrid-integer owner supplies the same token layout used by decoding. - JxlHybridUint.Zero.Encode(value, out uint token, out int extraBitCount, out uint extraBits); - uint prefix = prefixCodes[(int)token]; - int count = codeLength + extraBitCount; - - // The prefix comes first in the least-significant-bit-first stream. Join fields that fit one uint - // to update the reservoir once. Wider carriers retain two writes so fewer than 32 pending bits plus - // the next field always fit the 64-bit reservoir, including a full-width signed residual. - if (count <= 32) - { - this.WriteBits(count, prefix | (extraBits << codeLength), output); - } - else - { - this.WriteBits(codeLength, prefix, output); - this.WriteBits(extraBitCount, extraBits, output); - } - } - /// /// Selects the shortest applicable U32 alternative and writes its offset-relative payload. /// diff --git a/src/ImageSharp/Formats/PaletteExpander.cs b/src/ImageSharp/Formats/PaletteExpander.cs index f05228b6f6..1448c80208 100644 --- a/src/ImageSharp/Formats/PaletteExpander.cs +++ b/src/ImageSharp/Formats/PaletteExpander.cs @@ -1,6 +1,7 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +using System.Buffers.Binary; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -12,7 +13,10 @@ namespace SixLabors.ImageSharp.Formats; /// /// /// BMP and PNG pack 1, 2, 4 or 8 bits of index for each pixel. The first pixel is in the most significant bits of -/// a byte. Each pixel is one palette entry, so the decoder converts the palette to TPixel one time. Then each +/// a byte. WebP packs the indices of the color indexing transform the other way: the first pixel is in the least +/// significant bits. See the WebP Lossless Bitstream Specification, section 4.4 "Color Indexing Transform": +/// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#44_color_indexing_transform. +/// Each pixel is one palette entry, so the decoder converts the palette to TPixel one time. Then each /// pixel is one table load and one store, with no color conversion. /// /// @@ -20,6 +24,11 @@ namespace SixLabors.ImageSharp.Formats; /// whole source byte with constant shifts. /// /// +/// A byte palette with 1, 2 or 4 bits for each index has a faster form. A source byte has only 256 values, so a table of 256 +/// entries holds the palette bytes of all indices of each value. Then each source byte is one table load and one store of 8, 4 +/// or 2 bytes. +/// +/// /// The palette has one entry for each value that an index can have: 2, 4, 16 or 256 entries. The decoder fills /// the entries that the file palette does not define. Thus each index selects an entry, and the loads need no /// bounds checks. @@ -42,6 +51,13 @@ public interface IIndexOperator /// static abstract int IndicesPerByte { get; } + /// + /// Gets the right shift that moves the index at a position in the byte to bit 0. + /// + /// The position of the index in the byte, from 0 to - 1. + /// The shift. + static abstract int Shift(int position); + /// /// Writes the pixels of all indices in one byte, first index first. /// @@ -81,6 +97,175 @@ public static void Expand(ReadOnlySpan indices, int bitsPerIndex, } } + /// + /// Expands one row of palette indices that are packed with the first pixel in the least significant bits, as WebP packs them. + /// + /// The pixel type. + /// The packed indices. It holds at least the bytes of . + /// The bit count of one index: 1, 2, 4 or 8. + /// The palette, converted to . It has an entry for each possible index. + /// The destination pixels. + public static void ExpandLowBitsFirst(ReadOnlySpan indices, int bitsPerIndex, ReadOnlySpan palette, Span destination) + where TPixel : unmanaged + { + switch (bitsPerIndex) + { + case 1: + Expand(indices, palette, destination); + break; + case 2: + Expand(indices, palette, destination); + break; + case 4: + Expand(indices, palette, destination); + break; + default: + Expand(indices, palette, destination); + break; + } + } + + /// + /// Builds the table of for a byte palette whose indices are packed with the first pixel in the + /// least significant bits. + /// + /// The bit count of one index: 1, 2 or 4. + /// The palette. It has an entry for each possible index. + /// Receives the 256 entries. + public static void BuildByteTableLowBitsFirst(int bitsPerIndex, ReadOnlySpan palette, Span table) + { + switch (bitsPerIndex) + { + case 1: + BuildByteTable(palette, table); + break; + case 2: + BuildByteTable(palette, table); + break; + default: + BuildByteTable(palette, table); + break; + } + } + + /// + /// Expands one row of byte palette indices that are packed with the first pixel in the least significant bits, with a table from + /// . + /// + /// The packed indices. It holds at least the bytes of . + /// The bit count of one index: 1, 2 or 4. It is the bit count of the table. + /// The palette. It has an entry for each possible index. + /// The 256 entries for and . + /// The destination bytes. + public static void ExpandBytesLowBitsFirst( + ReadOnlySpan indices, + int bitsPerIndex, + ReadOnlySpan palette, + ReadOnlySpan table, + Span destination) + { + switch (bitsPerIndex) + { + case 1: + ExpandBytes(indices, palette, table, destination); + break; + case 2: + ExpandBytes(indices, palette, table, destination); + break; + default: + ExpandBytes(indices, palette, table, destination); + break; + } + } + + /// + /// Builds the table of : for each source byte value, the palette bytes of all its indices. + /// + /// + /// Byte k of an entry in memory order is the palette byte of index k of the source byte. The store of an entry writes the bytes in + /// memory order, so on a big-endian platform the entry is reversed. + /// + /// The index operator: 1, 2 or 4 bits for each index. + /// The palette. It has an entry for each possible index. + /// Receives the 256 entries. + public static void BuildByteTable(ReadOnlySpan palette, Span table) + where TOperator : struct, IIndexOperator + { + DebugGuard.MustBeGreaterThanOrEqualTo(palette.Length, 1 << TOperator.BitsPerIndex, nameof(palette)); + DebugGuard.MustBeGreaterThanOrEqualTo(table.Length, 256, nameof(table)); + + uint mask = (1U << TOperator.BitsPerIndex) - 1; + for (int value = 0; value < 256; value++) + { + ulong entry = 0; + for (int position = 0; position < TOperator.IndicesPerByte; position++) + { + entry |= (ulong)palette[(int)(((uint)value >> TOperator.Shift(position)) & mask)] << (8 * position); + } + + // The store writes IndicesPerByte bytes, so the reversed entry is shifted down to its low bytes. + table[value] = BitConverter.IsLittleEndian ? entry : BinaryPrimitives.ReverseEndianness(entry) >> (64 - (8 * TOperator.IndicesPerByte)); + } + } + + /// + /// Expands one row of byte palette indices with a table from . + /// + /// The index operator: 1, 2 or 4 bits for each index. + /// The packed indices. It holds at least the bytes of . + /// The palette. It has an entry for each possible index. + /// The 256 entries for and . + /// The destination bytes. + public static void ExpandBytes(ReadOnlySpan indices, ReadOnlySpan palette, ReadOnlySpan table, Span destination) + where TOperator : struct, IIndexOperator + { + int width = destination.Length; + int wholeBytes = width / TOperator.IndicesPerByte; + DebugGuard.MustBeGreaterThanOrEqualTo( + indices.Length, + wholeBytes + (width % TOperator.IndicesPerByte == 0 ? 0 : 1), + nameof(indices)); + + DebugGuard.MustBeGreaterThanOrEqualTo(table.Length, 256, nameof(table)); + + ref byte indexBase = ref MemoryMarshal.GetReference(indices); + ref ulong tableBase = ref MemoryMarshal.GetReference(table); + ref byte destinationBase = ref MemoryMarshal.GetReference(destination); + + // Source byte i gives destination bytes i * IndicesPerByte to (i + 1) * IndicesPerByte - 1: one table load, then one store of + // the low IndicesPerByte bytes of the entry. IndicesPerByte is a constant of the operator, so the JIT keeps one store width. + for (int i = 0; i < wholeBytes; i++) + { + ulong entry = Unsafe.Add(ref tableBase, (uint)Unsafe.Add(ref indexBase, (uint)i)); + ref byte target = ref Unsafe.Add(ref destinationBase, (uint)(i * TOperator.IndicesPerByte)); + if (TOperator.IndicesPerByte == 8) + { + Unsafe.WriteUnaligned(ref target, entry); + } + else if (TOperator.IndicesPerByte == 4) + { + Unsafe.WriteUnaligned(ref target, (uint)entry); + } + else + { + Unsafe.WriteUnaligned(ref target, (ushort)entry); + } + } + + // The last byte can hold fewer indices than the row needs. Its indices go through the palette, as in Expand. + int x = wholeBytes * TOperator.IndicesPerByte; + if (x < width) + { + ref byte paletteBase = ref MemoryMarshal.GetReference(palette); + uint value = Unsafe.Add(ref indexBase, (uint)wholeBytes); + uint mask = (1U << TOperator.BitsPerIndex) - 1; + for (int position = 0; x < width; x++, position++) + { + Unsafe.Add(ref destinationBase, (uint)x) = Unsafe.Add(ref paletteBase, (nuint)((value >> TOperator.Shift(position)) & mask)); + } + } + } + /// /// Expands one row of palette indices with . /// @@ -115,18 +300,17 @@ public static void Expand(ReadOnlySpan indices, ReadOnl TOperator.Expand(Unsafe.Add(ref indexBase, (uint)i), ref paletteBase, ref Unsafe.Add(ref destinationBase, (uint)(i * TOperator.IndicesPerByte))); } - // The last byte can hold fewer indices than the row needs. The row ends inside this byte, and its low bits - // are padding. The first index is in the top bits, so the shift starts at 8 - BitsPerIndex and decreases by - // BitsPerIndex for each pixel. The mask has the low BitsPerIndex bits set, for example 0b11 for 2 bits. - // This loop does the same shifts as the operator, but stops at the row width. + // The last byte can hold fewer indices than the row needs. The row ends inside this byte, and the bits after the + // last index are padding. The operator gives the shift of each position, so this loop does the same shifts as the + // operator, but stops at the row width. The mask has the low BitsPerIndex bits set, for example 0b11 for 2 bits. int x = wholeBytes * TOperator.IndicesPerByte; if (x < width) { uint value = Unsafe.Add(ref indexBase, (uint)wholeBytes); uint mask = (1U << TOperator.BitsPerIndex) - 1; - for (int shift = 8 - TOperator.BitsPerIndex; x < width; x++, shift -= TOperator.BitsPerIndex) + for (int position = 0; x < width; x++, position++) { - Unsafe.Add(ref destinationBase, (uint)x) = Unsafe.Add(ref paletteBase, (nuint)((value >> shift) & mask)); + Unsafe.Add(ref destinationBase, (uint)x) = Unsafe.Add(ref paletteBase, (nuint)((value >> TOperator.Shift(position)) & mask)); } } } @@ -142,6 +326,10 @@ public static void Expand(ReadOnlySpan indices, ReadOnl /// public static int IndicesPerByte => 8; + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Shift(int position) => 7 - position; + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Expand(uint value, ref TPixel palette, ref TPixel destination) @@ -151,13 +339,13 @@ public static void Expand(uint value, ref TPixel palette, ref TPixel des // Pixel i is bit 7 - i: shift it down to bit 0, then AND 1 removes the bits of the pixels before it. // Pixel 0 needs no AND because the shift by 7 leaves only one bit of the byte. destination = Unsafe.Add(ref palette, (nuint)(value >> 7)); - Unsafe.Add(ref destination, 1) = Unsafe.Add(ref palette, (nuint)((value >> 6) & 1)); - Unsafe.Add(ref destination, 2) = Unsafe.Add(ref palette, (nuint)((value >> 5) & 1)); - Unsafe.Add(ref destination, 3) = Unsafe.Add(ref palette, (nuint)((value >> 4) & 1)); - Unsafe.Add(ref destination, 4) = Unsafe.Add(ref palette, (nuint)((value >> 3) & 1)); - Unsafe.Add(ref destination, 5) = Unsafe.Add(ref palette, (nuint)((value >> 2) & 1)); - Unsafe.Add(ref destination, 6) = Unsafe.Add(ref palette, (nuint)((value >> 1) & 1)); - Unsafe.Add(ref destination, 7) = Unsafe.Add(ref palette, (nuint)(value & 1)); + Unsafe.Add(ref destination, 1U) = Unsafe.Add(ref palette, (nuint)((value >> 6) & 1)); + Unsafe.Add(ref destination, 2U) = Unsafe.Add(ref palette, (nuint)((value >> 5) & 1)); + Unsafe.Add(ref destination, 3U) = Unsafe.Add(ref palette, (nuint)((value >> 4) & 1)); + Unsafe.Add(ref destination, 4U) = Unsafe.Add(ref palette, (nuint)((value >> 3) & 1)); + Unsafe.Add(ref destination, 5U) = Unsafe.Add(ref palette, (nuint)((value >> 2) & 1)); + Unsafe.Add(ref destination, 6U) = Unsafe.Add(ref palette, (nuint)((value >> 1) & 1)); + Unsafe.Add(ref destination, 7U) = Unsafe.Add(ref palette, (nuint)(value & 1)); } } @@ -172,6 +360,10 @@ public static void Expand(uint value, ref TPixel palette, ref TPixel des /// public static int IndicesPerByte => 4; + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Shift(int position) => 6 - (2 * position); + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Expand(uint value, ref TPixel palette, ref TPixel destination) @@ -181,9 +373,9 @@ public static void Expand(uint value, ref TPixel palette, ref TPixel des // Pixel i is bits 7 - 2i and 6 - 2i: shift them down by 6 - 2i, then AND 3 (0b11) keeps two bits. // Pixel 0 needs no AND because the shift by 6 leaves only two bits of the byte. destination = Unsafe.Add(ref palette, (nuint)(value >> 6)); - Unsafe.Add(ref destination, 1) = Unsafe.Add(ref palette, (nuint)((value >> 4) & 3)); - Unsafe.Add(ref destination, 2) = Unsafe.Add(ref palette, (nuint)((value >> 2) & 3)); - Unsafe.Add(ref destination, 3) = Unsafe.Add(ref palette, (nuint)(value & 3)); + Unsafe.Add(ref destination, 1U) = Unsafe.Add(ref palette, (nuint)((value >> 4) & 3)); + Unsafe.Add(ref destination, 2U) = Unsafe.Add(ref palette, (nuint)((value >> 2) & 3)); + Unsafe.Add(ref destination, 3U) = Unsafe.Add(ref palette, (nuint)(value & 3)); } } @@ -198,6 +390,10 @@ public static void Expand(uint value, ref TPixel palette, ref TPixel des /// public static int IndicesPerByte => 2; + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Shift(int position) => 4 - (4 * position); + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Expand(uint value, ref TPixel palette, ref TPixel destination) @@ -206,7 +402,98 @@ public static void Expand(uint value, ref TPixel palette, ref TPixel des // Byte layout: [p0 p0 p0 p0 p1 p1 p1 p1]. Pixel 0 is the high nibble: shift it down by 4. // Pixel 1 is the low nibble: AND 15 (0b1111) removes the high nibble. destination = Unsafe.Add(ref palette, (nuint)(value >> 4)); - Unsafe.Add(ref destination, 1) = Unsafe.Add(ref palette, (nuint)(value & 15)); + Unsafe.Add(ref destination, 1U) = Unsafe.Add(ref palette, (nuint)(value & 15)); + } + } + + /// + /// Unpacks 8 indices of 1 bit from one byte, the first pixel in the least significant bit. + /// + public readonly struct Index1LowBitsFirstOperator : IIndexOperator + { + /// + public static int BitsPerIndex => 1; + + /// + public static int IndicesPerByte => 8; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Shift(int position) => position; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Expand(uint value, ref TPixel palette, ref TPixel destination) + where TPixel : unmanaged + { + // Byte layout, least significant bit first: [p7 p6 p5 p4 p3 p2 p1 p0], one bit for each pixel. + // Pixel i is bit i: shift it down to bit 0, then AND 1 removes the bits of the pixels after it. + // Pixel 7 needs no AND because the shift by 7 leaves only one bit of the byte. + destination = Unsafe.Add(ref palette, (nuint)(value & 1)); + Unsafe.Add(ref destination, 1U) = Unsafe.Add(ref palette, (nuint)((value >> 1) & 1)); + Unsafe.Add(ref destination, 2U) = Unsafe.Add(ref palette, (nuint)((value >> 2) & 1)); + Unsafe.Add(ref destination, 3U) = Unsafe.Add(ref palette, (nuint)((value >> 3) & 1)); + Unsafe.Add(ref destination, 4U) = Unsafe.Add(ref palette, (nuint)((value >> 4) & 1)); + Unsafe.Add(ref destination, 5U) = Unsafe.Add(ref palette, (nuint)((value >> 5) & 1)); + Unsafe.Add(ref destination, 6U) = Unsafe.Add(ref palette, (nuint)((value >> 6) & 1)); + Unsafe.Add(ref destination, 7U) = Unsafe.Add(ref palette, (nuint)(value >> 7)); + } + } + + /// + /// Unpacks 4 indices of 2 bits from one byte, the first pixel in the least significant bits. + /// + public readonly struct Index2LowBitsFirstOperator : IIndexOperator + { + /// + public static int BitsPerIndex => 2; + + /// + public static int IndicesPerByte => 4; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Shift(int position) => 2 * position; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Expand(uint value, ref TPixel palette, ref TPixel destination) + where TPixel : unmanaged + { + // Byte layout, least significant bits first: [p3 p3 p2 p2 p1 p1 p0 p0], two bits for each pixel. + // Pixel i is bits 2i and 2i + 1: shift them down by 2i, then AND 3 (0b11) keeps two bits. + // Pixel 3 needs no AND because the shift by 6 leaves only two bits of the byte. + destination = Unsafe.Add(ref palette, (nuint)(value & 3)); + Unsafe.Add(ref destination, 1U) = Unsafe.Add(ref palette, (nuint)((value >> 2) & 3)); + Unsafe.Add(ref destination, 2U) = Unsafe.Add(ref palette, (nuint)((value >> 4) & 3)); + Unsafe.Add(ref destination, 3U) = Unsafe.Add(ref palette, (nuint)(value >> 6)); + } + } + + /// + /// Unpacks 2 indices of 4 bits from one byte, the first pixel in the low nibble. + /// + public readonly struct Index4LowBitsFirstOperator : IIndexOperator + { + /// + public static int BitsPerIndex => 4; + + /// + public static int IndicesPerByte => 2; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Shift(int position) => 4 * position; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Expand(uint value, ref TPixel palette, ref TPixel destination) + where TPixel : unmanaged + { + // Byte layout: [p1 p1 p1 p1 p0 p0 p0 p0]. Pixel 0 is the low nibble: AND 15 (0b1111) removes the high nibble. + // Pixel 1 is the high nibble: shift it down by 4. + destination = Unsafe.Add(ref palette, (nuint)(value & 15)); + Unsafe.Add(ref destination, 1U) = Unsafe.Add(ref palette, (nuint)(value >> 4)); } } @@ -221,6 +508,10 @@ public static void Expand(uint value, ref TPixel palette, ref TPixel des /// public static int IndicesPerByte => 1; + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Shift(int position) => 0; + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Expand(uint value, ref TPixel palette, ref TPixel destination) diff --git a/src/ImageSharp/Formats/Png/Filters/IPngFilterOperator.cs b/src/ImageSharp/Formats/Png/Filters/IPngFilterOperator.cs index 0b9d89e21b..e2b817fa7c 100644 --- a/src/ImageSharp/Formats/Png/Filters/IPngFilterOperator.cs +++ b/src/ImageSharp/Formats/Png/Filters/IPngFilterOperator.cs @@ -3,8 +3,6 @@ using System.Runtime.CompilerServices; using System.Runtime.Intrinsics; -using System.Runtime.Intrinsics.Arm; -using System.Runtime.Intrinsics.X86; using SixLabors.ImageSharp.Common.Helpers; namespace SixLabors.ImageSharp.Formats.Png.Filters; @@ -206,40 +204,17 @@ public static Vector128 Predict(Vector128 left, Vector128 a /// [MethodImpl(InliningOptions.AlwaysInline)] public static Vector128 Predict(Vector128 left, Vector128 above, Vector128 upperLeft) - { - if (Sse2.IsSupported) - { - // PAVG rounds upward. Complementing both inputs and the result converts - // that rounding into the floor((left + above) / 2) required by PNG. - return ~Sse2.Average(~left, ~above); - } - - if (AdvSimd.IsSupported) - { - // ARM's halving add truncates directly and therefore needs no correction. - return AdvSimd.FusedAddHalving(left, above); - } - - // Portable 128-bit backends use the carry-free average identity. Shared - // bits supply the integer part while differing bits supply half the remainder. - return (left & above) + Vector128.ShiftRightLogical(left ^ above, 1); - } + => Vector128_.AverageRoundDown(left, above); /// [MethodImpl(InliningOptions.AlwaysInline)] public static Vector256 Predict(Vector256 left, Vector256 above, Vector256 upperLeft) - - // VPAVGB rounds (left + above) / 2 upward. Complementing both inputs and - // the result changes that to the truncated average required by PNG. - => ~Avx2.Average(~left, ~above); + => Vector256_.AverageRoundDown(left, above); /// [MethodImpl(InliningOptions.AlwaysInline)] public static Vector512 Predict(Vector512 left, Vector512 above, Vector512 upperLeft) - - // AVX-512BW retains VPAVGB's upward rounding, so use the same complement - // identity as AVX2 to obtain floor((left + above) / 2) in every byte lane. - => ~Avx512BW.Average(~left, ~above); + => Vector512_.AverageRoundDown(left, above); } /// diff --git a/src/ImageSharp/Formats/Png/Filters/PngFilterDecoder.cs b/src/ImageSharp/Formats/Png/Filters/PngFilterDecoder.cs index 43543f3f0a..098aa51c76 100644 --- a/src/ImageSharp/Formats/Png/Filters/PngFilterDecoder.cs +++ b/src/ImageSharp/Formats/Png/Filters/PngFilterDecoder.cs @@ -46,6 +46,13 @@ public static void Decode(Span scanline, ReadOnlySpan pre return; } + // The Sub predictor is the left pixel. For pixel sizes of 1, 2, 4 and 8 bytes, the shared prefix sum reconstructs 16 bytes for each step. + if (!TOperator.UsesAbove && bytesPerPixel is 1 or 2 or 4 or 8) + { + SimdUtils.AddLeft(scanline[1..], bytesPerPixel, 0); + return; + } + if (!Vector128.IsHardwareAccelerated) { DecodeScalar(scanline, previousScanline, (uint)bytesPerPixel); @@ -154,6 +161,7 @@ private static void Decode(Span scanline, ReadO // A predictor that does not read the row above is the left pixel itself. Its byte add wraps modulo 256 as // PNG requires, so the byte lanes need no 16-bit widening. The dependency chain is one byte add for each pixel. + // Decode uses this loop only for pixels of 3 and 6 bytes. The other sizes use the prefix sum. if (!TOperator.UsesAbove) { Vector128 leftBytes = Vector128.Zero; diff --git a/src/ImageSharp/Formats/Webp/AlphaDecoder.cs b/src/ImageSharp/Formats/Webp/AlphaDecoder.cs index b0254fa009..b5b5727f7d 100644 --- a/src/ImageSharp/Formats/Webp/AlphaDecoder.cs +++ b/src/ImageSharp/Formats/Webp/AlphaDecoder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System.Buffers; @@ -6,8 +6,6 @@ using System.Numerics.Tensors; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Runtime.Intrinsics; -using System.Runtime.Intrinsics.X86; using SixLabors.ImageSharp.Common.Helpers; using SixLabors.ImageSharp.Compression; using SixLabors.ImageSharp.Formats.Webp.BitReader; @@ -21,13 +19,27 @@ namespace SixLabors.ImageSharp.Formats.Webp; /// internal class AlphaDecoder : IDisposable { - private readonly MemoryAllocator memoryAllocator; - /// /// The image data integrity mode. It controls damaged or truncated alpha data. /// private readonly SegmentIntegrityHandling segmentIntegrityHandling; + /// + /// The memory allocator. allocates the lossless pixel buffer after it reads the lossless headers, because the headers set its size. + /// + private readonly MemoryAllocator memoryAllocator; + + /// + /// The alpha value of each palette index of the paletted path: the green channel of each palette entry. builds it once. + /// + private InlineArray256 alphaPalette; + + /// + /// The expansion table of a palette with 1, 2 or 4 bits for each index: for each byte of packed indices, the alpha values of all its + /// indices. builds it once from . It is null for 8-bit indices and for the other paths. + /// + private IMemoryOwner? alphaTable; + /// /// Initializes a new instance of the class. /// @@ -53,20 +65,17 @@ public AlphaDecoder( this.Width = width; this.Height = height; this.Data = data; - this.memoryAllocator = memoryAllocator; this.segmentIntegrityHandling = segmentIntegrityHandling; - this.LastRow = 0; - int totalPixels = width * height; + this.memoryAllocator = memoryAllocator; // Header bits 0 and 1 are the compression method, and bits 2 and 3 are the filter. this.Compressed = (WebpAlphaCompressionMethod)(alphaChunkHeader & 0x03) == WebpAlphaCompressionMethod.WebpLosslessCompression; - // The allocation is not clean. Decode() writes each decoded row and sets the other alpha values to 0, the - // transparent fill of the other codecs. A complete decode writes every value, so it clears nothing. - this.Alpha = memoryAllocator.Allocate(totalPixels); + // As in the JPEG decoder, the rows come from the pool in blocks of whole rows. The allocation is not clean. Decode() writes each decoded row and + // sets the other alpha values to 0, the transparent fill of the other codecs. A complete decode writes every value, so it clears nothing. + this.Alpha = memoryAllocator.Allocate2D(width, height); this.AlphaFilterType = (WebpAlphaFilterType)((alphaChunkHeader >> 2) & 0x03); this.Vp8LDec = new Vp8LDecoder(width, height); - this.Vp8LDec.AllocatePixels(memoryAllocator); if (this.Compressed) { @@ -94,14 +103,9 @@ public AlphaDecoder( public WebpAlphaFilterType AlphaFilterType { get; } /// - /// Gets or sets the last decoded row. - /// - public int LastRow { get; set; } - - /// - /// Gets or sets the row before the last decoded row. + /// Gets the row after the last row that the paletted path converted to alpha values. /// - public int PrevRow { get; set; } + public int LastRow { get; private set; } /// /// Gets information for decoding Vp8L compressed alpha data. @@ -109,9 +113,9 @@ public AlphaDecoder( public Vp8LDecoder Vp8LDec { get; } /// - /// Gets the decoded alpha data. + /// Gets the decoded alpha values, one row for each image row. /// - public IMemoryOwner Alpha { get; } + public Buffer2D Alpha { get; } /// /// Gets a value indicating whether the alpha channel uses compression. @@ -143,143 +147,121 @@ public AlphaDecoder( /// public void Decode() { + int rows; if (!this.Compressed) { - Span dataSpan = this.Data.Memory.Span; - int rows = this.Height; - Span alphaSpan = this.Alpha.Memory.Span; - if (dataSpan.Length < this.Width * this.Height) + ReadOnlySpan data = this.Data.GetSpan(); + rows = this.Height; + if (data.Length < this.Width * this.Height) { // Raw alpha that is too short is truncated image data. The decoder keeps the complete rows. this.segmentIntegrityHandling.ThrowOrIgnoreImageDataError("Not enough data in the ALPH chunk."); - rows = dataSpan.Length / this.Width; - alphaSpan[(rows * this.Width)..].Clear(); - } - - if (this.AlphaFilterType == WebpAlphaFilterType.None) - { - dataSpan[..(rows * this.Width)].CopyTo(alphaSpan); - return; + rows = data.Length / this.Width; } - Span deltas = dataSpan; - Span dst = alphaSpan; - Span prev = default; + // The filters work in place on the rows, so the raw rows are copied first. for (int y = 0; y < rows; y++) { - switch (this.AlphaFilterType) - { - case WebpAlphaFilterType.Horizontal: - HorizontalUnfilter(prev, deltas, dst, this.Width); - break; - case WebpAlphaFilterType.Vertical: - VerticalUnfilter(prev, deltas, dst, this.Width); - break; - case WebpAlphaFilterType.Gradient: - GradientUnfilter(prev, deltas, dst, this.Width); - break; - } - - prev = dst; - deltas = deltas[this.Width..]; - dst = dst[this.Width..]; + data.Slice(y * this.Width, this.Width).CopyTo(this.Alpha.DangerousGetRowSpan(y)); } + + this.UnfilterRows(0, rows); + } + else if (!this.LosslessDecoder.TryReadHeaders(this.Vp8LDec, this.segmentIntegrityHandling, true)) + { + // The color image exists before the alpha data. Thus, in the IgnoreImageData mode, the decoder does not throw for damaged headers. The header is + // damaged, so the decoder cannot decode an alpha value, and all alpha values are 0. + rows = 0; } else { - // The color image exists before the alpha data. Thus, in the IgnoreImageData mode, the decoder does not throw for damaged headers, and the alpha - // values are 0. - if (!this.LosslessDecoder.TryReadHeaders(this.Vp8LDec, this.segmentIntegrityHandling, true)) - { - // The header is damaged, so the decoder cannot decode an alpha value. - this.Alpha.Memory.Span.Clear(); - return; - } - // If the alpha data uses only the color indexing transform, no color cache and trivial red, blue and // alpha codes, DecodeAlphaData() decodes it. This frequent case needs only 1 byte per pixel. this.Use8BDecode = this.Vp8LDec.Transforms.Count is 1 && this.Vp8LDec.Transforms[0].TransformType == Vp8LTransformType.ColorIndexingTransform && Is8BOptimizable(this.Vp8LDec.Metadata); - int rows; if (this.Use8BDecode) { + // The palette maps each index to the green channel of its entry. It has 1 << bitsPerIndex entries, one for each value of an index. + Vp8LTransform transform = this.Vp8LDec.Transforms[0]; + ReadOnlySpan colorMap = transform.Data.GetSpan(); + Span palette = this.alphaPalette; + int bitsPerIndex = 8 >> transform.Bits; + for (int i = 0; i < 1 << bitsPerIndex; i++) + { + palette[i] = (byte)(colorMap[i] >> 8); + } + + // With 1, 2 or 4 bits for each index, a table of the 256 values of a packed byte expands each byte with one load and one store. + // The table holds 256 values of 8 bytes, so it comes from the allocator. + if (bitsPerIndex < 8) + { + this.alphaTable = this.memoryAllocator.Allocate(256); + PaletteExpander.BuildByteTableLowBitsFirst(bitsPerIndex, palette[..(1 << bitsPerIndex)], this.alphaTable.GetSpan()); + } + + // The paletted path stores one palette index byte for each pixel, so its buffer is a quarter of the ARGB buffer. + this.Vp8LDec.AllocatePaletteIndices(this.memoryAllocator); this.LosslessDecoder.DecodeAlphaData(this, this.segmentIntegrityHandling); rows = this.LastRow; } else { + this.Vp8LDec.AllocatePixels(this.memoryAllocator); rows = this.LosslessDecoder.DecodeImageRows( this.Vp8LDec, this.segmentIntegrityHandling, "The WebP alpha data is damaged or ends before the last value."); - this.ExtractAlphaRows(this.Vp8LDec, this.Width, rows); + this.ExtractAlphaRows(rows); } - - // After damaged data, the rows after the decoded rows get 0. - this.Alpha.Memory.Span[(rows * this.Width)..].Clear(); - } - } - - /// - /// Applies filtering to a set of rows. - /// - /// The first row index to start filtering. - /// The last row index for filtering. - /// The destination to store the filtered data. - /// The stride to use. - public void AlphaApplyFilter(int firstRow, int lastRow, Span dst, int stride) - { - if (this.AlphaFilterType == WebpAlphaFilterType.None) - { - return; } - Span alphaSpan = this.Alpha.Memory.Span; - Span prev = this.PrevRow == 0 ? null : alphaSpan[(this.Width * this.PrevRow)..]; - for (int y = firstRow; y < lastRow; y++) + // After damaged data, the rows after the decoded rows get 0. + for (int y = rows; y < this.Height; y++) { - switch (this.AlphaFilterType) - { - case WebpAlphaFilterType.Horizontal: - HorizontalUnfilter(prev, dst, dst, this.Width); - break; - case WebpAlphaFilterType.Vertical: - VerticalUnfilter(prev, dst, dst, this.Width); - break; - case WebpAlphaFilterType.Gradient: - GradientUnfilter(prev, dst, dst, this.Width); - break; - } - - prev = dst; - dst = dst[stride..]; + this.Alpha.DangerousGetRowSpan(y).Clear(); } - - this.PrevRow = lastRow - 1; } + /// + /// Converts the decoded palette indices of the rows from up to to alpha values. + /// Then it reverses the alpha filter of these rows and sets to . + /// + /// + /// uses this path only when is . Then the palette index buffer holds one + /// palette index byte for each value. Small palettes pack 2, 4 or 8 indices in one byte, the first pixel in the low bits, so + /// expands each row. See the WebP Lossless Bitstream Specification, section 4.4 + /// "Color Indexing Transform": https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// + /// The row after the last decoded row. public void ExtractPalettedAlphaRows(int lastRow) { - // For vertical and gradient filtering, we need to decode the part above the - // cropTop row, in order to have the correct spatial predictors. - int topRow = this.AlphaFilterType is WebpAlphaFilterType.None or WebpAlphaFilterType.Horizontal ? 0 : this.LastRow; - int firstRow = this.LastRow < topRow ? topRow : this.LastRow; + int firstRow = this.LastRow; if (lastRow > firstRow) { - // Special method for paletted alpha data. - Span output = this.Alpha.Memory.Span; - Span pixelData = this.Vp8LDec.Pixels.Memory.Span; - Span pixelDataAsBytes = MemoryMarshal.Cast(pixelData); - Span dst = output[(this.Width * firstRow)..]; - Span input = pixelDataAsBytes[(this.Vp8LDec.Width * firstRow)..]; - // Decode() uses this path only for a stream with one transform, the color indexing transform. - Vp8LTransform transform = this.Vp8LDec.Transforms[0]; - ColorIndexInverseTransformAlpha(transform, firstRow, lastRow, input, dst); - this.AlphaApplyFilter(firstRow, lastRow, dst, this.Width); + int bitsPerIndex = 8 >> this.Vp8LDec.Transforms[0].Bits; + ReadOnlySpan palette = ((ReadOnlySpan)this.alphaPalette)[..(1 << bitsPerIndex)]; + Buffer2D indices = this.Vp8LDec.PaletteIndices; + if (this.alphaTable is null) + { + for (int y = firstRow; y < lastRow; y++) + { + PaletteExpander.ExpandLowBitsFirst(indices.DangerousGetRowSpan(y), bitsPerIndex, palette, this.Alpha.DangerousGetRowSpan(y)); + } + } + else + { + ReadOnlySpan table = this.alphaTable.GetSpan(); + for (int y = firstRow; y < lastRow; y++) + { + PaletteExpander.ExpandBytesLowBitsFirst(indices.DangerousGetRowSpan(y), bitsPerIndex, palette, table, this.Alpha.DangerousGetRowSpan(y)); + } + } + + this.UnfilterRows(firstRow, lastRow); } this.LastRow = lastRow; @@ -288,137 +270,128 @@ public void ExtractPalettedAlphaRows(int lastRow) /// /// Once the image-stream is decoded into ARGB color values, the transparency information will be extracted from the green channel of the ARGB quadruplet. /// - /// The VP8L decoder. - /// The image width. - /// The number of decoded rows. The alpha values of the other rows stay 0. - private void ExtractAlphaRows(Vp8LDecoder dec, int width, int numRowsToProcess) + /// + /// The inverse transforms run on batches of rows, as for the main image, so each batch stays in the L2 cache. + /// The filter of a batch runs while the batch is in the cache too. + /// + /// The number of decoded rows. The caller clears the other rows. + private void ExtractAlphaRows(int rowCount) { - Span input = dec.Pixels.Memory.Span; - Span output = this.Alpha.Memory.Span; - - // Extract alpha (which is stored in the green plane). - // the final width (!= dec->width_) - int pixelCount = width * numRowsToProcess; - WebpLosslessDecoder.ApplyInverseTransforms(dec, input, this.memoryAllocator); - ExtractGreen(input, output, pixelCount); - this.AlphaApplyFilter(0, numRowsToProcess, output, width); - } - - private static void ColorIndexInverseTransformAlpha( - Vp8LTransform transform, - int yStart, - int yEnd, - ReadOnlySpan src, - Span dst) - { - int bitsPerPixel = 8 >> transform.Bits; - int width = transform.XSize; - Span colorMap = transform.Data.Memory.Span; - if (bitsPerPixel < 8) + int width = this.Width; + using IMemoryOwner cacheOwner = WebpLosslessDecoder.AllocateTransformCache(this.memoryAllocator, width); + Span cache = cacheOwner.GetSpan(); + for (int firstRow = 0; firstRow < rowCount; firstRow += WebpConstants.NumArgbCacheRows) { - int srcOffset = 0; - int dstOffset = 0; - int pixelsPerByte = 1 << transform.Bits; - int countMask = pixelsPerByte - 1; - int bitMask = (1 << bitsPerPixel) - 1; - for (int y = yStart; y < yEnd; y++) - { - int packedPixels = 0; - for (int x = 0; x < width; x++) - { - if ((x & countMask) == 0) - { - packedPixels = src[srcOffset]; - srcOffset++; - } + int batchRows = Math.Min(WebpConstants.NumArgbCacheRows, rowCount - firstRow); + ReadOnlySpan argb = WebpLosslessDecoder.ApplyInverseTransforms(this.Vp8LDec, firstRow, batchRows, cache, width); - dst[dstOffset] = GetAlphaValue((int)colorMap[packedPixels & bitMask]); - dstOffset++; - packedPixels >>= bitsPerPixel; - } + // The green channel holds the alpha value. + for (int y = 0; y < batchRows; y++) + { + SimdUtils.ExtractBytes(argb.Slice(y * width, width), this.Alpha.DangerousGetRowSpan(firstRow + y), 1); } - } - else - { - MapAlpha(src, colorMap, dst, yStart, yEnd, width); + + this.UnfilterRows(firstRow, firstRow + batchRows); } } - private static void HorizontalUnfilter(ReadOnlySpan prev, Span input, Span dst, int width) + /// + /// Reverses the alpha filter of the rows from up to , in place. The rows before + /// are final. + /// + /// + /// The filter of the image is chosen once, and each case runs its own row loop. See the WebP Container Specification, the ALPH chunk, filtering + /// method: https://developers.google.com/speed/webp/docs/riff_container. Each filter reads the final row above, and the first row has no row above. + /// The vertical and the gradient filters use the horizontal filter for the first row, and the horizontal filter predicts the first value of a row + /// from the value above it, or from 0 in the first row. + /// + /// The first row to unfilter. + /// The row after the last row to unfilter. + private void UnfilterRows(int firstRow, int lastRow) { - if (Vector128.IsHardwareAccelerated && width >= 9) + Buffer2D alpha = this.Alpha; + switch (this.AlphaFilterType) { - dst[0] = (byte)(input[0] + (prev.IsEmpty ? 0 : prev[0])); - nuint i; - Vector128 last = Vector128.Zero.WithElement(0, dst[0]); - ref byte srcRef = ref MemoryMarshal.GetReference(input); - ref byte dstRef = ref MemoryMarshal.GetReference(dst); + case WebpAlphaFilterType.Horizontal: + for (int y = firstRow; y < lastRow; y++) + { + HorizontalUnfilter(y > 0 ? alpha.DangerousGetRowSpan(y - 1) : default, alpha.DangerousGetRowSpan(y)); + } - for (i = 1; i <= (uint)width - 8; i += 8) - { - Vector128 a0 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, i)), 0); - Vector128 a1 = a0.AsByte() + last.AsByte(); - Vector128 a2 = Vector128_.ShiftLeftBytesInVector(a1, 1); - Vector128 a3 = a1 + a2; - Vector128 a4 = Vector128_.ShiftLeftBytesInVector(a3, 2); - Vector128 a5 = a3 + a4; - Vector128 a6 = Vector128_.ShiftLeftBytesInVector(a5, 4); - Vector128 a7 = a5 + a6; - - ref byte outputRef = ref Unsafe.Add(ref dstRef, i); - Unsafe.As>(ref outputRef) = a7.GetLower(); - last = Vector128.ShiftRightLogical(a7.AsInt64(), 56).AsInt32(); - } + break; + case WebpAlphaFilterType.Vertical: + for (int y = firstRow; y < lastRow; y++) + { + Span row = alpha.DangerousGetRowSpan(y); + if (y == 0) + { + HorizontalUnfilter(default, row); + } + else + { + // Byte addition wraps modulo 256, as the filter requires. + TensorPrimitives.Add(row, alpha.DangerousGetRowSpan(y - 1), row); + } + } - for (; i < (uint)width; ++i) - { - dst[(int)i] = (byte)(input[(int)i] + dst[(int)i - 1]); - } - } - else - { - byte pred = (byte)(prev.IsEmpty ? 0 : prev[0]); + break; + case WebpAlphaFilterType.Gradient: + for (int y = firstRow; y < lastRow; y++) + { + Span row = alpha.DangerousGetRowSpan(y); + if (y == 0) + { + HorizontalUnfilter(default, row); + } + else + { + GradientUnfilter(alpha.DangerousGetRowSpan(y - 1), row); + } + } - for (int i = 0; i < width; i++) - { - byte val = (byte)(pred + input[i]); - pred = val; - dst[i] = val; - } + break; } } - private static void VerticalUnfilter(Span prev, Span input, Span dst, int width) + /// + /// Reverses the horizontal filter for one row, in place. Each value adds the value to its left. + /// The first value adds the first value of the previous row, or 0 if there is no previous row. + /// + /// + /// After the first value, the row is a run of left-predicted 1-byte pixels, so reconstructs it. + /// + /// The previous unfiltered row, or an empty span for the first row. + /// The filtered row. On return, the unfiltered row. + private static void HorizontalUnfilter(ReadOnlySpan prev, Span row) { - if (prev.IsEmpty) - { - HorizontalUnfilter(null, input, dst, width); - } - else - { - // Byte addition intentionally wraps modulo 256, matching the WebP alpha predictor. - TensorPrimitives.Add(input[..width], prev[..width], dst[..width]); - } + row[0] = (byte)(row[0] + (prev.IsEmpty ? 0 : prev[0])); + SimdUtils.AddLeft(row[1..], 1, row[0]); } - private static void GradientUnfilter(ReadOnlySpan prev, Span input, Span dst, int width) + /// + /// Reverses the gradient filter for one row, in place. Each value adds the clipped gradient of its left, top and top-left values. + /// The first value adds the value above it. + /// + /// + /// The first value has no left or top-left value. With both set to the value above, the gradient is the value above. Each value waits for the value to + /// its left, so the row is one serial chain. The top and top-left values are final, so only the left value is on the chain. + /// + /// The previous unfiltered row. + /// The filtered row. On return, the unfiltered row. + private static void GradientUnfilter(ReadOnlySpan prev, Span row) { - if (prev.IsEmpty) - { - HorizontalUnfilter(null, input, dst, width); - } - else + ref byte prevRef = ref MemoryMarshal.GetReference(prev); + ref byte rowRef = ref MemoryMarshal.GetReference(row); + nuint width = (uint)row.Length; + int topLeft = prevRef; + int left = prevRef; + for (nuint i = 0; i < width; i++) { - byte prev0 = prev[0]; - byte topLeft = prev0; - byte left = prev0; - for (int i = 0; i < width; i++) - { - byte top = prev[i]; - left = (byte)(input[i] + GradientPredictor(left, top, topLeft)); - topLeft = top; - dst[i] = left; - } + int top = Unsafe.Add(ref prevRef, i); + ref byte value = ref Unsafe.Add(ref rowRef, i); + left = (byte)(value + Numerics.ClampToByte(left + top - topLeft)); + value = (byte)left; + topLeft = top; } } @@ -435,20 +408,22 @@ private static bool Is8BOptimizable(Vp8LMetadata hdr) return false; } + Span tables = hdr.HuffmanTables.GetSpan(); + Span groups = hdr.HTreeGroups.GetSpan(); for (int i = 0; i < hdr.NumHTreeGroups; i++) { - List htrees = hdr.HTreeGroups[i].HTrees; - if (htrees[HuffIndex.Red][0].BitsUsed > 0) + ref HuffmanTreeGroup group = ref groups[i]; + if (tables[group.Red].BitsUsed > 0) { return false; } - if (htrees[HuffIndex.Blue][0].BitsUsed > 0) + if (tables[group.Blue].BitsUsed > 0) { return false; } - if (htrees[HuffIndex.Alpha][0].BitsUsed > 0) + if (tables[group.Alpha].BitsUsed > 0) { return false; } @@ -457,42 +432,11 @@ private static bool Is8BOptimizable(Vp8LMetadata hdr) return true; } - private static void MapAlpha(ReadOnlySpan src, ReadOnlySpan colorMap, Span dst, int yStart, int yEnd, int width) - { - int offset = 0; - for (int y = yStart; y < yEnd; y++) - { - for (int x = 0; x < width; x++) - { - dst[offset] = GetAlphaValue((int)colorMap[src[offset]]); - offset++; - } - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static byte GetAlphaValue(int val) => (byte)((val >> 8) & 0xff); - - [MethodImpl(InliningOptions.ShortMethod)] - private static int GradientPredictor(byte a, byte b, byte c) - { - int g = a + b - c; - return (g & ~0xff) == 0 ? g : g < 0 ? 0 : 255; // clip to 8bit. - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void ExtractGreen(ReadOnlySpan argb, Span alpha, int size) - { - for (int i = 0; i < size; i++) - { - alpha[i] = (byte)(argb[i] >> 8); - } - } - /// public void Dispose() { this.Vp8LDec?.Dispose(); + this.alphaTable?.Dispose(); this.Data.Dispose(); this.Alpha?.Dispose(); } diff --git a/src/ImageSharp/Formats/Webp/AlphaEncoder.cs b/src/ImageSharp/Formats/Webp/AlphaEncoder.cs index fd6f508e4a..7140cdca35 100644 --- a/src/ImageSharp/Formats/Webp/AlphaEncoder.cs +++ b/src/ImageSharp/Formats/Webp/AlphaEncoder.cs @@ -2,7 +2,9 @@ // Licensed under the Six Labors Split License. using System.Buffers; -using SixLabors.ImageSharp.Advanced; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; using SixLabors.ImageSharp.Formats.Webp.Lossless; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; @@ -18,25 +20,29 @@ internal static class AlphaEncoder /// Encodes the alpha channel data. /// Data is either compressed as lossless webp image or uncompressed. /// - /// The pixel format. - /// The to encode from. + /// The alpha plane with the 8-bit transparency values. It has the image size. + /// The image width. + /// The image height. /// The global configuration. /// The memory manager. /// Whether to skip metadata encoding. /// Indicates, if the data should be compressed with the lossless webp compression. - /// The size in bytes of the alpha data. - /// The encoded alpha data. - public static IMemoryOwner EncodeAlpha( - Buffer2DRegion frame, + /// Receives the number of bytes of the compressed data, or 0 when the method returns null. + /// + /// The compressed data, when is set and the compressed data is smaller than the plane. Otherwise null, and the + /// plane stays uncompressed. The caller owns and disposes the data. + /// + public static IMemoryOwner? EncodeAlpha( + Buffer2D alphaData, + int width, + int height, Configuration configuration, MemoryAllocator memoryAllocator, bool skipMetadata, bool compress, out int size) - where TPixel : unmanaged, IPixel { - IMemoryOwner alphaData = ExtractAlphaChannel(frame, configuration, memoryAllocator); - + size = 0; if (compress) { const WebpEncodingMethod effort = WebpEncodingMethod.Default; @@ -44,8 +50,8 @@ public static IMemoryOwner EncodeAlpha( using Vp8LEncoder lossLessEncoder = new( memoryAllocator, configuration, - frame.Width, - frame.Height, + width, + height, quality, skipMetadata, effort, @@ -55,81 +61,179 @@ public static IMemoryOwner EncodeAlpha( // The transparency information will be stored in the green channel of the ARGB quadruplet. // The green channel is allowed extra transformation steps in the specification -- unlike the other channels, - // that can improve compression. - using ImageFrame alphaAsFrame = DispatchAlphaToGreen(configuration, frame, alphaData.GetSpan()); - - size = lossLessEncoder.EncodeAlphaImageData(alphaAsFrame.PixelBuffer.GetRegion(), alphaData); + // that can improve compression. The values go straight into the encoder's pixel plane, one row at a time, so no other copy is + // necessary. + for (int y = 0; y < height; y++) + { + DispatchAlphaToGreen(alphaData.DangerousGetRowSpan(y), lossLessEncoder.Bgra.DangerousGetRowSpan(y)); + } - return alphaData; + return lossLessEncoder.EncodeAlphaImageData(width, height, out size); } - size = frame.Width * frame.Height; - return alphaData; + return null; } /// - /// Store the transparency in the green channel. + /// Copies the alpha byte of each packed BGRA pixel into an alpha row. /// - /// The pixel format. - /// The configuration. - /// The pixel buffer to encode from. - /// A byte sequence of length width * height, containing all the 8-bit transparency values in scan order. - /// The transparency frame. - private static ImageFrame DispatchAlphaToGreen(Configuration configuration, Buffer2DRegion frame, Span alphaData) - where TPixel : unmanaged, IPixel + /// The source BGRA pixels. + /// The destination alpha row. It has the same length as . + /// when all alpha values are 255; otherwise, . + public static bool ExtractAlpha(ReadOnlySpan pixels, Span alpha) { - int width = frame.Width; - int height = frame.Height; - ImageFrame alphaAsFrame = new(configuration, width, height); + // Each BGRA pixel read as one little-endian uint has alpha in bits 24..31. + // A logical right shift by 24 puts alpha in bits 0..7 and clears the bits above. + ref uint source = ref Unsafe.As(ref MemoryMarshal.GetReference(pixels)); + ref byte destination = ref MemoryMarshal.GetReference(alpha); + nuint length = (uint)pixels.Length; + nuint x = 0; + + // The AND of all alpha values stays 255 only when all pixels are opaque. + uint alphaAnd = byte.MaxValue; - for (int y = 0; y < height; y++) + if (Vector512.IsHardwareAccelerated) { - Memory rowBuffer = alphaAsFrame.DangerousGetPixelRowMemory(y); - Span pixelRow = rowBuffer.Span; - Span alphaRow = alphaData.Slice(y * width, width); + Vector512 vectorAnd = Vector512.AllBitsSet; - // TODO: This can be probably simd optimized. - for (int x = 0; x < width; x++) + // Four loads of 16 pixels give 64 alpha values. Each shifted lane holds one alpha value, so the truncating + // narrows (uint to ushort, then ushort to byte) keep the value. Narrow keeps lane order, so byte i is pixel x + i. + for (; x + (uint)Vector512.Count <= length; x += (uint)Vector512.Count) { - // Leave A/R/B channels zero'd. - pixelRow[x] = new Bgra32(0, alphaRow[x], 0, 0); + Vector512 pixels0 = Vector512.ShiftRightLogical(Vector512.LoadUnsafe(ref source, x), 24); + Vector512 pixels1 = Vector512.ShiftRightLogical(Vector512.LoadUnsafe(ref source, x + 16), 24); + Vector512 pixels2 = Vector512.ShiftRightLogical(Vector512.LoadUnsafe(ref source, x + 32), 24); + Vector512 pixels3 = Vector512.ShiftRightLogical(Vector512.LoadUnsafe(ref source, x + 48), 24); + Vector512 values = Vector512.Narrow(Vector512.Narrow(pixels0, pixels1), Vector512.Narrow(pixels2, pixels3)); + values.StoreUnsafe(ref destination, x); + vectorAnd &= values; + } + + if (vectorAnd != Vector512.AllBitsSet) + { + alphaAnd = 0; } } - return alphaAsFrame; + if (Vector256.IsHardwareAccelerated) + { + Vector256 vectorAnd = Vector256.AllBitsSet; + + // Four loads of 8 pixels give 32 alpha values, with the same lane layout as the 512-bit path. + for (; x + (uint)Vector256.Count <= length; x += (uint)Vector256.Count) + { + Vector256 pixels0 = Vector256.ShiftRightLogical(Vector256.LoadUnsafe(ref source, x), 24); + Vector256 pixels1 = Vector256.ShiftRightLogical(Vector256.LoadUnsafe(ref source, x + 8), 24); + Vector256 pixels2 = Vector256.ShiftRightLogical(Vector256.LoadUnsafe(ref source, x + 16), 24); + Vector256 pixels3 = Vector256.ShiftRightLogical(Vector256.LoadUnsafe(ref source, x + 24), 24); + Vector256 values = Vector256.Narrow(Vector256.Narrow(pixels0, pixels1), Vector256.Narrow(pixels2, pixels3)); + values.StoreUnsafe(ref destination, x); + vectorAnd &= values; + } + + if (vectorAnd != Vector256.AllBitsSet) + { + alphaAnd = 0; + } + } + + if (Vector128.IsHardwareAccelerated) + { + Vector128 vectorAnd = Vector128.AllBitsSet; + + // Four loads of 4 pixels give 16 alpha values, with the same lane layout as the 512-bit path. + for (; x + (uint)Vector128.Count <= length; x += (uint)Vector128.Count) + { + Vector128 pixels0 = Vector128.ShiftRightLogical(Vector128.LoadUnsafe(ref source, x), 24); + Vector128 pixels1 = Vector128.ShiftRightLogical(Vector128.LoadUnsafe(ref source, x + 4), 24); + Vector128 pixels2 = Vector128.ShiftRightLogical(Vector128.LoadUnsafe(ref source, x + 8), 24); + Vector128 pixels3 = Vector128.ShiftRightLogical(Vector128.LoadUnsafe(ref source, x + 12), 24); + Vector128 values = Vector128.Narrow(Vector128.Narrow(pixels0, pixels1), Vector128.Narrow(pixels2, pixels3)); + values.StoreUnsafe(ref destination, x); + vectorAnd &= values; + } + + if (vectorAnd != Vector128.AllBitsSet) + { + alphaAnd = 0; + } + } + + // Finish a partial vector, or the entire row when hardware acceleration is unavailable. + for (; x < length; x++) + { + byte value = (byte)(Unsafe.Add(ref source, x) >> 24); + Unsafe.Add(ref destination, x) = value; + alphaAnd &= value; + } + + return alphaAnd == byte.MaxValue; } /// - /// Extract the alpha data of the image. + /// Stores each alpha value in the green channel of a packed BGRA pixel. The other channels are zero. /// - /// The pixel format. - /// The to encode from. - /// The global configuration. - /// The memory manager. - /// A byte sequence of length width * height, containing all the 8-bit transparency values in scan order. - private static IMemoryOwner ExtractAlphaChannel(Buffer2DRegion frame, Configuration configuration, MemoryAllocator memoryAllocator) - where TPixel : unmanaged, IPixel + /// The source alpha values. + /// The destination packed BGRA pixels. It has at least the length of . + public static void DispatchAlphaToGreen(ReadOnlySpan alpha, Span bgra) { - int width = frame.Width; - int height = frame.Height; + // A packed BGRA pixel has green in bits 8..15, so each destination value is alpha << 8. + ref byte source = ref MemoryMarshal.GetReference(alpha); + ref uint destination = ref MemoryMarshal.GetReference(bgra); + nuint length = (uint)alpha.Length; + nuint x = 0; - IMemoryOwner alphaDataBuffer = memoryAllocator.Allocate(width * height); - Span alphaData = alphaDataBuffer.GetSpan(); + if (Vector512.IsHardwareAccelerated) + { + // One load gives 64 alpha values. The first widen gives two registers of 32 ushort lanes. + // A left shift by 8 moves each value to the green byte; then the second widen gives four registers of 16 uint lanes. + // Widen keeps lane order, so destination value i is pixel x + i. + for (; x + (uint)Vector512.Count <= length; x += (uint)Vector512.Count) + { + (Vector512 lower, Vector512 upper) = Vector512.Widen(Vector512.LoadUnsafe(ref source, x)); + (Vector512 pixels0, Vector512 pixels1) = Vector512.Widen(Vector512.ShiftLeft(lower, 8)); + (Vector512 pixels2, Vector512 pixels3) = Vector512.Widen(Vector512.ShiftLeft(upper, 8)); + pixels0.StoreUnsafe(ref destination, x); + pixels1.StoreUnsafe(ref destination, x + 16); + pixels2.StoreUnsafe(ref destination, x + 32); + pixels3.StoreUnsafe(ref destination, x + 48); + } + } - using IMemoryOwner rowBuffer = memoryAllocator.Allocate(width); - Span rgbaRow = rowBuffer.GetSpan(); + if (Vector256.IsHardwareAccelerated) + { + // One load gives 32 alpha values, with the same lane layout as the 512-bit path. + for (; x + (uint)Vector256.Count <= length; x += (uint)Vector256.Count) + { + (Vector256 lower, Vector256 upper) = Vector256.Widen(Vector256.LoadUnsafe(ref source, x)); + (Vector256 pixels0, Vector256 pixels1) = Vector256.Widen(Vector256.ShiftLeft(lower, 8)); + (Vector256 pixels2, Vector256 pixels3) = Vector256.Widen(Vector256.ShiftLeft(upper, 8)); + pixels0.StoreUnsafe(ref destination, x); + pixels1.StoreUnsafe(ref destination, x + 8); + pixels2.StoreUnsafe(ref destination, x + 16); + pixels3.StoreUnsafe(ref destination, x + 24); + } + } - for (int y = 0; y < height; y++) + if (Vector128.IsHardwareAccelerated) { - Span rowSpan = frame.DangerousGetRowSpan(y); - PixelOperations.Instance.ToRgba32(configuration, rowSpan, rgbaRow); - int offset = y * width; - for (int x = 0; x < width; x++) + // One load gives 16 alpha values, with the same lane layout as the 512-bit path. + for (; x + (uint)Vector128.Count <= length; x += (uint)Vector128.Count) { - alphaData[offset + x] = rgbaRow[x].A; + (Vector128 lower, Vector128 upper) = Vector128.Widen(Vector128.LoadUnsafe(ref source, x)); + (Vector128 pixels0, Vector128 pixels1) = Vector128.Widen(Vector128.ShiftLeft(lower, 8)); + (Vector128 pixels2, Vector128 pixels3) = Vector128.Widen(Vector128.ShiftLeft(upper, 8)); + pixels0.StoreUnsafe(ref destination, x); + pixels1.StoreUnsafe(ref destination, x + 4); + pixels2.StoreUnsafe(ref destination, x + 8); + pixels3.StoreUnsafe(ref destination, x + 12); } } - return alphaDataBuffer; + // Finish a partial vector, or all values when hardware acceleration is unavailable. + for (; x < length; x++) + { + Unsafe.Add(ref destination, x) = (uint)Unsafe.Add(ref source, x) << 8; + } } } diff --git a/src/ImageSharp/Formats/Webp/BitReader/BitReaderBase.cs b/src/ImageSharp/Formats/Webp/BitReader/BitReaderBase.cs index 4276199ee0..d01aef8091 100644 --- a/src/ImageSharp/Formats/Webp/BitReader/BitReaderBase.cs +++ b/src/ImageSharp/Formats/Webp/BitReader/BitReaderBase.cs @@ -11,11 +11,28 @@ namespace SixLabors.ImageSharp.Formats.Webp.BitReader; /// internal abstract class BitReaderBase : IDisposable { + /// + /// A value indicating whether the reader released its data. + /// private bool isDisposed; + /// + /// Initializes a new instance of the class. + /// + /// + /// The raw encoded image data. A reader that owns the data disposes it. A token partition reader of the lossy decoder shares the data of + /// the first partition reader, and it is not disposed. + /// protected BitReaderBase(IMemoryOwner data) => this.Data = data; + /// + /// Initializes a new instance of the class. + /// The constructor reads the raw encoded image data from the stream. + /// + /// The input stream to read from. + /// The number of bytes to read. + /// Used for allocating memory during reading data from the stream. protected BitReaderBase(Stream inputStream, int imageDataSize, MemoryAllocator memoryAllocator) => this.Data = ReadImageDataFromStream(inputStream, imageDataSize, memoryAllocator); @@ -30,15 +47,27 @@ protected BitReaderBase(Stream inputStream, int imageDataSize, MemoryAllocator m /// The input stream. /// Number of bytes to read as indicated from the chunk size. /// Used for allocating memory during reading data from the stream. + /// + /// The buffer that holds the data. The first bytes hold the stream data. + /// When the stream ends early, the remaining bytes are zero. The caller owns the buffer and must dispose it. + /// protected static IMemoryOwner ReadImageDataFromStream(Stream input, int bytesToRead, MemoryAllocator memoryAllocator) { - IMemoryOwner data = memoryAllocator.Allocate(bytesToRead, AllocationOptions.Clean); - Span dataSpan = data.Memory.Span; - input.Read(dataSpan[..bytesToRead]); + IMemoryOwner data = memoryAllocator.Allocate(bytesToRead); + Span dataSpan = data.Memory.Span[..bytesToRead]; + + // A truncated stream gives fewer bytes. The bit readers can read the rest of the chunk, so clear only that rest: + // pooled memory must not reach the decoder. + int read = input.ReadAtLeast(dataSpan, bytesToRead, false); + dataSpan[read..].Clear(); return data; } + /// + /// Releases the raw encoded image data. A second call does nothing. + /// + /// to release managed resources; when called from a finalizer. protected virtual void Dispose(bool disposing) { if (this.isDisposed) @@ -57,7 +86,7 @@ protected virtual void Dispose(bool disposing) /// public void Dispose() { - this.Dispose(disposing: true); + this.Dispose(true); GC.SuppressFinalize(this); } } diff --git a/src/ImageSharp/Formats/Webp/BitReader/Vp8BitReader.cs b/src/ImageSharp/Formats/Webp/BitReader/Vp8BitReader.cs index d71bcf0e38..8cff40101b 100644 --- a/src/ImageSharp/Formats/Webp/BitReader/Vp8BitReader.cs +++ b/src/ImageSharp/Formats/Webp/BitReader/Vp8BitReader.cs @@ -14,6 +14,9 @@ namespace SixLabors.ImageSharp.Formats.Webp.BitReader; /// internal class Vp8BitReader : BitReaderBase { + /// + /// The number of bits that one refill loads. A refill reads 8 bytes and keeps 7 of them. + /// private const int BitsCount = 56; /// @@ -36,6 +39,9 @@ internal class Vp8BitReader : BitReaderBase /// private uint bufferMax; + /// + /// End position of the partition in the buffer. The reader does not read at or after this position. + /// private uint bufferEnd; /// @@ -80,78 +86,147 @@ public Vp8BitReader(IMemoryOwner imageData, uint partitionLength, int star this.IsStartValid = this.InitBitreader(partitionLength, startPos); } - public int Pos => (int)this.pos; - /// /// Gets a value indicating whether a read went past the end of the data. /// The reader then returns zero bits. libwebp treats this as the end of the data. /// public bool Eof => this.eof; + /// + /// Gets the size of the raw encoded image data in bytes. + /// public uint ImageDataSize { get; } + /// + /// Gets the length in bytes of the partition that the reader started with. + /// public uint PartitionLength { get; } /// - /// Gets a value indicating whether the first value of the partition is not larger than the range. RFC 6386, section 7.2, keeps the value less than the - /// range at all times. Thus, a partition that starts with 0xFF is not valid, and libwebp rejects it. + /// Gets a value indicating whether the first byte of the partition is less than the start range of 255. RFC 6386, section 7.2, keeps the value + /// less than the range at all times. Thus, a partition that starts with 0xFF is not valid. /// public bool IsStartValid { get; } + /// + /// Reads one bit with the probability that the bit is 0, in units of 1/256. + /// + /// The probability. + /// The bit. [MethodImpl(InliningOptions.ShortMethod)] - public int GetBit(int prob) + public int GetBit(int prob) => GetBit(this, ref this.value, ref this.bits, ref this.range, prob); + + /// + /// Copies the arithmetic state to the locals of a decode loop. The reader keeps only the input position. + /// + /// The value window. + /// The number of valid bits below the 8-bit comparison window. + /// The range minus 1. + public void LoadState(out ulong value, out int bits, out uint range) + { + value = this.value; + bits = this.bits; + range = this.range; + } + + /// + /// Copies the arithmetic state from the locals of a decode loop. + /// + /// The value window. + /// The number of valid bits below the 8-bit comparison window. + /// The range minus 1. + public void StoreState(ulong value, int bits, uint range) + { + this.value = value; + this.bits = bits; + this.range = range; + } + + /// + /// Reads one bit with the probability that the bit is 0, in units of 1/256. See RFC 6386, section 7.3. + /// + /// + /// The arithmetic state is in the caller's locals, so the JIT can keep it in registers. A field of a class stays in memory, and each bit then waits + /// for a store and a load. Only the input position is in . A refill uses it once for each 56 bits. + /// + /// The reader that holds the input position. + /// The value window. + /// The number of valid bits below the 8-bit comparison window. + /// The range minus 1, from 127 to 254. + /// The probability. + /// The bit. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int GetBit(Vp8BitReader reader, ref ulong value, ref int bits, ref uint range, int prob) { - uint range = this.range; - if (this.bits < 0) + if (bits < 0) { - this.LoadNewBytes(); + Refill(reader, ref value, ref bits); } - int pos = this.bits; - uint split = (uint)((range * prob) >> 8); - ulong value = this.value >> pos; - bool bit = value > split; - if (bit) + // The range is range - 1, so the split is split - 1 too. The bit is 1 when the window is more than split - 1. + uint split = (range * (uint)prob) >> 8; + uint newRange; + int bit; + if ((value >> bits) > split) { - range -= split; - this.value -= (ulong)(split + 1) << pos; + value -= (ulong)(split + 1) << bits; + newRange = range - split; + bit = 1; } else { - range = split + 1; + newRange = split + 1; + bit = 0; } - int shift = 7 ^ BitOperations.Log2(range); - range <<= shift; - this.bits -= shift; - - this.range = range - 1; - - return bit ? 1 : 0; + // The new range is from 1 to 255. The shift moves it back to 128 to 255. + int shift = 7 ^ BitOperations.Log2(newRange); + range = (newRange << shift) - 1; + bits -= shift; + return bit; } - // Simplified version of GetBit for prob=0x80 (note shift is always 1 here) - public int GetSigned(int v) + /// + /// Reads one sign bit with the probability 1/2, and applies it to . + /// + /// + /// A sign is a coin flip, so a branch would mispredict about half of the time. The mask is -1 when the bit is 1 and 0 when it is 0. With the + /// probability 1/2 the new range is at least 128, so the shift is always 1. + /// + /// The reader that holds the input position. + /// The value window. + /// The number of valid bits below the 8-bit comparison window. + /// The range minus 1, from 127 to 254. + /// The magnitude. + /// The magnitude, negated when the bit is 1. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int GetSigned(Vp8BitReader reader, ref ulong value, ref int bits, ref uint range, int v) { - if (this.bits < 0) + if (bits < 0) { - this.LoadNewBytes(); + Refill(reader, ref value, ref bits); } - int pos = this.bits; - uint split = this.range >> 1; - ulong value = this.value >> pos; - ulong mask = (split - value) >> 31; // -1 or 0 - this.bits--; - this.range = (this.range + (uint)mask) | 1; - this.value -= ((split + 1) & mask) << pos; - + uint split = range >> 1; + ulong mask = (split - (value >> bits)) >> 31; + bits--; + range = (range + (uint)mask) | 1; + value -= ((split + 1) & mask) << (bits + 1); return (v ^ (int)mask) - (int)mask; } + /// + /// Reads one flag bit with the probability 1/2. + /// + /// if the bit is 1; otherwise . [MethodImpl(InliningOptions.ShortMethod)] public bool ReadBool() => this.ReadValue(1) is 1; + /// + /// Reads an unsigned value of bits, most significant bit first. Each bit has the probability 1/2. + /// + /// The number of bits to read, from 1 to 32. + /// The value. [MethodImpl(InliningOptions.ShortMethod)] public uint ReadValue(int nBits) { @@ -167,6 +242,11 @@ public uint ReadValue(int nBits) return v; } + /// + /// Reads a magnitude of bits and then one sign bit. Each bit has the probability 1/2. + /// + /// The number of magnitude bits to read, from 1 to 32. + /// The magnitude, negated when the sign bit is 1. [MethodImpl(InliningOptions.ShortMethod)] public int ReadSignedValue(int nBits) { @@ -196,30 +276,61 @@ private bool InitBitreader(uint size, int pos = 0) this.bufferEnd = (uint)posPlusSize; this.bufferMax = (uint)(size > 8 ? posPlusSize - 8 + 1 : pos); - this.LoadNewBytes(); + Refill(this, ref this.value, ref this.bits); // The range field holds Range - 1. Thus, the first 8 bits of the value must be 254 or less. return (this.value >> this.bits) <= this.range; } - [MethodImpl(InliningOptions.ColdPath)] - private void LoadNewBytes() + /// + /// Loads the next bytes below the value window. The window holds fewer than 8 valid bits, so 7 more bytes fit. + /// + /// The reader that holds the input position. + /// The value window. + /// The number of valid bits below the 8-bit comparison window. It is negative. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Refill(Vp8BitReader reader, ref ulong value, ref int bits) { - if (this.pos < this.bufferMax) + if (reader.pos < reader.bufferMax) { - ulong inBits = BinaryPrimitives.ReadUInt64LittleEndian(this.Data.Memory.Span.Slice((int)this.pos, 8)); - this.pos += BitsCount >> 3; - ulong bits = ByteSwap64(inBits); - bits >>= 64 - BitsCount; - this.value = bits | (this.value << BitsCount); - this.bits += BitsCount; + // The position is at least 8 bytes before the end of the partition. The load reads 8 bytes in big-endian order and keeps 7 of them. + ulong inBits = reader.LoadNextBytes(); + value = (inBits >> (64 - BitsCount)) | (value << BitsCount); + bits += BitsCount; } else { - this.LoadFinalBytes(); + // The rare path near the end of the partition works on the fields, so the locals of the caller do not need an address. + reader.value = value; + reader.bits = bits; + reader.LoadFinalBytes(); + value = reader.value; + bits = reader.bits; } } + /// + /// Reads the next 8 bytes in big-endian order and moves the position by the 7 bytes that a refill keeps. + /// + /// + /// The JIT inlines at many places in each decode loop, and each place has a refill. + /// The input comes through , and each inlined read of it adds a temporary to the stack + /// frame of the loop. The JIT clears these temporaries at each call of the loop method. In the coefficient parse, that was a 648-byte clear for each + /// 4x4 block. A refill happens once for each 56 bits, so a call here costs much less than that clear. + /// + /// The 8 bytes as a big-endian value. + [MethodImpl(MethodImplOptions.NoInlining)] + private ulong LoadNextBytes() + { + ulong inBits = BinaryPrimitives.ReadUInt64BigEndian(this.Data.Memory.Span.Slice((int)this.pos, 8)); + this.pos += BitsCount >> 3; + return inBits; + } + + /// + /// Loads one byte near the end of the partition. Past the end, the first call shifts in 8 zero bits and sets . + /// Later calls set the bit count to 0, so shifts stay defined and the reader returns zero bits. + /// private void LoadFinalBytes() { // Only read 8bits at a time. @@ -239,13 +350,4 @@ private void LoadFinalBytes() this.bits = 0; // This is to avoid undefined behaviour with shifts. } } - - [MethodImpl(InliningOptions.ShortMethod)] - private static ulong ByteSwap64(ulong x) - { - x = ((x & 0xffffffff00000000ul) >> 32) | ((x & 0x00000000fffffffful) << 32); - x = ((x & 0xffff0000ffff0000ul) >> 16) | ((x & 0x0000ffff0000fffful) << 16); - x = ((x & 0xff00ff00ff00ff00ul) >> 8) | ((x & 0x00ff00ff00ff00fful) << 8); - return x; - } } diff --git a/src/ImageSharp/Formats/Webp/BitReader/Vp8LBitReader.cs b/src/ImageSharp/Formats/Webp/BitReader/Vp8LBitReader.cs index 1596cf0b40..11b7daec01 100644 --- a/src/ImageSharp/Formats/Webp/BitReader/Vp8LBitReader.cs +++ b/src/ImageSharp/Formats/Webp/BitReader/Vp8LBitReader.cs @@ -2,7 +2,9 @@ // Licensed under the Six Labors Split License. using System.Buffers; +using System.Buffers.Binary; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using SixLabors.ImageSharp.Memory; namespace SixLabors.ImageSharp.Formats.Webp.BitReader; @@ -10,53 +12,38 @@ namespace SixLabors.ImageSharp.Formats.Webp.BitReader; /// /// A bit reader for reading lossless webp streams. /// +/// +/// The reader keeps the bits that it did not read in the low end of a 64-bit value, in least-significant-bit-first order. A refill loads 8 bytes with one +/// read and keeps the whole bytes that fit, so each refill gives at least 56 bits. The decode loops copy the state to locals with +/// , use the static members, and copy it back with . Thus the JIT can keep the state in registers. +/// internal class Vp8LBitReader : BitReaderBase { /// - /// Maximum number of bits (inclusive) the bit-reader can handle. + /// The number of bits that make sure that a refill is necessary. A Huffman symbol uses at most 15 bits and the extra bits of a length or a distance use at + /// most 18 bits. Thus, after a refill, two reads can follow before the next refill. /// - private const int Vp8LMaxNumBitRead = 24; + private const int RefillBits = 32; /// - /// Number of bits prefetched. + /// The length of the data, in bytes. /// - private const int Lbits = 64; + private readonly int length; /// - /// Minimum number of bytes ready after VP8LFillBitWindow. - /// - private const int Wbits = 32; - - private static readonly uint[] BitMask = - [ - 0, - 0x000001, 0x000003, 0x000007, 0x00000f, - 0x00001f, 0x00003f, 0x00007f, 0x0000ff, - 0x0001ff, 0x0003ff, 0x0007ff, 0x000fff, - 0x001fff, 0x003fff, 0x007fff, 0x00ffff, - 0x01ffff, 0x03ffff, 0x07ffff, 0x0fffff, - 0x1fffff, 0x3fffff, 0x7fffff, 0xffffff - ]; - - /// - /// Pre-fetched bits. + /// The bits that are not read. The low bits are valid. /// private ulong value; /// - /// Buffer length. + /// The number of valid bits in . /// - private readonly long len; + private int bitCount; /// - /// Byte position in buffer. + /// The position of the next byte to load. After the end of the data, the position continues to count the zero bytes that the refills add. /// - private long pos; - - /// - /// Current bit-reading position in value. - /// - private int bitPos; + private int position; /// /// Initializes a new instance of the class. @@ -64,21 +51,7 @@ internal class Vp8LBitReader : BitReaderBase /// Lossless compressed image data. public Vp8LBitReader(IMemoryOwner data) : base(data) - { - this.len = data.Memory.Length; - - // Data that ends early can be shorter than the 8-byte bit window. The method loads only the bytes that exist. - int length = (int)Math.Min(this.len, sizeof(long)); - ulong currentValue = 0; - Span dataSpan = this.Data.Memory.Span; - for (int i = 0; i < length; i++) - { - currentValue |= (ulong)dataSpan[i] << (8 * i); - } - - this.value = currentValue; - this.pos = length; - } + => this.length = data.Memory.Length; /// /// Initializes a new instance of the class. @@ -92,37 +65,29 @@ public Vp8LBitReader(Stream inputStream, uint imageDataSize, MemoryAllocator mem } /// - /// Gets a value indicating whether a read went past the end of the data. After the value becomes true, it stays true. After the end, each read returns 0, - /// as in libwebp. + /// Gets the length of the data, in bytes. /// - public bool Eos { get; private set; } + public int Length => this.length; /// - /// Gets an upper bound of the number of bits that are not read: the bytes after the bit window and the 64 bits of the window. libwebp uses the same bound + /// Gets an upper bound of the number of bits that are not read: the bytes that are not loaded and the 64 bits of the window. libwebp uses the same bound /// to reject a stream that is too short for its Huffman groups. /// - public ulong MaxBitsLeft => ((ulong)(this.len - this.pos) * 8) + Lbits; + public ulong MaxBitsLeft => ((ulong)Math.Max(this.length - this.position, 0) * 8) + 64; /// - /// Reads a unsigned short value from the buffer. The bits of each byte are read in least-significant-bit-first order. + /// Reads a value of up to 24 bits. The bits of each byte are read in least-significant-bit-first order. After the end of the data, the bits are 0. /// - /// The number of bits to read (should not exceed 16). - /// A ushort value. + /// The number of bits to read, from 1 to 24. + /// The value. [MethodImpl(InliningOptions.ShortMethod)] public uint ReadValue(int nBits) { - DebugGuard.MustBeGreaterThan(nBits, 0, nameof(nBits)); - - if (!this.Eos && nBits <= Vp8LMaxNumBitRead) - { - ulong val = this.PrefetchBits() & BitMask[nBits]; - this.bitPos += nBits; - this.ShiftBytes(); - return (uint)val; - } + DebugGuard.MustBeBetweenOrEqualTo(nBits, 1, 24, nameof(nBits)); - this.SetEndOfStream(); - return 0; + ref byte data = ref MemoryMarshal.GetReference(this.Data.Memory.Span); + Refill(ref data, this.length, ref this.value, ref this.bitCount, ref this.position); + return ReadBits(nBits, ref this.value, ref this.bitCount); } /// @@ -130,74 +95,123 @@ public uint ReadValue(int nBits) /// /// True if the bit read was 1, false otherwise. [MethodImpl(InliningOptions.ShortMethod)] - public bool ReadBit() - { - uint bit = this.ReadValue(1); - return bit != 0; - } + public bool ReadBit() => this.ReadValue(1) != 0; /// - /// For jumping over a number of bits in the bit stream when accessed with PrefetchBits and FillBitWindow. + /// Returns a value that tells if a read used bits after the end of the data. /// - /// The number of bits to advance the position. + /// True, if a read used bits after the end of the data. [MethodImpl(InliningOptions.ShortMethod)] - public void AdvanceBitPosition(int numberOfBits) => this.bitPos += numberOfBits; + public bool IsEndOfStream() => IsEndOfStream(this.length, this.bitCount, this.position); /// - /// Return the pre-fetched bits, so they can be looked up. + /// Copies the bit state to the locals of a decode loop. /// - /// The pre-fetched bits. - [MethodImpl(InliningOptions.ShortMethod)] - public ulong PrefetchBits() => this.value >> (this.bitPos & (Lbits - 1)); + /// The bits that are not read. + /// The number of valid bits. + /// The position of the next byte to load. + public void LoadState(out ulong bits, out int count, out int next) + { + bits = this.value; + count = this.bitCount; + next = this.position; + } /// - /// Advances the read buffer by 4 bytes to make room for reading next 32 bits. + /// Copies the bit state from the locals of a decode loop. /// - [MethodImpl(InliningOptions.ShortMethod)] - public void FillBitWindow() + /// The bits that are not read. + /// The number of valid bits. + /// The position of the next byte to load. + public void StoreState(ulong bits, int count, int next) { - if (this.bitPos >= Wbits) + this.value = bits; + this.bitCount = count; + this.position = next; + } + + /// + /// Makes sure that at least 32 bits are valid. A refill gives at least 56 bits. + /// + /// The first byte of the data. + /// The length of the data, in bytes. + /// The bits that are not read. + /// The number of valid bits. + /// The position of the next byte to load. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Refill(ref byte data, int length, ref ulong bits, ref int count, ref int next) + { + if (count >= RefillBits) { - this.ShiftBytes(); + return; } + + // One 8-byte load puts byte k at bit count + 8k. The bytes that fit in the 64 bits are whole when count + 8k <= 56, so the refill keeps + // (63 - count) / 8 bytes and the count becomes 56 + (count % 8), that is count | 56. The bits above the count hold the next bytes of the data. They + // are the same bits that the next load puts there, so the OR of the next load keeps them correct. + ulong loaded = next <= length - sizeof(ulong) + ? BinaryPrimitives.ReadUInt64LittleEndian(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.Add(ref data, (uint)next), sizeof(ulong))) + : LoadTail(ref data, length, next); + + bits |= loaded << count; + next += (63 - count) >> 3; + count |= 56; } /// - /// Returns true if there was an attempt at reading bit past the end of the buffer. + /// Reads a value of up to 24 bits. At least that many bits must be valid. /// - /// True, if end of buffer was reached. - [MethodImpl(InliningOptions.ShortMethod)] - public bool IsEndOfStream() => this.Eos || (this.pos == this.len && this.bitPos > Lbits); + /// The number of bits to read. + /// The bits that are not read. + /// The number of valid bits. + /// The value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint ReadBits(int nBits, ref ulong bits, ref int count) + { + uint result = (uint)bits & ((1u << nBits) - 1); + Skip(nBits, ref bits, ref count); + return result; + } /// - /// If not at EOS, reload up to Vp8LLbits byte-by-byte. + /// Skips bits that the caller looked up in the low bits of . At least that many bits must be valid. /// - [MethodImpl(InliningOptions.ShortMethod)] - private void ShiftBytes() + /// The number of bits to skip, from 0 to 63. + /// The bits that are not read. + /// The number of valid bits. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Skip(int nBits, ref ulong bits, ref int count) { - Span dataSpan = this.Data!.Memory.Span; - while (this.bitPos >= 8 && this.pos < this.len) - { - this.value >>= 8; - this.value |= (ulong)dataSpan[(int)this.pos] << (Lbits - 8); - ++this.pos; - this.bitPos -= 8; - } - - // A bit position after the window here means that the loop above stopped at the end of the data. Thus, this one comparison is the condition of - // IsEndOfStream. - if (this.bitPos > Lbits) - { - this.SetEndOfStream(); - } + bits >>= nBits; + count -= nBits; } /// - /// Marks the end of the data. The bit position goes back to 0, so that the shifts of the later reads stay in range. + /// Returns a value that tells if a read used bits after the end of the data. The bits that the reads used are the loaded bits minus the valid bits. /// - private void SetEndOfStream() + /// The length of the data, in bytes. + /// The number of valid bits. + /// The position of the next byte to load. + /// True, if a read used bits after the end of the data. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsEndOfStream(int length, int count, int next) => ((long)next * 8) - count > (long)length * 8; + + /// + /// Loads the bytes from to the end of the data. The bytes after the end are 0. + /// + /// The first byte of the data. + /// The length of the data, in bytes. + /// The position of the first byte to load. + /// The loaded bytes, in little-endian order. + [MethodImpl(MethodImplOptions.NoInlining)] + private static ulong LoadTail(ref byte data, int length, int next) { - this.Eos = true; - this.bitPos = 0; + ulong loaded = 0; + for (int i = next; i < length; i++) + { + loaded |= (ulong)Unsafe.Add(ref data, (uint)i) << ((i - next) * 8); + } + + return loaded; } } diff --git a/src/ImageSharp/Formats/Webp/BitWriter/BitWriterBase.cs b/src/ImageSharp/Formats/Webp/BitWriter/BitWriterBase.cs index 95c2a26121..3bf4616381 100644 --- a/src/ImageSharp/Formats/Webp/BitWriter/BitWriterBase.cs +++ b/src/ImageSharp/Formats/Webp/BitWriter/BitWriterBase.cs @@ -1,7 +1,9 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +using System.Buffers; using SixLabors.ImageSharp.Formats.Webp.Chunks; +using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.Metadata.Profiles.Exif; using SixLabors.ImageSharp.Metadata.Profiles.Icc; using SixLabors.ImageSharp.Metadata.Profiles.Xmp; @@ -9,31 +11,49 @@ namespace SixLabors.ImageSharp.Formats.Webp.BitWriter; -internal abstract class BitWriterBase +/// +/// Base class for the VP8 and VP8L bit writers. It owns the output buffer and writes the RIFF container chunks. +/// +internal abstract class BitWriterBase : IDisposable { + /// + /// The maximum canvas width or height that the writer accepts for the extended format header. The value is 2^24 - 1. + /// private const uint MaxDimension = 16777215; + /// + /// The maximum product of the canvas width and height. The WebP container specification limits it to 2^32 - 1. + /// private const ulong MaxCanvasPixels = 4294967295ul; /// - /// Buffer to write to. + /// The owner of the buffer to write to. /// - private byte[] buffer; + private IMemoryOwner bufferOwner; /// - /// Initializes a new instance of the class. + /// The length of the buffer in bytes. /// - /// The expected size in bytes. - protected BitWriterBase(int expectedSize) => this.buffer = new byte[expectedSize]; + private int capacity; /// /// Initializes a new instance of the class. - /// Used internally for cloning. /// - /// The byte buffer. - private protected BitWriterBase(byte[] buffer) => this.buffer = buffer; + /// The memory allocator for the buffer. + /// The expected size in bytes. + protected BitWriterBase(MemoryAllocator memoryAllocator, int expectedSize) + { + this.MemoryAllocator = memoryAllocator; - public byte[] Buffer => this.buffer; + // No clear: the writer writes each byte before it reads the byte or writes it to the output. + this.bufferOwner = memoryAllocator.Allocate(expectedSize); + this.capacity = expectedSize; + } + + /// + /// Gets the buffer to write to. The length is the current capacity in bytes. + /// + public Span Buffer => this.bufferOwner.GetSpan()[..this.capacity]; /// /// Gets the number of bytes of the encoded image data. @@ -41,20 +61,25 @@ internal abstract class BitWriterBase /// The number of bytes of the image data. public abstract int NumBytes { get; } + /// + /// Gets the memory allocator for the buffer. + /// + protected MemoryAllocator MemoryAllocator { get; } + /// /// Writes the encoded bytes of the image to the stream. Call Finish() before this. /// /// The stream to write to. - public void WriteToStream(Stream stream) => stream.Write(this.Buffer.AsSpan(0, this.NumBytes)); + public void WriteToStream(Stream stream) => stream.Write(this.Buffer[..this.NumBytes]); /// /// Writes the encoded bytes of the image to the given buffer. Call Finish() before this. /// /// The destination buffer. - public void WriteToBuffer(Span dest) => this.Buffer.AsSpan(0, this.NumBytes).CopyTo(dest); + public void WriteToBuffer(Span dest) => this.Buffer[..this.NumBytes].CopyTo(dest); /// - /// Resizes the buffer to write to. + /// Makes sure that the buffer has space for the given number of bytes after the written bytes. /// /// The extra size in bytes needed. public abstract void BitWriterResize(int extraSize); @@ -64,9 +89,27 @@ internal abstract class BitWriterBase /// public abstract void Finish(); + /// + public void Dispose() + { + this.bufferOwner.Dispose(); + this.capacity = 0; + } + + /// + /// Replaces the buffer with a larger buffer. The new buffer starts with the bytes of the old buffer. + /// + /// + /// The caller calls this only when the written bytes and the extra bytes do not fit into the current buffer. + /// The writers grow only when the written bytes nearly fill the buffer, so the copy of the full old buffer copies almost no unused bytes. + /// + /// The current capacity in bytes. + /// The minimum new capacity in bytes. protected void ResizeBuffer(int maxBytes, int sizeRequired) { - int newSize = (3 * maxBytes) >> 1; + // Grow by 1.5 times, so the number of copies stays logarithmic in the output size. + // maxBytes + (maxBytes >> 1) is equal to (3 * maxBytes) >> 1, but the product cannot overflow. + int newSize = maxBytes + (maxBytes >> 1); if (newSize < sizeRequired) { newSize = sizeRequired; @@ -74,7 +117,13 @@ protected void ResizeBuffer(int maxBytes, int sizeRequired) // Make new size multiple of 1k. newSize = ((newSize >> 10) + 1) << 10; - Array.Resize(ref this.buffer, newSize); + + IMemoryOwner newOwner = this.MemoryAllocator.Allocate(newSize); + this.Buffer.CopyTo(newOwner.GetSpan()); + + this.bufferOwner.Dispose(); + this.bufferOwner = newOwner; + this.capacity = newSize; } /// @@ -186,20 +235,33 @@ public static void WriteAnimationParameter(Stream stream, Color background, usho /// Writes the alpha chunk to the stream. /// /// The stream to write to. - /// The alpha channel data bytes. - /// Indicates, if the alpha channel data is compressed. - public static void WriteAlphaChunk(Stream stream, ReadOnlySpan dataBytes, bool alphaDataIsCompressed) + /// The alpha channel data, compressed with the lossless WebP compression. + public static void WriteAlphaChunk(Stream stream, ReadOnlySpan dataBytes) + { + long pos = RiffHelper.BeginWriteChunk(stream, (uint)WebpChunkType.Alpha); + + // TODO: Filtering and preprocessing + stream.WriteByte(1); + stream.Write(dataBytes); + RiffHelper.EndWriteChunk(stream, pos); + } + + /// + /// Writes an uncompressed alpha chunk to the stream: the alpha values of each row, in scan order. + /// + /// The stream to write to. + /// The alpha plane. + /// The image width. + /// The image height. + public static void WriteAlphaChunk(Stream stream, Buffer2D alpha, int width, int height) { long pos = RiffHelper.BeginWriteChunk(stream, (uint)WebpChunkType.Alpha); - byte flags = 0; - if (alphaDataIsCompressed) + stream.WriteByte(0); + for (int y = 0; y < height; y++) { - // TODO: Filtering and preprocessing - flags = 1; + stream.Write(alpha.DangerousGetRowSpan(y)[..width]); } - stream.WriteByte(flags); - stream.Write(dataBytes); RiffHelper.EndWriteChunk(stream, pos); } @@ -214,6 +276,7 @@ public static void WriteAlphaChunk(Stream stream, ReadOnlySpan dataBytes, /// The height of the image. /// Flag indicating, if a alpha channel is present. /// Flag indicating, if an animation parameter is present. + /// The VP8X chunk that the method wrote to the stream. protected static WebpVp8X WriteVp8XHeader( Stream stream, ExifProfile? exifProfile, diff --git a/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs b/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs index 0f0d3b5c87..972c630530 100644 --- a/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs +++ b/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs @@ -3,6 +3,7 @@ using System.Buffers.Binary; using SixLabors.ImageSharp.Formats.Webp.Lossy; +using SixLabors.ImageSharp.Memory; namespace SixLabors.ImageSharp.Formats.Webp.BitWriter; @@ -12,28 +13,90 @@ namespace SixLabors.ImageSharp.Formats.Webp.BitWriter; internal class Vp8BitWriter : BitWriterBase { #pragma warning disable SA1310 // Field names should not contain underscore + /// + /// The DC prediction mode for a 16x16 luma block or an 8x8 chroma block. + /// private const int DC_PRED = 0; + + /// + /// The TrueMotion prediction mode for a 16x16 luma block or an 8x8 chroma block. + /// private const int TM_PRED = 1; + + /// + /// The vertical prediction mode for a 16x16 luma block or an 8x8 chroma block. + /// private const int V_PRED = 2; + + /// + /// The horizontal prediction mode for a 16x16 luma block or an 8x8 chroma block. + /// private const int H_PRED = 3; - // 4x4 modes + /// + /// The DC prediction mode for a 4x4 luma block. + /// private const int B_DC_PRED = 0; + + /// + /// The TrueMotion prediction mode for a 4x4 luma block. + /// private const int B_TM_PRED = 1; + + /// + /// The vertical prediction mode for a 4x4 luma block. + /// private const int B_VE_PRED = 2; + + /// + /// The horizontal prediction mode for a 4x4 luma block. + /// private const int B_HE_PRED = 3; + + /// + /// The down-right diagonal prediction mode for a 4x4 luma block. + /// private const int B_RD_PRED = 4; + + /// + /// The vertical-right prediction mode for a 4x4 luma block. + /// private const int B_VR_PRED = 5; + + /// + /// The down-left diagonal prediction mode for a 4x4 luma block. + /// private const int B_LD_PRED = 6; + + /// + /// The vertical-left prediction mode for a 4x4 luma block. + /// private const int B_VL_PRED = 7; + + /// + /// The horizontal-down prediction mode for a 4x4 luma block. + /// private const int B_HD_PRED = 8; + + /// + /// The horizontal-up prediction mode for a 4x4 luma block. + /// private const int B_HU_PRED = 9; #pragma warning restore SA1310 // Field names should not contain underscore + /// + /// The encoder that holds the headers, the probabilities and the macroblock modes to write. + /// private readonly Vp8Encoder enc; + /// + /// Current range minus 1. After each bit, the writer keeps it in the [127, 254] interval. + /// private int range; + /// + /// The low end of the arithmetic coder interval. It holds the bits that the writer did not flush yet. + /// private int value; /// @@ -46,15 +109,19 @@ internal class Vp8BitWriter : BitWriterBase /// private int nbBits; + /// + /// The number of bytes written to the buffer. + /// private uint pos; /// /// Initializes a new instance of the class. /// + /// The memory allocator for the buffer. /// The expected size in bytes. /// The Vp8Encoder. - public Vp8BitWriter(int expectedSize, Vp8Encoder enc) - : base(expectedSize) + public Vp8BitWriter(MemoryAllocator memoryAllocator, int expectedSize, Vp8Encoder enc) + : base(memoryAllocator, expectedSize) { this.range = 255 - 1; this.value = 0; @@ -68,42 +135,53 @@ public Vp8BitWriter(int expectedSize, Vp8Encoder enc) /// public override int NumBytes => (int)this.pos; - public int PutCoeffs(int ctx, Vp8Residual residual) + /// + /// Writes the tokens that code one block. + /// + /// The context of the first token. + /// The residual with the coefficient type and the probabilities. + /// The 16 coefficients of the block. + /// 1 if the block has a non-zero coefficient, else 0. + public int PutCoeffs(int ctx, Vp8Residual residual, ReadOnlySpan coeffs) { + residual.SetCoeffs(coeffs); + ReadOnlySpan probas = residual.Probas; int n = residual.First; - Vp8ProbaArray p = residual.Prob[n].Probabilities[ctx]; - if (!this.PutBit(residual.Last >= 0, p.Probabilities[0])) + + // p is the index of the first probability of (band, context). The band of the positions 0 and 1 is the position itself. + int p = Vp8EncoderProbabilities.ProbaIndex(n, ctx); + if (!this.PutBit(residual.Last >= 0, probas[p])) { return 0; } while (n < 16) { - int c = residual.Coeffs[n++]; + int c = coeffs[n++]; bool sign = c < 0; int v = sign ? -c : c; - if (!this.PutBit(v != 0, p.Probabilities[1])) + if (!this.PutBit(v != 0, probas[p + 1])) { - p = residual.Prob[WebpConstants.Vp8EncBands[n]].Probabilities[0]; + p = Vp8EncoderProbabilities.ProbaIndex(WebpConstants.Vp8EncBands[n], 0); continue; } - if (!this.PutBit(v > 1, p.Probabilities[2])) + if (!this.PutBit(v > 1, probas[p + 2])) { - p = residual.Prob[WebpConstants.Vp8EncBands[n]].Probabilities[1]; + p = Vp8EncoderProbabilities.ProbaIndex(WebpConstants.Vp8EncBands[n], 1); } else { - if (!this.PutBit(v > 4, p.Probabilities[3])) + if (!this.PutBit(v > 4, probas[p + 3])) { - if (this.PutBit(v != 2, p.Probabilities[4])) + if (this.PutBit(v != 2, probas[p + 4])) { - this.PutBit(v == 4, p.Probabilities[5]); + this.PutBit(v == 4, probas[p + 5]); } } - else if (!this.PutBit(v > 10, p.Probabilities[6])) + else if (!this.PutBit(v > 10, probas[p + 6])) { - if (!this.PutBit(v > 6, p.Probabilities[7])) + if (!this.PutBit(v > 6, probas[p + 7])) { this.PutBit(v == 6, 159); } @@ -116,12 +194,12 @@ public int PutCoeffs(int ctx, Vp8Residual residual) else { int mask; - byte[] tab; + ReadOnlySpan tab; if (v < 3 + (8 << 1)) { // Cat3 (3b) - this.PutBit(0, p.Probabilities[8]); - this.PutBit(0, p.Probabilities[9]); + this.PutBit(0, probas[p + 8]); + this.PutBit(0, probas[p + 9]); v -= 3 + (8 << 0); mask = 1 << 2; tab = WebpConstants.Cat3; @@ -129,8 +207,8 @@ public int PutCoeffs(int ctx, Vp8Residual residual) else if (v < 3 + (8 << 2)) { // Cat4 (4b) - this.PutBit(0, p.Probabilities[8]); - this.PutBit(1, p.Probabilities[9]); + this.PutBit(0, probas[p + 8]); + this.PutBit(1, probas[p + 9]); v -= 3 + (8 << 1); mask = 1 << 3; tab = WebpConstants.Cat4; @@ -138,8 +216,8 @@ public int PutCoeffs(int ctx, Vp8Residual residual) else if (v < 3 + (8 << 3)) { // Cat5 (5b) - this.PutBit(1, p.Probabilities[8]); - this.PutBit(0, p.Probabilities[10]); + this.PutBit(1, probas[p + 8]); + this.PutBit(0, probas[p + 10]); v -= 3 + (8 << 2); mask = 1 << 4; tab = WebpConstants.Cat5; @@ -147,8 +225,8 @@ public int PutCoeffs(int ctx, Vp8Residual residual) else { // Cat6 (11b) - this.PutBit(1, p.Probabilities[8]); - this.PutBit(1, p.Probabilities[10]); + this.PutBit(1, probas[p + 8]); + this.PutBit(1, probas[p + 10]); v -= 3 + (8 << 3); mask = 1 << 10; tab = WebpConstants.Cat6; @@ -162,11 +240,11 @@ public int PutCoeffs(int ctx, Vp8Residual residual) } } - p = residual.Prob[WebpConstants.Vp8EncBands[n]].Probabilities[2]; + p = Vp8EncoderProbabilities.ProbaIndex(WebpConstants.Vp8EncBands[n], 2); } this.PutBitUniform(sign ? 1 : 0); - if (n == 16 || !this.PutBit(n <= residual.Last, p.Probabilities[0])) + if (n == 16 || !this.PutBit(n <= residual.Last, probas[p])) { return 1; // EOB } @@ -175,6 +253,58 @@ public int PutCoeffs(int ctx, Vp8Residual residual) return 1; } + /// + /// Writes recorded coefficient tokens. + /// + /// The tokens. Bit 15 holds the bit value. If is set, bits 0 to 7 + /// hold a constant probability. Else bits 0 to 13 hold the index of the probability in . + /// The final probabilities in the flat [type][band][context][proba] order. + public void PutTokens(ReadOnlySpan tokens, ReadOnlySpan probas) + { + // This loop does the same steps as PutBit for each token. The coder state is kept in locals, so that it can stay + // in registers. The state goes back to the fields only around Flush, which reads and changes the value and the bit count. + ReadOnlySpan norm = WebpLookupTables.Norm; + ReadOnlySpan newRange = WebpLookupTables.NewRange; + int range = this.range; + int value = this.value; + int nbBits = this.nbBits; + foreach (ushort token in tokens) + { + int proba = (token & Vp8Residual.FixedProbaBit) != 0 ? token & 0xff : probas[token & 0x3fff]; + int split = (range * proba) >> 8; + if ((token >> 15) != 0) + { + value += split + 1; + range -= split + 1; + } + else + { + range = split; + } + + if (range < 127) + { + // Emit 'shift' bits out and renormalize. + int shift = norm[range]; + range = newRange[range]; + value <<= shift; + nbBits += shift; + if (nbBits > 0) + { + this.value = value; + this.nbBits = nbBits; + this.Flush(); + value = this.value; + nbBits = this.nbBits; + } + } + } + + this.range = range; + this.value = value; + this.nbBits = nbBits; + } + /// /// Resizes the buffer to write to. /// @@ -201,6 +331,11 @@ public override void Finish() this.Flush(); } + /// + /// Writes the segment of a macroblock with the segment tree. The first bit selects segments 2 and 3. The second bit selects the segment in that pair. + /// + /// The segment, from 0 to 3. + /// The 3 segment tree probabilities. public void PutSegment(int s, Span p) { if (this.PutBit(s >= 2, p[0])) @@ -211,6 +346,10 @@ public void PutSegment(int s, Span p) this.PutBit(s & 1, p[1]); } + /// + /// Writes the 16x16 luma prediction mode of a key frame macroblock with the fixed tree probabilities. + /// + /// The prediction mode: , , or . public void PutI16Mode(int mode) { if (this.PutBit(mode is TM_PRED or H_PRED, 156)) @@ -223,6 +362,12 @@ public void PutI16Mode(int mode) } } + /// + /// Writes the prediction mode of a 4x4 luma block with the 4x4 mode tree. + /// + /// The prediction mode, from to . + /// The 9 tree probabilities for the modes of the top and left blocks. + /// The mode, so that the caller can use it as the left context of the next block. public int PutI4Mode(int mode, ReadOnlySpan prob) { if (this.PutBit(mode != B_DC_PRED, prob[0])) @@ -255,6 +400,10 @@ public int PutI4Mode(int mode, ReadOnlySpan prob) return mode; } + /// + /// Writes the chroma prediction mode of a key frame macroblock with the fixed tree probabilities. + /// + /// The prediction mode: , , or . public void PutUvMode(int uvMode) { // DC_PRED @@ -269,6 +418,11 @@ public void PutUvMode(int uvMode) } } + /// + /// Writes the low bits of , most significant bit first. Each bit has the probability 1/2. + /// + /// The value. + /// The number of bits to write. private void PutBits(uint value, int nbBits) { for (uint mask = 1u << (nbBits - 1); mask != 0; mask >>= 1) @@ -277,8 +431,20 @@ private void PutBits(uint value, int nbBits) } } + /// + /// Writes one bit with the probability that the bit is 0, in units of 1/256. + /// + /// The bit. + /// The probability. + /// The bit, so that the caller can branch on it. private bool PutBit(bool bit, int prob) => this.PutBit(bit ? 1 : 0, prob); + /// + /// Writes one bit with the probability that the bit is 0, in units of 1/256. See RFC 6386, section 7.3. + /// + /// The bit. Any value other than 0 writes a 1. + /// The probability. + /// if the bit is not 0; otherwise . private bool PutBit(int bit, int prob) { int split = (this.range * prob) >> 8; @@ -308,6 +474,11 @@ private bool PutBit(int bit, int prob) return bit != 0; } + /// + /// Writes one bit with the probability 1/2. With this probability the range needs at most one shift to renormalize. + /// + /// The bit. Any value other than 0 writes a 1. + /// The argument, so that the caller can branch on it. private int PutBitUniform(int bit) { int split = this.range >> 1; @@ -335,6 +506,12 @@ private int PutBitUniform(int bit) return bit; } + /// + /// Writes an optional signed value. A flag bit tells if the value is not 0. A value that is not 0 follows as + /// magnitude bits and then one sign bit. Each bit has the probability 1/2. + /// + /// The value. Its magnitude must fit in bits. + /// The number of magnitude bits. private void PutSignedBits(int value, int nbBits) { if (this.PutBitUniform(value != 0 ? 1 : 0) == 0) @@ -353,6 +530,10 @@ private void PutSignedBits(int value, int nbBits) } } + /// + /// Moves the next complete byte from to the buffer. A 0xFF byte can still receive a carry, so the writer counts it in + /// and writes it later. A carry adds 1 to the last written byte and turns the pending 0xFF bytes into 0x00. + /// private void Flush() { int s = 8 + this.nbBits; @@ -369,7 +550,7 @@ private void Flush() // overflow -> propagate carry over pending 0xff's if (pos > 0) { - this.Buffer[pos - 1]++; + this.Buffer[(int)pos - 1]++; } } @@ -378,11 +559,11 @@ private void Flush() int value = (bits & 0x100) != 0 ? 0x00 : 0xff; for (; this.run > 0; --this.run) { - this.Buffer[pos++] = (byte)value; + this.Buffer[(int)pos++] = (byte)value; } } - this.Buffer[pos++] = (byte)(bits & 0xff); + this.Buffer[(int)pos++] = (byte)(bits & 0xff); this.pos = pos; } else @@ -399,7 +580,7 @@ public override void WriteEncodedImageToStream(Stream stream) int mbSize = this.enc.Mbw * this.enc.Mbh; int expectedSize = (int)((uint)mbSize * 7 / 8); - Vp8BitWriter bitWriterPartZero = new(expectedSize, this.enc); + using Vp8BitWriter bitWriterPartZero = new(this.MemoryAllocator, expectedSize, this.enc); // Partition #0 with header and partition sizes. uint size0 = bitWriterPartZero.GeneratePartition0(); @@ -410,7 +591,7 @@ public override void WriteEncodedImageToStream(Stream stream) vp8Size += pad; // Emit header and partition #0 - this.WriteVp8Header(stream, vp8Size); + WriteVp8Header(stream, vp8Size); this.WriteFrameHeader(stream, size0); bitWriterPartZero.WriteToStream(stream); @@ -423,6 +604,11 @@ public override void WriteEncodedImageToStream(Stream stream) } } + /// + /// Writes the first partition to this writer. It holds the color space and clamp bits, the segment, filter and quantizer headers, + /// the coefficient probabilities and the prediction modes of all macroblocks. + /// + /// The size of the partition in bytes. private uint GeneratePartition0() { this.PutBitUniform(0); // colorspace @@ -443,10 +629,14 @@ private uint GeneratePartition0() return (uint)this.NumBytes; } + /// + /// Writes the segment header. With more than one segment, it writes the absolute quantizer and filter strength of each segment and, + /// when the segment map changes, the segment tree probabilities. + /// private void WriteSegmentHeader() { - Vp8EncSegmentHeader hdr = this.enc.SegmentHeader; - Vp8EncProba proba = this.enc.Proba; + Vp8EncoderSegmentHeader hdr = this.enc.SegmentHeader; + Vp8EncoderProbabilities proba = this.enc.Proba; if (this.PutBitUniform(hdr.NumSegments > 1 ? 1 : 0) != 0) { // We always 'update' the quant and filter strength values. @@ -480,6 +670,9 @@ private void WriteSegmentHeader() } } + /// + /// Writes the loop filter header: the filter type, level and sharpness, and the optional loop filter delta of the 4x4 intra mode. + /// private void WriteFilterHeader() { Vp8FilterHeader hdr = this.enc.FilterHeader; @@ -503,7 +696,9 @@ private void WriteFilterHeader() } } - // Nominal quantization parameters + /// + /// Writes the base quantizer index and the deltas for the luma DC, Y2 and chroma quantizers. + /// private void WriteQuant() { this.PutBits((uint)this.enc.BaseQuant, 7); @@ -514,25 +709,23 @@ private void WriteQuant() this.PutSignedBits(this.enc.DqUvAc, 4); } + /// + /// Writes the coefficient probability updates and the skip probability. An update flag for each probability tells if the value differs + /// from the default. A changed value follows as 8 bits. + /// private void WriteProbas() { - Vp8EncProba probas = this.enc.Proba; - for (int t = 0; t < WebpConstants.NumTypes; ++t) + Vp8EncoderProbabilities probas = this.enc.Proba; + ReadOnlySpan coeffs = probas.Coeffs; + ReadOnlySpan defaults = Vp8EncoderProbabilities.DefaultProbas; + ReadOnlySpan updates = Vp8EncoderProbabilities.UpdateProbas; + for (int i = 0; i < coeffs.Length; i++) { - for (int b = 0; b < WebpConstants.NumBands; ++b) + byte p0 = coeffs[i]; + bool update = p0 != defaults[i]; + if (this.PutBit(update, updates[i])) { - for (int c = 0; c < WebpConstants.NumCtx; ++c) - { - for (int p = 0; p < WebpConstants.NumProbas; ++p) - { - byte p0 = probas.Coeffs[t][b].Probabilities[c].Probabilities[p]; - bool update = p0 != WebpLookupTables.DefaultCoeffsProba[t, b, c, p]; - if (this.PutBit(update, WebpLookupTables.CoeffsUpdateProba[t, b, c, p])) - { - this.PutBits(p0, 8); - } - } - } + this.PutBits(p0, 8); } } @@ -542,17 +735,23 @@ private void WriteProbas() } } - // Writes the partition #0 modes (that is: all intra modes) + /// + /// Writes the segment, the skip flag and the luma and chroma prediction modes of each macroblock in raster order. + /// + /// + /// Partition 0 holds the intra modes of all macroblocks. + /// private void CodeIntraModes() { - Vp8EncIterator it = new(this.enc); + Vp8EncoderIterator it = new(this.enc); int predsWidth = this.enc.PredsWidth; + Span allPreds = it.Preds; do { - Vp8MacroBlockInfo mb = it.CurrentMacroBlockInfo; + ref Vp8MacroBlockInfo mb = ref it.CurrentMacroBlockInfo; int predIdx = it.PredIdx; - Span preds = it.Preds.AsSpan(predIdx); + Span preds = allPreds[predIdx..]; if (this.enc.SegmentHeader.UpdateMap) { this.PutSegment(mb.Segment, this.enc.Proba.Segments); @@ -570,17 +769,17 @@ private void CodeIntraModes() } else { - Span topPred = it.Preds.AsSpan(predIdx - predsWidth); + Span topPred = allPreds[(predIdx - predsWidth)..]; for (int y = 0; y < 4; y++) { - int left = it.Preds[predIdx - 1]; + int left = allPreds[predIdx - 1]; for (int x = 0; x < 4; x++) { - byte[] probas = WebpLookupTables.ModesProba[topPred[x], left]; - left = this.PutI4Mode(it.Preds[predIdx + x], probas); + ReadOnlySpan probas = WebpLookupTables.ModesProba.Slice(((topPred[x] * WebpConstants.NumBModes) + left) * 9, 9); + left = this.PutI4Mode(allPreds[predIdx + x], probas); } - topPred = it.Preds.AsSpan(predIdx); + topPred = allPreds[predIdx..]; predIdx += predsWidth; } } @@ -590,21 +789,36 @@ private void CodeIntraModes() while (it.Next()); } - private void WriteVp8Header(Stream stream, uint size) + /// + /// Writes the VP8 chunk tag and the chunk size. + /// + /// The stream to write to. + /// The chunk payload size in bytes. + private static void WriteVp8Header(Stream stream, uint size) { - Span buf = stackalloc byte[WebpConstants.TagSize]; + // WebpConstants.TagSize is 4, so one four-byte inline array holds the tag and then the size. + InlineArray4 buffer = default; + Span buf = buffer; BinaryPrimitives.WriteUInt32BigEndian(buf, (uint)WebpChunkType.Vp8); stream.Write(buf); BinaryPrimitives.WriteUInt32LittleEndian(buf, size); stream.Write(buf); } + /// + /// Writes the 10-byte key frame header: the frame tag with the first partition size, the start code and the image dimensions. + /// + /// The stream to write to. + /// The size of the first partition in bytes. private void WriteFrameHeader(Stream stream, uint size0) { uint profile = 0; int width = this.enc.Width; int height = this.enc.Height; - Span vp8FrameHeader = stackalloc byte[WebpConstants.Vp8FrameHeaderSize]; + + // WebpConstants.Vp8FrameHeaderSize is 10, the size of this inline array. + InlineArray10 frameHeaderBuffer = default; + Span vp8FrameHeader = frameHeaderBuffer; // Paragraph 9.1. uint bits = 0 // keyframe (1b) diff --git a/src/ImageSharp/Formats/Webp/BitWriter/Vp8LBitWriter.cs b/src/ImageSharp/Formats/Webp/BitWriter/Vp8LBitWriter.cs index dc867fa85e..6206156a31 100644 --- a/src/ImageSharp/Formats/Webp/BitWriter/Vp8LBitWriter.cs +++ b/src/ImageSharp/Formats/Webp/BitWriter/Vp8LBitWriter.cs @@ -3,6 +3,7 @@ using System.Buffers.Binary; using SixLabors.ImageSharp.Formats.Webp.Lossless; +using SixLabors.ImageSharp.Memory; namespace SixLabors.ImageSharp.Formats.Webp.BitWriter; @@ -16,8 +17,14 @@ internal class Vp8LBitWriter : BitWriterBase /// private const int MinExtraSize = 32768; + /// + /// The number of bytes that one flush moves from the bit accumulator to the buffer. + /// private const int WriterBytes = 4; + /// + /// The number of bits that one flush moves from the bit accumulator to the buffer. + /// private const int WriterBits = 32; /// @@ -38,31 +45,27 @@ internal class Vp8LBitWriter : BitWriterBase /// /// Initializes a new instance of the class. /// + /// The memory allocator for the buffer. /// The expected size in bytes. - public Vp8LBitWriter(int expectedSize) - : base(expectedSize) - { - } - - /// - /// Initializes a new instance of the class. - /// Used internally for cloning. - /// - private Vp8LBitWriter(byte[] buffer, ulong bits, int used, int cur) - : base(buffer) + public Vp8LBitWriter(MemoryAllocator memoryAllocator, int expectedSize) + : base(memoryAllocator, expectedSize) { - this.bits = bits; - this.used = used; - this.cur = cur; } /// public override int NumBytes => this.cur + ((this.used + 7) >> 3); + /// + /// Gets the current write position: the pending bits, the number of pending bits, and the byte position. + /// + public (ulong Bits, int Used, int Cur) Position => (this.bits, this.used, this.cur); + /// /// This function writes bits into bytes in increasing addresses (little endian), /// and within a byte least-significant-bit first. This function can write up to 32 bits in one go. /// + /// The bits to write. Only the low bits can be set. + /// The number of bits to write, in the range 0 to 32. A value of 0 writes nothing. public void PutBits(uint bits, int nBits) { if (nBits > 0) @@ -77,32 +80,64 @@ public void PutBits(uint bits, int nBits) } } - public void Reset(Vp8LBitWriter bwInit) + /// + /// Moves the writer back to a position that returned earlier. The bytes before that position stay unchanged. + /// + /// The saved write position. + public void Reset((ulong Bits, int Used, int Cur) position) { - this.bits = bwInit.bits; - this.used = bwInit.used; - this.cur = bwInit.cur; + this.bits = position.Bits; + this.used = position.Used; + this.cur = position.Cur; } - public void WriteHuffmanCode(HuffmanTreeCode code, int codeIndex) + /// + /// Writes the Huffman code of one symbol. + /// + /// The code lengths of the Huffman code. + /// The bit-reversed codes of the Huffman code. + /// The index of the symbol in and . + public void WriteHuffmanCode(ReadOnlySpan codeLengths, ReadOnlySpan codes, int codeIndex) { - int depth = code.CodeLengths[codeIndex]; - int symbol = code.Codes[codeIndex]; + int depth = codeLengths[codeIndex]; + int symbol = codes[codeIndex]; this.PutBits((uint)symbol, depth); } - public void WriteHuffmanCodeWithExtraBits(HuffmanTreeCode code, int codeIndex, int bits, int nBits) + /// + /// Writes the Huffman code of one symbol and then its extra bits, in one write. + /// + /// The code lengths of the Huffman code. + /// The bit-reversed codes of the Huffman code. + /// The index of the symbol in and . + /// The extra bits. + /// The number of extra bits. The code length plus this number must be 32 or less. + public void WriteHuffmanCodeWithExtraBits(ReadOnlySpan codeLengths, ReadOnlySpan codes, int codeIndex, int bits, int nBits) { - int depth = code.CodeLengths[codeIndex]; - int symbol = code.Codes[codeIndex]; + int depth = codeLengths[codeIndex]; + int symbol = codes[codeIndex]; this.PutBits((uint)((bits << depth) | symbol), depth + nBits); } + /// + /// Creates a writer with the same written bytes and bit state. + /// + /// + /// The clone has the same capacity, so it can write another encoding of the same image without growth. + /// Only the written bytes are copied. The caller disposes the clone. + /// + /// The new writer. public Vp8LBitWriter Clone() { - byte[] clonedBuffer = new byte[this.Buffer.Length]; - System.Buffer.BlockCopy(this.Buffer, 0, clonedBuffer, 0, this.cur); - return new Vp8LBitWriter(clonedBuffer, this.bits, this.used, this.cur); + Vp8LBitWriter clone = new(this.MemoryAllocator, this.Buffer.Length) + { + bits = this.bits, + used = this.used, + cur = this.cur + }; + + this.Buffer[..this.cur].CopyTo(clone.Buffer); + return clone; } /// @@ -126,7 +161,9 @@ public override void WriteEncodedImageToStream(Stream stream) uint pad = size & 1; // Write magic bytes indicating its a lossless webp. - Span scratchBuffer = stackalloc byte[WebpConstants.TagSize]; + // TagSize is 4, so the 4 byte inline array holds one tag or one size. + InlineArray4 scratchStorage = default; + Span scratchBuffer = scratchStorage; BinaryPrimitives.WriteUInt32BigEndian(scratchBuffer, (uint)WebpChunkType.Vp8L); stream.Write(scratchBuffer); @@ -148,16 +185,18 @@ public override void WriteEncodedImageToStream(Stream stream) /// private void PutBitsFlushBits() { - // If needed, make some room by flushing some bits out. - if (this.cur + WriterBytes > this.Buffer.Length) + // The buffer span is read once. Only a resize replaces the buffer, so the span is read again only after a resize. + Span buffer = this.Buffer; + if (this.cur + WriterBytes > buffer.Length) { - int extraSize = this.Buffer.Length - this.cur + MinExtraSize; - this.BitWriterResize(extraSize); + // Ask for the current capacity plus MinExtraSize after the write position. The new capacity is then + // at least the write position plus MinExtraSize, so the next 4 bytes always fit, and a small buffer grows fast. + this.BitWriterResize(buffer.Length + MinExtraSize); + buffer = this.Buffer; } - Span scratchBuffer = stackalloc byte[8]; - BinaryPrimitives.WriteUInt64LittleEndian(scratchBuffer, this.bits); - scratchBuffer[..4].CopyTo(this.Buffer.AsSpan(this.cur)); + // The low 32 bits of the accumulator are the next 4 bytes of the stream, in little-endian order. + BinaryPrimitives.WriteUInt32LittleEndian(buffer[this.cur..], (uint)this.bits); this.cur += WriterBytes; this.bits >>= WriterBits; @@ -170,8 +209,14 @@ private void PutBitsFlushBits() /// The extra size in bytes needed. public override void BitWriterResize(int extraSize) { - int maxBytes = this.Buffer.Length + this.Buffer.Length; int sizeRequired = this.cur + extraSize; - this.ResizeBuffer(maxBytes, sizeRequired); + + // Grow only when the buffer is full. Finish calls this method for each image, and usually the bytes fit. + if (sizeRequired <= this.Buffer.Length) + { + return; + } + + this.ResizeBuffer(this.Buffer.Length, sizeRequired); } } diff --git a/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Decoding.cs b/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Decoding.cs deleted file mode 100644 index 9daa41ff2f..0000000000 --- a/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Decoding.cs +++ /dev/null @@ -1,1217 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -using System.Numerics; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Runtime.Intrinsics; -using System.Runtime.Intrinsics.X86; -using SixLabors.ImageSharp.ColorProfiles; -using SixLabors.ImageSharp.Common.Helpers; -using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.PixelFormats.Utils; - -namespace SixLabors.ImageSharp.Formats.Webp.ColorConverters; - -internal abstract partial class WebpColorConverterBase -{ - private static readonly Vector128[] PlanarMasks128 = CreatePlanarMasks128(); - private static readonly Vector256[] PlanarMasks256 = CreatePlanarMasks256(); - private static readonly Vector512[] PlanarMasks512 = CreatePlanarMasks512(); - private static readonly Vector512[] PlanarLaneIndices512 = CreatePlanarLaneIndices(); - - // Only W has all mask bits set. Wider masks repeat this RGBA layout for each pixel. - private static readonly Vector128 AlphaMaskFloat128 = Vector128.Create(0, 0, 0, -1).AsSingle(); - private static readonly Vector256 AlphaMaskFloat256 = Vector256.Create(AlphaMaskFloat128, AlphaMaskFloat128); - private static readonly Vector512 AlphaMaskFloat512 = Vector512.Create(AlphaMaskFloat256, AlphaMaskFloat256); - - /// - /// Packs straight scaled vectors produced by an ICC conversion. - /// - /// The destination pixel format. - /// The pixel conversion configuration. - /// The converted straight RGB values. - /// The separate alpha row, or empty to preserve vector alpha. - /// The destination pixels. - protected static void PackIccRgbRow(Configuration configuration, Span row, ReadOnlySpan alpha, Span destination) - where TPixel : unmanaged, IPixel - { - if (!alpha.IsEmpty) - { - // ICC transforms straight RGB. Add the separate alpha afterwards; each byte maps to W as alpha / 255. - ref float rowBase = ref MemoryMarshal.GetReference(MemoryMarshal.Cast(row)); - - ref byte alphaBase = ref MemoryMarshal.GetReference(alpha); - int pixelOffset = 0; - - if (Vector512.IsHardwareAccelerated) - { - // Four RGBA pixels occupy sixteen float lanes. Repeat each alpha across its pixel, then select only W. - Vector512 alphaIndices = Vector512.Create(0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3); - - int pixelEnd = (int)Numerics.Vector512Count(row.Length * 4) * 4; - - // Sixteen float lanes hold four RGBA pixels, so advance four pixels per vector. - // pixelEnd excludes any partial group that cannot fill the vector. - for (; pixelOffset < pixelEnd; pixelOffset += 4) - { - // Read exactly four bytes and widen them to four floats; the final block cannot read past alpha. - Vector128 bytes = Vector128.CreateScalar(Unsafe.ReadUnaligned(ref Unsafe.Add(ref alphaBase, (uint)pixelOffset))).AsByte(); - - Vector128 alphaCodes = Vector128.WidenLower(Vector128.WidenLower(bytes)); - Vector128 normalizedAlpha = Vector128.ConvertToSingle(alphaCodes.AsInt32()) / Vector128.Create((float)byte.MaxValue); - Vector512 alphaValues = Vector512.Shuffle(normalizedAlpha.ToVector256().ToVector512(), alphaIndices); - nuint floatOffset = (nuint)pixelOffset * 4; - Vector512 pixels = Vector512.LoadUnsafe(ref rowBase, floatOffset); - - // The mask replaces W bits only, preserving every ICC-produced RGB value exactly. - Vector512.ConditionalSelect(AlphaMaskFloat512, alphaValues, pixels).StoreUnsafe(ref rowBase, floatOffset); - } - } - - if (Vector256.IsHardwareAccelerated) - { - // Two RGBA pixels occupy eight float lanes. The same shuffle and W mask handle this width. - Vector256 alphaIndices = Vector256.Create(0, 0, 0, 0, 1, 1, 1, 1); - - int pixelEnd = pixelOffset + ((int)Numerics.Vector256Count((row.Length - pixelOffset) * 4) * 2); - - // Eight float lanes hold two RGBA pixels, so advance two pixels per vector. - // pixelEnd excludes any partial group that cannot fill the vector. - for (; pixelOffset < pixelEnd; pixelOffset += 2) - { - // Only two alpha bytes are required for these two pixels. - Vector128 bytes = Vector128.CreateScalar( - (uint)Unsafe.ReadUnaligned(ref Unsafe.Add(ref alphaBase, (uint)pixelOffset))).AsByte(); - - Vector128 alphaCodes = Vector128.WidenLower(Vector128.WidenLower(bytes)); - Vector128 normalizedAlpha = Vector128.ConvertToSingle(alphaCodes.AsInt32()) / Vector128.Create((float)byte.MaxValue); - Vector256 alphaValues = Vector256.Shuffle(normalizedAlpha.ToVector256(), alphaIndices); - nuint floatOffset = (nuint)pixelOffset * 4; - Vector256 pixels = Vector256.LoadUnsafe(ref rowBase, floatOffset); - Vector256.ConditionalSelect(AlphaMaskFloat256, alphaValues, pixels).StoreUnsafe(ref rowBase, floatOffset); - } - } - - if (Vector128.IsHardwareAccelerated) - { - // One RGBA pixel fills a 128-bit vector. The W mask keeps its RGB bits unchanged. - ReadOnlySpan remaining = MemoryMarshal.Cast(row[pixelOffset..]); - int pixelEnd = pixelOffset + (int)remaining.Vector128Count(); - - for (; pixelOffset < pixelEnd; pixelOffset++) - { - Vector128 alphaValues = Vector128.Create((float)alpha[pixelOffset]) / Vector128.Create((float)byte.MaxValue); - nuint floatOffset = (nuint)pixelOffset * 4; - Vector128 pixels = Vector128.LoadUnsafe(ref rowBase, floatOffset); - Vector128.ConditionalSelect(AlphaMaskFloat128, alphaValues, pixels).StoreUnsafe(ref rowBase, floatOffset); - } - } - - // Complete the remaining pixels, or the whole row when SIMD is unavailable. - for (; pixelOffset < row.Length; pixelOffset++) - { - row[pixelOffset].W = alpha[pixelOffset] / (float)byte.MaxValue; - } - } - - // These vectors are straight RGBA. The explicit source contract lets TPixel apply its required alpha representation. - PixelOperations.Instance.FromUnassociatedScaledVector4Destructive(configuration, row, destination); - } - - /// - /// Creates cached masks that interleave three 16-byte planes into three packed output vectors. - /// - /// Three masks per packed output block, ordered by source channel. - private static Vector128[] CreatePlanarMasks128() - { - Vector128[] masks = new Vector128[9]; - InlineArray16 mask = default; - - // Each of the three output vectors needs one mask per source channel. - for (int block = 0; block < 3; block++) - { - for (int channel = 0; channel < 3; channel++) - { - FillPlanarMask(mask, block * Vector128.Count, channel); - masks[(block * 3) + channel] = Vector128.LoadUnsafe(ref mask[0]); - } - } - - return masks; - } - - /// - /// Creates cached masks that interleave three 32-byte planes into three packed output vectors. - /// - /// Three masks per packed output block, ordered by source channel. - private static Vector256[] CreatePlanarMasks256() - { - Vector256[] masks = new Vector256[9]; - InlineArray32 mask = default; - - // Each of the three output vectors needs one mask per source channel. - for (int block = 0; block < 3; block++) - { - for (int channel = 0; channel < 3; channel++) - { - FillPlanarMask(mask, block * Vector256.Count, channel); - masks[(block * 3) + channel] = Vector256.LoadUnsafe(ref mask[0]); - } - } - - return masks; - } - - /// - /// Creates cached masks that interleave three 64-byte planes into three packed output vectors. - /// - /// Three masks per packed output block, ordered by source channel. - private static Vector512[] CreatePlanarMasks512() - { - Vector512[] masks = new Vector512[9]; - InlineArray64 mask = default; - - // Each of the three output vectors needs one mask per source channel. - for (int block = 0; block < 3; block++) - { - for (int channel = 0; channel < 3; channel++) - { - FillPlanarMask(mask, block * Vector512.Count, channel); - masks[(block * 3) + channel] = Vector512.LoadUnsafe(ref mask[0]); - } - } - - return masks; - } - - /// - /// Selects the source's 128-bit lanes needed by each packed 512-bit output block. - /// - /// The source lane indices for each of the three packed output blocks. - private static Vector512[] CreatePlanarLaneIndices() - { - Vector512[] indices = new Vector512[3]; - InlineArray16 mask = default; - - for (int block = 0; block < 3; block++) - { - // Each output lane holds 16 packed bytes. Its samples lie in one 16-byte source lane because - // a source lane's 16 pixels occupy exactly three output lanes: 16 pixels * 3 bytes = 48 bytes. - for (int i = 0; i < Vector512.Count; i++) - { - int outputByte = (block * Vector512.Count) + ((i / 4) * Vector128.Count); - int sourceLane = (outputByte / 3) / Vector128.Count; - - // Four int indices copy that source lane without changing its byte order. - mask[i] = (sourceLane * 4) + (i % 4); - } - - indices[block] = Vector512.LoadUnsafe(ref mask[0]); - } - - return indices; - } - - /// - /// Selects one channel's plane indices for a packed output block and zeros the other channel positions. - /// - /// The shuffle indices for one output vector. - /// The block's byte offset in the packed output. - /// The channel's position within each three-byte pixel. - private static void FillPlanarMask(Span mask, int outputOffset, int channel) - { - // Packed bytes repeat channels 0, 1, 2. Dividing their offset by three selects the pixel in the full source plane. - // Index 255 is outside every supported vector width. The shuffle returns zero at these other channel positions. - for (int i = 0; i < mask.Length; i++) - { - int outputByte = outputOffset + i; - mask[i] = outputByte % 3 == channel ? (byte)(outputByte / 3) : byte.MaxValue; - } - } - - private sealed partial class WebpColorConverter - { - /// - public override void UpSample( - Span topY, - Span bottomY, - Span topU, - Span topV, - Span curU, - Span curV, - Span topDestination, - Span bottomDestination, - int length, - Span uvBuffer) - { - // Chroma interpolation and color conversion share the same block width. The scalar path uses identical rounding. - if (!Vector128.IsHardwareAccelerated) - { - UpSampleScalar(topY, bottomY, topU, topV, curU, curV, topDestination, bottomDestination, length); - return; - } - - UpSampleVector(topY, bottomY, topU, topV, curU, curV, topDestination, bottomDestination, length, uvBuffer); - } - - /// - /// Converts one interpolated pixel using the selected native color operation. - /// - /// The luma or first source channel. - /// The first chroma or second source channel. - /// The second chroma or third source channel. - /// Three destination byte codes. - private static void ConvertPixel(int y, int u, int v, Span destination) - { - TOperator.ConvertToSamples(ref y, ref u, ref v); - destination[0] = (byte)y; - destination[1] = (byte)u; - destination[2] = (byte)v; - } - - /// - /// Converts sixty-four interpolated samples and interleaves their three output channels. - /// - /// Sixty-four luma or first-channel byte codes. - /// Sixty-four first-chroma or second-channel byte codes. - /// Sixty-four second-chroma or third-channel byte codes. - /// The 192 packed output bytes. - private static void Convert64(ReadOnlySpan y, ReadOnlySpan u, ReadOnlySpan v, Span destination) - { - ref byte yRef = ref MemoryMarshal.GetReference(y); - ref byte uRef = ref MemoryMarshal.GetReference(u); - ref byte vRef = ref MemoryMarshal.GetReference(v); - - // Four sixteen-pixel groups produce each 64-byte output channel plane in source order. - Convert16Vector512( - ref yRef, ref uRef, ref vRef, out Vector128 channel0Group0, out Vector128 channel1Group0, out Vector128 channel2Group0); - - ref byte y16 = ref Unsafe.Add(ref yRef, 16U); - - ref byte u16 = ref Unsafe.Add(ref uRef, 16U); - ref byte v16 = ref Unsafe.Add(ref vRef, 16U); - Convert16Vector512( - ref y16, ref u16, ref v16, out Vector128 channel0Group1, out Vector128 channel1Group1, out Vector128 channel2Group1); - - ref byte y32 = ref Unsafe.Add(ref yRef, 32U); - - ref byte u32 = ref Unsafe.Add(ref uRef, 32U); - ref byte v32 = ref Unsafe.Add(ref vRef, 32U); - Convert16Vector512( - ref y32, ref u32, ref v32, out Vector128 channel0Group2, out Vector128 channel1Group2, out Vector128 channel2Group2); - - ref byte y48 = ref Unsafe.Add(ref yRef, 48U); - - ref byte u48 = ref Unsafe.Add(ref uRef, 48U); - ref byte v48 = ref Unsafe.Add(ref vRef, 48U); - Convert16Vector512( - ref y48, ref u48, ref v48, out Vector128 channel0Group3, out Vector128 channel1Group3, out Vector128 channel2Group3); - - PlanarTo24b( - Vector512.Create(Vector256.Create(channel0Group0, channel0Group1), Vector256.Create(channel0Group2, channel0Group3)), - Vector512.Create(Vector256.Create(channel1Group0, channel1Group1), Vector256.Create(channel1Group2, channel1Group3)), - Vector512.Create(Vector256.Create(channel2Group0, channel2Group1), Vector256.Create(channel2Group2, channel2Group3)), - destination); - } - - /// - /// Converts thirty-two byte samples with 256-bit integer lanes and packs the channel planes. - /// - /// The luma byte codes in pixel order. - /// The U chroma byte codes in pixel order. - /// The V chroma byte codes in pixel order. - /// The packed output bytes in pixel order. - private static void Convert32(ReadOnlySpan y, ReadOnlySpan u, ReadOnlySpan v, Span destination) - { - ref byte yRef = ref MemoryMarshal.GetReference(y); - ref byte uRef = ref MemoryMarshal.GetReference(u); - ref byte vRef = ref MemoryMarshal.GetReference(v); - - // Each helper converts sixteen consecutive pixels, then the packed store interleaves complete channel planes. - Convert16Vector256( - ref yRef, ref uRef, ref vRef, out Vector128 channel0Group0, out Vector128 channel1Group0, out Vector128 channel2Group0); - - ref byte y16 = ref Unsafe.Add(ref yRef, 16U); - - ref byte u16 = ref Unsafe.Add(ref uRef, 16U); - ref byte v16 = ref Unsafe.Add(ref vRef, 16U); - Convert16Vector256( - ref y16, ref u16, ref v16, out Vector128 channel0Group1, out Vector128 channel1Group1, out Vector128 channel2Group1); - - PlanarTo24b( - Vector256.Create(channel0Group0, channel0Group1), - Vector256.Create(channel1Group0, channel1Group1), - Vector256.Create(channel2Group0, channel2Group1), - destination); - } - - /// - /// Converts sixteen byte samples with four 128-bit integer groups and packs them as a row block. - /// - /// The luma byte codes in pixel order. - /// The U chroma byte codes in pixel order. - /// The V chroma byte codes in pixel order. - /// The packed output bytes in pixel order. - private static void Convert16(ReadOnlySpan y, ReadOnlySpan u, ReadOnlySpan v, Span destination) - { - ref byte yRef = ref MemoryMarshal.GetReference(y); - ref byte uRef = ref MemoryMarshal.GetReference(u); - ref byte vRef = ref MemoryMarshal.GetReference(v); - - // Each helper converts sixteen consecutive pixels, then the packed store interleaves complete channel planes. - Convert16Vector128(ref yRef, ref uRef, ref vRef, out Vector128 c0, out Vector128 c1, out Vector128 c2); - PlanarTo24b(c0, c1, c2, destination); - } - - /// - /// Loads exactly sixteen byte codes into sixteen integer lanes. - /// - /// The first source byte; the caller supplies all samples required by this load. - /// The loaded byte codes widened into consecutive lanes. - private static Vector512 Load16(ref byte source) - { - Vector128 bytes = Unsafe.ReadUnaligned>(ref source); - (Vector128 lower, Vector128 upper) = Vector128.Widen(bytes); - - // Byte codes are at most 255, so their widened words remain positive when interpreted as signed for this helper. - return Vector512.Create(Vector256_.Widen(lower.AsInt16()), Vector256_.Widen(upper.AsInt16())); - } - - /// - /// Loads exactly eight byte codes into eight integer lanes. - /// - /// The first source byte; the caller supplies all samples required by this load. - /// The loaded byte codes widened into consecutive lanes. - private static Vector256 Load8(ref byte source) - { - Vector128 bytes = Vector128.CreateScalar(Unsafe.ReadUnaligned(ref source)).AsByte(); - (Vector128 lower, _) = Vector128.Widen(bytes); - - // The widened byte codes are 0..255, so the signed word conversion preserves their values. - return Vector256_.Widen(lower.AsInt16()); - } - - /// - /// Loads exactly four byte codes into four integer lanes. - /// - /// The first source byte; the caller supplies all samples required by this load. - /// The loaded byte codes widened into consecutive lanes. - private static Vector128 Load4(ref byte source) - { - Vector128 bytes = Vector128.CreateScalar(Unsafe.ReadUnaligned(ref source)).AsByte(); - (Vector128 lower, _) = Vector128.Widen(bytes); - (Vector128 result, _) = Vector128.Widen(lower); - return result.AsInt32(); - } - - /// - /// Applies the selected color operation to sixteen samples using one 512-bit group. - /// - /// The luma byte codes in pixel order. - /// The U chroma byte codes in pixel order. - /// The V chroma byte codes in pixel order. - /// The first output channel plane in pixel order. - /// The second output channel plane in pixel order. - /// The third output channel plane in pixel order. - private static void Convert16Vector512(ref byte y, ref byte u, ref byte v, out Vector128 c0, out Vector128 c1, out Vector128 c2) - { - // Load consecutive sample groups in pixel order. Each signed int lane carries one unsigned byte code. - Vector512 channel0Group0 = Load16(ref y); - - Vector512 channel1Group0 = Load16(ref u); - Vector512 channel2Group0 = Load16(ref v); - - TOperator.ConvertToSamples(ref channel0Group0, ref channel1Group0, ref channel2Group0); - - // The operator returns byte-range channels. Narrow in the original group order before interleaving them. - c0 = Narrow(channel0Group0); - c1 = Narrow(channel1Group0); - c2 = Narrow(channel2Group0); - } - - /// - /// Applies the selected color operation to sixteen samples using two 256-bit groups. - /// - /// The luma byte codes in pixel order. - /// The U chroma byte codes in pixel order. - /// The V chroma byte codes in pixel order. - /// The first output channel plane in pixel order. - /// The second output channel plane in pixel order. - /// The third output channel plane in pixel order. - private static void Convert16Vector256(ref byte y, ref byte u, ref byte v, out Vector128 c0, out Vector128 c1, out Vector128 c2) - { - // Load consecutive sample groups in pixel order. Each signed int lane carries one unsigned byte code. - Vector256 channel0Group0 = Load8(ref y); - - Vector256 channel1Group0 = Load8(ref u); - Vector256 channel2Group0 = Load8(ref v); - Vector256 channel0Group1 = Load8(ref Unsafe.Add(ref y, 8U)); - Vector256 channel1Group1 = Load8(ref Unsafe.Add(ref u, 8U)); - Vector256 channel2Group1 = Load8(ref Unsafe.Add(ref v, 8U)); - - TOperator.ConvertToSamples(ref channel0Group0, ref channel1Group0, ref channel2Group0); - TOperator.ConvertToSamples(ref channel0Group1, ref channel1Group1, ref channel2Group1); - - // The operator returns byte-range channels. Narrow in the original group order before interleaving them. - c0 = Narrow(channel0Group0, channel0Group1); - c1 = Narrow(channel1Group0, channel1Group1); - c2 = Narrow(channel2Group0, channel2Group1); - } - - /// - /// Applies the selected color operation to sixteen samples using four 128-bit groups. - /// - /// The luma byte codes in pixel order. - /// The U chroma byte codes in pixel order. - /// The V chroma byte codes in pixel order. - /// The first output channel plane in pixel order. - /// The second output channel plane in pixel order. - /// The third output channel plane in pixel order. - private static void Convert16Vector128(ref byte y, ref byte u, ref byte v, out Vector128 c0, out Vector128 c1, out Vector128 c2) - { - // Load consecutive sample groups in pixel order. Each signed int lane carries one unsigned byte code. - Vector128 channel0Group0 = Load4(ref y); - - Vector128 channel1Group0 = Load4(ref u); - Vector128 channel2Group0 = Load4(ref v); - Vector128 channel0Group1 = Load4(ref Unsafe.Add(ref y, 4U)); - Vector128 channel1Group1 = Load4(ref Unsafe.Add(ref u, 4U)); - Vector128 channel2Group1 = Load4(ref Unsafe.Add(ref v, 4U)); - Vector128 channel0Group2 = Load4(ref Unsafe.Add(ref y, 8U)); - Vector128 channel1Group2 = Load4(ref Unsafe.Add(ref u, 8U)); - Vector128 channel2Group2 = Load4(ref Unsafe.Add(ref v, 8U)); - Vector128 channel0Group3 = Load4(ref Unsafe.Add(ref y, 12U)); - Vector128 channel1Group3 = Load4(ref Unsafe.Add(ref u, 12U)); - Vector128 channel2Group3 = Load4(ref Unsafe.Add(ref v, 12U)); - - TOperator.ConvertToSamples(ref channel0Group0, ref channel1Group0, ref channel2Group0); - TOperator.ConvertToSamples(ref channel0Group1, ref channel1Group1, ref channel2Group1); - TOperator.ConvertToSamples(ref channel0Group2, ref channel1Group2, ref channel2Group2); - TOperator.ConvertToSamples(ref channel0Group3, ref channel1Group3, ref channel2Group3); - - // The operator returns byte-range channels. Narrow in the original group order before interleaving them. - c0 = Narrow(channel0Group0, channel0Group1, channel0Group2, channel0Group3); - c1 = Narrow(channel1Group0, channel1Group1, channel1Group2, channel1Group3); - c2 = Narrow(channel2Group0, channel2Group1, channel2Group2, channel2Group3); - } - - /// - /// Narrows sixteen clipped integer codes without changing their values. - /// - /// Sixteen consecutive channel codes, each in the range 0..255. - /// The sixteen channel codes as bytes, in their original order. - private static Vector128 Narrow(Vector512 value) - { - // The color operator already bounds each code to 0..255. Narrowing removes only zero upper bits and preserves group order. - Vector256 halves = Vector256.Narrow(value.GetLower(), value.GetUpper()); - - return Vector128.Narrow(halves.GetLower().AsUInt16(), halves.GetUpper().AsUInt16()); - } - - /// - /// Narrows two groups of eight clipped integer codes. - /// - /// The first eight channel codes, each in the range 0..255. - /// The following eight channel codes, each in the range 0..255. - /// The sixteen channel codes as bytes, in their original order. - private static Vector128 Narrow(Vector256 lower, Vector256 upper) - { - // The color operator already bounds each code to 0..255. Narrowing removes only zero upper bits and preserves group order. - Vector128 first = Vector128.Narrow(lower.GetLower(), lower.GetUpper()); - - Vector128 second = Vector128.Narrow(upper.GetLower(), upper.GetUpper()); - return Vector128.Narrow(first.AsUInt16(), second.AsUInt16()); - } - - /// - /// Narrows four groups of four clipped integer codes. - /// - /// The first four channel codes, each in the range 0..255. - /// The second four channel codes, each in the range 0..255. - /// The third four channel codes, each in the range 0..255. - /// The fourth four channel codes, each in the range 0..255. - /// The sixteen channel codes as bytes, in their original order. - private static Vector128 Narrow(Vector128 group0, Vector128 group1, Vector128 group2, Vector128 group3) - { - // The color operator already bounds each code to 0..255. Narrowing removes only zero upper bits and preserves group order. - Vector128 first = Vector128.Narrow(group0, group1); - - Vector128 second = Vector128.Narrow(group2, group3); - return Vector128.Narrow(first.AsUInt16(), second.AsUInt16()); - } - - /// - /// Packs two byte chroma codes into adjacent low and high words for the scalar filter. - /// - /// The U byte code. - /// The V byte code. - /// U in bits 0..7 and V in bits 16..23, with room for the filter sums. - private static uint LoadUv(byte u, byte v) => (uint)(u | (v << 16)); - - /// - /// Interpolates chroma and converts pixels with scalar arithmetic. - /// - /// The first output row's luma samples. - /// The second output row's luma samples, or empty for a single row. - /// The preceding U chroma row. - /// The preceding V chroma row. - /// The current U chroma row. - /// The current V chroma row. - /// The first packed output row. - /// The second packed output row, or empty for a single row. - /// The number of output pixels in each row. - private static void UpSampleScalar( - ReadOnlySpan topY, - ReadOnlySpan bottomY, - ReadOnlySpan topU, - ReadOnlySpan topV, - ReadOnlySpan curU, - ReadOnlySpan curV, - Span topDestination, - Span bottomDestination, - int length) - { - const int bytesPerPixel = 3; - int lastChromaPair = (length - 1) >> 1; - - // There is no left neighbor for pixel zero. Replicate its chroma horizontally and blend the two rows 3:1. - // 0x00020002 adds two to both packed channels before division by four, rounding each channel separately. - uint topLeft = LoadUv(topU[0], topV[0]); - uint bottomLeft = LoadUv(curU[0], curV[0]); - uint firstChroma = ((3 * topLeft) + bottomLeft + 0x00020002u) >> 2; - ConvertPixel(topY[0], (int)(firstChroma & 0xff), (int)(firstChroma >> 16), topDestination); - - if (!bottomY.IsEmpty) - { - firstChroma = ((3 * bottomLeft) + topLeft + 0x00020002u) >> 2; - ConvertPixel(bottomY[0], (int)firstChroma & 0xff, (int)(firstChroma >> 16), bottomDestination); - } - - for (int x = 1; x <= lastChromaPair; x++) - { - uint topRight = LoadUv(topU[x], topV[x]); - uint bottomRight = LoadUv(curU[x], curV[x]); - - // U and V occupy separate 16-bit words. The weighted sums remain below 65536, so U cannot carry into V. - // Adding eight to each word rounds the 9:3:3:1 filter before division by sixteen, split across these shifts. - uint roundedSum = topLeft + topRight + bottomLeft + bottomRight + 0x00080008u; - uint crossDiagonal = (roundedSum + (2 * (topRight + bottomLeft))) >> 3; - uint mainDiagonal = (roundedSum + (2 * (topLeft + bottomRight))) >> 3; - firstChroma = (crossDiagonal + topLeft) >> 1; - uint secondChroma = (mainDiagonal + topRight) >> 1; - - // Each pair of neighboring chroma samples supplies the odd pixel on its left and the following even pixel. - int evenPixel = x * 2; - - ConvertPixel(topY[evenPixel - 1], (int)(firstChroma & 0xff), (int)(firstChroma >> 16), topDestination[((evenPixel - 1) * bytesPerPixel)..]); - ConvertPixel(topY[evenPixel], (int)(secondChroma & 0xff), (int)(secondChroma >> 16), topDestination[(evenPixel * bytesPerPixel)..]); - - if (!bottomY.IsEmpty) - { - firstChroma = (mainDiagonal + bottomLeft) >> 1; - secondChroma = (crossDiagonal + bottomRight) >> 1; - ConvertPixel( - bottomY[evenPixel - 1], (int)(firstChroma & 0xff), (int)(firstChroma >> 16), bottomDestination[((evenPixel - 1) * bytesPerPixel)..]); - - ConvertPixel( - bottomY[evenPixel], (int)(secondChroma & 0xff), (int)(secondChroma >> 16), bottomDestination[(evenPixel * bytesPerPixel)..]); - } - - topLeft = topRight; - bottomLeft = bottomRight; - } - - // An even row width has one final pixel without a right chroma neighbor. Replicate that edge. - if ((length & 1) == 0) - { - // Repeating the missing right samples reduces the 9:3:3:1 filter to a 3:1 vertical blend. - // topLeft and bottomLeft each hold U in bits 0..7 and V in bits 16..23. - // For each channel, compute (3 * top + bottom + 2) / 4. The +2 rounds to the nearest byte code. - // 0x00020002 adds that bias to both 16-bit words. Each sum fits in ten bits, so U cannot carry into V. - // Shifting by two divides both sums by four. Discarded V bits enter the upper part of the U word; - // & 0xff extracts only the U byte, while >> 16 extracts the V byte. - firstChroma = ((3 * topLeft) + bottomLeft + 0x00020002u) >> 2; - - // Use this pixel's luma and write its three output bytes at the final pixel offset. - ConvertPixel(topY[length - 1], (int)(firstChroma & 0xff), (int)(firstChroma >> 16), topDestination[((length - 1) * bytesPerPixel)..]); - - if (!bottomY.IsEmpty) - { - // The bottom pixel is nearer the bottom chroma row, so reverse the 3:1 weights. - firstChroma = ((3 * bottomLeft) + topLeft + 0x00020002u) >> 2; - ConvertPixel(bottomY[length - 1], (int)(firstChroma & 0xff), (int)(firstChroma >> 16), bottomDestination[((length - 1) * bytesPerPixel)..]); - } - } - } - - /// - /// Processes complete SIMD blocks, then interpolates the remaining pixels with scalar arithmetic. - /// - /// The first output row's luma samples. - /// The second output row's luma samples, or empty for a single row. - /// The preceding U chroma row. - /// The preceding V chroma row. - /// The current U chroma row. - /// The current V chroma row. - /// The first packed output row. - /// The second packed output row, or empty for a single row. - /// The number of output pixels in each row. - /// The decoder-owned scratch space for four 64-byte interpolated chroma planes. - private static void UpSampleVector( - Span topY, - Span bottomY, - Span topU, - Span topV, - Span curU, - Span curV, - Span topDestination, - Span bottomDestination, - int length, - Span uvBuffer) - { - const int bytesPerPixel = 3; - - // A 512-bit block produces 64 chroma bytes per output plane. Keep U and V separate for both rows; - // the decoder owns these four 64-byte scratch planes, and smaller blocks reuse each plane's prefix. - Span topUOutput = uvBuffer[..64]; - Span topVOutput = uvBuffer[64..128]; - Span bottomUOutput = uvBuffer[128..192]; - Span bottomVOutput = uvBuffer[192..256]; - - // The first pixel uses the replicated left chroma edge from the scalar decoder. - int uVerticalAverage = ((topU[0] + curU[0]) >> 1) + 1; - int vVerticalAverage = ((topV[0] + curV[0]) >> 1) + 1; - ConvertPixel(topY[0], (topU[0] + uVerticalAverage) >> 1, (topV[0] + vVerticalAverage) >> 1, topDestination); - - if (!bottomY.IsEmpty) - { - ConvertPixel(bottomY[0], (curU[0] + uVerticalAverage) >> 1, (curV[0] + vVerticalAverage) >> 1, bottomDestination); - } - - int pixelOffset = 1; - int chromaOffset = 0; - int lastChromaPair = (length - 1) >> 1; - ref byte topURef = ref MemoryMarshal.GetReference(topU); - ref byte topVRef = ref MemoryMarshal.GetReference(topV); - ref byte curURef = ref MemoryMarshal.GetReference(curU); - ref byte curVRef = ref MemoryMarshal.GetReference(curV); - - // Each interpolation load also reads the next chroma sample. Excluding lastChromaPair from these counts - // leaves that right neighbor inside the source span. A chroma pair produces two output pixels. - // The 512-bit packer uses AVX512BW byte shuffles, so generic 512-bit acceleration alone is insufficient. - if (Avx512BW.IsSupported) - { - // 32 unsigned word lanes interpolate 64 output pixels from consecutive chroma pairs. - nuint vectorCount = topU[chromaOffset..lastChromaPair].Vector512Count(); - - for (nuint block = 0; block < vectorCount; block++) - { - InterpolateChroma512( - ref Unsafe.Add(ref topURef, (uint)chromaOffset), ref Unsafe.Add(ref curURef, (uint)chromaOffset), topUOutput, bottomUOutput); - - InterpolateChroma512( - ref Unsafe.Add(ref topVRef, (uint)chromaOffset), ref Unsafe.Add(ref curVRef, (uint)chromaOffset), topVOutput, bottomVOutput); - - Convert64(topY[pixelOffset..], topUOutput, topVOutput, topDestination[(pixelOffset * bytesPerPixel)..]); - - if (!bottomY.IsEmpty) - { - Convert64(bottomY[pixelOffset..], bottomUOutput, bottomVOutput, bottomDestination[(pixelOffset * bytesPerPixel)..]); - } - - pixelOffset += Vector512.Count * 2; - chromaOffset += Vector512.Count; - } - } - - if (Vector256.IsHardwareAccelerated) - { - // 16 unsigned word lanes interpolate 32 output pixels from consecutive chroma pairs. - nuint vectorCount = topU[chromaOffset..lastChromaPair].Vector256Count(); - - for (nuint block = 0; block < vectorCount; block++) - { - InterpolateChroma256( - ref Unsafe.Add(ref topURef, (uint)chromaOffset), ref Unsafe.Add(ref curURef, (uint)chromaOffset), topUOutput, bottomUOutput); - - InterpolateChroma256( - ref Unsafe.Add(ref topVRef, (uint)chromaOffset), ref Unsafe.Add(ref curVRef, (uint)chromaOffset), topVOutput, bottomVOutput); - - Convert32(topY[pixelOffset..], topUOutput, topVOutput, topDestination[(pixelOffset * bytesPerPixel)..]); - - if (!bottomY.IsEmpty) - { - Convert32(bottomY[pixelOffset..], bottomUOutput, bottomVOutput, bottomDestination[(pixelOffset * bytesPerPixel)..]); - } - - pixelOffset += Vector256.Count * 2; - chromaOffset += Vector256.Count; - } - } - - // Eight unsigned word lanes interpolate sixteen output pixels; the remaining pairs use scalar arithmetic. - nuint vectorCount128 = topU[chromaOffset..lastChromaPair].Vector128Count(); - - for (nuint block = 0; block < vectorCount128; block++) - { - InterpolateChroma128( - ref Unsafe.Add(ref topURef, (uint)chromaOffset), ref Unsafe.Add(ref curURef, (uint)chromaOffset), topUOutput, bottomUOutput); - - InterpolateChroma128( - ref Unsafe.Add(ref topVRef, (uint)chromaOffset), ref Unsafe.Add(ref curVRef, (uint)chromaOffset), topVOutput, bottomVOutput); - - Convert16(topY[pixelOffset..], topUOutput, topVOutput, topDestination[(pixelOffset * bytesPerPixel)..]); - - if (!bottomY.IsEmpty) - { - Convert16(bottomY[pixelOffset..], bottomUOutput, bottomVOutput, bottomDestination[(pixelOffset * bytesPerPixel)..]); - } - - pixelOffset += Vector128.Count * 2; - chromaOffset += Vector128.Count; - } - - if (pixelOffset < length) - { - // Continue the scalar pair traversal from the last consumed chroma pair without rewriting output. - uint topLeft = LoadUv(topU[chromaOffset], topV[chromaOffset]); - uint bottomLeft = LoadUv(curU[chromaOffset], curV[chromaOffset]); - - for (int x = chromaOffset + 1; x <= lastChromaPair; x++) - { - uint topRight = LoadUv(topU[x], topV[x]); - uint bottomRight = LoadUv(curU[x], curV[x]); - - // Pack U and V into separate words; +8 in each word gives the same rounding as the SIMD filter. - // The sums fit within their words, so adding U never carries into V. - uint sum = topLeft + topRight + bottomLeft + bottomRight + 0x00080008u; - uint crossDiagonal = (sum + (2 * (topRight + bottomLeft))) >> 3; - uint mainDiagonal = (sum + (2 * (topLeft + bottomRight))) >> 3; - int evenPixel = x * 2; - uint topOdd = (crossDiagonal + topLeft) >> 1; - uint topEven = (mainDiagonal + topRight) >> 1; - ConvertPixel(topY[evenPixel - 1], (int)(topOdd & 0xff), (int)(topOdd >> 16), topDestination[((evenPixel - 1) * bytesPerPixel)..]); - ConvertPixel(topY[evenPixel], (int)(topEven & 0xff), (int)(topEven >> 16), topDestination[(evenPixel * bytesPerPixel)..]); - - if (!bottomY.IsEmpty) - { - uint bottomOdd = (mainDiagonal + bottomLeft) >> 1; - uint bottomEven = (crossDiagonal + bottomRight) >> 1; - ConvertPixel( - bottomY[evenPixel - 1], (int)(bottomOdd & 0xff), (int)(bottomOdd >> 16), bottomDestination[((evenPixel - 1) * bytesPerPixel)..]); - - ConvertPixel(bottomY[evenPixel], (int)(bottomEven & 0xff), (int)(bottomEven >> 16), bottomDestination[(evenPixel * bytesPerPixel)..]); - } - - topLeft = topRight; - bottomLeft = bottomRight; - } - - // The last pixel of an even-width row repeats the right chroma edge instead of reading past it. - if ((length & 1) == 0) - { - // Repeating the missing right samples reduces the 9:3:3:1 filter to a 3:1 vertical blend. - // topLeft and bottomLeft each hold U in bits 0..7 and V in bits 16..23. - // For each channel, compute (3 * top + bottom + 2) / 4. The +2 rounds to the nearest byte code. - // 0x00020002 adds that bias to both 16-bit words. Each sum fits in ten bits, so U cannot carry into V. - // Shifting by two divides both sums by four. Discarded V bits enter the upper part of the U word; - // & 0xff extracts only the U byte, while >> 16 extracts the V byte. - uint edgeTop = ((3 * topLeft) + bottomLeft + 0x00020002u) >> 2; - - // Use this pixel's luma and write its three output bytes at the final pixel offset. - ConvertPixel(topY[length - 1], (int)(edgeTop & 0xff), (int)(edgeTop >> 16), topDestination[((length - 1) * bytesPerPixel)..]); - - if (!bottomY.IsEmpty) - { - // The bottom pixel is nearer the bottom chroma row, so reverse the 3:1 weights. - uint edgeBottom = ((3 * bottomLeft) + topLeft + 0x00020002u) >> 2; - ConvertPixel( - bottomY[length - 1], (int)(edgeBottom & 0xff), (int)(edgeBottom >> 16), bottomDestination[((length - 1) * bytesPerPixel)..]); - } - } - } - } - - /// - /// Applies the weighted chroma filter to thirty-two lanes using 512-bit word arithmetic. - /// - /// The first sample in the preceding chroma row, including the required right neighbor. - /// The first sample in the current chroma row, including the required right neighbor. - /// The interpolated chroma bytes for the first output row. - /// The interpolated chroma bytes for the second output row. - private static void InterpolateChroma512(ref byte top, ref byte current, Span topOutput, Span bottomOutput) - { - // Matching lane positions hold the four corners of one chroma neighborhood. Shifted loads select the right neighbors. - Vector512 topLeft = Load32Chroma(ref top); - - Vector512 topRight = Load32Chroma(ref Unsafe.Add(ref top, 1U)); - Vector512 bottomLeft = Load32Chroma(ref current); - Vector512 bottomRight = Load32Chroma(ref Unsafe.Add(ref current, 1U)); - Vector512 three = Vector512.Create((ushort)3); - Vector512 nine = Vector512.Create((ushort)9); - Vector512 roundingBias = Vector512.Create((ushort)8); - - // The nearest sample receives weight nine, the two adjacent samples weight three, and the diagonal weight one. - // The weights sum to sixteen. Adding eight rounds the division; the largest sum is 4088, within ushort range. - Vector512 topOdd = ((topLeft * nine) + (topRight * three) + (bottomLeft * three) + bottomRight + roundingBias) >> 4; - Vector512 topEven = ((topLeft * three) + (topRight * nine) + bottomLeft + (bottomRight * three) + roundingBias) >> 4; - Vector512 bottomOdd = ((topLeft * three) + topRight + (bottomLeft * nine) + (bottomRight * three) + roundingBias) >> 4; - Vector512 bottomEven = (topLeft + (topRight * three) + (bottomLeft * three) + (bottomRight * nine) + roundingBias) >> 4; - - // Store the odd pixel before the even pixel so the chroma plane follows the luma row's pixel order. - StoreInterleaved(topOdd, topEven, topOutput); - StoreInterleaved(bottomOdd, bottomEven, bottomOutput); - } - - /// - /// Applies the weighted chroma filter to sixteen lanes using 256-bit word arithmetic. - /// - /// The first sample in the preceding chroma row, including the required right neighbor. - /// The first sample in the current chroma row, including the required right neighbor. - /// The interpolated chroma bytes for the first output row. - /// The interpolated chroma bytes for the second output row. - private static void InterpolateChroma256(ref byte top, ref byte current, Span topOutput, Span bottomOutput) - { - // Matching lane positions hold the four corners of one chroma neighborhood. Shifted loads select the right neighbors. - Vector256 topLeft = Load16Chroma(ref top); - - Vector256 topRight = Load16Chroma(ref Unsafe.Add(ref top, 1U)); - Vector256 bottomLeft = Load16Chroma(ref current); - Vector256 bottomRight = Load16Chroma(ref Unsafe.Add(ref current, 1U)); - Vector256 three = Vector256.Create((ushort)3); - Vector256 nine = Vector256.Create((ushort)9); - Vector256 roundingBias = Vector256.Create((ushort)8); - - // The nearest sample receives weight nine, the two adjacent samples weight three, and the diagonal weight one. - // The weights sum to sixteen. Adding eight rounds the division; the largest sum is 4088, within ushort range. - Vector256 topOdd = ((topLeft * nine) + (topRight * three) + (bottomLeft * three) + bottomRight + roundingBias) >> 4; - Vector256 topEven = ((topLeft * three) + (topRight * nine) + bottomLeft + (bottomRight * three) + roundingBias) >> 4; - Vector256 bottomOdd = ((topLeft * three) + topRight + (bottomLeft * nine) + (bottomRight * three) + roundingBias) >> 4; - Vector256 bottomEven = (topLeft + (topRight * three) + (bottomLeft * three) + (bottomRight * nine) + roundingBias) >> 4; - - // Store the odd pixel before the even pixel so the chroma plane follows the luma row's pixel order. - StoreInterleaved(topOdd, topEven, topOutput); - StoreInterleaved(bottomOdd, bottomEven, bottomOutput); - } - - /// - /// Applies the weighted chroma filter to eight lanes using 128-bit word arithmetic. - /// - /// The first sample in the preceding chroma row, including the required right neighbor. - /// The first sample in the current chroma row, including the required right neighbor. - /// The interpolated chroma bytes for the first output row. - /// The interpolated chroma bytes for the second output row. - private static void InterpolateChroma128(ref byte top, ref byte current, Span topOutput, Span bottomOutput) - { - // Matching lane positions hold the four corners of one chroma neighborhood. Shifted loads select the right neighbors. - Vector128 topLeft = Load8Chroma(ref top); - - Vector128 topRight = Load8Chroma(ref Unsafe.Add(ref top, 1U)); - Vector128 bottomLeft = Load8Chroma(ref current); - Vector128 bottomRight = Load8Chroma(ref Unsafe.Add(ref current, 1U)); - Vector128 three = Vector128.Create((ushort)3); - Vector128 nine = Vector128.Create((ushort)9); - Vector128 roundingBias = Vector128.Create((ushort)8); - - // The nearest sample receives weight nine, the two adjacent samples weight three, and the diagonal weight one. - // The weights sum to sixteen. Adding eight rounds the division; the largest sum is 4088, within ushort range. - Vector128 topOdd = ((topLeft * nine) + (topRight * three) + (bottomLeft * three) + bottomRight + roundingBias) >> 4; - Vector128 topEven = ((topLeft * three) + (topRight * nine) + bottomLeft + (bottomRight * three) + roundingBias) >> 4; - Vector128 bottomOdd = ((topLeft * three) + topRight + (bottomLeft * nine) + (bottomRight * three) + roundingBias) >> 4; - Vector128 bottomEven = (topLeft + (topRight * three) + (bottomLeft * three) + (bottomRight * nine) + roundingBias) >> 4; - - // Store the odd pixel before the even pixel so the chroma plane follows the luma row's pixel order. - StoreInterleaved(topOdd, topEven, topOutput); - StoreInterleaved(bottomOdd, bottomEven, bottomOutput); - } - - /// - /// Widens thirty-two byte chroma codes into unsigned word lanes. - /// - /// The first source byte; the caller supplies all samples required by this load. - /// The loaded byte codes widened into consecutive lanes. - private static Vector512 Load32Chroma(ref byte source) - { - Vector256 bytes = Unsafe.ReadUnaligned>(ref source); - (Vector256 lower, Vector256 upper) = Vector256.Widen(bytes); - return Vector512.Create(lower, upper); - } - - /// - /// Widens sixteen byte chroma codes into unsigned word lanes. - /// - /// The first source byte; the caller supplies all samples required by this load. - /// The loaded byte codes widened into consecutive lanes. - private static Vector256 Load16Chroma(ref byte source) - { - Vector128 bytes = Unsafe.ReadUnaligned>(ref source); - (Vector128 lower, Vector128 upper) = Vector128.Widen(bytes); - return Vector256.Create(lower, upper); - } - - /// - /// Widens eight byte chroma codes into unsigned word lanes. - /// - /// The first source byte; the caller supplies all samples required by this load. - /// The loaded byte codes widened into consecutive lanes. - private static Vector128 Load8Chroma(ref byte source) - { - Vector128 bytes = Vector128.CreateScalar(Unsafe.ReadUnaligned(ref source)).AsByte(); - (Vector128 lower, _) = Vector128.Widen(bytes); - return lower; - } - - /// - /// Interleaves two thirty-two-lane results into sixty-four chroma bytes in pixel order. - /// - /// The byte-range samples for odd pixel positions, stored in word lanes. - /// The byte-range samples for even pixel positions, stored in word lanes. - /// The packed output bytes in pixel order. - private static void StoreInterleaved(Vector512 odd, Vector512 even, Span destination) - { - // Both values fit in one byte. Place the odd pixel in the low byte and the even pixel in the high byte; - // little-endian storage then writes each pair in pixel order without a narrowing shuffle. - Vector512 pairs = odd | (even << 8); - - Unsafe.As>(ref MemoryMarshal.GetReference(destination)) = pairs.AsByte(); - } - - /// - /// Interleaves two sixteen-lane results into thirty-two chroma bytes in pixel order. - /// - /// The byte-range samples for odd pixel positions, stored in word lanes. - /// The byte-range samples for even pixel positions, stored in word lanes. - /// The packed output bytes in pixel order. - private static void StoreInterleaved(Vector256 odd, Vector256 even, Span destination) - { - // Both values fit in one byte. Place the odd pixel in the low byte and the even pixel in the high byte; - // little-endian storage then writes each pair in pixel order without a narrowing shuffle. - Vector256 pairs = odd | (even << 8); - - Unsafe.As>(ref MemoryMarshal.GetReference(destination)) = pairs.AsByte(); - } - - /// - /// Interleaves two eight-lane results into sixteen chroma bytes in pixel order. - /// - /// The byte-range samples for odd pixel positions, stored in word lanes. - /// The byte-range samples for even pixel positions, stored in word lanes. - /// The packed output bytes in pixel order. - private static void StoreInterleaved(Vector128 odd, Vector128 even, Span destination) - { - // Both values fit in one byte. Place the odd pixel in the low byte and the even pixel in the high byte; - // little-endian storage then writes each pair in pixel order without a narrowing shuffle. - Vector128 pairs = odd | (even << 8); - - Unsafe.As>(ref MemoryMarshal.GetReference(destination)) = pairs.AsByte(); - } - - /// - /// Interleaves three 64-byte planes into three packed 64-byte blocks. - /// - /// The first source channel plane. - /// The second source channel plane. - /// The third source channel plane. - /// The packed output bytes in pixel order. - private static void PlanarTo24b(Vector512 c0, Vector512 c1, Vector512 c2, Span destination) - { - // The caller requires AVX512BW. Select whole 128-bit source lanes with a 512-bit int shuffle first; - // the BW byte shuffle can then interleave within each lane without requiring AVX512VBMI. - for (int block = 0; block < 3; block++) - { - int maskIndex = block * 3; - Vector512 laneIndices = PlanarLaneIndices512[block]; - Vector512 plane0 = Vector512.Shuffle(c0.AsInt32(), laneIndices).AsByte(); - Vector512 plane1 = Vector512.Shuffle(c1.AsInt32(), laneIndices).AsByte(); - Vector512 plane2 = Vector512.Shuffle(c2.AsInt32(), laneIndices).AsByte(); - - // BW uses each index's low four bits within its lane and zeros indices with the high bit set. - // Thus the full-plane byte masks also select the right byte after the source lanes are positioned. - Vector512 packed = Avx512BW.Shuffle(plane0, PlanarMasks512[maskIndex]) - | Avx512BW.Shuffle(plane1, PlanarMasks512[maskIndex + 1]) - | Avx512BW.Shuffle(plane2, PlanarMasks512[maskIndex + 2]); - - packed.StoreUnsafe(ref MemoryMarshal.GetReference(destination), (nuint)(block * Vector512.Count)); - } - } - - /// - /// Interleaves three 32-byte planes into three packed 32-byte blocks. - /// - /// The first source channel plane. - /// The second source channel plane. - /// The third source channel plane. - /// The packed output bytes in pixel order. - private static void PlanarTo24b(Vector256 c0, Vector256 c1, Vector256 c2, Span destination) - { - // Three source planes produce three full output vectors. Each shuffle reads the full source plane - // and zeros the other two channels, so OR combines them into consecutive three-byte pixels. - for (int block = 0; block < 3; block++) - { - int maskIndex = block * 3; - Vector256 packed = Vector256.Shuffle(c0, PlanarMasks256[maskIndex]) - | Vector256.Shuffle(c1, PlanarMasks256[maskIndex + 1]) - | Vector256.Shuffle(c2, PlanarMasks256[maskIndex + 2]); - - packed.StoreUnsafe(ref MemoryMarshal.GetReference(destination), (nuint)(block * Vector256.Count)); - } - } - - /// - /// Interleaves three 16-byte planes into three packed 16-byte blocks. - /// - /// The first source channel plane. - /// The second source channel plane. - /// The third source channel plane. - /// The packed output bytes in pixel order. - private static void PlanarTo24b(Vector128 c0, Vector128 c1, Vector128 c2, Span destination) - { - // Three source planes produce three full output vectors. Each shuffle reads the full source plane - // and zeros the other two channels, so OR combines them into consecutive three-byte pixels. - for (int block = 0; block < 3; block++) - { - int maskIndex = block * 3; - Vector128 packed = Vector128.Shuffle(c0, PlanarMasks128[maskIndex]) - | Vector128.Shuffle(c1, PlanarMasks128[maskIndex + 1]) - | Vector128.Shuffle(c2, PlanarMasks128[maskIndex + 2]); - - packed.StoreUnsafe(ref MemoryMarshal.GetReference(destination), (nuint)(block * Vector128.Count)); - } - } - - /// - public override void ConvertRgbRow( - Configuration configuration, - ReadOnlySpan source, - ColorProfileConverter? converter, - Span vectors, - Span rgb, - Span destination) - { - if (converter is null) - { - PixelOperations.Instance.From(configuration, source, destination); - return; - } - - // Both encoding and decoding transform straight RGB. The configured profiles select the direction; - // packing applies the destination pixel format's precision and alpha representation. - Span row = vectors[..source.Length]; - converter.Convert(configuration, source, row); - PackIccRgbRow(configuration, row, ReadOnlySpan.Empty, destination); - } - - /// - public override void ConvertYuvRow( - Configuration configuration, - ReadOnlySpan source, - ReadOnlySpan alpha, - ColorProfileConverter? converter, - Span vectors, - Span rgb, - Span destination) - { - if (converter is null) - { - if (alpha.IsEmpty) - { - PixelOperations.Instance.FromBgr24Bytes(configuration, source, destination, destination.Length); - return; - } - - // This 256-byte stack block avoids a row allocation, and the bulk destination packer owns alpha association. - InlineArray64 pixelsBuffer = default; - Span pixels = pixelsBuffer; - int offset = 0; - - while (offset < destination.Length) - { - int count = Math.Min(pixels.Length, destination.Length - offset); - Span block = pixels[..count]; - - // The existing Pad3Shuffle4 path expands BGR before JoinAlpha replaces each padding byte. - PixelConverter.FromBgr24.ToBgra32(source.Slice(offset * 3, count * 3), MemoryMarshal.AsBytes(block)); - JoinAlpha(block, alpha.Slice(offset, count)); - PixelOperations.Instance.FromBgra32(configuration, block, destination.Slice(offset, count)); - offset += count; - } - - return; - } - - // Source bytes are BGR or YCbCr, selected before decoding. Separate lossy alpha is joined only after ICC. - Span row = vectors[..destination.Length]; - TOperator.ConvertSamplesWithIcc(configuration, source[..(destination.Length * 3)], converter, row, rgb[..destination.Length]); - PackIccRgbRow(configuration, row, alpha, destination); - } - - /// - /// Replaces each padded BGR pixel's high byte with its separate alpha sample. - /// - /// The expanded B,G,R,unused-byte pixels. - /// The matching unassociated alpha bytes. - private static void JoinAlpha(Span pixels, ReadOnlySpan alpha) - { - ref Bgra32 pixelsBase = ref MemoryMarshal.GetReference(pixels); - ref uint pixelValues = ref Unsafe.As(ref pixelsBase); - ref byte alphaBase = ref MemoryMarshal.GetReference(alpha); - int i = 0; - - // Each uint stores B,G,R,A on little-endian systems. The shift moves straight alpha into bits 24-31, and the mask preserves RGB. - // The destination packer handles alpha association after this merge. - if (Vector512.IsHardwareAccelerated) - { - nuint vectorCount = alpha.Vector512Count(); - - for (nuint block = 0; block < vectorCount; block++) - { - int offset = (int)(block * (uint)Vector512.Count); - Vector512 alphaValues = Load16(ref Unsafe.Add(ref alphaBase, (uint)offset)).AsUInt32() << 24; - ref Vector512 pixel = ref Unsafe.As>(ref Unsafe.Add(ref pixelValues, (uint)offset)); - - pixel = Vector512.ConditionalSelect(Vector512.Create(0xFF000000U), alphaValues, pixel); - } - - i = (int)(vectorCount * (uint)Vector512.Count); - } - - // This tier widens bytes to eight integer lanes and merges eight packed BGRA pixels at a time. - if (Avx2.IsSupported) - { - nuint vectorCount = alpha[i..].Vector256Count(); - - for (nuint block = 0; block < vectorCount; block++) - { - int offset = i + (int)(block * (uint)Vector256.Count); - Vector256 alphaValues = Load8(ref Unsafe.Add(ref alphaBase, (uint)offset)).AsUInt32() << 24; - ref Vector256 pixel = ref Unsafe.As>(ref Unsafe.Add(ref pixelValues, (uint)offset)); - pixel = Vector256.ConditionalSelect(Vector256.Create(0xFF000000U), alphaValues, pixel); - } - - i += (int)(vectorCount * (uint)Vector256.Count); - } - - if (Vector128.IsHardwareAccelerated) - { - nuint vectorCount = alpha[i..].Vector128Count(); - - for (nuint block = 0; block < vectorCount; block++) - { - int offset = i + (int)(block * (uint)Vector128.Count); - Vector128 alphaValues = Load4(ref Unsafe.Add(ref alphaBase, (uint)offset)).AsUInt32() << 24; - ref Vector128 pixel = ref Unsafe.As>(ref Unsafe.Add(ref pixelValues, (uint)offset)); - pixel = Vector128.ConditionalSelect(Vector128.Create(0xFF000000U), alphaValues, pixel); - } - - i += (int)(vectorCount * (uint)Vector128.Count); - } - - // The scalar tail handles pixels that do not fill a 128-bit block. - for (; i < alpha.Length; i++) - { - pixels[i].A = alpha[i]; - } - } - } -} diff --git a/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Encoding.cs b/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Encoding.cs deleted file mode 100644 index 24a774207b..0000000000 --- a/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Encoding.cs +++ /dev/null @@ -1,524 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -using System.Buffers; -using System.Numerics; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Runtime.Intrinsics; -using SixLabors.ImageSharp.ColorProfiles; -using SixLabors.ImageSharp.Common.Helpers; -using SixLabors.ImageSharp.Formats.Webp.Lossy; -using SixLabors.ImageSharp.Memory; -using SixLabors.ImageSharp.PixelFormats; - -namespace SixLabors.ImageSharp.Formats.Webp.ColorConverters; - -internal abstract partial class WebpColorConverterBase -{ - private sealed partial class WebpColorConverter - { - /// - public override bool ConvertFromRgb( - Buffer2DRegion frame, - Configuration configuration, - MemoryAllocator memoryAllocator, - ColorProfileConverter? converter, - Span vectors, - Span rgb, - Span y, - Span u, - Span v) - { - int width = frame.Width; - int height = frame.Height; - int uvWidth = (width + 1) >> 1; - - // Reuse two BGRA source rows and one resampled RGB row. Chroma needs both source rows in linear light - // before the color matrix runs; luma still uses each original full-resolution row. - using IMemoryOwner resampledRgbBuffer = memoryAllocator.Allocate(4 * uvWidth); - using IMemoryOwner bgraRow0Buffer = memoryAllocator.Allocate(width); - using IMemoryOwner bgraRow1Buffer = memoryAllocator.Allocate(width); - Span resampledRgb = resampledRgbBuffer.GetSpan(); - Span bgraRow0 = bgraRow0Buffer.GetSpan(); - Span bgraRow1 = bgraRow1Buffer.GetSpan(); - int uvRowIndex = 0; - int rowIndex; - bool hasAlpha = false; - - for (rowIndex = 0; rowIndex < height - 1; rowIndex += 2) - { - Span rowSpan = frame.DangerousGetRowSpan(rowIndex); - Span nextRowSpan = frame.DangerousGetRowSpan(rowIndex + 1); - if (converter is null) - { - PixelOperations.Instance.ToBgra32(configuration, rowSpan, bgraRow0); - PixelOperations.Instance.ToBgra32(configuration, nextRowSpan, bgraRow1); - } - else - { - // Apply ICC before the existing luma matrix and alpha-weighted chroma resampling. - // The same float scratch is reused after each BGRA row has been packed. - this.ConvertRgbRow(configuration, rowSpan, converter, vectors, rgb, bgraRow0); - this.ConvertRgbRow(configuration, nextRowSpan, converter, vectors, rgb, bgraRow1); - } - - // Both rows contribute to each chroma sample; transparency in either row requires alpha-weighted resampling. - bool rowsHaveAlpha = WebpCommonUtils.CheckNonOpaque(bgraRow0) || WebpCommonUtils.CheckNonOpaque(bgraRow1); - if (rowsHaveAlpha) - { - hasAlpha = true; - } - - // Downsample U/V planes, two rows at a time. - if (!rowsHaveAlpha) - { - AccumulateRgb(bgraRow0, bgraRow1, resampledRgb, width); - } - else - { - AccumulateRgba(bgraRow0, bgraRow1, resampledRgb, width); - } - - ConvertChromaRow(resampledRgb, u[(uvRowIndex * uvWidth)..], v[(uvRowIndex * uvWidth)..]); - uvRowIndex++; - - ConvertLumaRow(bgraRow0, y[(rowIndex * width)..]); - ConvertLumaRow(bgraRow1, y[((rowIndex + 1) * width)..]); - } - - // Repeat the final row when height is odd so chroma still receives a complete 2x2 sample group. - if ((height & 1) != 0) - { - Span rowSpan = frame.DangerousGetRowSpan(rowIndex); - if (converter is null) - { - PixelOperations.Instance.ToBgra32(configuration, rowSpan, bgraRow0); - } - else - { - // For an odd height, convert the final row into the output profile before YCbCr encoding. - this.ConvertRgbRow(configuration, rowSpan, converter, vectors, rgb, bgraRow0); - } - - ConvertLumaRow(bgraRow0, y[(rowIndex * width)..]); - - if (!WebpCommonUtils.CheckNonOpaque(bgraRow0)) - { - AccumulateRgb(bgraRow0, bgraRow0, resampledRgb, width); - } - else - { - AccumulateRgba(bgraRow0, bgraRow0, resampledRgb, width); - hasAlpha = true; - } - - ConvertChromaRow(resampledRgb, u[(uvRowIndex * uvWidth)..], v[(uvRowIndex * uvWidth)..]); - } - - return hasAlpha; - } - - /// - /// Converts BGRA pixels to full-resolution luma. - /// - /// The source pixels in B,G,R,A byte order. - /// The output luma samples. - private static void ConvertLumaRow(ReadOnlySpan pixels, Span y) - { - // Reading each BGRA pixel as a uint exposes B in bits 0..7, G in 8..15, and R in 16..23. - ReadOnlySpan samples = MemoryMarshal.Cast(pixels); - ref uint source = ref MemoryMarshal.GetReference(samples); - ref byte destination = ref MemoryMarshal.GetReference(y); - int sampleOffset = 0; - - if (Vector512.IsHardwareAccelerated) - { - // 16 int lanes convert 16 samples. Complete groups bound all source loads and the narrowed byte stores. - int sampleEnd = sampleOffset + ((int)samples[sampleOffset..].Vector512Count() * Vector512.Count); - - for (; sampleOffset < sampleEnd; sampleOffset += Vector512.Count) - { - Vector512 packed = Vector512.LoadUnsafe(ref source, (nuint)sampleOffset); - Vector512 mask = Vector512.Create((uint)byte.MaxValue); - Vector512 red = ((packed >> 16) & mask).AsInt32(); - Vector512 green = ((packed >> 8) & mask).AsInt32(); - Vector512 blue = (packed & mask).AsInt32(); - - // Pixel codes have no fractional bits. Static binding and inlining let the JIT discard unused chroma work. - TOperator.ConvertFromRgb(red, green, blue, 0, out Vector512 luma, out _, out _); - StoreConvertedSamples(luma, ref Unsafe.Add(ref destination, (uint)sampleOffset)); - } - } - - if (Vector256.IsHardwareAccelerated) - { - // Eight int lanes convert eight samples. Complete groups bound all source loads and the narrowed byte stores. - int sampleEnd = sampleOffset + ((int)samples[sampleOffset..].Vector256Count() * Vector256.Count); - - for (; sampleOffset < sampleEnd; sampleOffset += Vector256.Count) - { - Vector256 packed = Vector256.LoadUnsafe(ref source, (nuint)sampleOffset); - Vector256 mask = Vector256.Create((uint)byte.MaxValue); - Vector256 red = ((packed >> 16) & mask).AsInt32(); - Vector256 green = ((packed >> 8) & mask).AsInt32(); - Vector256 blue = (packed & mask).AsInt32(); - - // Pixel codes have no fractional bits. Static binding and inlining let the JIT discard unused chroma work. - TOperator.ConvertFromRgb(red, green, blue, 0, out Vector256 luma, out _, out _); - StoreConvertedSamples(luma, ref Unsafe.Add(ref destination, (uint)sampleOffset)); - } - } - - if (Vector128.IsHardwareAccelerated) - { - // Four int lanes convert four samples. Complete groups bound all source loads and the narrowed byte stores. - int sampleEnd = sampleOffset + ((int)samples[sampleOffset..].Vector128Count() * Vector128.Count); - - for (; sampleOffset < sampleEnd; sampleOffset += Vector128.Count) - { - Vector128 packed = Vector128.LoadUnsafe(ref source, (nuint)sampleOffset); - Vector128 mask = Vector128.Create((uint)byte.MaxValue); - Vector128 red = ((packed >> 16) & mask).AsInt32(); - Vector128 green = ((packed >> 8) & mask).AsInt32(); - Vector128 blue = (packed & mask).AsInt32(); - - // Pixel codes have no fractional bits. Static binding and inlining let the JIT discard unused chroma work. - TOperator.ConvertFromRgb(red, green, blue, 0, out Vector128 luma, out _, out _); - StoreConvertedSamples(luma, ref Unsafe.Add(ref destination, (uint)sampleOffset)); - } - } - - // Finish a partial vector, or the entire row when hardware acceleration is unavailable. - for (; sampleOffset < pixels.Length; sampleOffset++) - { - Bgra32 pixel = pixels[sampleOffset]; - TOperator.ConvertFromRgb(pixel.R, pixel.G, pixel.B, 0, out int luma, out _, out _); - y[sampleOffset] = (byte)luma; - } - } - - /// - /// Converts resampled RGB values with two fractional bits into half-resolution U and V rows. - /// - /// Four words per sample: red, green, blue, and an unused fourth word. - /// The output U samples. - /// The output V samples. - private static void ConvertChromaRow(ReadOnlySpan rgb, Span u, Span v) - { - // Each ulong contains one R,G,B,unused group. The fourth word need not be initialized and is never selected. - ReadOnlySpan samples = MemoryMarshal.Cast(rgb); - ref ulong source = ref MemoryMarshal.GetReference(samples); - ref byte uDestination = ref MemoryMarshal.GetReference(u); - ref byte vDestination = ref MemoryMarshal.GetReference(v); - int sampleOffset = 0; - - if (Vector512.IsHardwareAccelerated) - { - // 16 int lanes convert 16 samples. Complete groups bound all source loads and the narrowed byte stores. - int sampleEnd = sampleOffset + ((int)(samples[sampleOffset..].Vector512Count() / 2) * Vector512.Count); - - for (; sampleOffset < sampleEnd; sampleOffset += Vector512.Count) - { - // Two ulong vectors contain enough packed samples for one int vector per RGB channel. - // Shift each channel into the low word, then narrow in sample order and discard the other words. - Vector512 first = Vector512.LoadUnsafe(ref source, (nuint)sampleOffset); - - Vector512 second = Vector512.LoadUnsafe(ref source, (nuint)(sampleOffset + Vector512.Count)); - Vector512 mask = Vector512.Create(0xFFFFU); - Vector512 red = (Vector512.Narrow(first, second) & mask).AsInt32(); - Vector512 green = (Vector512.Narrow(first >> 16, second >> 16) & mask).AsInt32(); - Vector512 blue = (Vector512.Narrow(first >> 32, second >> 32) & mask).AsInt32(); - - // Resampling retains two fractional bits. Static binding and inlining let the JIT discard unused luma work. - TOperator.ConvertFromRgb(red, green, blue, 2, out _, out Vector512 uValues, out Vector512 vValues); - StoreConvertedSamples(uValues, ref Unsafe.Add(ref uDestination, (uint)sampleOffset)); - StoreConvertedSamples(vValues, ref Unsafe.Add(ref vDestination, (uint)sampleOffset)); - } - } - - if (Vector256.IsHardwareAccelerated) - { - // Eight int lanes convert eight samples. Complete groups bound all source loads and the narrowed byte stores. - int sampleEnd = sampleOffset + ((int)(samples[sampleOffset..].Vector256Count() / 2) * Vector256.Count); - - for (; sampleOffset < sampleEnd; sampleOffset += Vector256.Count) - { - // Two ulong vectors contain enough packed samples for one int vector per RGB channel. - // Shift each channel into the low word, then narrow in sample order and discard the other words. - Vector256 first = Vector256.LoadUnsafe(ref source, (nuint)sampleOffset); - - Vector256 second = Vector256.LoadUnsafe(ref source, (nuint)(sampleOffset + Vector256.Count)); - Vector256 mask = Vector256.Create(0xFFFFU); - Vector256 red = (Vector256.Narrow(first, second) & mask).AsInt32(); - Vector256 green = (Vector256.Narrow(first >> 16, second >> 16) & mask).AsInt32(); - Vector256 blue = (Vector256.Narrow(first >> 32, second >> 32) & mask).AsInt32(); - - // Resampling retains two fractional bits. Static binding and inlining let the JIT discard unused luma work. - TOperator.ConvertFromRgb(red, green, blue, 2, out _, out Vector256 uValues, out Vector256 vValues); - StoreConvertedSamples(uValues, ref Unsafe.Add(ref uDestination, (uint)sampleOffset)); - StoreConvertedSamples(vValues, ref Unsafe.Add(ref vDestination, (uint)sampleOffset)); - } - } - - if (Vector128.IsHardwareAccelerated) - { - // Four int lanes convert four samples. Complete groups bound all source loads and the narrowed byte stores. - int sampleEnd = sampleOffset + ((int)(samples[sampleOffset..].Vector128Count() / 2) * Vector128.Count); - - for (; sampleOffset < sampleEnd; sampleOffset += Vector128.Count) - { - // Two ulong vectors contain enough packed samples for one int vector per RGB channel. - // Shift each channel into the low word, then narrow in sample order and discard the other words. - Vector128 first = Vector128.LoadUnsafe(ref source, (nuint)sampleOffset); - - Vector128 second = Vector128.LoadUnsafe(ref source, (nuint)(sampleOffset + Vector128.Count)); - Vector128 mask = Vector128.Create(0xFFFFU); - Vector128 red = (Vector128.Narrow(first, second) & mask).AsInt32(); - Vector128 green = (Vector128.Narrow(first >> 16, second >> 16) & mask).AsInt32(); - Vector128 blue = (Vector128.Narrow(first >> 32, second >> 32) & mask).AsInt32(); - - // Resampling retains two fractional bits. Static binding and inlining let the JIT discard unused luma work. - TOperator.ConvertFromRgb(red, green, blue, 2, out _, out Vector128 uValues, out Vector128 vValues); - StoreConvertedSamples(uValues, ref Unsafe.Add(ref uDestination, (uint)sampleOffset)); - StoreConvertedSamples(vValues, ref Unsafe.Add(ref vDestination, (uint)sampleOffset)); - } - } - - // Remaining samples use the identical integer matrix, including the two fractional input bits. - for (; sampleOffset < samples.Length; sampleOffset++) - { - ulong packed = samples[sampleOffset]; - int red = (int)(packed & 0xFFFF); - int green = (int)((packed >> 16) & 0xFFFF); - int blue = (int)((packed >> 32) & 0xFFFF); - TOperator.ConvertFromRgb(red, green, blue, 2, out _, out int uValue, out int vValue); - u[sampleOffset] = (byte)uValue; - v[sampleOffset] = (byte)vValue; - } - } - - /// - /// Stores sixteen byte-range channel codes in their original sample order. - /// - /// The converted channel values, each in the range 0..255. - /// The first of sixteen output bytes. - private static void StoreConvertedSamples(Vector512 values, ref byte destination) - { - // Reuse the decoder's exact sixteen-sample narrowing; all values already fit in a byte. - Narrow(values).StoreUnsafe(ref destination); - } - - /// - /// Stores eight byte-range channel codes in their original sample order. - /// - /// The converted channel values, each in the range 0..255. - /// The first of eight output bytes. - private static void StoreConvertedSamples(Vector256 values, ref byte destination) - { - Vector128 words = Vector128.Narrow(values.GetLower().AsUInt32(), values.GetUpper().AsUInt32()); - Vector128 bytes = Vector128.Narrow(words, Vector128.Zero); - - // Only the low eight bytes contain samples; an eight-byte store cannot overwrite the following row data. - Unsafe.WriteUnaligned(ref destination, bytes.AsUInt64().ToScalar()); - } - - /// - /// Stores four byte-range channel codes in their original sample order. - /// - /// The converted channel values, each in the range 0..255. - /// The first of four output bytes. - private static void StoreConvertedSamples(Vector128 values, ref byte destination) - { - Vector128 words = Vector128.Narrow(values.AsUInt32(), Vector128.Zero); - Vector128 bytes = Vector128.Narrow(words, Vector128.Zero); - - // Narrowing places the four samples in the low word. Store exactly those four bytes. - Unsafe.WriteUnaligned(ref destination, bytes.AsUInt32().ToScalar()); - } - - /// - /// Resamples each 2x2 RGB group in linear light and retains two fractional bits for chroma conversion. - /// - /// The first source row. - /// The second source row, or the first row again at the bottom edge. - /// Four words per output sample: red, green, blue, and an unused fourth word. - /// The number of source pixels per row. - private static void AccumulateRgb(ReadOnlySpan rowSpan, ReadOnlySpan nextRowSpan, Span dst, int width) - { - Bgra32 topLeft; - Bgra32 topRight; - int sampleIndex, pixelOffset; - int destinationOffset = 0; - - // A 2x2 group produces one chroma sample; gamma conversion happens before averaging the four source values. - for (sampleIndex = 0, pixelOffset = 0; sampleIndex < (width >> 1); sampleIndex += 1, pixelOffset += 2, destinationOffset += 4) - { - topLeft = rowSpan[pixelOffset]; - topRight = rowSpan[pixelOffset + 1]; - Bgra32 bottomLeft = nextRowSpan[pixelOffset]; - Bgra32 bottomRight = nextRowSpan[pixelOffset + 1]; - - dst[destinationOffset] = (ushort)LinearToGamma( - GammaToLinear(topLeft.R) + GammaToLinear(topRight.R) + GammaToLinear(bottomLeft.R) + GammaToLinear(bottomRight.R), 0); - - dst[destinationOffset + 1] = (ushort)LinearToGamma( - GammaToLinear(topLeft.G) + GammaToLinear(topRight.G) + GammaToLinear(bottomLeft.G) + GammaToLinear(bottomRight.G), 0); - - dst[destinationOffset + 2] = (ushort)LinearToGamma( - GammaToLinear(topLeft.B) + GammaToLinear(topRight.B) + GammaToLinear(bottomLeft.B) + GammaToLinear(bottomRight.B), 0); - } - - // Repeat the rightmost source column when width is odd. The doubled contribution keeps the four-sample scale. - if ((width & 1) != 0) - { - topLeft = rowSpan[pixelOffset]; - Bgra32 bottomLeft = nextRowSpan[pixelOffset]; - - dst[destinationOffset] = (ushort)LinearToGamma(GammaToLinear(topLeft.R) + GammaToLinear(bottomLeft.R), 1); - dst[destinationOffset + 1] = (ushort)LinearToGamma(GammaToLinear(topLeft.G) + GammaToLinear(bottomLeft.G), 1); - dst[destinationOffset + 2] = (ushort)LinearToGamma(GammaToLinear(topLeft.B) + GammaToLinear(bottomLeft.B), 1); - } - } - - /// - /// Resamples each 2x2 RGB group in linear light with alpha weighting and retains two fractional bits. - /// - /// The first source row. - /// The second source row, or the first row again at the bottom edge. - /// Four words per output sample: red, green, blue, and the sum of the contributing alpha values. - /// The number of source pixels per row. - private static void AccumulateRgba(ReadOnlySpan rowSpan, ReadOnlySpan nextRowSpan, Span dst, int width) - { - Bgra32 topLeft; - Bgra32 topRight; - int sampleIndex, pixelOffset; - int destinationOffset = 0; - - // A 2x2 group produces one chroma sample; gamma conversion happens before averaging the four source values. - for (sampleIndex = 0, pixelOffset = 0; sampleIndex < width >> 1; sampleIndex += 1, pixelOffset += 2, destinationOffset += 4) - { - topLeft = rowSpan[pixelOffset]; - topRight = rowSpan[pixelOffset + 1]; - Bgra32 bottomLeft = nextRowSpan[pixelOffset]; - Bgra32 bottomRight = nextRowSpan[pixelOffset + 1]; - uint alphaSum = (uint)(topLeft.A + topRight.A + bottomLeft.A + bottomRight.A); - int r, g, b; - - // Fully opaque samples need no weighting. A fully transparent group has no visible color and avoids division by zero. - if (alphaSum is 4 * 0xff or 0) - { - r = (ushort)LinearToGamma( - GammaToLinear(topLeft.R) + GammaToLinear(topRight.R) + GammaToLinear(bottomLeft.R) + GammaToLinear(bottomRight.R), 0); - - g = (ushort)LinearToGamma( - GammaToLinear(topLeft.G) + GammaToLinear(topRight.G) + GammaToLinear(bottomLeft.G) + GammaToLinear(bottomRight.G), 0); - - b = (ushort)LinearToGamma( - GammaToLinear(topLeft.B) + GammaToLinear(topRight.B) + GammaToLinear(bottomLeft.B) + GammaToLinear(bottomRight.B), 0); - } - else - { - r = LinearToGammaWeighted(topLeft.R, topRight.R, bottomLeft.R, bottomRight.R, topLeft.A, topRight.A, bottomLeft.A, bottomRight.A, alphaSum); - g = LinearToGammaWeighted(topLeft.G, topRight.G, bottomLeft.G, bottomRight.G, topLeft.A, topRight.A, bottomLeft.A, bottomRight.A, alphaSum); - b = LinearToGammaWeighted(topLeft.B, topRight.B, bottomLeft.B, bottomRight.B, topLeft.A, topRight.A, bottomLeft.A, bottomRight.A, alphaSum); - } - - dst[destinationOffset] = (ushort)r; - dst[destinationOffset + 1] = (ushort)g; - dst[destinationOffset + 2] = (ushort)b; - dst[destinationOffset + 3] = (ushort)alphaSum; - } - - // Repeat the rightmost source column when width is odd. The doubled contribution keeps the four-sample scale. - if ((width & 1) != 0) - { - topLeft = rowSpan[pixelOffset]; - Bgra32 bottomLeft = nextRowSpan[pixelOffset]; - uint alphaSum = (uint)(2u * (topLeft.A + bottomLeft.A)); - int r, g, b; - - // Fully opaque samples need no weighting. A fully transparent group has no visible color and avoids division by zero. - if (alphaSum is 4 * 0xff or 0) - { - r = (ushort)LinearToGamma(GammaToLinear(topLeft.R) + GammaToLinear(bottomLeft.R), 1); - g = (ushort)LinearToGamma(GammaToLinear(topLeft.G) + GammaToLinear(bottomLeft.G), 1); - b = (ushort)LinearToGamma(GammaToLinear(topLeft.B) + GammaToLinear(bottomLeft.B), 1); - } - else - { - r = LinearToGammaWeighted(topLeft.R, bottomLeft.R, topLeft.R, bottomLeft.R, topLeft.A, bottomLeft.A, topLeft.A, bottomLeft.A, alphaSum); - g = LinearToGammaWeighted(topLeft.G, bottomLeft.G, topLeft.G, bottomLeft.G, topLeft.A, bottomLeft.A, topLeft.A, bottomLeft.A, alphaSum); - b = LinearToGammaWeighted(topLeft.B, bottomLeft.B, topLeft.B, bottomLeft.B, topLeft.A, bottomLeft.A, topLeft.A, bottomLeft.A, alphaSum); - } - - dst[destinationOffset] = (ushort)r; - dst[destinationOffset + 1] = (ushort)g; - dst[destinationOffset + 2] = (ushort)b; - dst[destinationOffset + 3] = (ushort)alphaSum; - } - } - - /// - /// Averages four linear-light values by alpha and returns a gamma-encoded value with two fractional bits. - /// - /// The first channel value. - /// The second channel value. - /// The third channel value. - /// The fourth channel value. - /// The first alpha value. - /// The second alpha value. - /// The third alpha value. - /// The fourth alpha value. - /// The nonzero sum of the four alpha values. - /// The weighted channel value scaled by four. - [MethodImpl(InliningOptions.ShortMethod)] - private static int LinearToGammaWeighted(byte rgb0, byte rgb1, byte rgb2, byte rgb3, byte a0, byte a1, byte a2, byte a3, uint totalA) - { - uint sum = (a0 * GammaToLinear(rgb0)) + (a1 * GammaToLinear(rgb1)) + (a2 * GammaToLinear(rgb2)) + (a3 * GammaToLinear(rgb3)); - - // InvAlpha supplies the fixed-point reciprocal of the alpha sum; retain two extra bits for the chroma matrix. - return LinearToGamma((sum * WebpLookupTables.InvAlpha[totalA]) >> (WebpConstants.AlphaFix - 2), 0); - } - - /// - /// Converts a linear-light sum to a gamma-encoded channel value with two fractional bits. - /// - /// The sum of the linear-light source values. - /// One when two samples replace the four-sample group; otherwise zero. - /// The gamma-encoded channel value scaled by four. - [MethodImpl(InliningOptions.ShortMethod)] - private static int LinearToGamma(uint baseValue, int shift) - { - // At an odd image edge, doubling a two-sample sum keeps the same scale as a complete 2x2 group. - int interpolated = Interpolate((int)(baseValue << shift)); - return (interpolated + WebpConstants.GammaTabRounder) >> WebpConstants.GammaTabFix; - } - - /// - /// Maps a gamma-encoded byte to the linear-light lookup-table scale. - /// - /// The gamma-encoded channel byte. - /// The linear-light value. - [MethodImpl(InliningOptions.ShortMethod)] - private static uint GammaToLinear(byte v) => WebpLookupTables.GammaToLinearTab[v]; - - /// - /// Interpolates neighboring entries in the linear-to-gamma table for a four-sample sum. - /// - /// The linear-light sum at the four-sample scale. - /// The interpolated gamma value at the table's fixed-point scale. - [MethodImpl(InliningOptions.ShortMethod)] - private static int Interpolate(int v) - { - // The low bits give the position between table entries. The extra two bits account for the four-sample sum. - int tabPos = v >> (WebpConstants.GammaTabFix + 2); - int x = v & ((WebpConstants.GammaTabScale << 2) - 1); - int v0 = WebpLookupTables.LinearToGammaTab[tabPos]; - int v1 = WebpLookupTables.LinearToGammaTab[tabPos + 1]; - int y = (v1 * x) + (v0 * ((WebpConstants.GammaTabScale << 2) - x)); - - return y; - } - } -} diff --git a/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Icc.cs b/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Icc.cs new file mode 100644 index 0000000000..3f1bb9e0b9 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Icc.cs @@ -0,0 +1,208 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.ColorProfiles; +using SixLabors.ImageSharp.Metadata.Profiles.Icc; +using SixLabors.ImageSharp.PixelFormats; + +namespace SixLabors.ImageSharp.Formats.Webp.ColorConverters; + +internal abstract partial class WebpColorConverterBase +{ + private sealed partial class WebpColorConverter + { + /// + public override void ConvertToRgb( + ReadOnlySpan c0, + ReadOnlySpan c1, + ReadOnlySpan c2, + ReadOnlySpan alpha, + ColorProfileConverter converter, + Span destination) + { + // Each vector lane carries one pixel through the operator. Interleave4 then writes [P0 P1 P2 A] for each pixel, + // so the ICC transform reads the vectors with no other model conversion. A is 1 when the row has no alpha. + IccColorSpaceType profileSpace = converter.Options.SourceIccProfile!.Header.DataColorSpace; + ref byte s0 = ref MemoryMarshal.GetReference(c0); + ref byte s1 = ref MemoryMarshal.GetReference(c1); + ref byte s2 = ref MemoryMarshal.GetReference(c2); + ref byte a = ref MemoryMarshal.GetReference(alpha); + ref float packed = ref Unsafe.As(ref MemoryMarshal.GetReference(destination)); + bool hasAlpha = !alpha.IsEmpty; + int length = c0.Length; + int i = 0; + + if (Vector512.IsHardwareAccelerated) + { + Vector512 maximum = Vector512.Create((float)byte.MaxValue); + for (; i + 16 <= length; i += 16) + { + TOperator.ConvertToProfile( + Load16(ref Unsafe.Add(ref s0, (uint)i)), + Load16(ref Unsafe.Add(ref s1, (uint)i)), + Load16(ref Unsafe.Add(ref s2, (uint)i)), + maximum, + profileSpace, + out Vector512 p0, + out Vector512 p1, + out Vector512 p2); + + Vector512 w = hasAlpha ? Vector512.ConvertToSingle(Load16(ref Unsafe.Add(ref a, (uint)i))) / maximum : Vector512.One; + SimdUtils.Interleave4(p0, p1, p2, w, ref Unsafe.Add(ref packed, (nuint)(uint)i * 4)); + } + } + + if (Vector256.IsHardwareAccelerated) + { + Vector256 maximum = Vector256.Create((float)byte.MaxValue); + for (; i + 8 <= length; i += 8) + { + TOperator.ConvertToProfile( + Load8(ref Unsafe.Add(ref s0, (uint)i)), + Load8(ref Unsafe.Add(ref s1, (uint)i)), + Load8(ref Unsafe.Add(ref s2, (uint)i)), + maximum, + profileSpace, + out Vector256 p0, + out Vector256 p1, + out Vector256 p2); + + Vector256 w = hasAlpha ? Vector256.ConvertToSingle(Load8(ref Unsafe.Add(ref a, (uint)i))) / maximum : Vector256.One; + SimdUtils.Interleave4(p0, p1, p2, w, ref Unsafe.Add(ref packed, (nuint)(uint)i * 4)); + } + } + + if (Vector128.IsHardwareAccelerated) + { + Vector128 maximum = Vector128.Create((float)byte.MaxValue); + for (; i + 4 <= length; i += 4) + { + TOperator.ConvertToProfile( + Load4(ref Unsafe.Add(ref s0, (uint)i)), + Load4(ref Unsafe.Add(ref s1, (uint)i)), + Load4(ref Unsafe.Add(ref s2, (uint)i)), + maximum, + profileSpace, + out Vector128 p0, + out Vector128 p1, + out Vector128 p2); + + Vector128 w = hasAlpha ? Vector128.ConvertToSingle(Load4(ref Unsafe.Add(ref a, (uint)i))) / maximum : Vector128.One; + SimdUtils.Interleave4(p0, p1, p2, w, ref Unsafe.Add(ref packed, (nuint)(uint)i * 4)); + } + } + + // Finish a partial vector, or the whole row when hardware acceleration is unavailable. + for (; i < length; i++) + { + TOperator.ConvertToProfile( + Unsafe.Add(ref s0, (uint)i), + Unsafe.Add(ref s1, (uint)i), + Unsafe.Add(ref s2, (uint)i), + byte.MaxValue, + profileSpace, + out float p0, + out float p1, + out float p2); + + destination[i] = new Vector4(p0, p1, p2, hasAlpha ? Unsafe.Add(ref a, (uint)i) / (float)byte.MaxValue : 1F); + } + + // ICC transforms the profile components in place. W stays alpha. + converter.Convert(destination); + } + + /// + public override void ConvertToRgb(ReadOnlySpan source, ColorProfileConverter converter, Span destination) + { + // Each uint lane holds one BGRA pixel: B in bits 0..7, G in 8..15, R in 16..23 and A in 24..31. + // The shifts and the mask give the native R, G, B components, and the operator gives the profile components. + IccColorSpaceType profileSpace = converter.Options.SourceIccProfile!.Header.DataColorSpace; + ref uint pixels = ref Unsafe.As(ref MemoryMarshal.GetReference(source)); + ref float packed = ref Unsafe.As(ref MemoryMarshal.GetReference(destination)); + int length = source.Length; + int i = 0; + + if (Vector512.IsHardwareAccelerated) + { + Vector512 maximum = Vector512.Create((float)byte.MaxValue); + Vector512 mask = Vector512.Create((uint)byte.MaxValue); + for (; i + 16 <= length; i += 16) + { + Vector512 bgra = Vector512.LoadUnsafe(ref pixels, (nuint)(uint)i); + TOperator.ConvertToProfile( + ((bgra >> 16) & mask).AsInt32(), + ((bgra >> 8) & mask).AsInt32(), + (bgra & mask).AsInt32(), + maximum, + profileSpace, + out Vector512 p0, + out Vector512 p1, + out Vector512 p2); + + Vector512 w = Vector512.ConvertToSingle((bgra >> 24).AsInt32()) / maximum; + SimdUtils.Interleave4(p0, p1, p2, w, ref Unsafe.Add(ref packed, (nuint)(uint)i * 4)); + } + } + + if (Vector256.IsHardwareAccelerated) + { + Vector256 maximum = Vector256.Create((float)byte.MaxValue); + Vector256 mask = Vector256.Create((uint)byte.MaxValue); + for (; i + 8 <= length; i += 8) + { + Vector256 bgra = Vector256.LoadUnsafe(ref pixels, (nuint)(uint)i); + TOperator.ConvertToProfile( + ((bgra >> 16) & mask).AsInt32(), + ((bgra >> 8) & mask).AsInt32(), + (bgra & mask).AsInt32(), + maximum, + profileSpace, + out Vector256 p0, + out Vector256 p1, + out Vector256 p2); + + Vector256 w = Vector256.ConvertToSingle((bgra >> 24).AsInt32()) / maximum; + SimdUtils.Interleave4(p0, p1, p2, w, ref Unsafe.Add(ref packed, (nuint)(uint)i * 4)); + } + } + + if (Vector128.IsHardwareAccelerated) + { + Vector128 maximum = Vector128.Create((float)byte.MaxValue); + Vector128 mask = Vector128.Create((uint)byte.MaxValue); + for (; i + 4 <= length; i += 4) + { + Vector128 bgra = Vector128.LoadUnsafe(ref pixels, (nuint)(uint)i); + TOperator.ConvertToProfile( + ((bgra >> 16) & mask).AsInt32(), + ((bgra >> 8) & mask).AsInt32(), + (bgra & mask).AsInt32(), + maximum, + profileSpace, + out Vector128 p0, + out Vector128 p1, + out Vector128 p2); + + Vector128 w = Vector128.ConvertToSingle((bgra >> 24).AsInt32()) / maximum; + SimdUtils.Interleave4(p0, p1, p2, w, ref Unsafe.Add(ref packed, (nuint)(uint)i * 4)); + } + } + + // Finish a partial vector, or the whole row when hardware acceleration is unavailable. + for (; i < length; i++) + { + Bgra32 pixel = source[i]; + TOperator.ConvertToProfile(pixel.R, pixel.G, pixel.B, byte.MaxValue, profileSpace, out float p0, out float p1, out float p2); + destination[i] = new Vector4(p0, p1, p2, pixel.A / (float)byte.MaxValue); + } + + // ICC transforms the profile components in place. W stays alpha. + converter.Convert(destination); + } + } +} diff --git a/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Operator.cs b/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Operator.cs index 6de2a44737..9daca0819e 100644 --- a/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Operator.cs +++ b/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.Operator.cs @@ -2,67 +2,71 @@ // Licensed under the Six Labors Split License. using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using System.Runtime.Intrinsics; -using SixLabors.ImageSharp.ColorProfiles; +using SixLabors.ImageSharp.Common.Helpers; +using SixLabors.ImageSharp.Formats.Webp.Lossy; +using SixLabors.ImageSharp.Metadata.Profiles.Icc; +using SixLabors.ImageSharp.PixelFormats; namespace SixLabors.ImageSharp.Formats.Webp.ColorConverters; internal abstract partial class WebpColorConverterBase { /// - /// Defines scalar and SIMD conversion between RGB and native WebP samples. + /// Defines the scalar and SIMD conversions of one WebP color type, as IJpegColorConverterOperator does for JPEG. /// + /// + /// Each member has a scalar, Vector128, Vector256 and Vector512 form. Each lane holds one pixel. + /// The integer members work on 8-bit codes. The vector forms of ConvertToRgb use 16-bit lanes, because the products of the WebP matrix fit + /// 16 bits. The other integer members use int lanes. The profile members work on normalized components in [0, 1]. + /// internal interface IWebpColorConverterOperator { /// - /// Converts one native sample to three destination byte codes. + /// Gets the WebP color type that the operator converts. /// - /// The first native source channel. - /// The second native source channel. - /// The third native source channel. - public static abstract void ConvertToSamples(ref int c0, ref int c1, ref int c2); + public static abstract WebpColorType ColorType { get; } /// - /// Converts four native samples using 128-bit integer lanes. + /// Converts one native sample to red, green and blue codes. /// - /// The first native source channel in four lanes. - /// The second native source channel in four lanes. - /// The third native source channel in four lanes. - public static abstract void ConvertToSamples(ref Vector128 c0, ref Vector128 c1, ref Vector128 c2); + /// The first native component. On return, the red code. + /// The second native component. On return, the green code. + /// The third native component. On return, the blue code. + public static abstract void ConvertToRgb(ref int c0, ref int c1, ref int c2); /// - /// Converts eight native samples using 256-bit integer lanes. + /// Converts eight native samples to red, green and blue codes. /// - /// The first native source channel in eight lanes. - /// The second native source channel in eight lanes. - /// The third native source channel in eight lanes. - public static abstract void ConvertToSamples(ref Vector256 c0, ref Vector256 c1, ref Vector256 c2); + /// The first native component. On return, the red codes. + /// The second native component. On return, the green codes. + /// The third native component. On return, the blue codes. + public static abstract void ConvertToRgb(ref Vector128 c0, ref Vector128 c1, ref Vector128 c2); /// - /// Converts sixteen native samples using 512-bit integer lanes. + /// Converts sixteen native samples to red, green and blue codes. /// - /// The first native source channel in sixteen lanes. - /// The second native source channel in sixteen lanes. - /// The third native source channel in sixteen lanes. - public static abstract void ConvertToSamples(ref Vector512 c0, ref Vector512 c1, ref Vector512 c2); + /// The first native component. On return, the red codes. + /// The second native component. On return, the green codes. + /// The third native component. On return, the blue codes. + public static abstract void ConvertToRgb(ref Vector256 c0, ref Vector256 c1, ref Vector256 c2); /// - /// Converts one row of native source bytes through its ICC profile. + /// Converts thirty-two native samples to red, green and blue codes. /// - /// The decoding configuration. - /// The native three-byte samples. - /// The ICC converter. - /// Vector scratch with one entry per pixel. - /// RGB scratch with one entry per pixel. - public static abstract void ConvertSamplesWithIcc( - Configuration configuration, ReadOnlySpan source, ColorProfileConverter converter, Span vectors, Span rgb); + /// The first native component. On return, the red codes. + /// The second native component. On return, the green codes. + /// The third native component. On return, the blue codes. + public static abstract void ConvertToRgb(ref Vector512 c0, ref Vector512 c1, ref Vector512 c2); /// - /// Converts one RGB sample to the selected native components. + /// Converts one RGB sample to native components. /// - /// The red codes, including the declared fractional bits. - /// The green codes, including the declared fractional bits. - /// The blue codes, including the declared fractional bits. + /// The red code, including the declared fractional bits. + /// The green code, including the declared fractional bits. + /// The blue code, including the declared fractional bits. /// The fractional input bits: zero for pixel samples or two for resampled chroma inputs. /// The first native byte-range component. /// The second native byte-range component. @@ -70,7 +74,7 @@ public static abstract void ConvertSamplesWithIcc( public static abstract void ConvertFromRgb(int r, int g, int b, int inputShift, out int c0, out int c1, out int c2); /// - /// Converts four RGB samples to the selected native components. + /// Converts four RGB samples to native components. /// /// The red codes, including the declared fractional bits. /// The green codes, including the declared fractional bits. @@ -83,7 +87,7 @@ public static abstract void ConvertFromRgb( Vector128 r, Vector128 g, Vector128 b, int inputShift, out Vector128 c0, out Vector128 c1, out Vector128 c2); /// - /// Converts eight RGB samples to the selected native components. + /// Converts eight RGB samples to native components. /// /// The red codes, including the declared fractional bits. /// The green codes, including the declared fractional bits. @@ -96,7 +100,7 @@ public static abstract void ConvertFromRgb( Vector256 r, Vector256 g, Vector256 b, int inputShift, out Vector256 c0, out Vector256 c1, out Vector256 c2); /// - /// Converts sixteen RGB samples to the selected native components. + /// Converts sixteen RGB samples to native components. /// /// The red codes, including the declared fractional bits. /// The green codes, including the declared fractional bits. @@ -107,5 +111,614 @@ public static abstract void ConvertFromRgb( /// The third native byte-range component. public static abstract void ConvertFromRgb( Vector512 r, Vector512 g, Vector512 b, int inputShift, out Vector512 c0, out Vector512 c1, out Vector512 c2); + + /// + /// Converts one native sample to normalized source profile components. + /// + /// The first native component. + /// The second native component. + /// The third native component. + /// The maximum code, 255. + /// The source profile's device color space. It selects the model of the profile components. + /// The first profile component. + /// The second profile component. + /// The third profile component. + public static abstract void ConvertToProfile( + int c0, int c1, int c2, float maximum, IccColorSpaceType profileSpace, out float p0, out float p1, out float p2); + + /// + /// Converts four native samples to normalized source profile components. + /// + /// The first native components. + /// The second native components. + /// The third native components. + /// The maximum code, 255, in each lane. + /// The source profile's device color space. It selects the model of the profile components. + /// The first profile components. + /// The second profile components. + /// The third profile components. + public static abstract void ConvertToProfile( + Vector128 c0, + Vector128 c1, + Vector128 c2, + Vector128 maximum, + IccColorSpaceType profileSpace, + out Vector128 p0, + out Vector128 p1, + out Vector128 p2); + + /// + /// Converts eight native samples to normalized source profile components. + /// + /// The first native components. + /// The second native components. + /// The third native components. + /// The maximum code, 255, in each lane. + /// The source profile's device color space. It selects the model of the profile components. + /// The first profile components. + /// The second profile components. + /// The third profile components. + public static abstract void ConvertToProfile( + Vector256 c0, + Vector256 c1, + Vector256 c2, + Vector256 maximum, + IccColorSpaceType profileSpace, + out Vector256 p0, + out Vector256 p1, + out Vector256 p2); + + /// + /// Converts sixteen native samples to normalized source profile components. + /// + /// The first native components. + /// The second native components. + /// The third native components. + /// The maximum code, 255, in each lane. + /// The source profile's device color space. It selects the model of the profile components. + /// The first profile components. + /// The second profile components. + /// The third profile components. + public static abstract void ConvertToProfile( + Vector512 c0, + Vector512 c1, + Vector512 c2, + Vector512 maximum, + IccColorSpaceType profileSpace, + out Vector512 p0, + out Vector512 p1, + out Vector512 p2); + } + + /// + /// Converts rows between RGB and native WebP samples using the selected operator. + /// + /// The scalar and SIMD color conversion operator. + private sealed partial class WebpColorConverter : WebpColorConverterBase + where TOperator : struct, IWebpColorConverterOperator + { + /// + public override void ConvertFromRgb( + ReadOnlySpan row0, + ReadOnlySpan row1, + bool weightByAlpha, + Span y0, + Span y1, + Span u, + Span v) + { + // Each block holds 16 chroma samples, the 2x2 groups of 32 pixels in each row. The downsample writes four + // words for each sample to the staging block, and the chroma conversion reads them while they are still in L1. + // The luma of the same pixels follows, so the call reads each source pixel in one pass over the rows. + const int samplesPerBlock = 16; + InlineArray64 staging = default; + Span resampled = staging; + int width = row0.Length; + int uvWidth = u.Length; + + for (int sample = 0; sample < uvWidth; sample += samplesPerBlock) + { + int samples = Math.Min(samplesPerBlock, uvWidth - sample); + int pixel = 2 * sample; + int pixels = Math.Min(2 * samplesPerBlock, width - pixel); + ReadOnlySpan top = row0.Slice(pixel, pixels); + ReadOnlySpan bottom = row1.Slice(pixel, pixels); + + ChromaDownsampler.Downsample(top, bottom, weightByAlpha, resampled[..(4 * samples)]); + ConvertToChroma(resampled[..(4 * samples)], u.Slice(sample, samples), v.Slice(sample, samples)); + ConvertToLuma(top, y0.Slice(pixel, pixels)); + if (!y1.IsEmpty) + { + ConvertToLuma(bottom, y1.Slice(pixel, pixels)); + } + } + } + + /// + /// Converts BGRA pixels to luma. + /// + /// The BGRA pixels. + /// The luma samples, one for each pixel. + private static void ConvertToLuma(ReadOnlySpan pixels, Span y) + { + // Reading each BGRA pixel as a uint exposes B in bits 0..7, G in 8..15, and R in 16..23. + // Each stage converts complete vectors from where the wider stage stopped, and the scalar stage converts the rest. + ref uint source = ref Unsafe.As(ref MemoryMarshal.GetReference(pixels)); + ref byte destination = ref MemoryMarshal.GetReference(y); + nuint length = (uint)pixels.Length; + nuint i = 0; + + if (Vector512.IsHardwareAccelerated) + { + for (; i + (uint)Vector512.Count <= length; i += (uint)Vector512.Count) + { + ConvertLuma(Vector512.LoadUnsafe(ref source, i), ref Unsafe.Add(ref destination, i)); + } + } + + if (Vector256.IsHardwareAccelerated) + { + for (; i + (uint)Vector256.Count <= length; i += (uint)Vector256.Count) + { + ConvertLuma(Vector256.LoadUnsafe(ref source, i), ref Unsafe.Add(ref destination, i)); + } + } + + if (Vector128.IsHardwareAccelerated) + { + for (; i + (uint)Vector128.Count <= length; i += (uint)Vector128.Count) + { + ConvertLuma(Vector128.LoadUnsafe(ref source, i), ref Unsafe.Add(ref destination, i)); + } + } + + for (; i < length; i++) + { + Unsafe.Add(ref destination, i) = ConvertLuma(Unsafe.Add(ref source, i)); + } + } + + /// + /// Converts resampled RGB sums with two fractional bits to U and V samples. + /// + /// Four words for each sample: red, green, blue, and a word that is not read. + /// The U samples. + /// The V samples, one for each U sample. + private static void ConvertToChroma(ReadOnlySpan resampled, Span u, Span v) + { + // Each ulong holds the red, green, blue and alpha words of one sample. Two ulong vectors give one int vector + // of samples. Each stage converts complete groups from where the wider stage stopped. + ref ulong source = ref Unsafe.As(ref MemoryMarshal.GetReference(resampled)); + ref byte uBase = ref MemoryMarshal.GetReference(u); + ref byte vBase = ref MemoryMarshal.GetReference(v); + nuint length = (uint)u.Length; + nuint i = 0; + + if (Vector512.IsHardwareAccelerated) + { + for (; i + (uint)Vector512.Count <= length; i += (uint)Vector512.Count) + { + ConvertChroma( + Vector512.LoadUnsafe(ref source, i), + Vector512.LoadUnsafe(ref source, i + (uint)Vector512.Count), + ref Unsafe.Add(ref uBase, i), + ref Unsafe.Add(ref vBase, i)); + } + } + + if (Vector256.IsHardwareAccelerated) + { + for (; i + (uint)Vector256.Count <= length; i += (uint)Vector256.Count) + { + ConvertChroma( + Vector256.LoadUnsafe(ref source, i), + Vector256.LoadUnsafe(ref source, i + (uint)Vector256.Count), + ref Unsafe.Add(ref uBase, i), + ref Unsafe.Add(ref vBase, i)); + } + } + + if (Vector128.IsHardwareAccelerated) + { + for (; i + (uint)Vector128.Count <= length; i += (uint)Vector128.Count) + { + ConvertChroma( + Vector128.LoadUnsafe(ref source, i), + Vector128.LoadUnsafe(ref source, i + (uint)Vector128.Count), + ref Unsafe.Add(ref uBase, i), + ref Unsafe.Add(ref vBase, i)); + } + } + + // The remaining samples use the identical integer matrix, including the two fractional input bits. + for (; i < length; i++) + { + ulong packed = Unsafe.Add(ref source, i); + int red = (int)(packed & 0xFFFF); + int green = (int)((packed >> 16) & 0xFFFF); + int blue = (int)((packed >> 32) & 0xFFFF); + TOperator.ConvertFromRgb(red, green, blue, 2, out _, out int uValue, out int vValue); + Unsafe.Add(ref uBase, i) = (byte)uValue; + Unsafe.Add(ref vBase, i) = (byte)vValue; + } + } + + /// + public override void ConvertToRgb( + ReadOnlySpan c0, + ReadOnlySpan nearC1, + ReadOnlySpan nearC2, + ReadOnlySpan farC1, + ReadOnlySpan farC2, + Span red, + Span green, + Span blue) + { + ref byte c0Base = ref MemoryMarshal.GetReference(c0); + ref byte nearC1Base = ref MemoryMarshal.GetReference(nearC1); + ref byte nearC2Base = ref MemoryMarshal.GetReference(nearC2); + ref byte farC1Base = ref MemoryMarshal.GetReference(farC1); + ref byte farC2Base = ref MemoryMarshal.GetReference(farC2); + ref byte redBase = ref MemoryMarshal.GetReference(red); + ref byte greenBase = ref MemoryMarshal.GetReference(green); + ref byte blueBase = ref MemoryMarshal.GetReference(blue); + int length = c0.Length; + nuint lastPair = (uint)(length - 1) >> 1; + nuint x = 0; + + // Pixel 0 has no chroma neighbor on its left. + ConvertPixel( + c0Base, + ChromaUpsampler.Edge(nearC1Base, farC1Base), + ChromaUpsampler.Edge(nearC2Base, farC2Base), + ref redBase, + ref greenBase, + ref blueBase, + 0); + + // Chroma pair x gives pixels 2x + 1 and 2x + 2, so one vector of chroma pairs gives one byte vector of pixels. + // The interpolation and the conversion stay in registers: the interpolated chroma bytes widen to 16-bit lanes + // with the luma bytes of the same pixels, the operator converts both halves, and the codes narrow back to bytes. + // Each interpolation also reads the chroma at x + Count, so x + Count stays at or before the last chroma sample. + if (Vector512.IsHardwareAccelerated) + { + for (; x + (uint)Vector512.Count <= lastPair; x += (uint)Vector512.Count) + { + nuint pixel = (2 * x) + 1; + (Vector512 y0, Vector512 y1) = Vector512.Widen(Vector512.LoadUnsafe(ref c0Base, pixel)); + (Vector512 u0, Vector512 u1) = Vector512.Widen( + ChromaUpsampler.Interpolate512(ref Unsafe.Add(ref nearC1Base, x), ref Unsafe.Add(ref farC1Base, x))); + + (Vector512 v0, Vector512 v1) = Vector512.Widen( + ChromaUpsampler.Interpolate512(ref Unsafe.Add(ref nearC2Base, x), ref Unsafe.Add(ref farC2Base, x))); + + TOperator.ConvertToRgb(ref y0, ref u0, ref v0); + TOperator.ConvertToRgb(ref y1, ref u1, ref v1); + Vector512.Narrow(y0, y1).StoreUnsafe(ref redBase, pixel); + Vector512.Narrow(u0, u1).StoreUnsafe(ref greenBase, pixel); + Vector512.Narrow(v0, v1).StoreUnsafe(ref blueBase, pixel); + } + } + + if (Vector256.IsHardwareAccelerated) + { + for (; x + (uint)Vector256.Count <= lastPair; x += (uint)Vector256.Count) + { + nuint pixel = (2 * x) + 1; + (Vector256 y0, Vector256 y1) = Vector256.Widen(Vector256.LoadUnsafe(ref c0Base, pixel)); + (Vector256 u0, Vector256 u1) = Vector256.Widen( + ChromaUpsampler.Interpolate256(ref Unsafe.Add(ref nearC1Base, x), ref Unsafe.Add(ref farC1Base, x))); + + (Vector256 v0, Vector256 v1) = Vector256.Widen( + ChromaUpsampler.Interpolate256(ref Unsafe.Add(ref nearC2Base, x), ref Unsafe.Add(ref farC2Base, x))); + + TOperator.ConvertToRgb(ref y0, ref u0, ref v0); + TOperator.ConvertToRgb(ref y1, ref u1, ref v1); + Vector256.Narrow(y0, y1).StoreUnsafe(ref redBase, pixel); + Vector256.Narrow(u0, u1).StoreUnsafe(ref greenBase, pixel); + Vector256.Narrow(v0, v1).StoreUnsafe(ref blueBase, pixel); + } + } + + if (Vector128.IsHardwareAccelerated) + { + for (; x + (uint)Vector128.Count <= lastPair; x += (uint)Vector128.Count) + { + nuint pixel = (2 * x) + 1; + (Vector128 y0, Vector128 y1) = Vector128.Widen(Vector128.LoadUnsafe(ref c0Base, pixel)); + (Vector128 u0, Vector128 u1) = Vector128.Widen( + ChromaUpsampler.Interpolate128(ref Unsafe.Add(ref nearC1Base, x), ref Unsafe.Add(ref farC1Base, x))); + + (Vector128 v0, Vector128 v1) = Vector128.Widen( + ChromaUpsampler.Interpolate128(ref Unsafe.Add(ref nearC2Base, x), ref Unsafe.Add(ref farC2Base, x))); + + TOperator.ConvertToRgb(ref y0, ref u0, ref v0); + TOperator.ConvertToRgb(ref y1, ref u1, ref v1); + Vector128.Narrow(y0, y1).StoreUnsafe(ref redBase, pixel); + Vector128.Narrow(u0, u1).StoreUnsafe(ref greenBase, pixel); + Vector128.Narrow(v0, v1).StoreUnsafe(ref blueBase, pixel); + } + } + + // Finish the remaining chroma pairs, or the whole row when hardware acceleration is unavailable. + for (; x < lastPair; x++) + { + ChromaUpsampler.Interpolate( + Unsafe.Add(ref nearC1Base, x), + Unsafe.Add(ref nearC1Base, x + 1), + Unsafe.Add(ref farC1Base, x), + Unsafe.Add(ref farC1Base, x + 1), + out int oddC1, + out int evenC1); + + ChromaUpsampler.Interpolate( + Unsafe.Add(ref nearC2Base, x), + Unsafe.Add(ref nearC2Base, x + 1), + Unsafe.Add(ref farC2Base, x), + Unsafe.Add(ref farC2Base, x + 1), + out int oddC2, + out int evenC2); + + nuint pixel = (2 * x) + 1; + ConvertPixel(Unsafe.Add(ref c0Base, pixel), oddC1, oddC2, ref redBase, ref greenBase, ref blueBase, pixel); + ConvertPixel(Unsafe.Add(ref c0Base, pixel + 1), evenC1, evenC2, ref redBase, ref greenBase, ref blueBase, pixel + 1); + } + + // An even width has a last pixel with no chroma neighbor on its right. + if ((length & 1) == 0) + { + nuint pixel = (uint)length - 1; + ConvertPixel( + Unsafe.Add(ref c0Base, pixel), + ChromaUpsampler.Edge(Unsafe.Add(ref nearC1Base, lastPair), Unsafe.Add(ref farC1Base, lastPair)), + ChromaUpsampler.Edge(Unsafe.Add(ref nearC2Base, lastPair), Unsafe.Add(ref farC2Base, lastPair)), + ref redBase, + ref greenBase, + ref blueBase, + pixel); + } + } + + /// + /// Converts one full-resolution native sample to red, green and blue codes. + /// + /// The first native component. + /// The second native component. + /// The third native component. + /// The first red code of the row. + /// The first green code of the row. + /// The first blue code of the row. + /// The pixel index. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ConvertPixel(int c0, int c1, int c2, ref byte red, ref byte green, ref byte blue, nuint pixel) + { + TOperator.ConvertToRgb(ref c0, ref c1, ref c2); + Unsafe.Add(ref red, pixel) = (byte)c0; + Unsafe.Add(ref green, pixel) = (byte)c1; + Unsafe.Add(ref blue, pixel) = (byte)c2; + } + + /// + /// Converts one BGRA pixel to luma. + /// + /// The BGRA pixel read as a uint. + /// The luma code. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static byte ConvertLuma(uint pixel) + { + // Pixel codes have no fractional bits. Static binding and inlining let the JIT discard unused chroma work. + TOperator.ConvertFromRgb((byte)(pixel >> 16), (byte)(pixel >> 8), (byte)pixel, 0, out int luma, out _, out _); + return (byte)luma; + } + + /// + /// Converts sixteen BGRA pixels to luma. + /// + /// Sixteen BGRA pixels, one in each uint lane. + /// The first of sixteen luma bytes. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ConvertLuma(Vector512 pixels, ref byte destination) + { + // A shift moves each channel to bits 0..7 of its lane, and the mask removes the channels above it. + Vector512 mask = Vector512.Create((uint)byte.MaxValue); + Vector512 red = ((pixels >> 16) & mask).AsInt32(); + Vector512 green = ((pixels >> 8) & mask).AsInt32(); + Vector512 blue = (pixels & mask).AsInt32(); + TOperator.ConvertFromRgb(red, green, blue, 0, out Vector512 luma, out _, out _); + StoreConvertedSamples(luma, ref destination); + } + + /// + /// Converts eight BGRA pixels to luma. + /// + /// Eight BGRA pixels, one in each uint lane. + /// The first of eight luma bytes. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ConvertLuma(Vector256 pixels, ref byte destination) + { + // A shift moves each channel to bits 0..7 of its lane, and the mask removes the channels above it. + Vector256 mask = Vector256.Create((uint)byte.MaxValue); + Vector256 red = ((pixels >> 16) & mask).AsInt32(); + Vector256 green = ((pixels >> 8) & mask).AsInt32(); + Vector256 blue = (pixels & mask).AsInt32(); + TOperator.ConvertFromRgb(red, green, blue, 0, out Vector256 luma, out _, out _); + StoreConvertedSamples(luma, ref destination); + } + + /// + /// Converts four BGRA pixels to luma. + /// + /// Four BGRA pixels, one in each uint lane. + /// The first of four luma bytes. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ConvertLuma(Vector128 pixels, ref byte destination) + { + // A shift moves each channel to bits 0..7 of its lane, and the mask removes the channels above it. + Vector128 mask = Vector128.Create((uint)byte.MaxValue); + Vector128 red = ((pixels >> 16) & mask).AsInt32(); + Vector128 green = ((pixels >> 8) & mask).AsInt32(); + Vector128 blue = (pixels & mask).AsInt32(); + TOperator.ConvertFromRgb(red, green, blue, 0, out Vector128 luma, out _, out _); + StoreConvertedSamples(luma, ref destination); + } + + /// + /// Converts sixteen resampled RGB samples to U and V. + /// + /// Samples 0 to 7. Each ulong holds the red, green, blue and alpha words of one sample. + /// Samples 8 to 15, with the same layout. + /// The first of sixteen U bytes. + /// The first of sixteen V bytes. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ConvertChroma(Vector512 first, Vector512 second, ref byte u, ref byte v) + { + // Shift each channel into the low word, then narrow in sample order. The mask removes the other words. + Vector512 mask = Vector512.Create(0xFFFFU); + Vector512 red = (Vector512.Narrow(first, second) & mask).AsInt32(); + Vector512 green = (Vector512.Narrow(first >> 16, second >> 16) & mask).AsInt32(); + Vector512 blue = (Vector512.Narrow(first >> 32, second >> 32) & mask).AsInt32(); + + // Resampling retains two fractional bits. Static binding and inlining let the JIT discard unused luma work. + TOperator.ConvertFromRgb(red, green, blue, 2, out _, out Vector512 uValues, out Vector512 vValues); + StoreConvertedSamples(uValues, ref u); + StoreConvertedSamples(vValues, ref v); + } + + /// + /// Converts eight resampled RGB samples to U and V. + /// + /// Samples 0 to 3. Each ulong holds the red, green, blue and alpha words of one sample. + /// Samples 4 to 7, with the same layout. + /// The first of eight U bytes. + /// The first of eight V bytes. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ConvertChroma(Vector256 first, Vector256 second, ref byte u, ref byte v) + { + // Shift each channel into the low word, then narrow in sample order. The mask removes the other words. + Vector256 mask = Vector256.Create(0xFFFFU); + Vector256 red = (Vector256.Narrow(first, second) & mask).AsInt32(); + Vector256 green = (Vector256.Narrow(first >> 16, second >> 16) & mask).AsInt32(); + Vector256 blue = (Vector256.Narrow(first >> 32, second >> 32) & mask).AsInt32(); + + // Resampling retains two fractional bits. Static binding and inlining let the JIT discard unused luma work. + TOperator.ConvertFromRgb(red, green, blue, 2, out _, out Vector256 uValues, out Vector256 vValues); + StoreConvertedSamples(uValues, ref u); + StoreConvertedSamples(vValues, ref v); + } + + /// + /// Converts four resampled RGB samples to U and V. + /// + /// Samples 0 and 1. Each ulong holds the red, green, blue and alpha words of one sample. + /// Samples 2 and 3, with the same layout. + /// The first of four U bytes. + /// The first of four V bytes. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ConvertChroma(Vector128 first, Vector128 second, ref byte u, ref byte v) + { + // Shift each channel into the low word, then narrow in sample order. The mask removes the other words. + Vector128 mask = Vector128.Create(0xFFFFU); + Vector128 red = (Vector128.Narrow(first, second) & mask).AsInt32(); + Vector128 green = (Vector128.Narrow(first >> 16, second >> 16) & mask).AsInt32(); + Vector128 blue = (Vector128.Narrow(first >> 32, second >> 32) & mask).AsInt32(); + + // Resampling retains two fractional bits. Static binding and inlining let the JIT discard unused luma work. + TOperator.ConvertFromRgb(red, green, blue, 2, out _, out Vector128 uValues, out Vector128 vValues); + StoreConvertedSamples(uValues, ref u); + StoreConvertedSamples(vValues, ref v); + } + + /// + /// Stores sixteen byte-range channel codes in their original sample order. + /// + /// The converted channel values, each in the range 0..255. + /// The first of sixteen output bytes. + private static void StoreConvertedSamples(Vector512 values, ref byte destination) + { + // Reuse the decoder's exact sixteen-sample narrowing; all values already fit in a byte. + Narrow(values).StoreUnsafe(ref destination); + } + + /// + /// Stores eight byte-range channel codes in their original sample order. + /// + /// The converted channel values, each in the range 0..255. + /// The first of eight output bytes. + private static void StoreConvertedSamples(Vector256 values, ref byte destination) + { + Vector128 words = Vector128.Narrow(values.GetLower().AsUInt32(), values.GetUpper().AsUInt32()); + Vector128 bytes = Vector128.Narrow(words, Vector128.Zero); + + // Only the low eight bytes contain samples; an eight-byte store cannot overwrite the following row data. + Unsafe.WriteUnaligned(ref destination, bytes.AsUInt64().ToScalar()); + } + + /// + /// Stores four byte-range channel codes in their original sample order. + /// + /// The converted channel values, each in the range 0..255. + /// The first of four output bytes. + private static void StoreConvertedSamples(Vector128 values, ref byte destination) + { + Vector128 words = Vector128.Narrow(values.AsUInt32(), Vector128.Zero); + Vector128 bytes = Vector128.Narrow(words, Vector128.Zero); + + // Narrowing places the four samples in the low word. Store exactly those four bytes. + Unsafe.WriteUnaligned(ref destination, bytes.AsUInt32().ToScalar()); + } + + /// + /// Loads exactly sixteen byte codes into sixteen integer lanes. + /// + /// The first source byte; the caller supplies all samples required by this load. + /// The loaded byte codes widened into consecutive lanes. + private static Vector512 Load16(ref byte source) + { + Vector128 bytes = Unsafe.ReadUnaligned>(ref source); + (Vector128 lower, Vector128 upper) = Vector128.Widen(bytes); + + // Byte codes are at most 255, so their widened words remain positive when interpreted as signed for this helper. + return Vector512.Create(Vector256_.Widen(lower.AsInt16()), Vector256_.Widen(upper.AsInt16())); + } + + /// + /// Loads exactly eight byte codes into eight integer lanes. + /// + /// The first source byte; the caller supplies all samples required by this load. + /// The loaded byte codes widened into consecutive lanes. + private static Vector256 Load8(ref byte source) + { + Vector128 bytes = Vector128.CreateScalar(Unsafe.ReadUnaligned(ref source)).AsByte(); + (Vector128 lower, _) = Vector128.Widen(bytes); + + // The widened byte codes are 0..255, so the signed word conversion preserves their values. + return Vector256_.Widen(lower.AsInt16()); + } + + /// + /// Loads exactly four byte codes into four integer lanes. + /// + /// The first source byte; the caller supplies all samples required by this load. + /// The loaded byte codes widened into consecutive lanes. + private static Vector128 Load4(ref byte source) + { + Vector128 bytes = Vector128.CreateScalar(Unsafe.ReadUnaligned(ref source)).AsByte(); + (Vector128 lower, _) = Vector128.Widen(bytes); + (Vector128 result, _) = Vector128.Widen(lower); + return result.AsInt32(); + } + + /// + /// Narrows sixteen clipped integer codes without changing their values. + /// + /// Sixteen consecutive channel codes, each in the range 0..255. + /// The sixteen channel codes as bytes, in their original order. + private static Vector128 Narrow(Vector512 value) + { + // The color operator already bounds each code to 0..255. Narrowing removes only zero upper bits and preserves group order. + Vector256 halves = Vector256.Narrow(value.GetLower(), value.GetUpper()); + + return Vector128.Narrow(halves.GetLower().AsUInt16(), halves.GetUpper().AsUInt16()); + } } } diff --git a/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.RgbOperator.cs b/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.RgbOperator.cs index 7472056a66..dc530f064e 100644 --- a/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.RgbOperator.cs +++ b/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.RgbOperator.cs @@ -1,65 +1,54 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. -using System.Numerics; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using System.Runtime.Intrinsics; -using SixLabors.ImageSharp.ColorProfiles; -using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Metadata.Profiles.Icc; namespace SixLabors.ImageSharp.Formats.Webp.ColorConverters; internal abstract partial class WebpColorConverterBase { /// - /// Preserves native RGB sample bytes for the RGB profile converter. + /// Converts the native lossless samples, which are already R, G, B codes. /// internal readonly struct RgbOperator : IWebpColorConverterOperator { /// - public static void ConvertToSamples(ref int c0, ref int c1, ref int c2) - { - // Native RGB already has its destination byte codes. - } + public static WebpColorType ColorType => WebpColorType.Rgba; /// - public static void ConvertToSamples(ref Vector128 c0, ref Vector128 c1, ref Vector128 c2) + public static void ConvertToRgb(ref int c0, ref int c1, ref int c2) { - // Preserve these source channel codes; this operator does not apply the YCbCr-to-BGR matrix. + // Native RGB already has its destination codes. } /// - public static void ConvertToSamples(ref Vector256 c0, ref Vector256 c1, ref Vector256 c2) + public static void ConvertToRgb(ref Vector128 c0, ref Vector128 c1, ref Vector128 c2) { - // Preserve these source channel codes; this operator does not apply the YCbCr-to-BGR matrix. + // Native RGB already has its destination codes. } /// - public static void ConvertToSamples(ref Vector512 c0, ref Vector512 c1, ref Vector512 c2) + public static void ConvertToRgb(ref Vector256 c0, ref Vector256 c1, ref Vector256 c2) { - // Preserve these source channel codes; this operator does not apply the YCbCr-to-BGR matrix. + // Native RGB already has its destination codes. } /// - public static void ConvertSamplesWithIcc( - Configuration configuration, ReadOnlySpan source, ColorProfileConverter converter, Span vectors, Span rgb) + public static void ConvertToRgb(ref Vector512 c0, ref Vector512 c1, ref Vector512 c2) { - // Three-byte decoder output stores B, G, R. The pixel API exposes straight RGB vectors to the ICC transform. - ReadOnlySpan bgr = MemoryMarshal.Cast(source); - PixelOperations.Instance.ToUnassociatedScaledVector4(configuration, bgr, vectors); - converter.Convert(vectors); + // Native RGB already has its destination codes. } /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ConvertFromRgb(int r, int g, int b, int inputShift, out int c0, out int c1, out int c2) { - // The source planes are R, G, B; native packed RGB output uses B, G, R byte order. - // Remove any fractional input bits while preserving that component order. - c0 = b >> inputShift; + // Native RGB keeps the R, G, B order. Remove the fractional input bits. + c0 = r >> inputShift; c1 = g >> inputShift; - c2 = r >> inputShift; + c2 = b >> inputShift; } /// @@ -67,11 +56,10 @@ public static void ConvertFromRgb(int r, int g, int b, int inputShift, out int c public static void ConvertFromRgb( Vector128 r, Vector128 g, Vector128 b, int inputShift, out Vector128 c0, out Vector128 c1, out Vector128 c2) { - // The source planes are R, G, B; native packed RGB output uses B, G, R byte order. - // Remove any fractional input bits while preserving that component order. - c0 = b >> inputShift; + // Native RGB keeps the R, G, B order. Remove the fractional input bits. + c0 = r >> inputShift; c1 = g >> inputShift; - c2 = r >> inputShift; + c2 = b >> inputShift; } /// @@ -79,11 +67,10 @@ public static void ConvertFromRgb( public static void ConvertFromRgb( Vector256 r, Vector256 g, Vector256 b, int inputShift, out Vector256 c0, out Vector256 c1, out Vector256 c2) { - // The source planes are R, G, B; native packed RGB output uses B, G, R byte order. - // Remove any fractional input bits while preserving that component order. - c0 = b >> inputShift; + // Native RGB keeps the R, G, B order. Remove the fractional input bits. + c0 = r >> inputShift; c1 = g >> inputShift; - c2 = r >> inputShift; + c2 = b >> inputShift; } /// @@ -91,11 +78,75 @@ public static void ConvertFromRgb( public static void ConvertFromRgb( Vector512 r, Vector512 g, Vector512 b, int inputShift, out Vector512 c0, out Vector512 c1, out Vector512 c2) { - // The source planes are R, G, B; native packed RGB output uses B, G, R byte order. - // Remove any fractional input bits while preserving that component order. - c0 = b >> inputShift; + // Native RGB keeps the R, G, B order. Remove the fractional input bits. + c0 = r >> inputShift; c1 = g >> inputShift; - c2 = r >> inputShift; + c2 = b >> inputShift; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ConvertToProfile( + int c0, int c1, int c2, float maximum, IccColorSpaceType profileSpace, out float p0, out float p1, out float p2) + { + // The lossless profile describes the stored RGB, so the codes only need the normalization. + p0 = c0 / maximum; + p1 = c1 / maximum; + p2 = c2 / maximum; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ConvertToProfile( + Vector128 c0, + Vector128 c1, + Vector128 c2, + Vector128 maximum, + IccColorSpaceType profileSpace, + out Vector128 p0, + out Vector128 p1, + out Vector128 p2) + { + // The lossless profile describes the stored RGB, so the codes only need the normalization. + p0 = Vector128.ConvertToSingle(c0) / maximum; + p1 = Vector128.ConvertToSingle(c1) / maximum; + p2 = Vector128.ConvertToSingle(c2) / maximum; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ConvertToProfile( + Vector256 c0, + Vector256 c1, + Vector256 c2, + Vector256 maximum, + IccColorSpaceType profileSpace, + out Vector256 p0, + out Vector256 p1, + out Vector256 p2) + { + // The lossless profile describes the stored RGB, so the codes only need the normalization. + p0 = Vector256.ConvertToSingle(c0) / maximum; + p1 = Vector256.ConvertToSingle(c1) / maximum; + p2 = Vector256.ConvertToSingle(c2) / maximum; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ConvertToProfile( + Vector512 c0, + Vector512 c1, + Vector512 c2, + Vector512 maximum, + IccColorSpaceType profileSpace, + out Vector512 p0, + out Vector512 p1, + out Vector512 p2) + { + // The lossless profile describes the stored RGB, so the codes only need the normalization. + p0 = Vector512.ConvertToSingle(c0) / maximum; + p1 = Vector512.ConvertToSingle(c1) / maximum; + p2 = Vector512.ConvertToSingle(c2) / maximum; } } } diff --git a/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.YCbCrIccOperator.cs b/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.YCbCrIccOperator.cs deleted file mode 100644 index 146311f115..0000000000 --- a/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.YCbCrIccOperator.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -using System.Numerics; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Runtime.Intrinsics; -using SixLabors.ImageSharp.ColorProfiles; -using SixLabors.ImageSharp.PixelFormats; - -namespace SixLabors.ImageSharp.Formats.Webp.ColorConverters; - -internal abstract partial class WebpColorConverterBase -{ - /// - /// Preserves native YCbCr samples for a YCbCr source ICC profile. - /// - internal readonly struct YCbCrIccOperator : IWebpColorConverterOperator - { - /// - public static void ConvertToSamples(ref int c0, ref int c1, ref int c2) - { - // Keep interpolated Y, Cb, and Cr codes for the YCbCr profile transform. - } - - /// - public static void ConvertToSamples(ref Vector128 c0, ref Vector128 c1, ref Vector128 c2) - { - // Preserve these source channel codes; this operator does not apply the YCbCr-to-BGR matrix. - } - - /// - public static void ConvertToSamples(ref Vector256 c0, ref Vector256 c1, ref Vector256 c2) - { - // Preserve these source channel codes; this operator does not apply the YCbCr-to-BGR matrix. - } - - /// - public static void ConvertToSamples(ref Vector512 c0, ref Vector512 c1, ref Vector512 c2) - { - // Preserve these source channel codes; this operator does not apply the YCbCr-to-BGR matrix. - } - - /// - public static void ConvertSamplesWithIcc( - Configuration configuration, ReadOnlySpan source, ColorProfileConverter converter, Span vectors, Span rgb) - { - // A YCbCr source profile consumes normalized Y, Cb, Cr codes directly. The two color structs each contain three floats. - // Each block reads three source components before writing three RGB components, so both views can share this storage. - Span yCbCr = MemoryMarshal.Cast(rgb); - SimdUtils.ByteToNormalizedFloat(source, MemoryMarshal.Cast(yCbCr)); - converter.Convert(yCbCr, rgb); - Rgb.ToScaledVector4(rgb, vectors); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ConvertFromRgb(int r, int g, int b, int inputShift, out int c0, out int c1, out int c2) - { - // WebP encodes the same Y, Cb, Cr codes whether decoding later retains them for an ICC transform or converts them to BGR. - YCbCrOperator.ConvertFromRgb(r, g, b, inputShift, out c0, out c1, out c2); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ConvertFromRgb( - Vector128 r, Vector128 g, Vector128 b, int inputShift, out Vector128 c0, out Vector128 c1, out Vector128 c2) - { - // WebP encodes the same Y, Cb, Cr codes whether decoding later retains them for an ICC transform or converts them to BGR. - YCbCrOperator.ConvertFromRgb(r, g, b, inputShift, out c0, out c1, out c2); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ConvertFromRgb( - Vector256 r, Vector256 g, Vector256 b, int inputShift, out Vector256 c0, out Vector256 c1, out Vector256 c2) - { - // WebP encodes the same Y, Cb, Cr codes whether decoding later retains them for an ICC transform or converts them to BGR. - YCbCrOperator.ConvertFromRgb(r, g, b, inputShift, out c0, out c1, out c2); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ConvertFromRgb( - Vector512 r, Vector512 g, Vector512 b, int inputShift, out Vector512 c0, out Vector512 c1, out Vector512 c2) - { - // WebP encodes the same Y, Cb, Cr codes whether decoding later retains them for an ICC transform or converts them to BGR. - YCbCrOperator.ConvertFromRgb(r, g, b, inputShift, out c0, out c1, out c2); - } - } -} diff --git a/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.YCbCrOperator.cs b/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.YCbCrOperator.cs index 52a05b0322..7ff9e1e59e 100644 --- a/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.YCbCrOperator.cs +++ b/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverter.YCbCrOperator.cs @@ -1,19 +1,17 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. -using System.Numerics; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using System.Runtime.Intrinsics; -using SixLabors.ImageSharp.ColorProfiles; -using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Common.Helpers; +using SixLabors.ImageSharp.Metadata.Profiles.Icc; namespace SixLabors.ImageSharp.Formats.Webp.ColorConverters; internal abstract partial class WebpColorConverterBase { /// - /// Converts native lossy YCbCr samples to BGR using the WebP fixed-point matrix. + /// Converts between RGB and the native lossy YCbCr samples with the WebP fixed-point matrix. /// internal readonly struct YCbCrOperator : IWebpColorConverterOperator { @@ -133,81 +131,88 @@ internal abstract partial class WebpColorConverterBase private const int ChromaCenter = 128; /// - public static void ConvertToSamples(ref int c0, ref int c1, ref int c2) + public static WebpColorType ColorType => WebpColorType.Yuv; + + /// + public static void ConvertToRgb(ref int c0, ref int c1, ref int c2) { // WebP's YCbCr matrix uses coefficients scaled by 2^14. The first shift removes eight fractional bits; - // the final shift removes six. Offsets include Y=16, U=V=128 and rounding, producing B, G, R in c0, c1, c2. + // the final shift removes six. Offsets include Y=16, U=V=128 and rounding, producing R, G, B in c0, c1, c2. int y = c0; int u = c1; int v = c2; int luma = (y * YMult) >> DecodeProductShift; // Each product is truncated before the channel terms are combined, as in WebP's scalar decoder. - c0 = Clip((luma + ((u * BCbMult) >> DecodeProductShift) - BOffset) >> DecodeResultShift); - c1 = Clip((luma - ((u * GCbMult) >> DecodeProductShift) - ((v * GCrMult) >> DecodeProductShift) + GOffset) >> DecodeResultShift); - c2 = Clip((luma + ((v * RCrMult) >> DecodeProductShift) - ROffset) >> DecodeResultShift); + c0 = Numerics.ClampToByte((luma + ((v * RCrMult) >> DecodeProductShift) - ROffset) >> DecodeResultShift); + c1 = Numerics.ClampToByte((luma - ((u * GCbMult) >> DecodeProductShift) - ((v * GCrMult) >> DecodeProductShift) + GOffset) >> DecodeResultShift); + c2 = Numerics.ClampToByte((luma + ((u * BCbMult) >> DecodeProductShift) - BOffset) >> DecodeResultShift); } /// - public static void ConvertToSamples(ref Vector128 c0, ref Vector128 c1, ref Vector128 c2) + public static void ConvertToRgb(ref Vector128 c0, ref Vector128 c1, ref Vector128 c2) { - // Each int lane is one pixel. Keep six fractional bits after the first shift, then apply the BGR offsets. - // Arithmetic shifts preserve negative intermediate values so clipping maps them to zero. - Vector128 luma = Vector128.ShiftRightArithmetic(c0 * Vector128.Create(YMult), DecodeProductShift); - - Vector128 uBlue = Vector128.ShiftRightArithmetic(c1 * Vector128.Create(BCbMult), DecodeProductShift); - Vector128 uGreen = Vector128.ShiftRightArithmetic(c1 * Vector128.Create(GCbMult), DecodeProductShift); - Vector128 vGreen = Vector128.ShiftRightArithmetic(c2 * Vector128.Create(GCrMult), DecodeProductShift); - Vector128 vRed = Vector128.ShiftRightArithmetic(c2 * Vector128.Create(RCrMult), DecodeProductShift); - - c0 = Clip(Vector128.ShiftRightArithmetic(luma + uBlue - Vector128.Create(BOffset), DecodeResultShift)); - c1 = Clip(Vector128.ShiftRightArithmetic(luma - uGreen - vGreen + Vector128.Create(GOffset), DecodeResultShift)); - c2 = Clip(Vector128.ShiftRightArithmetic(luma + vRed - Vector128.Create(ROffset), DecodeResultShift)); + // Each 16-bit lane holds one code. A code shifted left by 8 makes the high half of the unsigned product (code * mult) >> 8, the truncated + // product of the scalar form. The red and green sums are from -14234 to 30815, so they fit a signed lane. The blue sum is up to 51923, so it + // uses an unsigned lane, and the saturating subtraction stops at 0, where the scalar form clips a negative value to 0 too. + Vector128 luma = Vector128_.MultiplyHigh(c0 << 8, Vector128.Create((ushort)YMult)); + Vector128 u = c1 << 8; + Vector128 v = c2 << 8; + Vector128 red = (luma + Vector128_.MultiplyHigh(v, Vector128.Create((ushort)RCrMult)) - Vector128.Create((ushort)ROffset)).AsInt16(); + Vector128 uGreen = Vector128_.MultiplyHigh(u, Vector128.Create((ushort)GCbMult)); + Vector128 vGreen = Vector128_.MultiplyHigh(v, Vector128.Create((ushort)GCrMult)); + Vector128 green = (luma + Vector128.Create((ushort)GOffset) - uGreen - vGreen).AsInt16(); + Vector128 uBlue = Vector128_.MultiplyHigh(u, Vector128.Create((ushort)BCbMult)); + Vector128 blue = Vector128.SubtractSaturate(luma + uBlue, Vector128.Create((ushort)BOffset)); + + Vector128 max = Vector128.Create((short)byte.MaxValue); + c0 = Vector128.Clamp(Vector128.ShiftRightArithmetic(red, DecodeResultShift), Vector128.Zero, max).AsUInt16(); + c1 = Vector128.Clamp(Vector128.ShiftRightArithmetic(green, DecodeResultShift), Vector128.Zero, max).AsUInt16(); + c2 = Vector128.Min(Vector128.ShiftRightLogical(blue, DecodeResultShift), Vector128.Create((ushort)byte.MaxValue)); } /// - public static void ConvertToSamples(ref Vector256 c0, ref Vector256 c1, ref Vector256 c2) + public static void ConvertToRgb(ref Vector256 c0, ref Vector256 c1, ref Vector256 c2) { - // Each int lane is one pixel. Keep six fractional bits after the first shift, then apply the BGR offsets. - // Arithmetic shifts preserve negative intermediate values so clipping maps them to zero. - Vector256 luma = Vector256.ShiftRightArithmetic(c0 * Vector256.Create(YMult), DecodeProductShift); - - Vector256 uBlue = Vector256.ShiftRightArithmetic(c1 * Vector256.Create(BCbMult), DecodeProductShift); - Vector256 uGreen = Vector256.ShiftRightArithmetic(c1 * Vector256.Create(GCbMult), DecodeProductShift); - Vector256 vGreen = Vector256.ShiftRightArithmetic(c2 * Vector256.Create(GCrMult), DecodeProductShift); - Vector256 vRed = Vector256.ShiftRightArithmetic(c2 * Vector256.Create(RCrMult), DecodeProductShift); - - c0 = Clip(Vector256.ShiftRightArithmetic(luma + uBlue - Vector256.Create(BOffset), DecodeResultShift)); - c1 = Clip(Vector256.ShiftRightArithmetic(luma - uGreen - vGreen + Vector256.Create(GOffset), DecodeResultShift)); - c2 = Clip(Vector256.ShiftRightArithmetic(luma + vRed - Vector256.Create(ROffset), DecodeResultShift)); + // Each 16-bit lane holds one code. A code shifted left by 8 makes the high half of the unsigned product (code * mult) >> 8, the truncated + // product of the scalar form. The red and green sums are from -14234 to 30815, so they fit a signed lane. The blue sum is up to 51923, so it + // uses an unsigned lane, and the saturating subtraction stops at 0, where the scalar form clips a negative value to 0 too. + Vector256 luma = Vector256_.MultiplyHigh(c0 << 8, Vector256.Create((ushort)YMult)); + Vector256 u = c1 << 8; + Vector256 v = c2 << 8; + Vector256 red = (luma + Vector256_.MultiplyHigh(v, Vector256.Create((ushort)RCrMult)) - Vector256.Create((ushort)ROffset)).AsInt16(); + Vector256 uGreen = Vector256_.MultiplyHigh(u, Vector256.Create((ushort)GCbMult)); + Vector256 vGreen = Vector256_.MultiplyHigh(v, Vector256.Create((ushort)GCrMult)); + Vector256 green = (luma + Vector256.Create((ushort)GOffset) - uGreen - vGreen).AsInt16(); + Vector256 uBlue = Vector256_.MultiplyHigh(u, Vector256.Create((ushort)BCbMult)); + Vector256 blue = Vector256.SubtractSaturate(luma + uBlue, Vector256.Create((ushort)BOffset)); + + Vector256 max = Vector256.Create((short)byte.MaxValue); + c0 = Vector256.Clamp(Vector256.ShiftRightArithmetic(red, DecodeResultShift), Vector256.Zero, max).AsUInt16(); + c1 = Vector256.Clamp(Vector256.ShiftRightArithmetic(green, DecodeResultShift), Vector256.Zero, max).AsUInt16(); + c2 = Vector256.Min(Vector256.ShiftRightLogical(blue, DecodeResultShift), Vector256.Create((ushort)byte.MaxValue)); } /// - public static void ConvertToSamples(ref Vector512 c0, ref Vector512 c1, ref Vector512 c2) - { - // Each int lane is one pixel. Keep six fractional bits after the first shift, then apply the BGR offsets. - // Arithmetic shifts preserve negative intermediate values so clipping maps them to zero. - Vector512 luma = Vector512.ShiftRightArithmetic(c0 * Vector512.Create(YMult), DecodeProductShift); - - Vector512 uBlue = Vector512.ShiftRightArithmetic(c1 * Vector512.Create(BCbMult), DecodeProductShift); - Vector512 uGreen = Vector512.ShiftRightArithmetic(c1 * Vector512.Create(GCbMult), DecodeProductShift); - Vector512 vGreen = Vector512.ShiftRightArithmetic(c2 * Vector512.Create(GCrMult), DecodeProductShift); - Vector512 vRed = Vector512.ShiftRightArithmetic(c2 * Vector512.Create(RCrMult), DecodeProductShift); - - c0 = Clip(Vector512.ShiftRightArithmetic(luma + uBlue - Vector512.Create(BOffset), DecodeResultShift)); - c1 = Clip(Vector512.ShiftRightArithmetic(luma - uGreen - vGreen + Vector512.Create(GOffset), DecodeResultShift)); - c2 = Clip(Vector512.ShiftRightArithmetic(luma + vRed - Vector512.Create(ROffset), DecodeResultShift)); - } - - /// - /// Clamps a signed channel code to the byte range. - /// - /// The signed channel code with no remaining fractional bits. - /// Codes below zero become zero; codes above 255 become 255. Other codes remain unchanged. - private static int Clip(int value) + public static void ConvertToRgb(ref Vector512 c0, ref Vector512 c1, ref Vector512 c2) { - // Clamp before narrowing to byte, which would otherwise wrap out-of-range matrix results. - return Math.Clamp(value, 0, byte.MaxValue); + // Each 16-bit lane holds one code. A code shifted left by 8 makes the high half of the unsigned product (code * mult) >> 8, the truncated + // product of the scalar form. The red and green sums are from -14234 to 30815, so they fit a signed lane. The blue sum is up to 51923, so it + // uses an unsigned lane, and the saturating subtraction stops at 0, where the scalar form clips a negative value to 0 too. + Vector512 luma = Vector512_.MultiplyHigh(c0 << 8, Vector512.Create((ushort)YMult)); + Vector512 u = c1 << 8; + Vector512 v = c2 << 8; + Vector512 red = (luma + Vector512_.MultiplyHigh(v, Vector512.Create((ushort)RCrMult)) - Vector512.Create((ushort)ROffset)).AsInt16(); + Vector512 uGreen = Vector512_.MultiplyHigh(u, Vector512.Create((ushort)GCbMult)); + Vector512 vGreen = Vector512_.MultiplyHigh(v, Vector512.Create((ushort)GCrMult)); + Vector512 green = (luma + Vector512.Create((ushort)GOffset) - uGreen - vGreen).AsInt16(); + Vector512 uBlue = Vector512_.MultiplyHigh(u, Vector512.Create((ushort)BCbMult)); + Vector512 blue = Vector512.SubtractSaturate(luma + uBlue, Vector512.Create((ushort)BOffset)); + + Vector512 max = Vector512.Create((short)byte.MaxValue); + c0 = Vector512.Clamp(Vector512.ShiftRightArithmetic(red, DecodeResultShift), Vector512.Zero, max).AsUInt16(); + c1 = Vector512.Clamp(Vector512.ShiftRightArithmetic(green, DecodeResultShift), Vector512.Zero, max).AsUInt16(); + c2 = Vector512.Min(Vector512.ShiftRightLogical(blue, DecodeResultShift), Vector512.Create((ushort)byte.MaxValue)); } /// @@ -244,13 +249,113 @@ private static Vector512 Clip(Vector512 value) } /// - public static void ConvertSamplesWithIcc( - Configuration configuration, ReadOnlySpan source, ColorProfileConverter converter, Span vectors, Span rgb) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ConvertToProfile( + int c0, int c1, int c2, float maximum, IccColorSpaceType profileSpace, out float p0, out float p1, out float p2) + { + // A YCbCr profile reads the stored Y, Cb, Cr codes. An RGB profile reads RGB after the WebP matrix. + // The matrix clips RGB to the code range, so the normalized components stay in [0, 1]. + if (profileSpace != IccColorSpaceType.YCbCr) + { + ConvertToRgb(ref c0, ref c1, ref c2); + } + + p0 = c0 / maximum; + p1 = c1 / maximum; + p2 = c2 / maximum; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ConvertToProfile( + Vector128 c0, + Vector128 c1, + Vector128 c2, + Vector128 maximum, + IccColorSpaceType profileSpace, + out Vector128 p0, + out Vector128 p1, + out Vector128 p2) + { + // A YCbCr profile reads the stored Y, Cb, Cr codes. An RGB profile reads RGB after the WebP matrix. + // The matrix clips RGB to the code range, so the normalized components stay in [0, 1]. + if (profileSpace != IccColorSpaceType.YCbCr) + { + // The four codes narrow to the low four 16-bit lanes, and the high lanes are 0. + Vector128 s0 = Vector128.Narrow(c0.AsUInt32(), Vector128.Zero); + Vector128 s1 = Vector128.Narrow(c1.AsUInt32(), Vector128.Zero); + Vector128 s2 = Vector128.Narrow(c2.AsUInt32(), Vector128.Zero); + ConvertToRgb(ref s0, ref s1, ref s2); + c0 = Vector128.WidenLower(s0).AsInt32(); + c1 = Vector128.WidenLower(s1).AsInt32(); + c2 = Vector128.WidenLower(s2).AsInt32(); + } + + p0 = Vector128.ConvertToSingle(c0) / maximum; + p1 = Vector128.ConvertToSingle(c1) / maximum; + p2 = Vector128.ConvertToSingle(c2) / maximum; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ConvertToProfile( + Vector256 c0, + Vector256 c1, + Vector256 c2, + Vector256 maximum, + IccColorSpaceType profileSpace, + out Vector256 p0, + out Vector256 p1, + out Vector256 p2) + { + // A YCbCr profile reads the stored Y, Cb, Cr codes. An RGB profile reads RGB after the WebP matrix. + // The matrix clips RGB to the code range, so the normalized components stay in [0, 1]. + if (profileSpace != IccColorSpaceType.YCbCr) + { + // The eight codes narrow to one vector of 16-bit lanes and widen back in the same order. + Vector128 s0 = Vector128.Narrow(c0.GetLower().AsUInt32(), c0.GetUpper().AsUInt32()); + Vector128 s1 = Vector128.Narrow(c1.GetLower().AsUInt32(), c1.GetUpper().AsUInt32()); + Vector128 s2 = Vector128.Narrow(c2.GetLower().AsUInt32(), c2.GetUpper().AsUInt32()); + ConvertToRgb(ref s0, ref s1, ref s2); + c0 = Vector256.Create(Vector128.WidenLower(s0), Vector128.WidenUpper(s0)).AsInt32(); + c1 = Vector256.Create(Vector128.WidenLower(s1), Vector128.WidenUpper(s1)).AsInt32(); + c2 = Vector256.Create(Vector128.WidenLower(s2), Vector128.WidenUpper(s2)).AsInt32(); + } + + p0 = Vector256.ConvertToSingle(c0) / maximum; + p1 = Vector256.ConvertToSingle(c1) / maximum; + p2 = Vector256.ConvertToSingle(c2) / maximum; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ConvertToProfile( + Vector512 c0, + Vector512 c1, + Vector512 c2, + Vector512 maximum, + IccColorSpaceType profileSpace, + out Vector512 p0, + out Vector512 p1, + out Vector512 p2) { - // Three-byte decoder output stores B, G, R. The pixel API exposes straight RGB vectors to the ICC transform. - ReadOnlySpan bgr = MemoryMarshal.Cast(source); - PixelOperations.Instance.ToUnassociatedScaledVector4(configuration, bgr, vectors); - converter.Convert(vectors); + // A YCbCr profile reads the stored Y, Cb, Cr codes. An RGB profile reads RGB after the WebP matrix. + // The matrix clips RGB to the code range, so the normalized components stay in [0, 1]. + if (profileSpace != IccColorSpaceType.YCbCr) + { + // The sixteen codes narrow to one vector of 16-bit lanes and widen back in the same order. + Vector256 s0 = Vector256.Narrow(c0.GetLower().AsUInt32(), c0.GetUpper().AsUInt32()); + Vector256 s1 = Vector256.Narrow(c1.GetLower().AsUInt32(), c1.GetUpper().AsUInt32()); + Vector256 s2 = Vector256.Narrow(c2.GetLower().AsUInt32(), c2.GetUpper().AsUInt32()); + ConvertToRgb(ref s0, ref s1, ref s2); + c0 = Vector512.Create(Vector256.WidenLower(s0), Vector256.WidenUpper(s0)).AsInt32(); + c1 = Vector512.Create(Vector256.WidenLower(s1), Vector256.WidenUpper(s1)).AsInt32(); + c2 = Vector512.Create(Vector256.WidenLower(s2), Vector256.WidenUpper(s2)).AsInt32(); + } + + p0 = Vector512.ConvertToSingle(c0) / maximum; + p1 = Vector512.ConvertToSingle(c1) / maximum; + p2 = Vector512.ConvertToSingle(c2) / maximum; } /// diff --git a/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverterBase.cs b/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverterBase.cs index 791337141c..e2f32f109e 100644 --- a/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverterBase.cs +++ b/src/ImageSharp/Formats/Webp/ColorConverters/WebpColorConverterBase.cs @@ -4,57 +4,39 @@ using System.Numerics; using SixLabors.ImageSharp.ColorProfiles; using SixLabors.ImageSharp.ColorProfiles.Icc; -using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.Metadata.Profiles.Icc; using SixLabors.ImageSharp.PixelFormats; namespace SixLabors.ImageSharp.Formats.Webp.ColorConverters; /// -/// Selects the ordinary or ICC color path from the native WebP sample layout. +/// Converts rows between RGB and the native samples of one WebP color type. /// internal abstract partial class WebpColorConverterBase { - private static readonly WebpColorConverterBase YCbCrConverter = new WebpColorConverter(WebpColorType.Yuv); - private static readonly WebpColorConverterBase YCbCrIccConverter = new WebpColorConverter(WebpColorType.Yuv); - private static readonly WebpColorConverterBase RgbConverter = new WebpColorConverter(WebpColorType.Rgb); - private static readonly WebpColorConverterBase RgbaConverter = new WebpColorConverter(WebpColorType.Rgba); - /// - /// Initializes a new instance of the class. + /// The shared converter for lossy YCbCr samples. /// - /// The native decoded sample layout. - protected WebpColorConverterBase(WebpColorType colorSpace) => this.ColorSpace = colorSpace; + private static readonly WebpColorConverterBase YCbCrConverter = new WebpColorConverter(); /// - /// Gets the native WebP color space. + /// The shared converter for lossless RGB and RGBA samples. /// - public WebpColorType ColorSpace { get; } + private static readonly WebpColorConverterBase RgbConverter = new WebpColorConverter(); /// - /// Gets the converter for the actual decoded sample layout. + /// Gets the converter for a WebP color type. /// - /// The native decoded sample layout. + /// The color type of the native samples. /// The matching converter. - public static WebpColorConverterBase GetConverter(WebpColorType colorSpace) - => colorSpace switch + public static WebpColorConverterBase GetConverter(WebpColorType colorType) + => colorType switch { WebpColorType.Yuv => YCbCrConverter, - WebpColorType.Rgb => RgbConverter, - WebpColorType.Rgba => RgbaConverter, - _ => throw new InvalidImageContentException($"Unsupported WebP color space {colorSpace}.") + WebpColorType.Rgb or WebpColorType.Rgba => RgbConverter, + _ => throw new InvalidImageContentException($"Unsupported WebP color type {colorType}.") }; - /// - /// Gets the converter for native YCbCr samples and the selected source profile. - /// - /// The configured ICC converter, if present. - /// The converter that writes BGR or preserves YCbCr for its source profile. - public static WebpColorConverterBase GetYCbCrConverter(ColorProfileConverter? converter) - => converter?.Options.SourceIccProfile?.Header.DataColorSpace == IccColorSpaceType.YCbCr - ? YCbCrIccConverter - : YCbCrConverter; - /// /// Creates the conversion from an embedded profile to sRGB when required. /// @@ -79,112 +61,135 @@ public static WebpColorConverterBase GetYCbCrConverter(ColorProfileConverter? co } /// - /// Converts an image region to full-resolution luma and half-resolution chroma planes using the YCbCr converter. + /// Converts two rows of BGRA pixels to two luma rows and one half-resolution chroma row. /// - /// The source pixel format. - /// The source image region. - /// The pixel conversion configuration. - /// The allocator for temporary row storage. - /// The return transform from sRGB to the encoded RGB profile, or null. - /// Reusable straight RGBA row scratch, empty when no transform is required. - /// Reusable RGB transform scratch, empty when no transform is required. - /// The full-resolution luma plane. - /// The half-resolution Cb chroma plane. - /// The half-resolution Cr chroma plane. - /// Whether any source pixel is non-opaque. - public abstract bool ConvertFromRgb( - Buffer2DRegion frame, - Configuration configuration, - MemoryAllocator memoryAllocator, - ColorProfileConverter? converter, - Span vectors, - Span rgb, - Span y, + /// + /// Each chroma sample is the linear-light average of a 2x2 group of pixels. An odd width ends with a group of one column. + /// + /// The first source row. + /// The second source row. For the last row of an odd height, it is the first row again. + /// Whether the chroma average weights each pixel by its alpha. + /// The luma of the first row. + /// The luma of the second row, or empty when the second row has no output. + /// The U samples, one for each 2x2 group. + /// The V samples, one for each 2x2 group. + public abstract void ConvertFromRgb( + ReadOnlySpan row0, + ReadOnlySpan row1, + bool weightByAlpha, + Span y0, + Span y1, Span u, - Span v) - where TPixel : unmanaged, IPixel; + Span v); /// - /// Upsamples native lossy YCbCr rows into the converter's three-channel byte layout. + /// Converts one output row to red, green and blue planes. The second and third components are at half resolution: + /// the conversion interpolates them from the two nearest component rows in the same loop. /// - /// The current luma row. - /// The next luma row, or empty for a single output row. - /// The preceding chroma row. - /// The preceding second chroma row. - /// The current chroma row. - /// The current second chroma row. - /// The first output row. - /// The second output row, or empty for a single output row. - /// The number of luma samples in each row. - /// Scratch storage for four 64-byte interpolated chroma planes. - public abstract void UpSample( - Span topY, - Span bottomY, - Span topU, - Span topV, - Span curU, - Span curV, - Span topDestination, - Span bottomDestination, - int length, - Span uvBuffer); + /// The first native component of each pixel of the output row. + /// The half-resolution second component row nearer to the output row. + /// The half-resolution third component row nearer to the output row. + /// The other half-resolution second component row. + /// The other half-resolution third component row. + /// The red codes. + /// The green codes. + /// The blue codes. + public abstract void ConvertToRgb( + ReadOnlySpan c0, + ReadOnlySpan nearC1, + ReadOnlySpan nearC2, + ReadOnlySpan farC1, + ReadOnlySpan farC2, + Span red, + Span green, + Span blue); /// - /// Converts an RGB source row and packs its destination pixels. + /// Converts full-resolution native rows through the source profile to straight RGBA vectors. /// - /// The source RGB pixel format. - /// The destination pixel format. - /// The pixel conversion configuration. - /// The source row in its pixel format's alpha representation. - /// The configured ICC converter, or null for direct conversion. - /// Vector scratch for the row. - /// RGB scratch for the row. - /// The destination pixels. - public abstract void ConvertRgbRow( - Configuration configuration, - ReadOnlySpan source, - ColorProfileConverter? converter, - Span vectors, - Span rgb, - Span destination) - where TPixelFrom : unmanaged, IPixel - where TPixelTo : unmanaged, IPixel; + /// The first native component of each pixel. + /// The second native component of each pixel. + /// The third native component of each pixel. + /// The alpha codes, or empty for opaque pixels. + /// The configured ICC converter. + /// The straight RGBA vectors, one for each pixel. + public abstract void ConvertToRgb( + ReadOnlySpan c0, + ReadOnlySpan c1, + ReadOnlySpan c2, + ReadOnlySpan alpha, + ColorProfileConverter converter, + Span destination); /// - /// Converts native lossy YCbCr output and packs the destination pixels. + /// Converts decoded BGRA pixels through the source profile to straight RGBA vectors. /// - /// The destination pixel format. - /// The decoding configuration. - /// The interpolated native three-channel row. - /// The separate alpha row, or empty for opaque pixels. - /// The configured ICC converter, if present. - /// Vector scratch for the row. - /// RGB scratch for the row. - /// The destination pixels. - public abstract void ConvertYuvRow( - Configuration configuration, - ReadOnlySpan source, - ReadOnlySpan alpha, - ColorProfileConverter? converter, - Span vectors, - Span rgb, - Span destination) - where TPixel : unmanaged, IPixel; + /// The decoded BGRA pixels. Each pixel holds the native components and alpha. + /// The configured ICC converter. + /// The straight RGBA vectors, one for each pixel. + public abstract void ConvertToRgb(ReadOnlySpan source, ColorProfileConverter converter, Span destination); /// - /// Converts between RGB pixels and native WebP samples using the selected operator. + /// Converts straight source vectors through the encoded profile to the BGRA pixels that the encoders read. /// - /// The scalar and SIMD color conversion operator. - private sealed partial class WebpColorConverter : WebpColorConverterBase - where TOperator : struct, IWebpColorConverterOperator + /// The configuration that the pixel packer uses. + /// The straight RGBA vectors. The conversion changes them in place. + /// The return transform from sRGB to the encoded RGB profile. + /// The BGRA pixels, one for each vector. + public static void ConvertFromRgb(Configuration configuration, Span source, ColorProfileConverter converter, Span destination) { - /// - /// Initializes a new instance of the class. - /// - /// The native decoded sample layout. - public WebpColorConverter(WebpColorType colorSpace) - : base(colorSpace) + // The encoder selects only RGB profiles, so the transform gives the R, G and B components that the encoders read. + // W stays alpha. Thus, no model transform is necessary, and the pixel packer scales and rounds each component to a byte. + converter.Convert(source); + PixelOperations.Instance.FromUnassociatedScaledVector4Destructive(configuration, source, destination); + } + + /// + /// Converts one row of source pixels to the BGRA pixels that the lossless and lossy encoders read. + /// + /// + /// Without a profile transform and without the clear, the pixels convert directly to BGRA. Otherwise, they go through straight RGBA vectors. + /// As in the BMP, JPEG and JXL encoders, the clear tests the alpha of the source pixels, before the profile transform and before the + /// conversion to 8 bits. Thus a source alpha that is not zero keeps its RGB values, also when it rounds to zero in Bgra32. + /// + /// The type of the source pixels. + /// The configuration that the pixel operations use. + /// The source pixels. + /// The return transform from sRGB to the encoded RGB profile, or null. + /// Whether pixels with zero alpha get all components set to zero. + /// + /// Straight RGBA scratch with one vector for each source pixel. It can be empty when there is no transform and no clear. + /// + /// The BGRA pixels, one for each source pixel. + public static void ConvertSourceToBgra( + Configuration configuration, + ReadOnlySpan source, + ColorProfileConverter? converter, + bool clearTransparentPixels, + Span vectors, + Span destination) + where TPixel : unmanaged, IPixel + { + if (converter is null && !clearTransparentPixels) + { + PixelOperations.Instance.ToBgra32(configuration, source, destination); + return; + } + + Span row = vectors[..source.Length]; + PixelOperations.Instance.ToUnassociatedScaledVector4(configuration, source, row); + if (clearTransparentPixels) + { + EncodingUtilities.ReplaceTransparentPixels(row); + } + + if (converter is null) + { + PixelOperations.Instance.FromUnassociatedScaledVector4Destructive(configuration, row, destination); + } + else { + ConvertFromRgb(configuration, row, converter, destination); } } } diff --git a/src/ImageSharp/Formats/Webp/EntropyIx.cs b/src/ImageSharp/Formats/Webp/EntropyIndex.cs similarity index 91% rename from src/ImageSharp/Formats/Webp/EntropyIx.cs rename to src/ImageSharp/Formats/Webp/EntropyIndex.cs index e1dcf218ad..3bca0c6392 100644 --- a/src/ImageSharp/Formats/Webp/EntropyIx.cs +++ b/src/ImageSharp/Formats/Webp/EntropyIndex.cs @@ -6,7 +6,7 @@ namespace SixLabors.ImageSharp.Formats.Webp; /// /// These five modes are evaluated and their respective entropy is computed. /// -internal enum EntropyIx : byte +internal enum EntropyIndex : byte { Direct = 0, diff --git a/src/ImageSharp/Formats/Webp/HistoIx.cs b/src/ImageSharp/Formats/Webp/HistoIx.cs deleted file mode 100644 index 1d84494fd9..0000000000 --- a/src/ImageSharp/Formats/Webp/HistoIx.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp; - -internal enum HistoIx : byte -{ - HistoAlpha = 0, - - HistoAlphaPred, - - HistoGreen, - - HistoGreenPred, - - HistoRed, - - HistoRedPred, - - HistoBlue, - - HistoBluePred, - - HistoRedSubGreen, - - HistoRedPredSubGreen, - - HistoBlueSubGreen, - - HistoBluePredSubGreen, - - HistoPalette, - - HistoTotal -} diff --git a/src/ImageSharp/Formats/Webp/HistogramIndex.cs b/src/ImageSharp/Formats/Webp/HistogramIndex.cs new file mode 100644 index 0000000000..c2cdc6c080 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/HistogramIndex.cs @@ -0,0 +1,81 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.ImageSharp.Formats.Webp; + +/// +/// Identifies the 256-entry histograms that the lossless encoder fills to estimate the entropy of each transform mode. +/// Each value is the index of one histogram in a buffer of histograms. +/// +internal enum HistogramIndex : byte +{ + /// + /// The histogram of the alpha values. + /// + HistoAlpha = 0, + + /// + /// The histogram of the alpha differences to the previous pixel. + /// + HistoAlphaPred, + + /// + /// The histogram of the green values. + /// + HistoGreen, + + /// + /// The histogram of the green differences to the previous pixel. + /// + HistoGreenPred, + + /// + /// The histogram of the red values. + /// + HistoRed, + + /// + /// The histogram of the red differences to the previous pixel. + /// + HistoRedPred, + + /// + /// The histogram of the blue values. + /// + HistoBlue, + + /// + /// The histogram of the blue differences to the previous pixel. + /// + HistoBluePred, + + /// + /// The histogram of the red values after the subtract green transform. + /// + HistoRedSubGreen, + + /// + /// The histogram of the red differences to the previous pixel after the subtract green transform. + /// + HistoRedPredSubGreen, + + /// + /// The histogram of the blue values after the subtract green transform. + /// + HistoBlueSubGreen, + + /// + /// The histogram of the blue differences to the previous pixel after the subtract green transform. + /// + HistoBluePredSubGreen, + + /// + /// The histogram of a pixel hash. Its entropy approximates the cost of a palette. + /// + HistoPalette, + + /// + /// The number of histograms. + /// + HistoTotal +} diff --git a/src/ImageSharp/Formats/Webp/Lossless/BackwardReferenceEncoder.cs b/src/ImageSharp/Formats/Webp/Lossless/BackwardReferenceEncoder.cs index eb862aea81..f0ff57cb66 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/BackwardReferenceEncoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/BackwardReferenceEncoder.cs @@ -6,6 +6,9 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; +/// +/// Computes the lossless backward references (literals, color cache indices and copies) of an image. +/// internal static class BackwardReferenceEncoder { /// @@ -13,8 +16,14 @@ internal static class BackwardReferenceEncoder /// public const int MaxLengthBits = 12; + /// + /// The start value of an entropy search. It is larger than any real entropy. + /// private const float MaxEntropy = 1e30f; + /// + /// The number of the smallest plane codes that the box LZ77 search uses as window offsets. + /// private const int WindowOffsetsSizeMax = 32; /// @@ -29,106 +38,162 @@ internal static class BackwardReferenceEncoder private const int MinLength = 4; /// - /// Evaluates best possible backward references for specified quality. The input cacheBits to 'GetBackwardReferences' - /// sets the maximum cache bits to use (passing 0 implies disabling the local color cache). - /// The optimal cache bits is evaluated and set for the cacheBits parameter. - /// The return value is the pointer to the best of the two backward refs viz, refs[0] or refs[1]. + /// Finds the best backward references with a color cache and, when is set, also the best backward references + /// without a color cache. /// - public static Vp8LBackwardRefs GetBackwardReferences( + /// + /// Each LZ77 type in gives references without a cache. When is set, their cost + /// is compared first. Then the best cache size is found and the references get the cache codes. The best result of each case is kept. For + /// quality 25 and up, the trace-backwards search then tries to improve the LZ77 results. + /// The method swaps the slots of , so the caller reads the results from the slots after the call. + /// + /// The image width. + /// The image height. + /// The image pixels, at their flat positions. + /// The encoding quality, from 0 to 100. + /// The flags of the LZ77 types to try. + /// The maximum number of color cache bits. 0 disables the color cache. + /// Whether to also find the best references without a color cache. + /// The memory allocator. + /// The hash chain of the image. + /// + /// The reference buffers. Slot 0 gets the best references with a color cache. When is set, slot 1 gets the best + /// references without a color cache, and slot 2 is the working buffer. Else slot 1 is the working buffer. + /// + /// The number of color cache bits of the references in slot 0. 0 means no color cache. + public static void GetBackwardReferences( int width, int height, - ReadOnlySpan bgra, + Buffer2D bgra, uint quality, int lz77TypesToTry, - ref int cacheBits, + int cacheBitsMax, + bool doNotCache, MemoryAllocator memoryAllocator, Vp8LHashChain hashChain, - Vp8LBackwardRefs best, - Vp8LBackwardRefs worst) + Span refs, + out int cacheBitsBest) { - int lz77TypeBest = 0; - double bitCostBest = -1; - int cacheBitsInitial = cacheBits; - Vp8LHashChain? hashChainBox = null; - Vp8LStreaks stats = new(); - Vp8LBitEntropy bitsEntropy = new(); - - ColorCache[] colorCache = new ColorCache[WebpConstants.MaxColorCacheBits + 1]; + // Index 0 of the best values is for a color cache, index 1 for no color cache. + int tmpIndex = doNotCache ? 2 : 1; + int lz77TypeBestCache = 0; + int lz77TypeBestNoCache = 0; + double bitCostBestCache = double.MaxValue; + double bitCostBestNoCache = double.MaxValue; + cacheBitsBest = 0; + + // The box hash chain is for the box LZ77 type only, which runs at most one time. + using Vp8LHashChain? hashChainBox = (lz77TypesToTry & (int)Vp8LLz77Type.Lz77Box) != 0 ? new Vp8LHashChain(memoryAllocator, width, height) : null; + for (int lz77Type = 1; lz77TypesToTry > 0; lz77TypesToTry &= ~lz77Type, lz77Type <<= 1) { - int cacheBitsTmp = cacheBitsInitial; if ((lz77TypesToTry & lz77Type) == 0) { continue; } + Vp8LBackwardReferences tmp = refs[tmpIndex]; switch ((Vp8LLz77Type)lz77Type) { case Vp8LLz77Type.Lz77Rle: - BackwardReferencesRle(width, height, bgra, 0, worst); + BackwardReferencesRle(width, height, memoryAllocator, bgra, 0, tmp); break; case Vp8LLz77Type.Lz77Standard: // Compute LZ77 with no cache (0 bits), as the ideal LZ77 with a color cache is not that different in practice. - BackwardReferencesLz77(width, height, bgra, 0, hashChain, worst); + BackwardReferencesLz77(width, height, memoryAllocator, bgra, 0, hashChain, tmp); break; case Vp8LLz77Type.Lz77Box: - hashChainBox = new Vp8LHashChain(memoryAllocator, width * height); - BackwardReferencesLz77Box(width, height, bgra, 0, hashChain, hashChainBox, worst); + BackwardReferencesLz77Box(width, height, bgra, 0, memoryAllocator, hashChain, hashChainBox!, tmp); break; } + // The case without a color cache comes first: the color cache step below changes the working references. + double bitCostNoCache = 0; + if (doNotCache) + { + using OwnedVp8LHistogram histo = OwnedVp8LHistogram.Create(memoryAllocator, tmp, 0); + bitCostNoCache = histo.EstimateBits(); + if (bitCostNoCache < bitCostBestNoCache) + { + // A copy, not a swap: the color cache step below must start from these references. + tmp.CopyTo(refs[1]); + bitCostBestNoCache = bitCostNoCache; + lz77TypeBestNoCache = lz77Type; + } + } + // Next, try with a color cache and update the references. - cacheBitsTmp = CalculateBestCacheSize(memoryAllocator, colorCache, bgra, quality, worst, cacheBitsTmp); - if (cacheBitsTmp > 0) + int cacheBits = CalculateBestCacheSize(memoryAllocator, bgra, quality, tmp, cacheBitsMax); + if (cacheBits > 0) { - BackwardRefsWithLocalCache(bgra, cacheBitsTmp, worst); + BackwardRefsWithLocalCache(memoryAllocator, bgra, cacheBits, tmp); } - // Keep the best backward references. - using OwnedVp8LHistogram histo = OwnedVp8LHistogram.Create(memoryAllocator, worst, cacheBitsTmp); - double bitCost = histo.EstimateBits(stats, bitsEntropy); + double bitCost; + if (doNotCache && cacheBits == 0) + { + // The references did not change, so the cost of the case without a color cache applies. + bitCost = bitCostNoCache; + } + else + { + using OwnedVp8LHistogram histo = OwnedVp8LHistogram.Create(memoryAllocator, tmp, cacheBits); + bitCost = histo.EstimateBits(); + } - if (lz77TypeBest == 0 || bitCost < bitCostBest) + if (bitCost < bitCostBestCache) { - (best, worst) = (worst, best); - bitCostBest = bitCost; - cacheBits = cacheBitsTmp; - lz77TypeBest = lz77Type; + (refs[0], refs[tmpIndex]) = (refs[tmpIndex], refs[0]); + bitCostBestCache = bitCost; + lz77TypeBestCache = lz77Type; + cacheBitsBest = cacheBits; } } - // Improve on simple LZ77 but only for high quality (TraceBackwards is costly). - if ((lz77TypeBest == (int)Vp8LLz77Type.Lz77Standard || lz77TypeBest == (int)Vp8LLz77Type.Lz77Box) && quality >= 25) + // Improve on simple LZ77 but only for high quality (TraceBackwards is costly). The case without a color cache comes first, as above. + for (int i = doNotCache ? 1 : 0; i >= 0; i--) { - Vp8LHashChain hashChainTmp = lz77TypeBest == (int)Vp8LLz77Type.Lz77Standard ? hashChain : hashChainBox!; - BackwardReferencesTraceBackwards(width, height, memoryAllocator, bgra, cacheBits, hashChainTmp, best, worst); - using OwnedVp8LHistogram histo = OwnedVp8LHistogram.Create(memoryAllocator, worst, cacheBits); - double bitCostTrace = histo.EstimateBits(stats, bitsEntropy); - if (bitCostTrace < bitCostBest) + int lz77TypeBest = i == 1 ? lz77TypeBestNoCache : lz77TypeBestCache; + double bitCostBest = i == 1 ? bitCostBestNoCache : bitCostBestCache; + if ((lz77TypeBest == (int)Vp8LLz77Type.Lz77Standard || lz77TypeBest == (int)Vp8LLz77Type.Lz77Box) && quality >= 25) { - best = worst; + Vp8LHashChain hashChainTmp = lz77TypeBest == (int)Vp8LLz77Type.Lz77Standard ? hashChain : hashChainBox!; + int cacheBits = i == 1 ? 0 : cacheBitsBest; + BackwardReferencesTraceBackwards(width, height, memoryAllocator, bgra, cacheBits, hashChainTmp, refs[i], refs[tmpIndex]); + using OwnedVp8LHistogram histo = OwnedVp8LHistogram.Create(memoryAllocator, refs[tmpIndex], cacheBits); + double bitCostTrace = histo.EstimateBits(); + if (bitCostTrace < bitCostBest) + { + (refs[i], refs[tmpIndex]) = (refs[tmpIndex], refs[i]); + } } - } - - BackwardReferences2DLocality(width, best); - hashChainBox?.Dispose(); + BackwardReferences2DLocality(width, refs[i]); - return best; + if (i == 1 && lz77TypeBestCache == lz77TypeBestNoCache && cacheBitsBest == 0) + { + // The best case with a color cache uses no cache and the same LZ77 type, so both results are the same. + refs[1].CopyTo(refs[0]); + break; + } + } } /// - /// Evaluate optimal cache bits for the local color cache. - /// The input bestCacheBits sets the maximum cache bits to use (passing 0 implies disabling the local color cache). - /// The local color cache is also disabled for the lower (smaller then 25) quality. + /// Finds the number of color cache bits that gives the smallest entropy for the references. + /// A quality of 25 or less disables the color cache. /// - /// Best cache size. + /// The memory allocator. + /// The image pixels, at their flat positions. + /// The encoding quality, from 0 to 100. + /// The backward references without a color cache. + /// The maximum number of cache bits. 0 disables the color cache. + /// The best number of cache bits, from 0 to . private static int CalculateBestCacheSize( MemoryAllocator memoryAllocator, - Span colorCache, - ReadOnlySpan bgra, + Buffer2D bgra, uint quality, - Vp8LBackwardRefs refs, + Vp8LBackwardReferences refs, int bestCacheBits) { int cacheBitsMax = quality <= 25 ? 0 : bestCacheBits; @@ -141,93 +206,111 @@ private static int CalculateBestCacheSize( double entropyMin = MaxEntropy; int pos = 0; - using Vp8LHistogramSet histos = new(memoryAllocator, colorCache.Length, 0); - for (int i = 0; i < colorCache.Length; i++) + // Each histogram has the size for cacheBitsMax, which is the largest cache size of the search. + // The histograms count the literals directly, so they must start at zero. + // The set has at most 12 histograms, so one buffer holds it. + using Vp8LHistogramSet histos = new(memoryAllocator, cacheBitsMax + 1, cacheBitsMax, AllocationOptions.Clean, true); + for (int i = 0; i <= cacheBitsMax; i++) { histos[i].PaletteCodeBits = i; - colorCache[i] = new ColorCache(i); } - // Find the cacheBits giving the lowest entropy. - foreach (PixOrCopy v in refs) - { - if (v.IsLiteral()) - { - uint pix = bgra[pos++]; - int a = (int)(pix >> 24) & 0xff; - int r = (int)(pix >> 16) & 0xff; - int g = (int)(pix >> 8) & 0xff; - int b = (int)(pix >> 0) & 0xff; - - // The keys of the caches can be derived from the longest one. - int key = ColorCache.HashPix(pix, 32 - cacheBitsMax); + // The caches of 1 to cacheBitsMax bits are in one pooled buffer: cache i has 1 << i values at offset (1 << i) - 1. The caches start empty. + using IMemoryOwner cacheOwner = memoryAllocator.Allocate((2 << cacheBitsMax) - 1, AllocationOptions.Clean); + Span caches = cacheOwner.GetSpan(); - // Do not use the color cache for cacheBits = 0. - ++histos[0].Blue[b]; - ++histos[0].Literal[g]; - ++histos[0].Red[r]; - ++histos[0].Alpha[a]; + // Find the cacheBits giving the lowest entropy. All histograms have the size for cacheBitsMax, so histogram i + // starts at i * histogramSize in the memory of the set. Get that memory once, not once for each pixel. + Span histogramData = histos.Buffer; + int histogramSize = histos.HistogramSize; - // Deal with cacheBits > 0. - for (int i = cacheBitsMax; i >= 1; --i, key >>= 1) + // The pixels are read in order, so the plane read gets a new buffer only at a buffer end. + Span pixels = default; + int pixelsStart = 0; + int blockCount = refs.BlockCount; + for (int block = 0; block < blockCount; block++) + { + foreach (PixelOrCopy v in refs.GetBlock(block)) + { + if (v.IsLiteral()) { - if (colorCache[i].Lookup(key) == pix) - { - ++histos[i].Literal[WebpConstants.NumLiteralCodes + WebpConstants.NumLengthCodes + key]; - } - else + uint pix = LosslessUtils.GetPlaneValue(bgra, pos++, ref pixels, ref pixelsStart); + int a = (int)(pix >> 24) & 0xff; + int r = (int)(pix >> 16) & 0xff; + int g = (int)(pix >> 8) & 0xff; + int b = (int)(pix >> 0) & 0xff; + + // The keys of the caches can be derived from the longest one. + int key = ColorCache.HashPix(pix, 32 - cacheBitsMax); + + // Do not use the color cache for cacheBits = 0. + ++histogramData[Vp8LHistogram.BlueOffset + b]; + ++histogramData[Vp8LHistogram.LiteralOffset + g]; + ++histogramData[Vp8LHistogram.RedOffset + r]; + ++histogramData[Vp8LHistogram.AlphaOffset + a]; + + // Deal with cacheBits > 0. + for (int i = cacheBitsMax; i >= 1; --i, key >>= 1) { - colorCache[i].Set((uint)key, pix); - ++histos[i].Blue[b]; - ++histos[i].Literal[g]; - ++histos[i].Red[r]; - ++histos[i].Alpha[a]; + int histogramStart = i * histogramSize; + ref uint cached = ref caches[(1 << i) - 1 + key]; + if (cached == pix) + { + ++histogramData[histogramStart + Vp8LHistogram.LiteralOffset + WebpConstants.NumLiteralCodes + WebpConstants.NumLengthCodes + key]; + } + else + { + cached = pix; + ++histogramData[histogramStart + Vp8LHistogram.BlueOffset + b]; + ++histogramData[histogramStart + Vp8LHistogram.LiteralOffset + g]; + ++histogramData[histogramStart + Vp8LHistogram.RedOffset + r]; + ++histogramData[histogramStart + Vp8LHistogram.AlphaOffset + a]; + } } } - } - else - { - // We should compute the contribution of the (distance, length) - // histograms but those are the same independently from the cache size. - // As those constant contributions are in the end added to the other - // histogram contributions, we can ignore them, except for the length - // prefix that is part of the literal_ histogram. - int len = v.Len; - uint bgraPrev = bgra[pos] ^ 0xffffffffu; - - int extraBits = 0, extraBitsValue = 0; - int code = LosslessUtils.PrefixEncode(len, ref extraBits, ref extraBitsValue); - for (int i = 0; i <= cacheBitsMax; i++) + else { - ++histos[i].Literal[WebpConstants.NumLiteralCodes + code]; - } + // We should compute the contribution of the (distance, length) + // histograms but those are the same independently from the cache size. + // As those constant contributions are in the end added to the other + // histogram contributions, we can ignore them, except for the length + // prefix that is part of the literal_ histogram. + int len = v.Len; + uint bgraPrev = LosslessUtils.GetPlaneValue(bgra, pos, ref pixels, ref pixelsStart) ^ 0xffffffffu; + + int extraBits = 0, extraBitsValue = 0; + int code = LosslessUtils.PrefixEncode(len, ref extraBits, ref extraBitsValue); + for (int i = 0; i <= cacheBitsMax; i++) + { + ++histogramData[(i * histogramSize) + Vp8LHistogram.LiteralOffset + WebpConstants.NumLiteralCodes + code]; + } - // Update the color caches. - do - { - if (bgra[pos] != bgraPrev) + // Update the color caches. + do { - // Efficiency: insert only if the color changes. - int key = ColorCache.HashPix(bgra[pos], 32 - cacheBitsMax); - for (int i = cacheBitsMax; i >= 1; --i, key >>= 1) + uint pixel = LosslessUtils.GetPlaneValue(bgra, pos, ref pixels, ref pixelsStart); + if (pixel != bgraPrev) { - colorCache[i].Colors[key] = bgra[pos]; + // Efficiency: insert only if the color changes. + int key = ColorCache.HashPix(pixel, 32 - cacheBitsMax); + for (int i = cacheBitsMax; i >= 1; --i, key >>= 1) + { + caches[(1 << i) - 1 + key] = pixel; + } + + bgraPrev = pixel; } - bgraPrev = bgra[pos]; + pos++; } - - pos++; + while (--len != 0); } - while (--len != 0); } } - Vp8LStreaks stats = new(); - Vp8LBitEntropy bitsEntropy = new(); for (int i = 0; i <= cacheBitsMax; i++) { - double entropy = histos[i].EstimateBits(stats, bitsEntropy); + double entropy = histos[i].EstimateBits(); if (i == 0 || entropy < entropyMin) { entropyMin = entropy; @@ -238,71 +321,167 @@ private static int CalculateBestCacheSize( return bestCacheBits; } + /// + /// Finds the token sequence with the lowest estimated cost and writes it to the destination. + /// The cost model comes from the source references. The search uses the matches of the hash chain. + /// + /// The image width. + /// The image height. + /// The memory allocator. + /// The BGRA pixels, at their flat positions. + /// The number of color cache bits. 0 disables the color cache. + /// The hash chain with the best match at each pixel. + /// The references that give the cost model. + /// Receives the new references. private static void BackwardReferencesTraceBackwards( int xSize, int ySize, MemoryAllocator memoryAllocator, - ReadOnlySpan bgra, + Buffer2D bgra, int cacheBits, Vp8LHashChain hashChain, - Vp8LBackwardRefs refsSrc, - Vp8LBackwardRefs refsDst) + Vp8LBackwardReferences refsSrc, + Vp8LBackwardReferences refsDst) { + // The plane has one token length for each pixel. It comes from the pool in buffers of whole rows, so a large image causes no + // unpooled memory. No clear: the search writes the length of each pixel before the trace reads it. int distArraySize = xSize * ySize; - using IMemoryOwner distArrayBuffer = memoryAllocator.Allocate(distArraySize); - Span distArray = distArrayBuffer.GetSpan(); + using Buffer2D distArray = memoryAllocator.Allocate2D(xSize, ySize); - BackwardReferencesHashChainDistanceOnly(xSize, ySize, memoryAllocator, bgra, cacheBits, hashChain, refsSrc, distArrayBuffer); + BackwardReferencesHashChainDistanceOnly(xSize, ySize, memoryAllocator, bgra, cacheBits, hashChain, refsSrc, distArray); int chosenPathSize = TraceBackwards(distArray, distArraySize); - Span chosenPath = distArray[(distArraySize - chosenPathSize)..]; - BackwardReferencesHashChainFollowChosenPath(bgra, cacheBits, chosenPath, chosenPathSize, hashChain, refsDst); + int chosenPathStart = distArraySize - chosenPathSize; + BackwardReferencesHashChainFollowChosenPath(memoryAllocator, bgra, cacheBits, distArray, chosenPathStart, chosenPathSize, hashChain, refsDst); } + /// + /// Computes the minimum cost to reach each pixel, as a shortest path search over literals, cache indices and hash chain copies. + /// For each pixel, it stores the length of the last token on the cheapest path that ends at that pixel. + /// + /// The image width. + /// The image height. + /// The memory allocator. + /// The BGRA pixels, at their flat positions. + /// The number of color cache bits. 0 disables the color cache. + /// The hash chain with the best match at each pixel. + /// The references that give the cost model. + /// Receives the length of the last token of the cheapest path to each pixel, at the flat position of the pixel. private static void BackwardReferencesHashChainDistanceOnly( int xSize, int ySize, MemoryAllocator memoryAllocator, - ReadOnlySpan bgra, + Buffer2D bgra, int cacheBits, Vp8LHashChain hashChain, - Vp8LBackwardRefs refs, - IMemoryOwner distArrayBuffer) + Vp8LBackwardReferences refs, + Buffer2D distArray) { int pixCount = xSize * ySize; bool useColorCache = cacheBits > 0; int literalArraySize = WebpConstants.NumLiteralCodes + WebpConstants.NumLengthCodes + (cacheBits > 0 ? 1 << cacheBits : 0); - CostModel costModel = new(memoryAllocator, literalArraySize); + + // The five cost tables of the cost model are slices of one pooled buffer. + // No clear: CostModel.Build writes each entry of each table before any read. + const int valuesInBytes = CostModel.ValuesInBytes; + using IMemoryOwner costTablesBuffer = memoryAllocator.Allocate((3 * valuesInBytes) + WebpConstants.NumDistanceCodes + literalArraySize); + Span costTables = costTablesBuffer.GetSpan(); + Span alphaCosts = costTables[..valuesInBytes]; + Span redCosts = costTables.Slice(valuesInBytes, valuesInBytes); + Span blueCosts = costTables.Slice(2 * valuesInBytes, valuesInBytes); + Span distanceCosts = costTables.Slice(3 * valuesInBytes, WebpConstants.NumDistanceCodes); + Span literalCosts = costTables.Slice((3 * valuesInBytes) + WebpConstants.NumDistanceCodes, literalArraySize); int offsetPrev = -1; int lenPrev = -1; double offsetCost = -1; int firstOffsetIsConstant = -1; // initialized with 'impossible' value. int reach = 0; - ColorCache? colorCache = null; - if (useColorCache) - { - colorCache = new ColorCache(cacheBits); - } - - costModel.Build(xSize, cacheBits, refs); - using CostManager costManager = new(memoryAllocator, distArrayBuffer, pixCount, costModel); - Span costManagerCosts = costManager.Costs.GetSpan(); - Span distArray = distArrayBuffer.GetSpan(); - - // We loop one pixel at a time, but store all currently best points to non-processed locations from this point. - distArray[0] = 0; + // The color cache has at most 2^11 values, so it comes from the pool. The owner lives for the pass. A new cache holds zeros. + using IMemoryOwner? colorCacheOwner = useColorCache ? memoryAllocator.Allocate(1 << cacheBits, AllocationOptions.Clean) : null; + Span cacheColors = useColorCache ? colorCacheOwner!.GetSpan() : default; + int cacheShift = 32 - cacheBits; + + CostModel.Build(memoryAllocator, xSize, cacheBits, refs, alphaCosts, redCosts, blueCosts, distanceCosts, literalCosts); + Buffer2D offsetLength = hashChain.OffsetLength; + + // The search reads the pixels and the hash chain entries in order. The reach loop reads entries ahead of the current pixel, + // so it has its own buffer. + Span pixels = default; + int pixelsStart = 0; + Span entries = default; + int entriesStart = 0; + Span reachEntries = default; + int reachEntriesStart = 0; + Span lengths = default; + int lengthsStart = 0; + + // The cost manager buffers live for the search. No clear: each entry is written before it is read. + // The cost cache holds the cost of each copy length that can occur. + int costCacheSize = pixCount > MaxLength ? MaxLength : pixCount; + using IMemoryOwner costCacheBuffer = memoryAllocator.Allocate(costCacheSize); + Span costCache = costCacheBuffer.GetSpan()[..costCacheSize]; + int cacheIntervalsSize = CostManager.BuildCostCache(literalCosts, costCache); + + using IMemoryOwner cacheIntervalsBuffer = memoryAllocator.Allocate(cacheIntervalsSize); + Span cacheIntervals = cacheIntervalsBuffer.GetSpan()[..cacheIntervalsSize]; + CostManager.BuildCacheIntervals(costCache, cacheIntervals); + + // The interval pool starts with all intervals in the free list and no stored interval. + using IMemoryOwner intervalsBuffer = memoryAllocator.Allocate(CostManager.CostCacheIntervalSizeMax); + Span intervals = intervalsBuffer.GetSpan()[..CostManager.CostCacheIntervalSizeMax]; + int freeIntervals = CostManager.BuildFreeList(intervals); + int intervalHead = CostManager.None; + + // The search keeps the cost and the token length of each pixel in rings of CostManager.RingSize entries, at the index + // position & CostManager.RingMask. CostManager.RingSize explains why the ring holds all pixels that the search can read or write. + // Each pixel starts with a high cost, because the search keeps the minimum. The search writes each token length to the ring + // first. When the step of pixel i ends, no later step changes pixel i - 1, so its token length goes to the plane. + using IMemoryOwner costsBuffer = memoryAllocator.Allocate(CostManager.RingSize); + Span costs = costsBuffer.GetSpan()[..CostManager.RingSize]; + costs.Fill(1e38f); + using IMemoryOwner lengthsBuffer = memoryAllocator.Allocate(CostManager.RingSize); + Span lengthRing = lengthsBuffer.GetSpan()[..CostManager.RingSize]; // Add first pixel as literal. - AddSingleLiteralWithCostModel(bgra, colorCache, costModel, 0, useColorCache, 0.0f, costManagerCosts, distArray); + AddSingleLiteralWithCostModel( + LosslessUtils.GetPlaneValue(bgra, 0, ref pixels, ref pixelsStart), + cacheColors, + cacheShift, + alphaCosts, + redCosts, + blueCosts, + literalCosts, + 0, + useColorCache, + 0.0f, + costs, + lengthRing); for (int i = 1; i < pixCount; i++) { - float prevCost = costManagerCosts[i - 1]; - int offset = hashChain.FindOffset(i); - int len = hashChain.FindLength(i); + // A pixel enters the reach of the search CostManager.RingAhead pixels before the current pixel. Its ring entry belonged to a + // pixel that the search no longer reads, so it gets the start cost now. + costs[(i + CostManager.RingAhead) & CostManager.RingMask] = 1e38f; + + float prevCost = costs[(i - 1) & CostManager.RingMask]; + uint entry = LosslessUtils.GetPlaneValue(offsetLength, i, ref entries, ref entriesStart); + int offset = Vp8LHashChain.FindOffset(entry); + int len = Vp8LHashChain.FindLength(entry); // Try adding the pixel as a literal. - AddSingleLiteralWithCostModel(bgra, colorCache, costModel, i, useColorCache, prevCost, costManagerCosts, distArray); + AddSingleLiteralWithCostModel( + LosslessUtils.GetPlaneValue(bgra, i, ref pixels, ref pixelsStart), + cacheColors, + cacheShift, + alphaCosts, + redCosts, + blueCosts, + literalCosts, + i, + useColorCache, + prevCost, + costs, + lengthRing); // If we are dealing with a non-literal. if (len >= 2) @@ -310,14 +489,24 @@ private static void BackwardReferencesHashChainDistanceOnly( if (offset != offsetPrev) { int code = DistanceToPlaneCode(xSize, offset); - offsetCost = costModel.GetDistanceCost(code); + offsetCost = CostModel.GetDistanceCost(distanceCosts, code); firstOffsetIsConstant = 1; - costManager.PushInterval(prevCost + offsetCost, i, len); + CostManager.PushInterval( + intervals, + ref intervalHead, + ref freeIntervals, + cacheIntervals, + costCache, + costs, + lengthRing, + prevCost + offsetCost, + i, + len); } else { // Instead of considering all contributions from a pixel i by calling: - // costManager.PushInterval(prevCost + offsetCost, i, len); + // CostManager.PushInterval(..., prevCost + offsetCost, i, len); // we optimize these contributions in case offsetCost stays the same // for consecutive pixels. This describes a set of pixels similar to a // previous set (e.g. constant color regions). @@ -333,79 +522,134 @@ private static void BackwardReferencesHashChainDistanceOnly( int j; for (j = i; j <= reach; j++) { - int offsetJ = hashChain.FindOffset(j + 1); - lenJ = hashChain.FindLength(j + 1); + uint entryJ = LosslessUtils.GetPlaneValue(offsetLength, j + 1, ref reachEntries, ref reachEntriesStart); + int offsetJ = Vp8LHashChain.FindOffset(entryJ); + lenJ = Vp8LHashChain.FindLength(entryJ); if (offsetJ != offset) { - lenJ = hashChain.FindLength(j); + lenJ = Vp8LHashChain.FindLength(LosslessUtils.GetPlaneValue(offsetLength, j, ref reachEntries, ref reachEntriesStart)); break; } } // Update the cost at j - 1 and j. - costManager.UpdateCostAtIndex(j - 1, false); - costManager.UpdateCostAtIndex(j, false); + CostManager.UpdateCostAtIndex(intervals, ref intervalHead, ref freeIntervals, costs, lengthRing, j - 1, false); + CostManager.UpdateCostAtIndex(intervals, ref intervalHead, ref freeIntervals, costs, lengthRing, j, false); + + CostManager.PushInterval( + intervals, + ref intervalHead, + ref freeIntervals, + cacheIntervals, + costCache, + costs, + lengthRing, + costs[(j - 1) & CostManager.RingMask] + offsetCost, + j, + lenJ); - costManager.PushInterval(costManagerCosts[j - 1] + offsetCost, j, lenJ); reach = j + lenJ - 1; } } } - costManager.UpdateCostAtIndex(i, true); + CostManager.UpdateCostAtIndex(intervals, ref intervalHead, ref freeIntervals, costs, lengthRing, i, true); offsetPrev = offset; lenPrev = len; + + // No later step changes pixel i - 1. + LosslessUtils.GetPlaneValue(distArray, i - 1, ref lengths, ref lengthsStart) = lengthRing[(i - 1) & CostManager.RingMask]; } + + LosslessUtils.GetPlaneValue(distArray, pixCount - 1, ref lengths, ref lengthsStart) = lengthRing[(pixCount - 1) & CostManager.RingMask]; } - private static int TraceBackwards(Span distArray, int distArraySize) + /// + /// Follows the token lengths back from the last pixel to build the cheapest path. + /// The path is written in forward order at the end of the array. + /// + /// + /// The token length of the cheapest path to each pixel, at the flat position of the pixel. On return, the end holds the chosen path. + /// + /// The number of pixels. + /// The number of tokens in the chosen path. + private static int TraceBackwards(Buffer2D distArray, int distArraySize) { + // The path position is never below the current position, so the path overwrites only lengths that the trace has read. + Span current = default; + int currentStart = 0; + Span path = default; + int pathStart = 0; int chosenPathSize = 0; int pathPos = distArraySize; int curPos = distArraySize - 1; while (curPos >= 0) { - ushort cur = distArray[curPos]; + ushort cur = LosslessUtils.GetPlaneValue(distArray, curPos, ref current, ref currentStart); pathPos--; chosenPathSize++; - distArray[pathPos] = cur; + LosslessUtils.GetPlaneValue(distArray, pathPos, ref path, ref pathStart) = cur; curPos -= cur; } return chosenPathSize; } + /// + /// Creates the references for a chosen path. A length of 1 gives a literal or a cache index. Other lengths give a copy with the hash chain offset. + /// + /// The memory allocator of the color cache. + /// The BGRA pixels, at their flat positions. + /// The number of color cache bits. 0 disables the color cache. + /// The plane that holds the token lengths of the path in forward order. + /// The flat position of the first token length of the path. + /// The number of tokens in the path. + /// The hash chain with the best match at each pixel. + /// Receives the references. private static void BackwardReferencesHashChainFollowChosenPath( - ReadOnlySpan bgra, + MemoryAllocator memoryAllocator, + Buffer2D bgra, int cacheBits, - ReadOnlySpan chosenPath, + Buffer2D chosenPath, + int chosenPathStart, int chosenPathSize, Vp8LHashChain hashChain, - Vp8LBackwardRefs backwardRefs) + Vp8LBackwardReferences backwardRefs) { bool useColorCache = cacheBits > 0; - ColorCache? colorCache = null; - int i = 0; - if (useColorCache) - { - colorCache = new ColorCache(cacheBits); - } + // The color cache has at most 2^11 values, so it comes from the pool. The owner lives for the pass. A new cache holds zeros. + using IMemoryOwner? colorCacheOwner = useColorCache ? memoryAllocator.Allocate(1 << cacheBits, AllocationOptions.Clean) : null; + Span cacheColors = useColorCache ? colorCacheOwner!.GetSpan() : default; + int cacheShift = 32 - cacheBits; + Buffer2D offsetLength = hashChain.OffsetLength; + int i = 0; - backwardRefs.Clear(); + // The path, the pixels and the hash chain entries are read in order. + Span path = default; + int pathStart = 0; + Span pixels = default; + int pixelsStart = 0; + Span entries = default; + int entriesStart = 0; + + // Get the token storage one time for each block. Each path step adds one token. + Span tokens = backwardRefs.BeginWrite(); + int tokenCount = 0; for (int ix = 0; ix < chosenPathSize; ix++) { - int len = chosenPath[ix]; + PixelOrCopy v; + int len = LosslessUtils.GetPlaneValue(chosenPath, chosenPathStart + ix, ref path, ref pathStart); if (len != 1) { - int offset = hashChain.FindOffset(i); - backwardRefs.Add(PixOrCopy.CreateCopy((uint)offset, (ushort)len)); + int offset = Vp8LHashChain.FindOffset(LosslessUtils.GetPlaneValue(offsetLength, i, ref entries, ref entriesStart)); + v = PixelOrCopy.CreateCopy((uint)offset, (ushort)len); if (useColorCache) { for (int k = 0; k < len; k++) { - colorCache!.Insert(bgra[i + k]); + ColorCache.Insert(cacheColors, cacheShift, LosslessUtils.GetPlaneValue(bgra, i + k, ref pixels, ref pixelsStart)); } } @@ -413,34 +657,63 @@ private static void BackwardReferencesHashChainFollowChosenPath( } else { - PixOrCopy v; - int idx = useColorCache ? colorCache!.Contains(bgra[i]) : -1; + uint pixel = LosslessUtils.GetPlaneValue(bgra, i, ref pixels, ref pixelsStart); + int idx = useColorCache ? ColorCache.Contains(cacheColors, cacheShift, pixel) : -1; if (idx >= 0) { - // useColorCache is true and color cache contains bgra[i] + // useColorCache is true and color cache contains the pixel. // Push pixel as a color cache index. - v = PixOrCopy.CreateCacheIdx(idx); + v = PixelOrCopy.CreateCacheIdx(idx); } else { if (useColorCache) { - colorCache!.Insert(bgra[i]); + ColorCache.Insert(cacheColors, cacheShift, pixel); } - v = PixOrCopy.CreateLiteral(bgra[i]); + v = PixelOrCopy.CreateLiteral(pixel); } - backwardRefs.Add(v); i++; } + + if (tokenCount == tokens.Length) + { + tokens = backwardRefs.NextBlock(); + tokenCount = 0; + } + + tokens[tokenCount++] = v; } + + backwardRefs.EndWrite(tokenCount); } + /// + /// Tries to reach a pixel with one literal or cache index from the previous pixel. + /// The cost is updated when this is cheaper than the stored cost. The cost factors are empirical. + /// + /// The BGRA pixel at . + /// The entries of the color cache. They are not read when the color cache is disabled. + /// The shift of the color cache hash: 32 minus the cache bits. + /// The alpha cost table of the cost model. + /// The red cost table of the cost model. + /// The blue cost table of the cost model. + /// The literal cost table of the cost model. It holds the green and color cache index costs. + /// The pixel index. + /// Whether the color cache is enabled. + /// The cost to reach the previous pixel. + /// The ring of the minimum cost to reach each pixel. See . + /// The ring of the token length of the cheapest path to each pixel. private static void AddSingleLiteralWithCostModel( - ReadOnlySpan bgra, - ColorCache? colorCache, - CostModel costModel, + uint color, + Span cacheColors, + int cacheShift, + ReadOnlySpan alphaCosts, + ReadOnlySpan redCosts, + ReadOnlySpan blueCosts, + ReadOnlySpan literalCosts, int idx, bool useColorCache, float prevCost, @@ -448,49 +721,80 @@ private static void AddSingleLiteralWithCostModel( Span distArray) { double costVal = prevCost; - uint color = bgra[idx]; - int ix = useColorCache ? colorCache!.Contains(color) : -1; + int ix = useColorCache ? ColorCache.Contains(cacheColors, cacheShift, color) : -1; if (ix >= 0) { const double mul0 = 0.68; - costVal += costModel.GetCacheCost((uint)ix) * mul0; + costVal += CostModel.GetCacheCost(literalCosts, (uint)ix) * mul0; } else { const double mul1 = 0.82; if (useColorCache) { - colorCache!.Insert(color); + ColorCache.Insert(cacheColors, cacheShift, color); } - costVal += costModel.GetLiteralCost(color) * mul1; + costVal += CostModel.GetLiteralCost(alphaCosts, redCosts, blueCosts, literalCosts, color) * mul1; } - if (cost[idx] > costVal) + int ringIndex = idx & CostManager.RingMask; + if (cost[ringIndex] > costVal) { - cost[idx] = (float)costVal; - distArray[idx] = 1; // only one is inserted. + cost[ringIndex] = (float)costVal; + distArray[ringIndex] = 1; // only one is inserted. } } - private static void BackwardReferencesLz77(int xSize, int ySize, ReadOnlySpan bgra, int cacheBits, Vp8LHashChain hashChain, Vp8LBackwardRefs refs) + /// + /// Computes greedy LZ77 references from the hash chain matches. + /// A match can be shortened when the next match then reaches further. + /// + /// The image width. + /// The image height. + /// The memory allocator of the color cache. + /// The BGRA pixels, at their flat positions. + /// The number of color cache bits. 0 disables the color cache. + /// The hash chain with the best match at each pixel. + /// Receives the references. + private static void BackwardReferencesLz77( + int xSize, + int ySize, + MemoryAllocator memoryAllocator, + Buffer2D bgra, + int cacheBits, + Vp8LHashChain hashChain, + Vp8LBackwardReferences refs) { int iLastCheck = -1; bool useColorCache = cacheBits > 0; int pixCount = xSize * ySize; - ColorCache? colorCache = null; - if (useColorCache) - { - colorCache = new ColorCache(cacheBits); - } - refs.Clear(); + // The color cache has at most 2^11 values, so it comes from the pool. The owner lives for the pass. A new cache holds zeros. + using IMemoryOwner? colorCacheOwner = useColorCache ? memoryAllocator.Allocate(1 << cacheBits, AllocationOptions.Clean) : null; + Span cacheColors = useColorCache ? colorCacheOwner!.GetSpan() : default; + int cacheShift = 32 - cacheBits; + Buffer2D offsetLength = hashChain.OffsetLength; + + // The pixels and the hash chain entries are read in order. The search for a longer reach reads entries ahead of the current pixel, + // so it has its own buffer. + Span pixels = default; + int pixelsStart = 0; + Span entries = default; + int entriesStart = 0; + Span reachEntries = default; + int reachEntriesStart = 0; + + // Get the token storage one time for each block. + Span tokens = refs.BeginWrite(); + int tokenCount = 0; for (int i = 0; i < pixCount;) { // Alternative #1: Code the pixels starting at 'i' using backward reference. int j; - int offset = hashChain.FindOffset(i); - int len = hashChain.FindLength(i); + uint entry = LosslessUtils.GetPlaneValue(offsetLength, i, ref entries, ref entriesStart); + int offset = Vp8LHashChain.FindOffset(entry); + int len = Vp8LHashChain.FindLength(entry); if (len >= MinLength) { int lenIni = len; @@ -508,7 +812,7 @@ private static void BackwardReferencesLz77(int xSize, int ySize, ReadOnlySpan= MinLength ? lenJ : 1); // 1 for single literal. if (reach > maxReach) { @@ -527,67 +831,113 @@ private static void BackwardReferencesLz77(int xSize, int ySize, ReadOnlySpan - /// Compute an LZ77 by forcing matches to happen within a given distance cost. - /// We therefore limit the algorithm to the lowest 32 values in the PlaneCode definition. + /// Computes LZ77 references whose matches have a small distance cost: only the 32 lowest plane codes are used. /// + /// The image width. + /// The image height. + /// The image pixels, at their flat positions. + /// The number of color cache bits. 0 disables the color cache. + /// The memory allocator. + /// The hash chain of the image, with the best match of each pixel. + /// The hash chain that gets the box-limited matches. + /// The references that get the result. private static void BackwardReferencesLz77Box( int xSize, int ySize, - ReadOnlySpan bgra, + Buffer2D bgra, int cacheBits, + MemoryAllocator memoryAllocator, Vp8LHashChain hashChainBest, Vp8LHashChain hashChain, - Vp8LBackwardRefs refs) + Vp8LBackwardReferences refs) { int pixelCount = xSize * ySize; - int[] windowOffsets = new int[WindowOffsetsSizeMax]; - int[] windowOffsetsNew = new int[WindowOffsetsSizeMax]; + + // windowOffsets must start at zero, because a zero entry marks a plane code that no offset reaches. + // The default value of an inline array has every element zero. WindowOffsetsSizeMax is 32. + InlineArray32 windowOffsetsStorage = default; + InlineArray32 windowOffsetsNewStorage = default; + Span windowOffsets = windowOffsetsStorage; + Span windowOffsetsNew = windowOffsetsNewStorage; int windowOffsetsSize = 0; int windowOffsetsNewSize = 0; - short[] counts = new short[xSize * ySize]; + + // No clear: the loop below writes every entry of counts. The plane comes from the pool in buffers of whole rows, so a large + // image causes no unpooled memory. + using Buffer2D counts = memoryAllocator.Allocate2D(xSize, ySize); + Buffer2D bestOffsetLength = hashChainBest.OffsetLength; int bestOffsetPrev = -1; int bestLengthPrev = -1; + // Each plane read keeps the buffer of its last position. The reads at the current pixel and at the window offsets go to + // different places, so each has its own buffer. + Span pixels = default; + int pixelsStart = 0; + Span windowPixels = default; + int windowPixelsStart = 0; + Span currentCounts = default; + int currentCountsStart = 0; + Span windowCounts = default; + int windowCountsStart = 0; + Span bestEntries = default; + int bestEntriesStart = 0; + Span entries = default; + int entriesStart = 0; + // counts[i] counts how many times a pixel is repeated starting at position i. int i = pixelCount - 2; - int countsPos = i; - counts[countsPos + 1] = 1; - for (; i >= 0; --i, --countsPos) + short nextCount = 1; + LosslessUtils.GetPlaneValue(counts, i + 1, ref currentCounts, ref currentCountsStart) = nextCount; + uint nextPixel = LosslessUtils.GetPlaneValue(bgra, i + 1, ref pixels, ref pixelsStart); + for (; i >= 0; --i) { - if (bgra[i] == bgra[i + 1]) + uint pixel = LosslessUtils.GetPlaneValue(bgra, i, ref pixels, ref pixelsStart); + if (pixel == nextPixel) { // Max out the counts to MaxLength. - counts[countsPos] = counts[countsPos + 1]; - if (counts[countsPos + 1] != MaxLength) + if (nextCount != MaxLength) { - counts[countsPos]++; + nextCount++; } } else { - counts[countsPos] = 1; + nextCount = 1; } + + LosslessUtils.GetPlaneValue(counts, i, ref currentCounts, ref currentCountsStart) = nextCount; + nextPixel = pixel; } // Figure out the window offsets around a pixel. They are stored in a @@ -642,19 +992,20 @@ private static void BackwardReferencesLz77Box( } } - Span hashChainOffsetLength = hashChain.OffsetLength.GetSpan(); - hashChainOffsetLength[0] = 0; + Buffer2D hashChainOffsetLength = hashChain.OffsetLength; + LosslessUtils.GetPlaneValue(hashChainOffsetLength, 0, ref entries, ref entriesStart) = 0; for (i = 1; i < pixelCount; i++) { int ind; - int bestLength = hashChainBest.FindLength(i); + uint bestEntry = LosslessUtils.GetPlaneValue(bestOffsetLength, i, ref bestEntries, ref bestEntriesStart); + int bestLength = Vp8LHashChain.FindLength(bestEntry); int bestOffset = 0; bool doCompute = true; if (bestLength >= MaxLength) { // Do not recompute the best match if we already have a maximal one in the window. - bestOffset = hashChainBest.FindOffset(i); + bestOffset = Vp8LHashChain.FindOffset(bestEntry); for (ind = 0; ind < windowOffsetsSize; ind++) { if (bestOffset == windowOffsets[ind]) @@ -680,7 +1031,9 @@ private static void BackwardReferencesLz77Box( int currLength = 0; int j = i; int jOffset = usePrev ? i - windowOffsetsNew[ind] : i - windowOffsets[ind]; - if (jOffset < 0 || bgra[jOffset] != bgra[i]) + if (jOffset < 0 + || LosslessUtils.GetPlaneValue(bgra, jOffset, ref windowPixels, ref windowPixelsStart) + != LosslessUtils.GetPlaneValue(bgra, i, ref pixels, ref pixelsStart)) { continue; } @@ -688,8 +1041,8 @@ private static void BackwardReferencesLz77Box( // The longest match is the sum of how many times each pixel is repeated. do { - int countsJOffset = counts[jOffset]; - int countsJ = counts[j]; + int countsJOffset = LosslessUtils.GetPlaneValue(counts, jOffset, ref windowCounts, ref windowCountsStart); + int countsJ = LosslessUtils.GetPlaneValue(counts, j, ref currentCounts, ref currentCountsStart); if (countsJOffset != countsJ) { currLength += countsJOffset < countsJ ? countsJOffset : countsJ; @@ -701,7 +1054,10 @@ private static void BackwardReferencesLz77Box( jOffset += countsJOffset; j += countsJOffset; } - while (currLength <= MaxLength && j < pixelCount && bgra[jOffset] == bgra[j]); + while (currLength <= MaxLength + && j < pixelCount + && LosslessUtils.GetPlaneValue(bgra, jOffset, ref windowPixels, ref windowPixelsStart) + == LosslessUtils.GetPlaneValue(bgra, j, ref pixels, ref pixelsStart)); if (bestLength < currLength) { @@ -719,46 +1075,74 @@ private static void BackwardReferencesLz77Box( if (bestLength <= MinLength) { - hashChainOffsetLength[i] = 0; + LosslessUtils.GetPlaneValue(hashChainOffsetLength, i, ref entries, ref entriesStart) = 0; bestOffsetPrev = 0; bestLengthPrev = 0; } else { - hashChainOffsetLength[i] = (uint)((bestOffset << MaxLengthBits) | bestLength); + LosslessUtils.GetPlaneValue(hashChainOffsetLength, i, ref entries, ref entriesStart) = (uint)((bestOffset << MaxLengthBits) | bestLength); bestOffsetPrev = bestOffset; bestLengthPrev = bestLength; } } - hashChainOffsetLength[0] = 0; - BackwardReferencesLz77(xSize, ySize, bgra, cacheBits, hashChain, refs); + LosslessUtils.GetPlaneValue(hashChainOffsetLength, 0, ref entries, ref entriesStart) = 0; + BackwardReferencesLz77(xSize, ySize, memoryAllocator, bgra, cacheBits, hashChain, refs); } - private static void BackwardReferencesRle(int xSize, int ySize, ReadOnlySpan bgra, int cacheBits, Vp8LBackwardRefs refs) + /// + /// Computes references that use only copies from the previous pixel or from the pixel above. + /// + /// The image width. + /// The image height. + /// The memory allocator of the color cache. + /// The BGRA pixels, at their flat positions. + /// The number of color cache bits. 0 disables the color cache. + /// Receives the references. + private static void BackwardReferencesRle( + int xSize, + int ySize, + MemoryAllocator memoryAllocator, + Buffer2D bgra, + int cacheBits, + Vp8LBackwardReferences refs) { int pixelCount = xSize * ySize; bool useColorCache = cacheBits > 0; - ColorCache? colorCache = null; - if (useColorCache) - { - colorCache = new ColorCache(cacheBits); - } + // The color cache has at most 2^11 values, so it comes from the pool. The owner lives for the pass. A new cache holds zeros. + using IMemoryOwner? colorCacheOwner = useColorCache ? memoryAllocator.Allocate(1 << cacheBits, AllocationOptions.Clean) : null; + Span cacheColors = useColorCache ? colorCacheOwner!.GetSpan() : default; + int cacheShift = 32 - cacheBits; + + // The current pixels, the previous pixels and the pixels above are read in order, each with its own buffer. + Span pixels = default; + int pixelsStart = 0; + Span left = default; + int leftStart = 0; + Span above = default; + int aboveStart = 0; - refs.Clear(); + // Get the token storage one time for each block. A block holds at least one token, so the first literal fits. + Span tokens = refs.BeginWrite(); + int tokenCount = 0; // Add first pixel as literal. - AddSingleLiteral(bgra[0], useColorCache, colorCache, refs); + tokens[tokenCount++] = CreateSingleLiteral(LosslessUtils.GetPlaneValue(bgra, 0, ref pixels, ref pixelsStart), useColorCache, cacheColors, cacheShift); int i = 1; while (i < pixelCount) { + PixelOrCopy v; int maxLen = LosslessUtils.MaxFindCopyLength(pixelCount - i); - int rleLen = LosslessUtils.FindMatchLength(bgra[i..], bgra[(i - 1)..], 0, maxLen); - int prevRowLen = i < xSize ? 0 : LosslessUtils.FindMatchLength(bgra[i..], bgra[(i - xSize)..], 0, maxLen); + int rleLen = LosslessUtils.FindMatchLength(bgra, i, i - 1, 0, maxLen, ref pixels, ref pixelsStart, ref left, ref leftStart); + int prevRowLen = i < xSize + ? 0 + : LosslessUtils.FindMatchLength(bgra, i, i - xSize, 0, maxLen, ref pixels, ref pixelsStart, ref above, ref aboveStart); + if (rleLen >= prevRowLen && rleLen >= MinLength) { - refs.Add(PixOrCopy.CreateCopy(1, (ushort)rleLen)); + v = PixelOrCopy.CreateCopy(1, (ushort)rleLen); // We don't need to update the color cache here since it is always the // same pixel being copied, and that does not change the color cache state. @@ -766,12 +1150,12 @@ private static void BackwardReferencesRle(int xSize, int ySize, ReadOnlySpan= MinLength) { - refs.Add(PixOrCopy.CreateCopy((uint)xSize, (ushort)prevRowLen)); + v = PixelOrCopy.CreateCopy((uint)xSize, (ushort)prevRowLen); if (useColorCache) { for (int k = 0; k < prevRowLen; ++k) { - colorCache!.Insert(bgra[i + k]); + ColorCache.Insert(cacheColors, cacheShift, LosslessUtils.GetPlaneValue(bgra, i + k, ref pixels, ref pixelsStart)); } } @@ -779,85 +1163,135 @@ private static void BackwardReferencesRle(int xSize, int ySize, ReadOnlySpan - /// Update (in-place) backward references for the specified cacheBits. + /// Replaces the literals that the color cache holds with cache index tokens, in place. /// - private static void BackwardRefsWithLocalCache(ReadOnlySpan bgra, int cacheBits, Vp8LBackwardRefs refs) + /// The memory allocator of the color cache. + /// The image pixels, at their flat positions. + /// The number of color cache bits. + /// The backward references to update. + private static void BackwardRefsWithLocalCache(MemoryAllocator memoryAllocator, Buffer2D bgra, int cacheBits, Vp8LBackwardReferences refs) { + // The pixels are read in order, so the plane read gets a new buffer only at a buffer end. + Span pixels = default; + int pixelsStart = 0; int pixelIndex = 0; - ColorCache colorCache = new(cacheBits); - foreach (ref PixOrCopy v in refs) + + // A new cache holds zeros. + using IMemoryOwner colorCacheOwner = memoryAllocator.Allocate(1 << cacheBits, AllocationOptions.Clean); + Span cacheColors = colorCacheOwner.GetSpan(); + int cacheShift = 32 - cacheBits; + int blockCount = refs.BlockCount; + for (int block = 0; block < blockCount; block++) { - if (v.IsLiteral()) + foreach (ref PixelOrCopy v in refs.GetBlock(block)) { - uint bgraLiteral = v.BgraOrDistance; - int ix = colorCache.Contains(bgraLiteral); - if (ix >= 0) + if (v.IsLiteral()) { - // Color cache contains bgraLiteral - v = PixOrCopy.CreateCacheIdx(ix); + uint bgraLiteral = v.BgraOrDistance; + int ix = ColorCache.Contains(cacheColors, cacheShift, bgraLiteral); + if (ix >= 0) + { + // Color cache contains bgraLiteral + v = PixelOrCopy.CreateCacheIdx(ix); + } + else + { + ColorCache.Insert(cacheColors, cacheShift, bgraLiteral); + } + + pixelIndex++; } else { - colorCache.Insert(bgraLiteral); - } - - pixelIndex++; - } - else - { - // refs was created without local cache, so it can not have cache indexes. - for (int k = 0; k < v.Len; ++k) - { - colorCache.Insert(bgra[pixelIndex++]); + // refs was created without local cache, so it can not have cache indexes. + for (int k = 0; k < v.Len; ++k) + { + ColorCache.Insert(cacheColors, cacheShift, LosslessUtils.GetPlaneValue(bgra, pixelIndex++, ref pixels, ref pixelsStart)); + } } } } } - private static void BackwardReferences2DLocality(int xSize, Vp8LBackwardRefs refs) + /// + /// Converts the pixel distance of each copy to its plane code, in place. + /// + /// The image width. + /// The references to convert. + private static void BackwardReferences2DLocality(int xSize, Vp8LBackwardReferences refs) { - foreach (ref PixOrCopy v in refs) + int blockCount = refs.BlockCount; + for (int block = 0; block < blockCount; block++) { - if (v.IsCopy()) + foreach (ref PixelOrCopy v in refs.GetBlock(block)) { - int dist = (int)v.BgraOrDistance; - int transformedDist = DistanceToPlaneCode(xSize, dist); - v = PixOrCopy.CreateCopy((uint)transformedDist, v.Len); + if (v.IsCopy()) + { + int dist = (int)v.BgraOrDistance; + int transformedDist = DistanceToPlaneCode(xSize, dist); + v = PixelOrCopy.CreateCopy((uint)transformedDist, v.Len); + } } } } - private static void AddSingleLiteral(uint pixel, bool useColorCache, ColorCache? colorCache, Vp8LBackwardRefs refs) + /// + /// Creates the token of one pixel: a cache index when the color cache holds the pixel. Otherwise, a literal, and the pixel is stored + /// in the color cache. + /// + /// The BGRA pixel. + /// Whether the color cache is enabled. + /// The entries of the color cache. They are not read when the color cache is disabled. + /// The shift of the color cache hash: 32 minus the cache bits. + /// The token. + private static PixelOrCopy CreateSingleLiteral(uint pixel, bool useColorCache, Span cacheColors, int cacheShift) { - PixOrCopy v; + PixelOrCopy v; if (useColorCache) { - int key = colorCache!.GetIndex(pixel); - if (colorCache.Lookup(key) == pixel) + int key = ColorCache.HashPix(pixel, cacheShift); + if (cacheColors[key] == pixel) { - v = PixOrCopy.CreateCacheIdx(key); + v = PixelOrCopy.CreateCacheIdx(key); } else { - v = PixOrCopy.CreateLiteral(pixel); - colorCache.Set((uint)key, pixel); + v = PixelOrCopy.CreateLiteral(pixel); + cacheColors[key] = pixel; } } else { - v = PixOrCopy.CreateLiteral(pixel); + v = PixelOrCopy.CreateLiteral(pixel); } - refs.Add(v); + return v; } + /// + /// Converts a pixel distance to a distance code. A distance to one of the 120 nearest 2D neighbors gets a code from 1 to 120. + /// Any other distance gets the distance plus 120. + /// + /// The image width. + /// The backward distance in pixels. + /// The distance code. public static int DistanceToPlaneCode(int xSize, int dist) { int yOffset = dist / xSize; diff --git a/src/ImageSharp/Formats/Webp/Lossless/ColorCache.cs b/src/ImageSharp/Formats/Webp/Lossless/ColorCache.cs index e683fb5605..c59e043bd9 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/ColorCache.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/ColorCache.cs @@ -6,86 +6,48 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; /// -/// A small hash-addressed array to store recently used colors, to be able to recall them with shorter codes. +/// Contains the operations of the color cache: a small hash-addressed array of recently used colors, so that a color can be coded as a short index. /// -internal class ColorCache +/// +/// The callers own the entries of the cache and pass them as a span. See the WebP Lossless Bitstream Specification, section "Color Cache Coding": +/// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. +/// +internal static class ColorCache { - private const uint HashMul = 0x1e35a7bdu; - - /// - /// Initializes a new instance of the class. - /// - /// The hashBits determine the size of cache. It will be 1 left shifted by hashBits. - public ColorCache(int hashBits) - { - int hashSize = 1 << hashBits; - this.Colors = new uint[hashSize]; - this.HashBits = hashBits; - this.HashShift = 32 - hashBits; - } - - /// - /// Gets the color entries. - /// - public uint[] Colors { get; } - - /// - /// Gets the hash shift: 32 - hashBits. - /// - public int HashShift { get; } - /// - /// Gets the hash bits. + /// The multiplier of the hash. /// - public int HashBits { get; } - - /// - /// Inserts a new color into the cache. - /// - /// The color to insert. - [MethodImpl(InliningOptions.ShortMethod)] - public void Insert(uint bgra) - { - int key = HashPix(bgra, this.HashShift); - this.Colors[key] = bgra; - } + private const uint HashMul = 0x1e35a7bdu; /// - /// Gets a color for a given key. + /// Stores a color at its key. /// - /// The key to lookup. - /// The color for the key. + /// The entries of the cache: 1 << (32 - ) values. + /// The shift of the hash: 32 minus the cache bits. + /// The color to store. [MethodImpl(InliningOptions.ShortMethod)] - public uint Lookup(int key) => this.Colors[key]; + public static void Insert(Span colors, int shift, uint bgra) => colors[HashPix(bgra, shift)] = bgra; /// - /// Returns the index of the given color. + /// Gets the key of a color when the cache holds the color. /// - /// The color to check. - /// The index of the color in the cache or -1 if its not present. + /// The entries of the cache: 1 << (32 - ) values. + /// The shift of the hash: 32 minus the cache bits. + /// The color to find. + /// The key of the color, or -1 when the entry at the key holds a different color. [MethodImpl(InliningOptions.ShortMethod)] - public int Contains(uint bgra) + public static int Contains(ReadOnlySpan colors, int shift, uint bgra) { - int key = HashPix(bgra, this.HashShift); - return (this.Colors[key] == bgra) ? key : -1; + int key = HashPix(bgra, shift); + return colors[key] == bgra ? key : -1; } /// - /// Gets the index of a color. + /// Gets the cache key of a color: the top bits of its product with the hash multiplier. /// - /// The color. - /// The index for the color. - [MethodImpl(InliningOptions.ShortMethod)] - public int GetIndex(uint bgra) => HashPix(bgra, this.HashShift); - - /// - /// Adds a new color to the cache. - /// - /// The key. - /// The color to add. - [MethodImpl(InliningOptions.ShortMethod)] - public void Set(uint key, uint bgra) => this.Colors[key] = bgra; - + /// The color. + /// The shift: 32 minus the hash bits. + /// The key. [MethodImpl(InliningOptions.ShortMethod)] public static int HashPix(uint argb, int shift) => (int)((argb * HashMul) >> shift); } diff --git a/src/ImageSharp/Formats/Webp/Lossless/ColorSpaceTransformUtils.cs b/src/ImageSharp/Formats/Webp/Lossless/ColorSpaceTransformUtils.cs index 20a7e06a60..7dabb73e4b 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/ColorSpaceTransformUtils.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/ColorSpaceTransformUtils.cs @@ -8,446 +8,266 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; +/// +/// Collects the histograms of the color transform that the encoder uses to choose the color transform multipliers. +/// internal static class ColorSpaceTransformUtils { - public static void CollectColorBlueTransforms(Span bgra, int stride, int tileWidth, int tileHeight, int greenToBlue, int redToBlue, Span histo) + /// + /// Defines the transform of a packed ARGB pixel to one transformed color channel, the index of its histogram bin. + /// + /// + /// Each pixel is one little-endian uint: blue in bits 0..7, green in bits 8..15, red in bits 16..23 and alpha in + /// bits 24..31. A delta is (multiplier * color) >> 5, with both values signed 8-bit. The vector forms put + /// the color in the high byte of the low 16-bit lane of each pixel, which is color * 256, and multiply by + /// , which is multiplier * 8. The signed high multiply then gives + /// (color * multiplier) >> 5. The high 16-bit lane of each pixel is zero, so its product is zero. + /// Only the low byte of the result is kept, so the vector forms give the same index as the scalar form. + /// + private interface IColorIndexOperator { - if (Vector256.IsHardwareAccelerated && tileWidth >= 16) - { - const int span = 16; - Span values = stackalloc ushort[span]; + /// + /// Gets the transformed channel of one pixel. + /// + /// The pixel. + /// The transformed channel, from 0 to 255. + public int Index(uint argb); - // These shuffle masks are safe for use with Avx2.Shuffle because all indices are within their respective 128-bit lanes (0-15 for the low mask, 16-31 for the high mask), - // and all disabled lanes are set to 0xFF to zero those bytes per the vpshufb specification. This guarantees lane-local shuffling with no cross-lane violations. - Vector256 collectColorBlueTransformsShuffleLowMask256 = Vector256.Create( - 255, - 2, - 255, - 6, - 255, - 10, - 255, - 14, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 18, - 255, - 22, - 255, - 26, - 255, - 30, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255); + /// + /// Gets the transformed channel of four pixels. + /// + /// The pixels. + /// The transformed channels, from 0 to 255, one in each lane. + public Vector128 Index(Vector128 argb); - Vector256 collectColorBlueTransformsShuffleHighMask256 = Vector256.Create( - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 2, - 255, - 6, - 255, - 10, - 255, - 14, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 18, - 255, - 22, - 255, - 26, - 255, - 30); + /// + /// Gets the transformed channel of eight pixels. + /// + /// The pixels. + /// The transformed channels, from 0 to 255, one in each lane. + public Vector256 Index(Vector256 argb); - Vector256 collectColorBlueTransformsGreenBlueMask256 = Vector256.Create( - 255, - 255, - 0, - 0, - 255, - 255, - 0, - 0, - 255, - 255, - 0, - 0, - 255, - 255, - 0, - 0, - 255, - 255, - 0, - 0, - 255, - 255, - 0, - 0, - 255, - 255, - 0, - 0, - 255, - 255, - 0, - 0); + /// + /// Gets the transformed channel of sixteen pixels. + /// + /// The pixels. + /// The transformed channels, from 0 to 255, one in each lane. + public Vector512 Index(Vector512 argb); + } - Vector256 collectColorBlueTransformsGreenMask256 = Vector256.Create( - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255); + /// + /// Adds the blue channel of each tile pixel after the color transform to a histogram. + /// + /// The first pixel of the tile. + /// The number of pixels between tile rows. + /// The tile width. + /// The tile height. + /// The green-to-blue multiplier. + /// The red-to-blue multiplier. + /// The histogram with 256 bins. + public static void CollectColorBlueTransforms(Span bgra, int stride, int tileWidth, int tileHeight, int greenToBlue, int redToBlue, Span histo) + => CollectHistogram(bgra, stride, tileWidth, tileHeight, new BlueIndexOperator(greenToBlue, redToBlue), histo); - Vector256 collectColorBlueTransformsBlueMask256 = Vector256.Create( - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0); + /// + /// Adds the red channel of each tile pixel after the color transform to a histogram. + /// + /// The first pixel of the tile. + /// The number of pixels between tile rows. + /// The tile width. + /// The tile height. + /// The green-to-red multiplier. + /// The histogram with 256 bins. + public static void CollectColorRedTransforms(Span bgra, int stride, int tileWidth, int tileHeight, int greenToRed, Span histo) + => CollectHistogram(bgra, stride, tileWidth, tileHeight, new RedIndexOperator(greenToRed), histo); - Vector256 multsr = Vector256.Create(LosslessUtils.Cst5b(redToBlue)); - Vector256 multsg = Vector256.Create(LosslessUtils.Cst5b(greenToBlue)); - for (int y = 0; y < tileHeight; y++) - { - Span srcSpan = bgra[(y * stride)..]; - ref uint inputRef = ref MemoryMarshal.GetReference(srcSpan); - for (nuint x = 0; x <= (uint)tileWidth - span; x += span) - { - nuint input0Idx = x; - nuint input1Idx = x + (span / 2); - Vector256 input0 = Unsafe.As>(ref Unsafe.Add(ref inputRef, input0Idx)).AsByte(); - Vector256 input1 = Unsafe.As>(ref Unsafe.Add(ref inputRef, input1Idx)).AsByte(); - Vector256 r0 = Vector256_.ShufflePerLane(input0, collectColorBlueTransformsShuffleLowMask256); - Vector256 r1 = Vector256_.ShufflePerLane(input1, collectColorBlueTransformsShuffleHighMask256); - Vector256 r = r0 | r1; - Vector256 gb0 = input0 & collectColorBlueTransformsGreenBlueMask256; - Vector256 gb1 = input1 & collectColorBlueTransformsGreenBlueMask256; - Vector256 gb = Vector256_.PackUnsignedSaturate(gb0.AsInt32(), gb1.AsInt32()); - Vector256 g = gb.AsByte() & collectColorBlueTransformsGreenMask256; - Vector256 a = Vector256_.MultiplyHigh(r.AsInt16(), multsr); - Vector256 b = Vector256_.MultiplyHigh(g.AsInt16(), multsg); - Vector256 c = gb.AsByte() - b.AsByte(); - Vector256 d = c - a.AsByte(); - Vector256 e = d & collectColorBlueTransformsBlueMask256; + /// + /// Adds the transformed channel of each tile pixel to a histogram. + /// + /// The channel transform. + /// The first pixel of the tile. + /// The number of pixels between tile rows. + /// The tile width. + /// The tile height. + /// The channel transform and its multipliers. + /// The histogram with 256 bins. + private static void CollectHistogram( + Span bgra, + int stride, + int tileWidth, + int tileHeight, + TOperator operation, + Span histo) + where TOperator : struct, IColorIndexOperator + { + // The bin increments are scalar, so a vector form stores its indices here first. The 16 entries are the lane + // count of the widest vector. + InlineArray16 indices = default; + ref uint indexBase = ref indices[0]; + ref uint tileBase = ref MemoryMarshal.GetReference(bgra); + nuint width = (uint)tileWidth; - ref ushort outputRef = ref MemoryMarshal.GetReference(values); - Unsafe.As>(ref outputRef) = e.AsUInt16(); + for (int y = 0; y < tileHeight; y++) + { + ref uint row = ref Unsafe.Add(ref tileBase, (uint)(y * stride)); + nuint x = 0; - for (int i = 0; i < span; i++) + // The same column flows through descending widths, so a tile width that is not a multiple of the widest + // register keeps a vectorized tail. The bins count each pixel once, in any order. + if (Vector512.IsHardwareAccelerated) + { + for (; x + (uint)Vector512.Count <= width; x += (uint)Vector512.Count) + { + operation.Index(Vector512.LoadUnsafe(ref row, x)).StoreUnsafe(ref indexBase); + for (int i = 0; i < Vector512.Count; i++) { - ++histo[values[i]]; + ++histo[(int)indices[i]]; } } } - int leftOver = tileWidth & (span - 1); - if (leftOver > 0) + if (Vector256.IsHardwareAccelerated) { - CollectColorBlueTransformsScalar(bgra[(tileWidth - leftOver)..], stride, leftOver, tileHeight, greenToBlue, redToBlue, histo); + for (; x + (uint)Vector256.Count <= width; x += (uint)Vector256.Count) + { + operation.Index(Vector256.LoadUnsafe(ref row, x)).StoreUnsafe(ref indexBase); + for (int i = 0; i < Vector256.Count; i++) + { + ++histo[(int)indices[i]]; + } + } } - } - else if (Vector128.IsHardwareAccelerated) - { - const int span = 8; - Span values = stackalloc ushort[span]; - Vector128 collectColorBlueTransformsShuffleLowMask = Vector128.Create( - 255, - 2, - 255, - 6, - 255, - 10, - 255, - 14, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255); - Vector128 collectColorBlueTransformsShuffleHighMask = Vector128.Create( - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 2, - 255, - 6, - 255, - 10, - 255, - 14); - - Vector128 collectColorBlueTransformsGreenBlueMask = Vector128.Create(255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0); - Vector128 collectColorBlueTransformsGreenMask = Vector128.Create(0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255); - Vector128 collectColorBlueTransformsBlueMask = Vector128.Create(255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0); - Vector128 multsr = Vector128.Create(LosslessUtils.Cst5b(redToBlue)); - Vector128 multsg = Vector128.Create(LosslessUtils.Cst5b(greenToBlue)); - for (int y = 0; y < tileHeight; y++) + if (Vector128.IsHardwareAccelerated) { - Span srcSpan = bgra[(y * stride)..]; - ref uint inputRef = ref MemoryMarshal.GetReference(srcSpan); - for (nuint x = 0; (int)x <= tileWidth - span; x += span) + for (; x + (uint)Vector128.Count <= width; x += (uint)Vector128.Count) { - nuint input0Idx = x; - nuint input1Idx = x + (span / 2); - Vector128 input0 = Unsafe.As>(ref Unsafe.Add(ref inputRef, input0Idx)).AsByte(); - Vector128 input1 = Unsafe.As>(ref Unsafe.Add(ref inputRef, input1Idx)).AsByte(); - Vector128 r0 = Vector128.ShuffleNative(input0, collectColorBlueTransformsShuffleLowMask); - Vector128 r1 = Vector128.ShuffleNative(input1, collectColorBlueTransformsShuffleHighMask); - Vector128 r = r0 | r1; - Vector128 gb0 = input0 & collectColorBlueTransformsGreenBlueMask; - Vector128 gb1 = input1 & collectColorBlueTransformsGreenBlueMask; - Vector128 gb = Vector128_.PackUnsignedSaturate(gb0.AsInt32(), gb1.AsInt32()); - Vector128 g = gb.AsByte() & collectColorBlueTransformsGreenMask; - Vector128 a = Vector128_.MultiplyHigh(r.AsInt16(), multsr); - Vector128 b = Vector128_.MultiplyHigh(g.AsInt16(), multsg); - Vector128 c = gb.AsByte() - b.AsByte(); - Vector128 d = c - a.AsByte(); - Vector128 e = d & collectColorBlueTransformsBlueMask; - - ref ushort outputRef = ref MemoryMarshal.GetReference(values); - Unsafe.As>(ref outputRef) = e.AsUInt16(); - - for (int i = 0; i < span; i++) + operation.Index(Vector128.LoadUnsafe(ref row, x)).StoreUnsafe(ref indexBase); + for (int i = 0; i < Vector128.Count; i++) { - ++histo[values[i]]; + ++histo[(int)indices[i]]; } } } - int leftOver = tileWidth & (span - 1); - if (leftOver > 0) + for (; x < width; x++) { - CollectColorBlueTransformsScalar(bgra[(tileWidth - leftOver)..], stride, leftOver, tileHeight, greenToBlue, redToBlue, histo); + ++histo[operation.Index(Unsafe.Add(ref row, x))]; } } - else - { - CollectColorBlueTransformsScalar(bgra, stride, tileWidth, tileHeight, greenToBlue, redToBlue, histo); - } } - private static void CollectColorBlueTransformsScalar( - ReadOnlySpan bgra, - int stride, - int tileWidth, - int tileHeight, - int greenToBlue, - int redToBlue, - Span histo) + /// + /// Gets the blue channel after the color transform: blue - delta(green) - delta(red). + /// + private readonly struct BlueIndexOperator : IColorIndexOperator { - int pos = 0; - while (tileHeight-- > 0) - { - for (int x = 0; x < tileWidth; x++) - { - int idx = LosslessUtils.TransformColorBlue((sbyte)greenToBlue, (sbyte)redToBlue, bgra[pos + x]); - ++histo[idx]; - } + /// + /// The green-to-blue multiplier. + /// + private readonly sbyte greenToBlue; - pos += stride; - } - } + /// + /// The red-to-blue multiplier. + /// + private readonly sbyte redToBlue; - public static void CollectColorRedTransforms(Span bgra, int stride, int tileWidth, int tileHeight, int greenToRed, Span histo) - { - if (Vector256.IsHardwareAccelerated && tileWidth >= 16) + /// + /// Initializes a new instance of the struct. + /// + /// The green-to-blue multiplier. + /// The red-to-blue multiplier. + public BlueIndexOperator(int greenToBlue, int redToBlue) { - Vector256 collectColorRedTransformsGreenMask256 = Vector256.Create(0x00ff00).AsByte(); - Vector256 collectColorRedTransformsAndMask256 = Vector256.Create((short)0xff).AsByte(); - Vector256 multsg = Vector256.Create(LosslessUtils.Cst5b(greenToRed)); - const int span = 16; - Span values = stackalloc ushort[span]; - for (int y = 0; y < tileHeight; y++) - { - Span srcSpan = bgra[(y * stride)..]; - ref uint inputRef = ref MemoryMarshal.GetReference(srcSpan); - for (nuint x = 0; x <= (uint)tileWidth - span; x += span) - { - nuint input0Idx = x; - nuint input1Idx = x + (span / 2); - Vector256 input0 = Unsafe.As>(ref Unsafe.Add(ref inputRef, input0Idx)).AsByte(); - Vector256 input1 = Unsafe.As>(ref Unsafe.Add(ref inputRef, input1Idx)).AsByte(); - Vector256 g0 = input0 & collectColorRedTransformsGreenMask256; // 0 0 | g 0 - Vector256 g1 = input1 & collectColorRedTransformsGreenMask256; - Vector256 g = Vector256_.PackUnsignedSaturate(g0.AsInt32(), g1.AsInt32()); // g 0 - Vector256 a0 = Vector256.ShiftRightLogical(input0.AsInt32(), 16); // 0 0 | x r - Vector256 a1 = Vector256.ShiftRightLogical(input1.AsInt32(), 16); - Vector256 a = Vector256_.PackUnsignedSaturate(a0, a1); // x r - Vector256 b = Vector256_.MultiplyHigh(g.AsInt16(), multsg); // x dr - Vector256 c = a.AsByte() - b.AsByte(); // x r' - Vector256 d = c & collectColorRedTransformsAndMask256; // 0 r' + this.greenToBlue = (sbyte)greenToBlue; + this.redToBlue = (sbyte)redToBlue; + } - ref ushort outputRef = ref MemoryMarshal.GetReference(values); - Unsafe.As>(ref outputRef) = d.AsUInt16(); + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Index(uint argb) => LosslessUtils.TransformColorBlue(this.greenToBlue, this.redToBlue, argb); - for (int i = 0; i < span; i++) - { - ++histo[values[i]]; - } - } - } + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector128 Index(Vector128 argb) + { + // Green is in the high byte of the low 16-bit lane already. The shift by 8 moves red there. + Vector128 highByte = Vector128.Create(0x0000ff00u); + Vector128 greenDelta = Vector128_.MultiplyHigh((argb & highByte).AsInt16(), Vector128.Create(LosslessUtils.Cst5b(this.greenToBlue))); + Vector128 redDelta = Vector128_.MultiplyHigh(((argb >>> 8) & highByte).AsInt16(), Vector128.Create(LosslessUtils.Cst5b(this.redToBlue))); + return (argb - greenDelta.AsUInt32() - redDelta.AsUInt32()) & Vector128.Create(0xffu); + } - int leftOver = tileWidth & (span - 1); - if (leftOver > 0) - { - CollectColorRedTransformsScalar(bgra[(tileWidth - leftOver)..], stride, leftOver, tileHeight, greenToRed, histo); - } + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector256 Index(Vector256 argb) + { + // The same lane layout as the 128-bit form. + Vector256 highByte = Vector256.Create(0x0000ff00u); + Vector256 greenDelta = Vector256_.MultiplyHigh((argb & highByte).AsInt16(), Vector256.Create(LosslessUtils.Cst5b(this.greenToBlue))); + Vector256 redDelta = Vector256_.MultiplyHigh(((argb >>> 8) & highByte).AsInt16(), Vector256.Create(LosslessUtils.Cst5b(this.redToBlue))); + return (argb - greenDelta.AsUInt32() - redDelta.AsUInt32()) & Vector256.Create(0xffu); } - else if (Vector128.IsHardwareAccelerated) + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector512 Index(Vector512 argb) { - Vector128 collectColorRedTransformsGreenMask = Vector128.Create(0x00ff00).AsByte(); - Vector128 collectColorRedTransformsAndMask = Vector128.Create((short)0xff).AsByte(); - Vector128 multsg = Vector128.Create(LosslessUtils.Cst5b(greenToRed)); - const int span = 8; - Span values = stackalloc ushort[span]; - for (int y = 0; y < tileHeight; y++) - { - Span srcSpan = bgra[(y * stride)..]; - ref uint inputRef = ref MemoryMarshal.GetReference(srcSpan); - for (nuint x = 0; (int)x <= tileWidth - span; x += span) - { - nuint input0Idx = x; - nuint input1Idx = x + (span / 2); - Vector128 input0 = Unsafe.As>(ref Unsafe.Add(ref inputRef, input0Idx)).AsByte(); - Vector128 input1 = Unsafe.As>(ref Unsafe.Add(ref inputRef, input1Idx)).AsByte(); - Vector128 g0 = input0 & collectColorRedTransformsGreenMask; // 0 0 | g 0 - Vector128 g1 = input1 & collectColorRedTransformsGreenMask; - Vector128 g = Vector128_.PackUnsignedSaturate(g0.AsInt32(), g1.AsInt32()); // g 0 - Vector128 a0 = Vector128.ShiftRightLogical(input0.AsInt32(), 16); // 0 0 | x r - Vector128 a1 = Vector128.ShiftRightLogical(input1.AsInt32(), 16); - Vector128 a = Vector128_.PackUnsignedSaturate(a0, a1); // x r - Vector128 b = Vector128_.MultiplyHigh(g.AsInt16(), multsg); // x dr - Vector128 c = a.AsByte() - b.AsByte(); // x r' - Vector128 d = c & collectColorRedTransformsAndMask; // 0 r' + // The same lane layout as the 128-bit form. + Vector512 highByte = Vector512.Create(0x0000ff00u); + Vector512 greenDelta = Vector512_.MultiplyHigh((argb & highByte).AsInt16(), Vector512.Create(LosslessUtils.Cst5b(this.greenToBlue))); + Vector512 redDelta = Vector512_.MultiplyHigh(((argb >>> 8) & highByte).AsInt16(), Vector512.Create(LosslessUtils.Cst5b(this.redToBlue))); + return (argb - greenDelta.AsUInt32() - redDelta.AsUInt32()) & Vector512.Create(0xffu); + } + } - ref ushort outputRef = ref MemoryMarshal.GetReference(values); - Unsafe.As>(ref outputRef) = d.AsUInt16(); + /// + /// Gets the red channel after the color transform: red - delta(green). + /// + private readonly struct RedIndexOperator : IColorIndexOperator + { + /// + /// The green-to-red multiplier. + /// + private readonly sbyte greenToRed; - for (int i = 0; i < span; i++) - { - ++histo[values[i]]; - } - } - } + /// + /// Initializes a new instance of the struct. + /// + /// The green-to-red multiplier. + public RedIndexOperator(int greenToRed) => this.greenToRed = (sbyte)greenToRed; - int leftOver = tileWidth & (span - 1); - if (leftOver > 0) - { - CollectColorRedTransformsScalar(bgra[(tileWidth - leftOver)..], stride, leftOver, tileHeight, greenToRed, histo); - } - } - else + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Index(uint argb) => LosslessUtils.TransformColorRed(this.greenToRed, argb); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector128 Index(Vector128 argb) { - CollectColorRedTransformsScalar(bgra, stride, tileWidth, tileHeight, greenToRed, histo); + // Green is in the high byte of the low 16-bit lane. The shift by 16 moves red to the low byte. + Vector128 green = argb & Vector128.Create(0x0000ff00u); + Vector128 greenDelta = Vector128_.MultiplyHigh(green.AsInt16(), Vector128.Create(LosslessUtils.Cst5b(this.greenToRed))); + return ((argb >>> 16) - greenDelta.AsUInt32()) & Vector128.Create(0xffu); } - } - private static void CollectColorRedTransformsScalar(ReadOnlySpan bgra, int stride, int tileWidth, int tileHeight, int greenToRed, Span histo) - { - int pos = 0; - while (tileHeight-- > 0) + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector256 Index(Vector256 argb) { - for (int x = 0; x < tileWidth; x++) - { - int idx = LosslessUtils.TransformColorRed((sbyte)greenToRed, bgra[pos + x]); - ++histo[idx]; - } + // The same lane layout as the 128-bit form. + Vector256 green = argb & Vector256.Create(0x0000ff00u); + Vector256 greenDelta = Vector256_.MultiplyHigh(green.AsInt16(), Vector256.Create(LosslessUtils.Cst5b(this.greenToRed))); + return ((argb >>> 16) - greenDelta.AsUInt32()) & Vector256.Create(0xffu); + } - pos += stride; + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector512 Index(Vector512 argb) + { + // The same lane layout as the 128-bit form. + Vector512 green = argb & Vector512.Create(0x0000ff00u); + Vector512 greenDelta = Vector512_.MultiplyHigh(green.AsInt16(), Vector512.Create(LosslessUtils.Cst5b(this.greenToRed))); + return ((argb >>> 16) - greenDelta.AsUInt32()) & Vector512.Create(0xffu); } } } diff --git a/src/ImageSharp/Formats/Webp/Lossless/CostCacheInterval.cs b/src/ImageSharp/Formats/Webp/Lossless/CostCacheInterval.cs index a98b67166e..801a735218 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/CostCacheInterval.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/CostCacheInterval.cs @@ -9,11 +9,20 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; /// The GetLengthCost(costModel, k) are cached in a CostCacheInterval. /// [DebuggerDisplay("Start: {Start}, End: {End}, Cost: {Cost}")] -internal class CostCacheInterval +internal struct CostCacheInterval { - public double Cost { get; set; } + /// + /// The length cost of all lengths in the interval. + /// + public double Cost; - public int Start { get; set; } + /// + /// The first length of the interval. + /// + public int Start; - public int End { get; set; } // Exclusive. + /// + /// The length after the last length of the interval. + /// + public int End; } diff --git a/src/ImageSharp/Formats/Webp/Lossless/CostInterval.cs b/src/ImageSharp/Formats/Webp/Lossless/CostInterval.cs index 0cc4a30fd7..032dbf4765 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/CostInterval.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/CostInterval.cs @@ -20,19 +20,39 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; /// Intervals are stored in a linked list and ordered by start. When a new /// interval has a better value, old intervals are split or removed. There are /// therefore no overlapping intervals. +/// The intervals live in a pool that the caller of the methods owns, so the links are indices into that pool. /// [DebuggerDisplay("Start: {Start}, End: {End}, Cost: {Cost}")] -internal class CostInterval +internal struct CostInterval { - public float Cost { get; set; } - - public int Start { get; set; } - - public int End { get; set; } - - public int Index { get; set; } - - public CostInterval? Previous { get; set; } - - public CostInterval? Next { get; set; } + /// + /// The cost of the pixels in the interval. + /// + public float Cost; + + /// + /// The first pixel of the interval. + /// + public int Start; + + /// + /// The pixel after the last pixel of the interval. + /// + public int End; + + /// + /// The pixel that generated the interval. + /// + public int Index; + + /// + /// The pool index of the previous interval in the list, or for the head. + /// + public int Previous; + + /// + /// The pool index of the next interval in the list, or for the tail. + /// In the free list, the pool index of the next free interval. + /// + public int Next; } diff --git a/src/ImageSharp/Formats/Webp/Lossless/CostManager.cs b/src/ImageSharp/Formats/Webp/Lossless/CostManager.cs index f5738c7d35..1b709dbe0f 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/CostManager.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/CostManager.cs @@ -1,122 +1,170 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. -using System.Buffers; -using SixLabors.ImageSharp.Memory; - namespace SixLabors.ImageSharp.Formats.Webp.Lossless; /// /// The CostManager is in charge of managing intervals and costs. /// It caches the different CostCacheInterval, caches the different /// GetLengthCost(costModel, k) in costCache and the CostInterval's. +/// The number of stored CostInterval's is limited by . /// -internal sealed class CostManager : IDisposable +/// +/// +/// The caller owns the pooled buffers for one cost search. It gets each span one time and passes the spans to these methods, +/// so the calls for each pixel use the spans directly. +/// +/// +/// The stored intervals live in the interval pool. Each link is the index of an interval in the pool, or . +/// The caller keeps two links as local variables and passes them by reference: the head of the stored list, ordered by start, +/// and the head of the free list. The free intervals are linked through . +/// +/// +internal static class CostManager { - private CostInterval? head; + /// + /// The link value for no interval. + /// + public const int None = -1; - private const int FreeIntervalsStartCount = 25; + /// + /// The maximum number of stored intervals. This is the length of the interval pool. When this number of intervals is stored, + /// a new interval is written to the costs directly. This empirical value limits the memory use and the time to walk the list. + /// + public const int CostCacheIntervalSizeMax = 500; - private readonly Stack freeIntervals = new(FreeIntervalsStartCount); + /// + /// An interval shorter than this length is written to the costs directly. This constant is empirical. + /// + private const int SkipDistance = 10; - public CostManager(MemoryAllocator memoryAllocator, IMemoryOwner distArray, int pixCount, CostModel costModel) - { - int costCacheSize = pixCount > BackwardReferenceEncoder.MaxLength ? BackwardReferenceEncoder.MaxLength : pixCount; + /// + /// The number of entries of the cost ring and of the token length ring of the trace-backwards search. The entry of pixel p is at + /// p & . + /// + /// + /// The step of pixel i reads the cost of pixel i - 1 and of pixels after it. It writes pixels up to i + 2 * MaxLength - 2: + /// a copy that continues the previous copy starts at most at i + MaxLength - 1 and covers at most MaxLength pixels, and the stored + /// intervals and the costs that this class writes are inside such a copy. The search resets the entry of pixel i + + /// at the start of step i. Thus each pixel gets the start cost before its first write, and the reset never reaches a pixel that a + /// later step reads, because + 1 is less than the ring size. + /// + public const int RingSize = 1 << 14; - this.CacheIntervals = []; - this.CostCache = []; - this.Costs = memoryAllocator.Allocate(pixCount); - this.DistArray = distArray; - this.Count = 0; + /// + /// The mask that gives the ring entry of a pixel. See . + /// + public const int RingMask = RingSize - 1; - for (int i = 0; i < FreeIntervalsStartCount; i++) - { - this.freeIntervals.Push(new CostInterval()); - } + /// + /// The distance from the current pixel to the pixel whose ring entry gets the start cost. It is not less than the farthest pixel that + /// a step writes. See . + /// + public const int RingAhead = 2 * BackwardReferenceEncoder.MaxLength; - // Fill in the cost cache. - this.CacheIntervalsSize++; - this.CostCache.Add(costModel.GetLengthCost(0)); - for (int i = 1; i < costCacheSize; i++) + /// + /// Fills the cost cache with GetLengthCost(costModel, k) for each length k. + /// + /// The literal cost table of the cost model. + /// Receives the cost of each length. The length is the smaller of the pixel count and the maximum copy length. + /// The number of runs of equal values in . This is the length of the cache intervals. + public static int BuildCostCache(ReadOnlySpan literalCosts, Span costCache) + { + costCache[0] = CostModel.GetLengthCost(literalCosts, 0); + int intervalsSize = 1; + for (int i = 1; i < costCache.Length; i++) { - this.CostCache.Add(costModel.GetLengthCost(i)); - - // Get the number of bound intervals. - if (this.CostCache[i] != this.CostCache[i - 1]) + costCache[i] = CostModel.GetLengthCost(literalCosts, i); + if (costCache[i] != costCache[i - 1]) { - this.CacheIntervalsSize++; + intervalsSize++; } } - // Fill in the cache intervals. - CostCacheInterval cur = new() - { - Start = 0, - End = 1, - Cost = this.CostCache[0] - }; - this.CacheIntervals.Add(cur); + return intervalsSize; + } - for (int i = 1; i < costCacheSize; i++) +#pragma warning disable CA1517 // False positive: https://github.com/dotnet/sdk/issues/53388 + /// + /// Fills the cache intervals. Each interval holds one run of equal values in the cost cache. + /// + /// The cost cache that filled. + /// Receives the runs. The length is the value that returned. + public static void BuildCacheIntervals(ReadOnlySpan costCache, Span cacheIntervals) + { + int current = 0; + cacheIntervals[0].Start = 0; + cacheIntervals[0].End = 1; + cacheIntervals[0].Cost = costCache[0]; + for (int i = 1; i < costCache.Length; i++) { - double costVal = this.CostCache[i]; - if (costVal != cur.Cost) + double costVal = costCache[i]; + if (costVal != cacheIntervals[current].Cost) { - cur = new CostCacheInterval - { - Start = i, - Cost = costVal - }; - this.CacheIntervals.Add(cur); + current++; + cacheIntervals[current].Start = i; + cacheIntervals[current].Cost = costVal; } - cur.End = i + 1; + cacheIntervals[current].End = i + 1; } - - // Set the initial costs high for every pixel as we will keep the minimum. - this.Costs.GetSpan().Fill(1e38f); } +#pragma warning restore CA1517 +#pragma warning disable CA1517 // False positive: https://github.com/dotnet/sdk/issues/53388 /// - /// Gets or sets the number of stored intervals. + /// Links all intervals of the pool into the free list. /// - public int Count { get; set; } - - /// - /// Gets the costs cache. Contains the GetLengthCost(costModel, k). - /// - public List CostCache { get; } - - public int CacheIntervalsSize { get; } - - public IMemoryOwner Costs { get; } - - public IMemoryOwner DistArray { get; } + /// The interval pool. The length is . + /// The head of the free list. + public static int BuildFreeList(Span intervals) + { + int freeIntervals = None; + for (int i = 0; i < intervals.Length; i++) + { + intervals[i].Next = freeIntervals; + freeIntervals = i; + } - public List CacheIntervals { get; } + return freeIntervals; + } +#pragma warning restore CA1517 /// /// Update the cost at index i by going over all the stored intervals that overlap with i. /// + /// The interval pool. + /// The first stored interval, or . A removed interval can change it. + /// The head of the free list. A removed interval changes it. + /// The ring of the minimum cost found so far for each pixel. See . + /// The ring of the length of the token that ends at each pixel with the minimum cost. /// The index to update. /// If 'doCleanIntervals' is true, intervals that end before 'i' will be popped. - public void UpdateCostAtIndex(int i, bool doCleanIntervals) + public static void UpdateCostAtIndex( + Span intervals, + ref int head, + ref int freeIntervals, + Span costs, + Span distArray, + int i, + bool doCleanIntervals) { - CostInterval? current = this.head; - while (current != null && current.Start <= i) + int current = head; + while (current != None && intervals[current].Start <= i) { - CostInterval? next = current.Next; - if (current.End <= i) + ref CostInterval interval = ref intervals[current]; + int next = interval.Next; + if (interval.End <= i) { if (doCleanIntervals) { // We have an outdated interval, remove it. - this.PopInterval(current); + PopInterval(intervals, ref head, ref freeIntervals, current); } } else { - this.UpdateCost(i, current.Index, current.Cost); + UpdateCost(costs, distArray, i, interval.Index, interval.Cost); } current = next; @@ -129,43 +177,62 @@ public void UpdateCostAtIndex(int i, bool doCleanIntervals) /// If handling the interval or one of its sub-intervals becomes to heavy, its /// contribution is added to the costs right away. /// - public void PushInterval(double distanceCost, int position, int len) + /// The interval pool. + /// The first stored interval, or . The changes to the list can change it. + /// The head of the free list. The changes to the list can change it. + /// The cache intervals that filled. + /// The cost cache that filled. + /// The ring of the minimum cost found so far for each pixel. See . + /// The ring of the length of the token that ends at each pixel with the minimum cost. + /// The cost of the distance plus the cost of the pixel before position. + /// The first pixel that the copy covers. + /// The length of the copy. + public static void PushInterval( + Span intervals, + ref int head, + ref int freeIntervals, + ReadOnlySpan cacheIntervals, + ReadOnlySpan costCache, + Span costs, + Span distArray, + double distanceCost, + int position, + int len) { // If the interval is small enough, no need to deal with the heavy - // interval logic, just serialize it right away. This constant is empirical. - int skipDistance = 10; - - Span costs = this.Costs.GetSpan(); - Span distArray = this.DistArray.GetSpan(); - if (len < skipDistance) + // interval logic, just serialize it right away. + if (len < SkipDistance) { for (int j = position; j < position + len; j++) { int k = j - position; - float costTmp = (float)(distanceCost + this.CostCache[k]); + float costTmp = (float)(distanceCost + costCache[k]); - if (costs[j] > costTmp) + int ringIndex = j & RingMask; + if (costs[ringIndex] > costTmp) { - costs[j] = costTmp; - distArray[j] = (ushort)(k + 1); + costs[ringIndex] = costTmp; + distArray[ringIndex] = (ushort)(k + 1); } } return; } - CostInterval? interval = this.head; - for (int i = 0; i < this.CacheIntervalsSize && this.CacheIntervals[i].Start < len; i++) + int current = head; + for (int i = 0; i < cacheIntervals.Length && cacheIntervals[i].Start < len; i++) { // Define the intersection of the ith interval with the new one. - int start = position + this.CacheIntervals[i].Start; - int end = position + (this.CacheIntervals[i].End > len ? len : this.CacheIntervals[i].End); - float cost = (float)(distanceCost + this.CacheIntervals[i].Cost); + ref readonly CostCacheInterval cacheInterval = ref cacheIntervals[i]; + int start = position + cacheInterval.Start; + int end = position + (cacheInterval.End > len ? len : cacheInterval.End); + float cost = (float)(distanceCost + cacheInterval.Cost); - CostInterval? intervalNext; - for (; interval != null && interval.Start < end; interval = intervalNext) + int next; + for (; current != None && intervals[current].Start < end; current = next) { - intervalNext = interval.Next; + ref CostInterval interval = ref intervals[current]; + next = interval.Next; // Make sure we have some overlap. if (start >= interval.End) @@ -177,7 +244,7 @@ public void PushInterval(double distanceCost, int position, int len) { // If we are worse than what we already have, add whatever we have so far up to interval. int startNew = interval.End; - this.InsertInterval(interval, cost, position, start, interval.Start); + InsertInterval(intervals, ref head, ref freeIntervals, costs, distArray, current, cost, position, start, interval.Start); start = startNew; if (start >= end) { @@ -192,7 +259,7 @@ public void PushInterval(double distanceCost, int position, int len) if (interval.End <= end) { // We can safely remove the old interval as it is fully included. - this.PopInterval(interval); + PopInterval(intervals, ref head, ref freeIntervals, current); } else { @@ -207,7 +274,7 @@ public void PushInterval(double distanceCost, int position, int len) // We have to split the old interval as it fully contains the new one. int endOriginal = interval.End; interval.End = start; - this.InsertInterval(interval, interval.Cost, interval.Index, end, endOriginal); + InsertInterval(intervals, ref head, ref freeIntervals, costs, distArray, current, interval.Cost, interval.Index, end, endOriginal); break; } @@ -216,114 +283,155 @@ public void PushInterval(double distanceCost, int position, int len) } // Insert the remaining interval from start to end. - this.InsertInterval(interval, cost, position, start, end); + InsertInterval(intervals, ref head, ref freeIntervals, costs, distArray, current, cost, position, start, end); } } /// - /// Pop an interval from the manager. + /// Pop an interval from the manager and return it to the free list. /// - /// The interval to remove. - private void PopInterval(CostInterval? interval) + /// The interval pool. + /// The first stored interval. It changes when the removed interval is the head. + /// The head of the free list. It becomes . + /// The pool index of the stored interval to remove. + private static void PopInterval(Span intervals, ref int head, ref int freeIntervals, int index) { - if (interval == null) - { - return; - } - - this.ConnectIntervals(interval.Previous, interval.Next); - this.Count--; + ref CostInterval interval = ref intervals[index]; + ConnectIntervals(intervals, ref head, interval.Previous, interval.Next); - interval.Next = null; - interval.Previous = null; - this.freeIntervals.Push(interval); + interval.Next = freeIntervals; + freeIntervals = index; } - private void InsertInterval(CostInterval? intervalIn, float cost, int position, int start, int end) + /// + /// Insert an interval in the list by starting at 'intervalIn' as a hint. The intervals are sorted by start. + /// When intervals are stored, the interval is written to the costs directly. + /// + /// The interval pool. + /// The first stored interval, or . It changes when the new interval becomes the head. + /// The head of the free list. It changes when the interval is stored. + /// The ring of the minimum cost found so far for each pixel. See . + /// The ring of the length of the token that ends at each pixel with the minimum cost. + /// The pool index of a stored interval near the insert position, or . + /// The cost of the interval. + /// The pixel that generated the interval. + /// The first pixel of the interval. + /// The pixel after the last pixel of the interval. + private static void InsertInterval( + Span intervals, + ref int head, + ref int freeIntervals, + Span costs, + Span distArray, + int intervalIn, + float cost, + int position, + int start, + int end) { if (start >= end) { return; } - // TODO: should we use COST_CACHE_INTERVAL_SIZE_MAX? - CostInterval intervalNew; - if (this.freeIntervals.Count > 0) + // The pool holds CostCacheIntervalSizeMax intervals and each interval is either stored or free. + // So the free list is empty exactly when CostCacheIntervalSizeMax intervals are stored. + if (freeIntervals == None) { - intervalNew = this.freeIntervals.Pop(); - intervalNew.Cost = cost; - intervalNew.Start = start; - intervalNew.End = end; - intervalNew.Index = position; - } - else - { - intervalNew = new CostInterval { Cost = cost, Start = start, End = end, Index = position }; + // Serialize the interval if we cannot store it. + for (int i = start; i < end; i++) + { + UpdateCost(costs, distArray, i, position, cost); + } + + return; } - this.PositionOrphanInterval(intervalNew, intervalIn); - this.Count++; + int index = freeIntervals; + ref CostInterval intervalNew = ref intervals[index]; + freeIntervals = intervalNew.Next; + intervalNew.Cost = cost; + intervalNew.Index = position; + intervalNew.Start = start; + intervalNew.End = end; + + PositionOrphanInterval(intervals, ref head, index, intervalIn); } /// /// Given a current orphan interval and its previous interval, before - /// it was orphaned (which can be NULL), set it at the right place in the list - /// of intervals using the start_ ordering and the previous interval as a hint. + /// it was orphaned (which can be ), set it at the right place in the list + /// of intervals using the start ordering and the previous interval as a hint. /// - private void PositionOrphanInterval(CostInterval current, CostInterval? previous) + /// The interval pool. + /// The first stored interval, or . It changes when the orphan becomes the head. + /// The pool index of the orphan interval. + /// The pool index of the interval before the orphan, or . + private static void PositionOrphanInterval(Span intervals, ref int head, int current, int previous) { - previous ??= this.head; + if (previous == None) + { + previous = head; + } - while (previous != null && current.Start < previous.Start) + int start = intervals[current].Start; + while (previous != None && start < intervals[previous].Start) { - previous = previous.Previous; + previous = intervals[previous].Previous; } - while (previous?.Next != null && previous.Next.Start < current.Start) + while (previous != None && intervals[previous].Next != None && intervals[intervals[previous].Next].Start < start) { - previous = previous.Next; + previous = intervals[previous].Next; } - this.ConnectIntervals(current, previous != null ? previous.Next : this.head); - this.ConnectIntervals(previous, current); + ConnectIntervals(intervals, ref head, current, previous != None ? intervals[previous].Next : head); + ConnectIntervals(intervals, ref head, previous, current); } +#pragma warning disable CA1517 // False positive: https://github.com/dotnet/sdk/issues/53388 /// /// Given two intervals, make 'prev' be the previous one of 'next' in 'manager'. /// - private void ConnectIntervals(CostInterval? prev, CostInterval? next) + /// The interval pool. + /// The first stored interval. It becomes 'next' when 'prev' is . + /// The pool index of the first interval, or to make 'next' the head. + /// The pool index of the second interval, or . + private static void ConnectIntervals(Span intervals, ref int head, int prev, int next) { - if (prev != null) + if (prev != None) { - prev.Next = next; + intervals[prev].Next = next; } else { - this.head = next; + head = next; } - if (next != null) + if (next != None) { - next.Previous = prev; + intervals[next].Previous = prev; } } +#pragma warning restore CA1517 /// /// Given the cost and the position that define an interval, update the cost at /// pixel 'i' if it is smaller than the previously computed value. /// - private void UpdateCost(int i, int position, float cost) + /// The ring of the minimum cost found so far for each pixel. See . + /// The ring of the length of the token that ends at each pixel with the minimum cost. + /// The pixel to update. + /// The pixel that generated the interval. + /// The cost of the interval. + private static void UpdateCost(Span costs, Span distArray, int i, int position, float cost) { - Span costs = this.Costs.GetSpan(); - Span distArray = this.DistArray.GetSpan(); int k = i - position; - if (costs[i] > cost) + int ringIndex = i & RingMask; + if (costs[ringIndex] > cost) { - costs[i] = cost; - distArray[i] = (ushort)(k + 1); + costs[ringIndex] = cost; + distArray[ringIndex] = (ushort)(k + 1); } } - - /// - public void Dispose() => this.Costs.Dispose(); } diff --git a/src/ImageSharp/Formats/Webp/Lossless/CostModel.cs b/src/ImageSharp/Formats/Webp/Lossless/CostModel.cs index 3307a66eb3..2fae112ebd 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/CostModel.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/CostModel.cs @@ -1,80 +1,133 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +using System.Runtime.CompilerServices; using SixLabors.ImageSharp.Memory; namespace SixLabors.ImageSharp.Formats.Webp.Lossless; -internal class CostModel +/// +/// Estimates the bit cost of each lossless symbol from the symbol statistics of a set of backward references. +/// +/// +/// The caller owns the memory of the five cost tables. It gets the spans one time and passes them to these methods, +/// so the per-pixel cost lookups do not get the memory of the buffer again. +/// +internal static class CostModel { - private readonly MemoryAllocator memoryAllocator; - private const int ValuesInBytes = 256; - /// - /// Initializes a new instance of the class. + /// The number of 8-bit values. This is the length of the alpha, red and blue cost tables. /// - /// The memory allocator. - /// The literal array size. - public CostModel(MemoryAllocator memoryAllocator, int literalArraySize) - { - this.memoryAllocator = memoryAllocator; - this.Alpha = new double[ValuesInBytes]; - this.Red = new double[ValuesInBytes]; - this.Blue = new double[ValuesInBytes]; - this.Distance = new double[WebpConstants.NumDistanceCodes]; - this.Literal = new double[literalArraySize]; - } - - public double[] Alpha { get; } - - public double[] Red { get; } - - public double[] Blue { get; } + public const int ValuesInBytes = 256; - public double[] Distance { get; } - - public double[] Literal { get; } - - public void Build(int xSize, int cacheBits, Vp8LBackwardRefs backwardRefs) + /// + /// Builds the cost tables from the symbol statistics of the backward references. + /// The distances are converted to plane codes before they are counted. + /// + /// The memory allocator for the temporary histogram. + /// The image width. + /// The number of color cache bits. + /// The backward references to measure. + /// Receives the estimated bit cost of each alpha value. The length is . + /// Receives the estimated bit cost of each red value. The length is . + /// Receives the estimated bit cost of each blue value. The length is . + /// + /// Receives the estimated bit cost of each distance prefix code. The length is . + /// + /// + /// Receives the estimated bit cost of each green and length prefix symbol and each color cache index. + /// The length is the literal array size of . + /// + public static void Build( + MemoryAllocator memoryAllocator, + int xSize, + int cacheBits, + Vp8LBackwardReferences backwardRefs, + Span alphaCosts, + Span redCosts, + Span blueCosts, + Span distanceCosts, + Span literalCosts) { - using OwnedVp8LHistogram histogram = OwnedVp8LHistogram.Create(this.memoryAllocator, cacheBits); + using OwnedVp8LHistogram histogram = OwnedVp8LHistogram.Create(memoryAllocator, cacheBits); // The following code is similar to HistogramCreate but converts the distance to plane code. - foreach (PixOrCopy v in backwardRefs) - { - histogram.AddSinglePixOrCopy(in v, true, xSize); - } + histogram.StoreRefs(backwardRefs, true, xSize); - ConvertPopulationCountTableToBitEstimates(histogram.NumCodes(), histogram.Literal, this.Literal); - ConvertPopulationCountTableToBitEstimates(ValuesInBytes, histogram.Red, this.Red); - ConvertPopulationCountTableToBitEstimates(ValuesInBytes, histogram.Blue, this.Blue); - ConvertPopulationCountTableToBitEstimates(ValuesInBytes, histogram.Alpha, this.Alpha); - ConvertPopulationCountTableToBitEstimates(WebpConstants.NumDistanceCodes, histogram.Distance, this.Distance); + ConvertPopulationCountTableToBitEstimates(histogram.NumCodes(), histogram.Literal, literalCosts); + ConvertPopulationCountTableToBitEstimates(ValuesInBytes, histogram.Red, redCosts); + ConvertPopulationCountTableToBitEstimates(ValuesInBytes, histogram.Blue, blueCosts); + ConvertPopulationCountTableToBitEstimates(ValuesInBytes, histogram.Alpha, alphaCosts); + ConvertPopulationCountTableToBitEstimates(WebpConstants.NumDistanceCodes, histogram.Distance, distanceCosts); } - public double GetLengthCost(int length) + /// + /// Gets the estimated bit cost of a copy length. + /// + /// The literal cost table that filled. + /// The copy length. + /// The cost of the length prefix symbol plus its extra bits. + [MethodImpl(InliningOptions.ShortMethod)] + public static double GetLengthCost(ReadOnlySpan literalCosts, int length) { int extraBits = 0; int code = LosslessUtils.PrefixEncodeBits(length, ref extraBits); - return this.Literal[ValuesInBytes + code] + extraBits; + return literalCosts[ValuesInBytes + code] + extraBits; } - public double GetDistanceCost(int distance) + /// + /// Gets the estimated bit cost of a copy distance. + /// + /// The distance cost table that filled. + /// The distance plane code. + /// The cost of the distance prefix symbol plus its extra bits. + [MethodImpl(InliningOptions.ShortMethod)] + public static double GetDistanceCost(ReadOnlySpan distanceCosts, int distance) { int extraBits = 0; int code = LosslessUtils.PrefixEncodeBits(distance, ref extraBits); - return this.Distance[code] + extraBits; + return distanceCosts[code] + extraBits; } - public double GetCacheCost(uint idx) + /// + /// Gets the estimated bit cost of a color cache index. + /// + /// The literal cost table that filled. + /// The color cache index. + /// The cost of the cache symbol. + [MethodImpl(InliningOptions.ShortMethod)] + public static double GetCacheCost(ReadOnlySpan literalCosts, uint idx) { int literalIdx = (int)(ValuesInBytes + WebpConstants.NumLengthCodes + idx); - return this.Literal[literalIdx]; + return literalCosts[literalIdx]; } - public double GetLiteralCost(uint v) => this.Alpha[v >> 24] + this.Red[(v >> 16) & 0xff] + this.Literal[(v >> 8) & 0xff] + this.Blue[v & 0xff]; + /// + /// Gets the estimated bit cost of a literal pixel. + /// + /// The alpha cost table that filled. + /// The red cost table that filled. + /// The blue cost table that filled. + /// The literal cost table that filled. The green values use its first entries. + /// The BGRA pixel. + /// The sum of the costs of the alpha, red, green and blue values. + [MethodImpl(InliningOptions.ShortMethod)] + public static double GetLiteralCost( + ReadOnlySpan alphaCosts, + ReadOnlySpan redCosts, + ReadOnlySpan blueCosts, + ReadOnlySpan literalCosts, + uint v) + => alphaCosts[(int)(v >> 24)] + redCosts[(int)((v >> 16) & 0xff)] + literalCosts[(int)((v >> 8) & 0xff)] + blueCosts[(int)(v & 0xff)]; - private static void ConvertPopulationCountTableToBitEstimates(int numSymbols, ReadOnlySpan populationCounts, double[] output) + /// + /// Converts symbol counts to estimated bit costs. The cost of a symbol is log2(total count) - log2(symbol count). + /// When at most one symbol occurs, all costs are 0, because a single-symbol code needs no bits. + /// + /// The number of symbols. + /// The count of each symbol. + /// Receives the estimated cost of each symbol. + private static void ConvertPopulationCountTableToBitEstimates(int numSymbols, ReadOnlySpan populationCounts, Span output) { uint sum = 0; int nonzeros = 0; @@ -89,7 +142,7 @@ private static void ConvertPopulationCountTableToBitEstimates(int numSymbols, Re if (nonzeros <= 1) { - output.AsSpan(0, numSymbols).Clear(); + output[..numSymbols].Clear(); } else { diff --git a/src/ImageSharp/Formats/Webp/Lossless/CrunchConfig.cs b/src/ImageSharp/Formats/Webp/Lossless/CrunchConfig.cs deleted file mode 100644 index fb9c1fd5ca..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossless/CrunchConfig.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossless; - -internal class CrunchConfig -{ - public EntropyIx EntropyIdx { get; set; } - - public List SubConfigs { get; } = []; -} diff --git a/src/ImageSharp/Formats/Webp/Lossless/CrunchConfiguration.cs b/src/ImageSharp/Formats/Webp/Lossless/CrunchConfiguration.cs new file mode 100644 index 0000000000..25e4939df1 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossless/CrunchConfiguration.cs @@ -0,0 +1,20 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.ImageSharp.Formats.Webp.Lossless; + +/// +/// One transform combination that the lossless encoder tries, with the backward reference settings to try for it. +/// +internal class CrunchConfiguration +{ + /// + /// Gets or sets the transform combination to try. + /// + public EntropyIndex EntropyIdx { get; set; } + + /// + /// Gets the backward reference settings to try with the transform combination. + /// + public List SubConfigs { get; } = []; +} diff --git a/src/ImageSharp/Formats/Webp/Lossless/CrunchSubConfig.cs b/src/ImageSharp/Formats/Webp/Lossless/CrunchSubConfig.cs deleted file mode 100644 index e442fbe106..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossless/CrunchSubConfig.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossless; - -internal class CrunchSubConfig -{ - public int Lz77 { get; set; } - - public bool DoNotCache { get; set; } -} diff --git a/src/ImageSharp/Formats/Webp/Lossless/CrunchSubConfiguration.cs b/src/ImageSharp/Formats/Webp/Lossless/CrunchSubConfiguration.cs new file mode 100644 index 0000000000..286335ce90 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossless/CrunchSubConfiguration.cs @@ -0,0 +1,20 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.ImageSharp.Formats.Webp.Lossless; + +/// +/// One backward reference setting that the lossless encoder tries for a transform combination. +/// +internal class CrunchSubConfiguration +{ + /// + /// Gets or sets the LZ77 variants to try, as a combination of flags. + /// + public int Lz77 { get; set; } + + /// + /// Gets or sets a value indicating whether the encoder also tries the setting without a color cache. + /// + public bool DoNotCache { get; set; } +} diff --git a/src/ImageSharp/Formats/Webp/Lossless/HTreeGroup.cs b/src/ImageSharp/Formats/Webp/Lossless/HTreeGroup.cs deleted file mode 100644 index 20679df5e4..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossless/HTreeGroup.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -using SixLabors.ImageSharp.Compression; - -namespace SixLabors.ImageSharp.Formats.Webp.Lossless; - -/// -/// Huffman table group. -/// Includes special handling for the following cases: -/// - IsTrivialLiteral: one common literal base for RED/BLUE/ALPHA (not GREEN) -/// - IsTrivialCode: only 1 code (no bit is read from the bitstream) -/// - UsePackedTable: few enough literal symbols, so all the bit codes can fit into a small look-up table PackedTable[] -/// The common literal base, if applicable, is stored in 'LiteralArb'. -/// -internal struct HTreeGroup -{ - public HTreeGroup(uint packedTableSize) - { - this.HTrees = new List(WebpConstants.HuffmanCodesPerMetaCode); - this.PackedTable = new HuffmanCode[packedTableSize]; - this.IsTrivialCode = false; - this.IsTrivialLiteral = false; - this.LiteralArb = 0; - this.UsePackedTable = false; - } - - /// - /// Gets the Huffman trees. This has a maximum of (5) entry's. - /// - public List HTrees { get; } - - /// - /// Gets or sets a value indicating whether huffman trees for Red, Blue and Alpha Symbols are trivial (have a single code). - /// - public bool IsTrivialLiteral { get; set; } - - /// - /// Gets or sets a the literal argb value of the pixel. - /// If IsTrivialLiteral is true, this is the ARGB value of the pixel, with Green channel being set to zero. - /// - public uint LiteralArb { get; set; } - - /// - /// Gets or sets a value indicating whether there is only one code. - /// - public bool IsTrivialCode { get; set; } - - /// - /// Gets or sets a value indicating whether to use packed table below for short literal code. - /// - public bool UsePackedTable { get; set; } - - /// - /// Gets or sets table mapping input bits to packed values, or escape case to literal code. - /// - public HuffmanCode[] PackedTable { get; set; } -} diff --git a/src/ImageSharp/Formats/Webp/Lossless/HistogramEncoder.cs b/src/ImageSharp/Formats/Webp/Lossless/HistogramEncoder.cs index 4d80fb0f45..483d215084 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/HistogramEncoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/HistogramEncoder.cs @@ -8,6 +8,9 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; +/// +/// Builds the entropy image of a lossless image. It clusters the tile histograms and maps each tile to a cluster. +/// internal static class HistogramEncoder { /// @@ -25,15 +28,34 @@ internal static class HistogramEncoder /// private const int MaxHistoGreedy = 100; + /// + /// The trivial symbol value of a histogram that has no single trivial symbol. + /// private const uint NonTrivialSym = 0xffffffff; + /// + /// The symbol of a tile whose histogram is empty. + /// private const ushort InvalidHistogramSymbol = ushort.MaxValue; + /// + /// Builds one histogram for each tile, combines similar histograms and maps each tile to its final histogram. + /// + /// The memory allocator. + /// The image width. + /// The image height. + /// The backward references of the image. + /// The encoding quality, from 0 to 100. A higher quality spends more time on the combination. + /// The log2 of the tile size. + /// The number of color cache bits. + /// Receives the final histograms. + /// A scratch histogram. + /// Receives the final histogram index of each tile. public static void GetHistoImageSymbols( MemoryAllocator memoryAllocator, int xSize, int ySize, - Vp8LBackwardRefs refs, + Vp8LBackwardReferences refs, uint quality, int histoBits, int cacheBits, @@ -50,7 +72,8 @@ public static void GetHistoImageSymbols( Span mapTmp = tmp.Slice(0, imageHistoRawSize); Span clusterMappings = tmp.Slice(imageHistoRawSize, imageHistoRawSize); - using Vp8LHistogramSet origHisto = new(memoryAllocator, imageHistoRawSize, cacheBits); + // HistogramBuild counts into these histograms, so they must start at zero. + using Vp8LHistogramSet origHisto = new(memoryAllocator, imageHistoRawSize, cacheBits, AllocationOptions.Clean, false); // Construct the histograms from the backward references. HistogramBuild(xSize, histoBits, refs, origHisto); @@ -66,7 +89,15 @@ public static void GetHistoImageSymbols( HistogramAnalyzeEntropyBin(imageHisto, mapTmp); // Collapse histograms with similar entropy. - HistogramCombineEntropyBin(imageHisto, histogramSymbols, clusterMappings, tmpHisto, mapTmp, entropyCombineNumBins, combineCostFactor); + HistogramCombineEntropyBin( + memoryAllocator, + imageHisto, + histogramSymbols, + clusterMappings, + tmpHisto, + mapTmp, + entropyCombineNumBins, + combineCostFactor); OptimizeHistogramSymbols(clusterMappings, numClusters, mapTmp, histogramSymbols); } @@ -75,11 +106,11 @@ public static void GetHistoImageSymbols( // Cubic ramp between 1 and MaxHistoGreedy: int thresholdSize = (int)(1 + (x * x * x * (MaxHistoGreedy - 1))); - bool doGreedy = HistogramCombineStochastic(imageHisto, thresholdSize); + bool doGreedy = HistogramCombineStochastic(memoryAllocator, imageHisto, thresholdSize); if (doGreedy) { RemoveEmptyHistograms(imageHisto); - HistogramCombineGreedy(imageHisto); + HistogramCombineGreedy(memoryAllocator, imageHisto); } // Find the optimal map from original histograms to the final ones. @@ -87,6 +118,10 @@ public static void GetHistoImageSymbols( HistogramRemap(origHisto, imageHisto, histogramSymbols); } + /// + /// Removes the null histograms from the set. The remaining histograms keep their order. + /// + /// The histograms. private static void RemoveEmptyHistograms(Vp8LHistogramSet histograms) { for (int i = histograms.Count - 1; i >= 0; i--) @@ -101,24 +136,42 @@ private static void RemoveEmptyHistograms(Vp8LHistogramSet histograms) /// /// Construct the histograms from the backward references. /// + /// The image width in pixels. + /// The base-2 logarithm of the tile width and height in pixels. + /// The backward references of the image, in pixel order. + /// Receives the counts. The set holds one histogram for each tile, in row-major tile order. private static void HistogramBuild( int xSize, int histoBits, - Vp8LBackwardRefs backwardRefs, + Vp8LBackwardReferences backwardRefs, Vp8LHistogramSet histograms) { int x = 0, y = 0; int histoXSize = LosslessUtils.SubSampleSize(xSize, histoBits); - foreach (PixOrCopy v in backwardRefs) + // Each token goes to the histogram of its tile. The tile changes only every few tokens, so get the memory of a histogram only + // when the tile changes, not once for each token. + int histogramIndex = -1; + Span histogram = default; + int blockCount = backwardRefs.BlockCount; + for (int block = 0; block < blockCount; block++) { - int ix = ((y >> histoBits) * histoXSize) + (x >> histoBits); - histograms[ix].AddSinglePixOrCopy(in v, false); - x += v.Len; - while (x >= xSize) + foreach (PixelOrCopy v in backwardRefs.GetBlock(block)) { - x -= xSize; - y++; + int ix = ((y >> histoBits) * histoXSize) + (x >> histoBits); + if (ix != histogramIndex) + { + histogram = histograms.GetHistogramMemory(ix); + histogramIndex = ix; + } + + Vp8LHistogram.AddToken(histogram, in v, false, 0); + x += v.Len; + while (x >= xSize) + { + x -= xSize; + y++; + } } } } @@ -127,6 +180,8 @@ private static void HistogramBuild( /// Partition histograms to different entropy bins for three dominant (literal, /// red and blue) symbol costs and compute the histogram aggregate bitCost. /// + /// The histograms to partition. The method skips null entries. + /// Receives the entropy bin index of each histogram, at the index of the histogram. private static void HistogramAnalyzeEntropyBin(Vp8LHistogramSet histograms, Span binMap) { int histoSize = histograms.Count; @@ -156,17 +211,24 @@ private static void HistogramAnalyzeEntropyBin(Vp8LHistogramSet histograms, Span } } + /// + /// Computes the cost of each original histogram and copies the used histograms to the destination set. + /// An empty histogram is set to null in both sets and its tile gets . + /// The other tiles get consecutive cluster indices. + /// + /// The original tile histograms. + /// Receives the copies of the used histograms. + /// Receives the cluster index of each tile. + /// The number of used histograms. private static int HistogramCopyAndAnalyze( Vp8LHistogramSet origHistograms, Vp8LHistogramSet histograms, Span histogramSymbols) { - Vp8LStreaks stats = new(); - Vp8LBitEntropy bitsEntropy = new(); for (int clusterId = 0, i = 0; i < origHistograms.Count; i++) { Vp8LHistogram origHistogram = origHistograms[i]; - origHistogram.UpdateHistogramCost(stats, bitsEntropy); + origHistogram.UpdateHistogramCost(); // Skip the histogram if it is completely empty, which can happen for tiles with no information (when they are skipped because of LZ77). if (!origHistogram.IsUsed(0) && !origHistogram.IsUsed(1) && !origHistogram.IsUsed(2) && !origHistogram.IsUsed(3) && !origHistogram.IsUsed(4)) @@ -194,7 +256,20 @@ private static int HistogramCopyAndAnalyze( return numUsed; } + /// + /// Merges each histogram into the first histogram of its entropy bin when the merge saves enough bits. + /// A merged histogram is removed from the set, and its cluster maps to the cluster of the first histogram. + /// + /// The memory allocator. + /// The histograms. + /// The cluster index of each histogram. + /// Receives the cluster that each cluster merges into. + /// A scratch histogram for the merge result. + /// The entropy bin of each histogram. + /// The number of entropy bins. + /// The share of the histogram cost that a merge must save. private static void HistogramCombineEntropyBin( + MemoryAllocator memoryAllocator, Vp8LHistogramSet histograms, ReadOnlySpan clusters, Span clusterMappings, @@ -203,7 +278,9 @@ private static void HistogramCombineEntropyBin( int numBins, double combineCostFactor) { - Span binInfo = stackalloc HistogramBinInfo[BinSize]; + // BinSize is 64. The loop below sets each entry that a bin index reads. + InlineArray64 binInfoStorage = default; + Span binInfo = binInfoStorage; for (int idx = 0; idx < numBins; idx++) { binInfo[idx].First = -1; @@ -216,9 +293,11 @@ private static void HistogramCombineEntropyBin( clusterMappings[idx] = (ushort)idx; } - List indicesToRemove = []; - Vp8LStreaks stats = new(); - Vp8LBitEntropy bitsEntropy = new(); + // Each histogram is merged at most once, so the list holds at most one index for each histogram. + // No clear: only the first indicesToRemoveCount entries are read, and each of them is written first. + using IMemoryOwner indicesToRemoveBuffer = memoryAllocator.Allocate(histograms.Count); + Span indicesToRemove = indicesToRemoveBuffer.GetSpan(); + int indicesToRemoveCount = 0; for (int idx = 0; idx < histograms.Count; idx++) { if (histograms[idx] == null) @@ -237,7 +316,7 @@ private static void HistogramCombineEntropyBin( // Try to merge #idx into #first (both share the same binId) double bitCost = histograms[idx].BitCost; double bitCostThresh = -bitCost * combineCostFactor; - double currCostDiff = histograms[first].AddEval(histograms[idx], stats, bitsEntropy, bitCostThresh, curCombo); + double currCostDiff = histograms[first].AddEval(histograms[idx], bitCostThresh, curCombo); if (currCostDiff < bitCostThresh) { @@ -256,7 +335,7 @@ private static void HistogramCombineEntropyBin( (histograms[first], curCombo) = (curCombo, histograms[first]); histograms[idx] = null; - indicesToRemove.Add(idx); + indicesToRemove[indicesToRemoveCount++] = idx; clusterMappings[clusters[idx]] = clusters[first]; } else @@ -267,7 +346,8 @@ private static void HistogramCombineEntropyBin( } } - for (int i = indicesToRemove.Count - 1; i >= 0; i--) + // The indices increase, so a removal from the end does not move the histograms that are still to be removed. + for (int i = indicesToRemoveCount - 1; i >= 0; i--) { histograms.RemoveAt(indicesToRemove[i]); } @@ -277,6 +357,12 @@ private static void HistogramCombineEntropyBin( /// Given a Histogram set, the mapping of clusters 'clusterMapping' and the /// current assignment of the cells in 'symbols', merge the clusters and assign the smallest possible clusters values. /// + /// The cluster that each cluster merged into. The method replaces each entry with the root cluster of its chain. + /// The number of entries in to resolve. + /// The scratch map from a root cluster to its new cluster value. The method clears it before use. + /// + /// The cluster of each tile. Receives the new cluster value of each tile. Tiles with stay unchanged. + /// private static void OptimizeHistogramSymbols(Span clusterMappings, int numClusters, Span clusterMappingsTmp, Span symbols) { bool doContinue = true; @@ -328,16 +414,17 @@ private static void OptimizeHistogramSymbols(Span clusterMappings, int n /// /// Perform histogram aggregation using a stochastic approach. /// + /// The memory allocator. + /// The histograms to combine. The method merges pairs and sets each merged-away histogram to null. + /// The number of used histograms at which the method stops combining. /// true if a greedy approach needs to be performed afterwards, false otherwise. - private static bool HistogramCombineStochastic(Vp8LHistogramSet histograms, int minClusterSize) + private static bool HistogramCombineStochastic(MemoryAllocator memoryAllocator, Vp8LHistogramSet histograms, int minClusterSize) { uint seed = 1; int triesWithNoSuccess = 0; - int numUsed = histograms.Count(h => h != null); + int numUsed = CountUsed(histograms); int outerIters = numUsed; int numTriesNoSuccess = (int)((uint)outerIters / 2); - Vp8LStreaks stats = new(); - Vp8LBitEntropy bitsEntropy = new(); if (numUsed < minClusterSize) { @@ -346,11 +433,16 @@ private static bool HistogramCombineStochastic(Vp8LHistogramSet histograms, int // Priority list of histogram pairs. Its size impacts the quality of the compression and the speed: // the smaller the faster but the worse for the compression. - List histoPriorityList = []; + // The list is a slice of a 10 entry inline array, so its length is the maximum size. const int maxSize = 9; - - // Fill the initial mapping. - Span mappings = histograms.Count <= 64 ? stackalloc int[histograms.Count] : new int[histograms.Count]; + InlineArray10 histoPriorityListStorage = default; + Span histoPriorityList = ((Span)histoPriorityListStorage)[..maxSize]; + int histoPriorityListSize = 0; + + // Fill the initial mapping. The mapping holds the index of each used histogram, in increasing order. + // No clear: only the first numUsed entries are read, and the loop below writes each of them first. + using IMemoryOwner mappingsBuffer = memoryAllocator.Allocate(histograms.Count); + Span mappings = mappingsBuffer.GetSpan(); for (int j = 0, i = 0; i < histograms.Count; i++) { if (histograms[i] == null) @@ -364,7 +456,7 @@ private static bool HistogramCombineStochastic(Vp8LHistogramSet histograms, int // Collapse similar histograms. for (int i = 0; i < outerIters && numUsed >= minClusterSize && ++triesWithNoSuccess < numTriesNoSuccess; i++) { - double bestCost = histoPriorityList.Count == 0 ? 0D : histoPriorityList[0].CostDiff; + double bestCost = histoPriorityListSize == 0 ? 0D : histoPriorityList[0].CostDiff; int numTries = (int)((uint)numUsed / 2); uint randRange = (uint)((numUsed - 1) * numUsed); @@ -384,21 +476,21 @@ private static bool HistogramCombineStochastic(Vp8LHistogramSet histograms, int idx2 = mappings[idx2]; // Calculate cost reduction on combination. - double currCost = HistoPriorityListPush(histoPriorityList, maxSize, histograms, idx1, idx2, bestCost, stats, bitsEntropy); + double currCost = HistoPriorityListPush(histoPriorityList, ref histoPriorityListSize, histograms, idx1, idx2, bestCost); // Found a better pair? if (currCost < 0) { bestCost = currCost; - if (histoPriorityList.Count == maxSize) + if (histoPriorityListSize == maxSize) { break; } } } - if (histoPriorityList.Count == 0) + if (histoPriorityListSize == 0) { continue; } @@ -407,20 +499,21 @@ private static bool HistogramCombineStochastic(Vp8LHistogramSet histograms, int int bestIdx1 = histoPriorityList[0].Idx1; int bestIdx2 = histoPriorityList[0].Idx2; - int mappingIndex = mappings.IndexOf(bestIdx2); + int mappingIndex = mappings[..numUsed].IndexOf(bestIdx2); Span src = mappings.Slice(mappingIndex + 1, numUsed - mappingIndex - 1); Span dst = mappings[mappingIndex..]; src.CopyTo(dst); // Merge the histograms and remove bestIdx2 from the list. - HistogramAdd(histograms[bestIdx2], histograms[bestIdx1], histograms[bestIdx1]); + histograms[bestIdx2].Add(histograms[bestIdx1], histograms[bestIdx1]); histograms[bestIdx1].BitCost = histoPriorityList[0].CostCombo; histograms[bestIdx2] = null; numUsed--; - for (int j = 0; j < histoPriorityList.Count;) + for (int j = 0; j < histoPriorityListSize;) { - HistogramPair p = histoPriorityList[j]; + // The pair is updated in place in the list. + ref HistogramPair p = ref histoPriorityList[j]; bool isIdx1Best = p.Idx1 == bestIdx1 || p.Idx1 == bestIdx2; bool isIdx2Best = p.Idx2 == bestIdx1 || p.Idx2 == bestIdx2; bool doEval = false; @@ -429,8 +522,8 @@ private static bool HistogramCombineStochastic(Vp8LHistogramSet histograms, int // check for it all the time nevertheless. if (isIdx1Best && isIdx2Best) { - histoPriorityList[j] = histoPriorityList[^1]; - histoPriorityList.RemoveAt(histoPriorityList.Count - 1); + // Replace the pair with the last one and shrink the list. + p = histoPriorityList[--histoPriorityListSize]; continue; } @@ -456,17 +549,16 @@ private static bool HistogramCombineStochastic(Vp8LHistogramSet histograms, int if (doEval) { // Re-evaluate the cost of an updated pair. - HistoListUpdatePair(histograms[p.Idx1], histograms[p.Idx2], stats, bitsEntropy, 0D, p); + HistoListUpdatePair(histograms[p.Idx1], histograms[p.Idx2], 0D, ref p); if (p.CostDiff >= 0D) { - histoPriorityList[j] = histoPriorityList[^1]; - histoPriorityList.RemoveAt(histoPriorityList.Count - 1); + p = histoPriorityList[--histoPriorityListSize]; continue; } } - HistoListUpdateHead(histoPriorityList, p, j); + HistoListUpdateHead(histoPriorityList, j); j++; } @@ -476,15 +568,40 @@ private static bool HistogramCombineStochastic(Vp8LHistogramSet histograms, int return numUsed <= minClusterSize; } - private static void HistogramCombineGreedy(Vp8LHistogramSet histograms) + /// + /// Counts the histograms of the set that are in use. The merge steps set a merged histogram to null. + /// + /// The histograms. + /// The number of histograms that are not null. + private static int CountUsed(Vp8LHistogramSet histograms) + { + int used = 0; + for (int i = 0; i < histograms.Count; i++) + { + if (histograms[i] != null) + { + used++; + } + } + + return used; + } + + /// + /// Merges histogram pairs, best pair first, until no merge reduces the total cost. + /// A merged histogram is set to null. + /// + /// The memory allocator. + /// The histograms. On entry, the set must have no null histograms. + private static void HistogramCombineGreedy(MemoryAllocator memoryAllocator, Vp8LHistogramSet histograms) { - int histoSize = histograms.Count(h => h != null); + int histoSize = CountUsed(histograms); - // Priority list of histogram pairs. - List histoPriorityList = []; - int maxSize = histoSize * histoSize; - Vp8LStreaks stats = new(); - Vp8LBitEntropy bitsEntropy = new(); + // Priority list of histogram pairs. It can hold a pair for each two histograms. + // No clear: only the first histoPriorityListSize pairs are read, and each of them is written first. + using IMemoryOwner histoPriorityListBuffer = memoryAllocator.Allocate(histoSize * histoSize); + Span histoPriorityList = histoPriorityListBuffer.GetSpan(); + int histoPriorityListSize = 0; for (int i = 0; i < histoSize; i++) { @@ -500,33 +617,32 @@ private static void HistogramCombineGreedy(Vp8LHistogramSet histograms) continue; } - HistoPriorityListPush(histoPriorityList, maxSize, histograms, i, j, 0.0d, stats, bitsEntropy); + HistoPriorityListPush(histoPriorityList, ref histoPriorityListSize, histograms, i, j, 0.0d); } } - while (histoPriorityList.Count > 0) + while (histoPriorityListSize > 0) { int idx1 = histoPriorityList[0].Idx1; int idx2 = histoPriorityList[0].Idx2; - HistogramAdd(histograms[idx2], histograms[idx1], histograms[idx1]); + histograms[idx2].Add(histograms[idx1], histograms[idx1]); histograms[idx1].BitCost = histoPriorityList[0].CostCombo; // Remove merged histogram. histograms[idx2] = null; // Remove pairs intersecting the just combined best pair. - for (int i = 0; i < histoPriorityList.Count;) + for (int i = 0; i < histoPriorityListSize;) { - HistogramPair p = histoPriorityList[i]; + ref HistogramPair p = ref histoPriorityList[i]; if (p.Idx1 == idx1 || p.Idx2 == idx1 || p.Idx1 == idx2 || p.Idx2 == idx2) { // Replace item at pos i with the last one and shrinking the list. - histoPriorityList[i] = histoPriorityList[^1]; - histoPriorityList.RemoveAt(histoPriorityList.Count - 1); + p = histoPriorityList[--histoPriorityListSize]; } else { - HistoListUpdateHead(histoPriorityList, p, i); + HistoListUpdateHead(histoPriorityList, i); i++; } } @@ -539,11 +655,18 @@ private static void HistogramCombineGreedy(Vp8LHistogramSet histograms) continue; } - HistoPriorityListPush(histoPriorityList, maxSize, histograms, idx1, i, 0.0d, stats, bitsEntropy); + HistoPriorityListPush(histoPriorityList, ref histoPriorityListSize, histograms, idx1, i, 0.0d); } } } + /// + /// Maps each original histogram to the output histogram that adds the fewest bits. Then it rebuilds each output histogram + /// as the sum of the original histograms mapped to it. + /// + /// The original tile histograms. Empty tiles are null. + /// The final histograms. The set must have no null histograms. + /// Receives the output histogram index of each tile. An empty tile gets the index of the previous tile. private static void HistogramRemap( Vp8LHistogramSet input, Vp8LHistogramSet output, @@ -551,8 +674,6 @@ private static void HistogramRemap( { int inSize = input.Count; int outSize = output.Count; - Vp8LStreaks stats = new(); - Vp8LBitEntropy bitsEntropy = new(); if (outSize > 1) { for (int i = 0; i < inSize; i++) @@ -568,7 +689,7 @@ private static void HistogramRemap( double bestBits = double.MaxValue; for (int k = 0; k < outSize; k++) { - double curBits = output[k].AddThresh(input[i], stats, bitsEntropy, bestBits); + double curBits = output[k].AddThresh(input[i], bestBits); if (k == 0 || curBits < bestBits) { bestBits = curBits; @@ -610,20 +731,22 @@ private static void HistogramRemap( /// /// Create a pair from indices "idx1" and "idx2" provided its cost is inferior to "threshold", a negative entropy. /// + /// The priority list. Its length is the maximum number of pairs. + /// The number of pairs in the list. + /// The histograms. + /// The index of the first histogram. + /// The index of the second histogram. + /// The cost difference that the pair must be less than. /// The cost of the pair, or 0 if it superior to threshold. private static double HistoPriorityListPush( - List histoList, - int maxSize, + Span histoList, + ref int histoListSize, Vp8LHistogramSet histograms, int idx1, int idx2, - double threshold, - Vp8LStreaks stats, - Vp8LBitEntropy bitsEntropy) + double threshold) { - HistogramPair pair = new(); - - if (histoList.Count == maxSize) + if (histoListSize == histoList.Length) { return 0D; } @@ -633,12 +756,13 @@ private static double HistoPriorityListPush( (idx1, idx2) = (idx2, idx1); } + HistogramPair pair = default; pair.Idx1 = idx1; pair.Idx2 = idx2; Vp8LHistogram h1 = histograms[idx1]; Vp8LHistogram h2 = histograms[idx2]; - HistoListUpdatePair(h1, h2, stats, bitsEntropy, threshold, pair); + HistoListUpdatePair(h1, h2, threshold, ref pair); // Do not even consider the pair if it does not improve the entropy. if (pair.CostDiff >= threshold) @@ -646,9 +770,9 @@ private static double HistoPriorityListPush( return 0.0d; } - histoList.Add(pair); - - HistoListUpdateHead(histoList, pair, histoList.Count - 1); + histoList[histoListSize] = pair; + HistoListUpdateHead(histoList, histoListSize); + histoListSize++; return pair.CostDiff; } @@ -657,39 +781,40 @@ private static double HistoPriorityListPush( /// Update the cost diff and combo of a pair of histograms. This needs to be called when the histograms have been /// merged with a third one. /// - private static void HistoListUpdatePair( - Vp8LHistogram h1, - Vp8LHistogram h2, - Vp8LStreaks stats, - Vp8LBitEntropy bitsEntropy, - double threshold, - HistogramPair pair) + /// The first histogram of the pair. + /// The second histogram of the pair. + /// The cost difference above which the entropy estimate can stop early. + /// The pair to update. Receives the combined cost and the cost difference. + private static void HistoListUpdatePair(Vp8LHistogram h1, Vp8LHistogram h2, double threshold, ref HistogramPair pair) { double sumCost = h1.BitCost + h2.BitCost; pair.CostCombo = 0.0d; - h1.GetCombinedHistogramEntropy(h2, stats, bitsEntropy, sumCost + threshold, costInitial: pair.CostCombo, out double cost); + h1.GetCombinedHistogramEntropy(h2, sumCost + threshold, pair.CostCombo, out double cost); pair.CostCombo = cost; pair.CostDiff = pair.CostCombo - sumCost; } /// /// Check whether a pair in the list should be updated as head or not. + /// If its cost difference is less than the cost difference of the head, the two pairs change places. /// - private static void HistoListUpdateHead(List histoList, HistogramPair pair, int idx) + /// The priority list. + /// The index of the pair to check. + private static void HistoListUpdateHead(Span histoList, int idx) { - if (pair.CostDiff < histoList[0].CostDiff) + if (histoList[idx].CostDiff < histoList[0].CostDiff) { - histoList[idx] = histoList[0]; - histoList[0] = pair; + (histoList[idx], histoList[0]) = (histoList[0], histoList[idx]); } } - private static void HistogramAdd(Vp8LHistogram a, Vp8LHistogram b, Vp8LHistogram output) - { - a.Add(b, output); - output.TrivialSymbol = a.TrivialSymbol == b.TrivialSymbol ? a.TrivialSymbol : NonTrivialSym; - } - + /// + /// Gets the share of the histogram cost that an entropy bin merge must save. + /// Below quality 90, the factor gets smaller for many histograms and for low quality, so fewer merges occur. + /// + /// The number of tile histograms. + /// The encoding quality, from 0 to 100. + /// The cost factor. private static double GetCombineCostFactor(int histoSize, uint quality) { double combineCostFactor = 0.16d; @@ -719,7 +844,14 @@ private static double GetCombineCostFactor(int histoSize, uint quality) return combineCostFactor; } - // Implement a Lehmer random number generator with a multiplicative constant of 48271 and a modulo constant of 2^31 - 1. + /// + /// Gets the next value of a deterministic pseudo-random sequence. + /// + /// + /// The generator is a Lehmer generator with the multiplier 48271 and the modulus 2^31 - 1. + /// + /// The generator state. On return, the next state. + /// The next value, from 1 to 2^31 - 2 for a seed in the same range. [MethodImpl(InliningOptions.ShortMethod)] private static uint MyRand(ref uint seed) { diff --git a/src/ImageSharp/Formats/Webp/Lossless/HistogramPair.cs b/src/ImageSharp/Formats/Webp/Lossless/HistogramPair.cs index 5a31f1c820..79b64ead70 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/HistogramPair.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/HistogramPair.cs @@ -7,15 +7,28 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; /// /// Pair of histograms. Negative Idx1 value means that pair is out-of-date. +/// The pairs are values in a priority queue buffer, so a pair is never allocated on its own. /// [DebuggerDisplay("Idx1: {Idx1}, Idx2: {Idx2}, CostDiff: {CostDiff}, CostCombo: {CostCombo}")] -internal class HistogramPair +internal struct HistogramPair { - public int Idx1 { get; set; } + /// + /// The index of the first histogram. It is less than . + /// + public int Idx1; - public int Idx2 { get; set; } + /// + /// The index of the second histogram. + /// + public int Idx2; - public double CostDiff { get; set; } + /// + /// The cost of the combined histogram minus the costs of the two histograms. + /// + public double CostDiff; - public double CostCombo { get; set; } + /// + /// The cost of the combined histogram. + /// + public double CostCombo; } diff --git a/src/ImageSharp/Formats/Webp/Lossless/HuffIndex.cs b/src/ImageSharp/Formats/Webp/Lossless/HuffmanIndex.cs similarity index 95% rename from src/ImageSharp/Formats/Webp/Lossless/HuffIndex.cs rename to src/ImageSharp/Formats/Webp/Lossless/HuffmanIndex.cs index 82c1ce74dc..58f3bb8f39 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/HuffIndex.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/HuffmanIndex.cs @@ -6,7 +6,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; /// /// Five Huffman codes are used at each meta code. /// -internal static class HuffIndex +internal static class HuffmanIndex { /// /// Green + length prefix codes + color cache codes. diff --git a/src/ImageSharp/Formats/Webp/Lossless/HuffmanTreeCode.cs b/src/ImageSharp/Formats/Webp/Lossless/HuffmanTreeCode.cs deleted file mode 100644 index 4c101bc499..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossless/HuffmanTreeCode.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossless; - -/// -/// Represents the tree codes (depth and bits array). -/// -internal struct HuffmanTreeCode -{ - /// - /// Gets or sets the number of symbols. - /// - public int NumSymbols { get; set; } - - /// - /// Gets or sets the code lengths of the symbols. - /// - public byte[] CodeLengths { get; set; } - - /// - /// Gets or sets the symbol Codes. - /// - public short[] Codes { get; set; } -} diff --git a/src/ImageSharp/Formats/Webp/Lossless/HuffmanTreeGroup.cs b/src/ImageSharp/Formats/Webp/Lossless/HuffmanTreeGroup.cs new file mode 100644 index 0000000000..b4f18c2fb4 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossless/HuffmanTreeGroup.cs @@ -0,0 +1,85 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.ImageSharp.Formats.Webp.Lossless; + +/// +/// Huffman table group. +/// Includes special handling for the following cases: +/// - IsTrivialLiteral: one common literal base for RED/BLUE/ALPHA (not GREEN) +/// - IsTrivialCode: only 1 code (no bit is read from the bitstream) +/// - UsePackedTable: few enough literal symbols, so all the bit codes can fit into a small look-up table +/// The common literal base, if applicable, is stored in 'LiteralArb'. +/// +/// +/// The tables of all groups are in one buffer, . The packed tables are in . +/// A group keeps the offsets of its tables in these buffers. Thus the decode loop reads a table with one offset, and the group needs no allocation. +/// +internal struct HuffmanTreeGroup +{ + /// + /// Gets or sets the offset of the green, length prefix and color cache table. + /// + public int Green { get; set; } + + /// + /// Gets or sets the offset of the red table. + /// + public int Red { get; set; } + + /// + /// Gets or sets the offset of the blue table. + /// + public int Blue { get; set; } + + /// + /// Gets or sets the offset of the alpha table. + /// + public int Alpha { get; set; } + + /// + /// Gets or sets the offset of the distance prefix table. + /// + public int Dist { get; set; } + + /// + /// Gets or sets a value indicating whether huffman trees for Red, Blue and Alpha Symbols are trivial (have a single code). + /// + public bool IsTrivialLiteral { get; set; } + + /// + /// Gets or sets a the literal argb value of the pixel. + /// If IsTrivialLiteral is true, this is the ARGB value of the pixel, with Green channel being set to zero. + /// + public uint LiteralArb { get; set; } + + /// + /// Gets or sets a value indicating whether the alpha code has only one symbol. Then the code reads no bits, and holds the + /// alpha value. + /// + /// + /// Most images are opaque, so the alpha code usually has one symbol. As in libwebp, the decode loop then does not read the alpha table. This removes one + /// table load from the serial bit read of each literal pixel. + /// + public bool IsTrivialAlpha { get; set; } + + /// + /// Gets or sets the alpha value of the one alpha symbol in bits 24 to 31, when is . + /// + public uint TrivialAlpha { get; set; } + + /// + /// Gets or sets a value indicating whether there is only one code. + /// + public bool IsTrivialCode { get; set; } + + /// + /// Gets or sets a value indicating whether to use the packed table for short literal codes. + /// + public bool UsePackedTable { get; set; } + + /// + /// Gets or sets the offset of the packed table, which maps the input bits to packed values, or to the green code of a value that is not a literal. + /// + public int PackedTable { get; set; } +} diff --git a/src/ImageSharp/Formats/Webp/Lossless/HuffmanTreeToken.cs b/src/ImageSharp/Formats/Webp/Lossless/HuffmanTreeToken.cs index 39cb3bef38..81c0202797 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/HuffmanTreeToken.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/HuffmanTreeToken.cs @@ -8,8 +8,11 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; /// /// Holds the tree header in coded form. /// +/// +/// The type is a value type, so a token buffer is one block of memory and the tokens need no allocation each. +/// [DebuggerDisplay("Code = {Code}, ExtraBits = {ExtraBits}")] -internal class HuffmanTreeToken +internal struct HuffmanTreeToken { /// /// Gets or sets the code. Value (0..15) or escape code (16, 17, 18). diff --git a/src/ImageSharp/Formats/Webp/Lossless/HuffmanUtils.cs b/src/ImageSharp/Formats/Webp/Lossless/HuffmanUtils.cs index 497e282759..5ec242419c 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/HuffmanUtils.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/HuffmanUtils.cs @@ -11,37 +11,75 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; /// internal static class HuffmanUtils { + /// + /// The number of input bits that index the first-level Huffman decode table. + /// public const int HuffmanTableBits = 8; + /// + /// The number of input bits that index a packed table. A group uses a packed table only when the sum of its longest green, red, blue and alpha + /// code lengths is less than this value. + /// public const int HuffmanPackedBits = 6; + /// + /// The mask that selects the first-level table index from the input bits. + /// public const int HuffmanTableMask = (1 << HuffmanTableBits) - 1; + /// + /// The number of entries in a packed table. + /// public const uint HuffmanPackedTableSize = 1u << HuffmanPackedBits; - // Pre-reversed 4-bit values. + /// + /// The bit-reversed value of each 4-bit value. + /// private static readonly byte[] ReversedBits = [ 0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe, 0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf ]; - public static void CreateHuffmanTree(Span histogram, int treeDepthLimit, bool[] bufRle, Span huffTree, HuffmanTreeCode huffCode) + /// + /// Creates a length-limited Huffman code for a histogram. The histogram counts are first changed to give longer runs of equal code lengths. + /// + /// The symbol counts. The method changes the counts. + /// The maximum code length. + /// A scratch buffer with at least one entry for each symbol. + /// A scratch buffer for the tree nodes, with at least three entries for each symbol. + /// Receives the code length of each symbol. Its length sets the number of symbols. The code lengths must start at zero. + /// Receives the bit-reversed code of each symbol. It has the length of . + public static void CreateHuffmanTree( + Span histogram, + int treeDepthLimit, + Span bufRle, + Span huffTree, + Span codeLengths, + Span codes) { - int numSymbols = huffCode.NumSymbols; - bufRle.AsSpan().Clear(); - OptimizeHuffmanForRle(numSymbols, bufRle, histogram); - GenerateOptimalTree(huffTree, histogram, numSymbols, treeDepthLimit, huffCode.CodeLengths); + int numSymbols = codeLengths.Length; + + // The RLE step reads and writes only the flags of the symbols, so only these flags need a clear. + Span goodForRle = bufRle[..numSymbols]; + goodForRle.Clear(); + OptimizeHuffmanForRle(numSymbols, goodForRle, histogram); + HuffmanCodeLengths.GenerateOptimalTree(huffTree, histogram, numSymbols, treeDepthLimit, codeLengths); // Create the actual bit codes for the bit lengths. - ConvertBitDepthsToSymbols(huffCode); + ConvertBitDepthsToSymbols(codeLengths, codes); } /// /// Change the population counts in a way that the consequent /// Huffman tree compression, especially its RLE-part, give smaller output. /// - public static void OptimizeHuffmanForRle(int length, bool[] goodForRle, Span counts) + /// The number of symbols in . + /// + /// The scratch flags, one for each symbol. All flags must be false on entry. Receives true for each count that already belongs to a good RLE run. + /// + /// The population count of each symbol. Receives the changed counts. + public static void OptimizeHuffmanForRle(int length, Span goodForRle, Span counts) { // 1) Let's make the Huffman code more compatible with rle encoding. for (; length >= 0; --length) @@ -152,133 +190,23 @@ public static void OptimizeHuffmanForRle(int length, bool[] goodForRle, Span - /// Create an optimal Huffman tree. + /// Converts the code lengths of a Huffman code to code length tokens. Runs of zeros use codes 17 and 18. + /// Runs of a repeated nonzero length use code 16. The previous nonzero length starts at 8. /// - /// - /// The huffman tree. - /// The histogram. - /// The size of the histogram. - /// The tree depth limit. - /// How many bits are used for the symbol. - public static void GenerateOptimalTree(Span tree, ReadOnlySpan histogram, int histogramSize, int treeDepthLimit, byte[] bitDepths) + /// The code lengths of the Huffman code. + /// Receives the tokens. A code never has more tokens than symbols. + /// The number of tokens. + public static int CreateCompressedHuffmanTree(ReadOnlySpan codeLengths, Span tokens) { - uint countMin; - int treeSizeOrig = 0; - - for (int i = 0; i < histogramSize; i++) - { - if (histogram[i] != 0) - { - ++treeSizeOrig; - } - } - - if (treeSizeOrig == 0) - { - return; - } - - Span treePool = tree[treeSizeOrig..]; - - // For block sizes with less than 64k symbols we never need to do a - // second iteration of this loop. - for (countMin = 1; ; countMin *= 2) - { - int treeSize = treeSizeOrig; - - // We need to pack the Huffman tree in treeDepthLimit bits. - // So, we try by faking histogram entries to be at least 'countMin'. - int idx = 0; - for (int j = 0; j < histogramSize; j++) - { - if (histogram[j] != 0) - { - uint count = histogram[j] < countMin ? countMin : histogram[j]; - tree[idx].TotalCount = (int)count; - tree[idx].Value = j; - tree[idx].PoolIndexLeft = -1; - tree[idx].PoolIndexRight = -1; - idx++; - } - } - - // Build the Huffman tree. - Span treeSlice = tree[..treeSize]; - treeSlice.Sort(HuffmanTree.Compare); - - if (treeSize > 1) - { - // Normal case. - int treePoolSize = 0; - while (treeSize > 1) - { - // Finish when we have only one root. - treePool[treePoolSize++] = tree[treeSize - 1]; - treePool[treePoolSize++] = tree[treeSize - 2]; - int count = treePool[treePoolSize - 1].TotalCount + treePool[treePoolSize - 2].TotalCount; - treeSize -= 2; - - // Search for the insertion point. - int k; - for (k = 0; k < treeSize; k++) - { - if (tree[k].TotalCount <= count) - { - break; - } - } - - int endIdx = k + 1; - int num = treeSize - k; - int startIdx = endIdx + num - 1; - for (int i = startIdx; i >= endIdx; i--) - { - tree[i] = tree[i - 1]; - } - - tree[k].TotalCount = count; - tree[k].Value = -1; - tree[k].PoolIndexLeft = treePoolSize - 1; - tree[k].PoolIndexRight = treePoolSize - 2; - treeSize++; - } - - SetBitDepths(tree, treePool, bitDepths, 0); - } - else if (treeSize == 1) - { - // Trivial case: only one element. - bitDepths[tree[0].Value] = 1; - } - - // Test if this Huffman tree satisfies our 'treeDepthLimit' criteria. - int maxDepth = bitDepths[0]; - for (int j = 1; j < histogramSize; j++) - { - if (maxDepth < bitDepths[j]) - { - maxDepth = bitDepths[j]; - } - } - - if (maxDepth <= treeDepthLimit) - { - break; - } - } - } - - public static int CreateCompressedHuffmanTree(HuffmanTreeCode tree, HuffmanTreeToken[] tokensArray) - { - int depthSize = tree.NumSymbols; + int depthSize = codeLengths.Length; int prevValue = 8; // 8 is the initial value for rle. int i = 0; int tokenPos = 0; while (i < depthSize) { - int value = tree.CodeLengths[i]; + int value = codeLengths[i]; int k = i + 1; - while (k < depthSize && tree.CodeLengths[k] == value) + while (k < depthSize && codeLengths[k] == value) { k++; } @@ -286,11 +214,11 @@ public static int CreateCompressedHuffmanTree(HuffmanTreeCode tree, HuffmanTreeT int runs = k - i; if (value == 0) { - tokenPos += CodeRepeatedZeros(runs, tokensArray.AsSpan(tokenPos)); + tokenPos += CodeRepeatedZeros(runs, tokens[tokenPos..]); } else { - tokenPos += CodeRepeatedValues(runs, tokensArray.AsSpan(tokenPos), value, prevValue); + tokenPos += CodeRepeatedValues(runs, tokens[tokenPos..], value, prevValue); prevValue = value; } @@ -300,21 +228,15 @@ public static int CreateCompressedHuffmanTree(HuffmanTreeCode tree, HuffmanTreeT return tokenPos; } +#pragma warning disable CA1517 // False positive: https://github.com/dotnet/sdk/issues/53388 /// - /// Builds the lossless WebP Huffman table through the shared canonical table builder. + /// Writes the tokens for a run of zero code lengths. Code 17 repeats a zero 3 to 10 times. Code 18 repeats a zero 11 to 138 times. + /// A run of fewer than 3 zeros uses literal zeros. /// - /// The lookup storage. - /// The first lookup width. - /// The code lengths for the alphabet. - /// The number of alphabet symbols. - /// The table entry count, or zero for an invalid code. - public static int BuildHuffmanTable(Span table, int rootBits, int[] codeLengths, int codeLengthsSize) - { - Span sorted = codeLengthsSize <= 64 ? stackalloc int[codeLengthsSize] : new int[codeLengthsSize]; - return HuffmanTableBuilder.Build(table, rootBits, codeLengths.AsSpan(0, codeLengthsSize), sorted); - } - - private static int CodeRepeatedZeros(int repetitions, ReadOnlySpan tokens) + /// The run length. + /// Receives the tokens. + /// The number of tokens written. + private static int CodeRepeatedZeros(int repetitions, Span tokens) { int pos = 0; while (repetitions >= 1) @@ -356,7 +278,16 @@ private static int CodeRepeatedZeros(int repetitions, ReadOnlySpan tokens, int value, int prevValue) + /// + /// Writes the tokens for a run of one nonzero code length. When the length differs from the previous nonzero length, + /// the first token is the length itself. Code 16 then repeats the previous length 3 to 6 times. + /// + /// The run length. + /// Receives the tokens. + /// The code length of the run. + /// The previous nonzero code length. + /// The number of tokens written. + private static int CodeRepeatedValues(int repetitions, Span tokens, int value, int prevValue) { int pos = 0; @@ -399,21 +330,25 @@ private static int CodeRepeatedValues(int repetitions, ReadOnlySpan /// Get the actual bit values for a tree of bit depths. /// - /// The huffman tree. - private static void ConvertBitDepthsToSymbols(HuffmanTreeCode tree) + /// The code length of each symbol. + /// Receives the bit-reversed code of each symbol. It has the length of . + private static void ConvertBitDepthsToSymbols(ReadOnlySpan codeLengths, Span codes) { - // 0 bit-depth means that the symbol does not exist. - Span nextCode = stackalloc uint[WebpConstants.MaxAllowedCodeLength + 1]; - Span depthCount = stackalloc int[WebpConstants.MaxAllowedCodeLength + 1]; + // 0 bit-depth means that the symbol does not exist. MaxAllowedCodeLength is 15, so each table has 16 entries. + InlineArray16 nextCodeStorage = default; + InlineArray16 depthCountStorage = default; + Span nextCode = nextCodeStorage; + Span depthCount = depthCountStorage; - int len = tree.NumSymbols; + int len = codeLengths.Length; for (int i = 0; i < len; i++) { - int codeLength = tree.CodeLengths[i]; + int codeLength = codeLengths[i]; depthCount[codeLength]++; } @@ -429,24 +364,17 @@ private static void ConvertBitDepthsToSymbols(HuffmanTreeCode tree) for (int i = 0; i < len; i++) { - int codeLength = tree.CodeLengths[i]; - tree.Codes[i] = (short)ReverseBits(codeLength, nextCode[codeLength]++); - } - } - - private static void SetBitDepths(ReadOnlySpan tree, Span pool, byte[] bitDepths, int level) - { - if (tree[0].PoolIndexLeft >= 0) - { - SetBitDepths(pool[tree[0].PoolIndexLeft..], pool, bitDepths, level + 1); - SetBitDepths(pool[tree[0].PoolIndexRight..], pool, bitDepths, level + 1); - } - else - { - bitDepths[tree[0].Value] = (byte)level; + int codeLength = codeLengths[i]; + codes[i] = (short)ReverseBits(codeLength, nextCode[codeLength]++); } } + /// + /// Reverses the order of the low bits of a value. The method reverses 4 bits at a time with a lookup table. + /// + /// The number of bits to reverse. + /// The value. + /// The low bits of the value in reverse order. private static uint ReverseBits(int numBits, uint bits) { uint retval = 0; @@ -465,6 +393,9 @@ private static uint ReverseBits(int numBits, uint bits) /// /// Heuristics for selecting the stride ranges to collapse. /// + /// The population count of the current symbol. + /// The average population count of the current stride. + /// if the two counts differ by less than 4; otherwise, . [MethodImpl(InliningOptions.ShortMethod)] private static bool ValuesShouldBeCollapsedToStrideAverage(int a, int b) => Math.Abs(a - b) < 4; } diff --git a/src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.Operators.cs b/src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.Operators.cs new file mode 100644 index 0000000000..4f53e579e7 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.Operators.cs @@ -0,0 +1,249 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossless; + +/// +/// Contains the operators that packs a row of palette indices with. +/// +internal static partial class LosslessUtils +{ + /// + /// Packs palette indices into packed pixels for the color indexing transform. + /// + /// + /// A packed pixel holds 1 << XBits indices of 8 >> XBits bits each in the green byte (bits 8 to 15). + /// The index of the first pixel is in the low bits. The alpha byte is 255, and red and blue are zero. + /// Each form reads one vector of indices and writes Count >> XBits packed pixels. + /// The caller makes sure that each index is less than 1 << (8 >> XBits), because the palette size sets XBits. + /// Thus the packed bits of two indices do not overlap, as in the scalar form. + /// + private interface IBundleOperator + { + /// + /// Gets the base 2 logarithm of the number of indices in one packed pixel. + /// + static abstract int XBits { get; } + + /// + /// Packs 16 indices into 16 >> XBits packed pixels. + /// + /// The indices of 16 adjacent pixels, one in each byte lane. + /// The first packed pixel to write. + static abstract void Bundle(Vector128 indices, ref uint destination); + + /// + /// Packs 32 indices into 32 >> XBits packed pixels. + /// + /// The indices of 32 adjacent pixels, one in each byte lane. + /// The first packed pixel to write. + static abstract void Bundle(Vector256 indices, ref uint destination); + + /// + /// Packs 64 indices into 64 >> XBits packed pixels. + /// + /// The indices of 64 adjacent pixels, one in each byte lane. + /// The first packed pixel to write. + static abstract void Bundle(Vector512 indices, ref uint destination); + } + + /// + /// Stores one 8-bit index in each pixel: 0xff000000 | (index << 8). + /// + /// + /// The first widen gives two registers of 16-bit lanes. A left shift by 8 moves each index to the high byte of its lane. + /// The second widen gives four registers of 32-bit lanes, and an OR sets the alpha byte. + /// Widen keeps lane order, so packed pixel i holds index i. + /// + private readonly struct Bundle1Operator : IBundleOperator + { + /// + public static int XBits => 0; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Bundle(Vector128 indices, ref uint destination) + { + Vector128 alpha = Vector128.Create(0xff000000u); + (Vector128 lower, Vector128 upper) = Vector128.Widen(indices); + (Vector128 pixels0, Vector128 pixels1) = Vector128.Widen(Vector128.ShiftLeft(lower, 8)); + (Vector128 pixels2, Vector128 pixels3) = Vector128.Widen(Vector128.ShiftLeft(upper, 8)); + (pixels0 | alpha).StoreUnsafe(ref destination); + (pixels1 | alpha).StoreUnsafe(ref destination, 4); + (pixels2 | alpha).StoreUnsafe(ref destination, 8); + (pixels3 | alpha).StoreUnsafe(ref destination, 12); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Bundle(Vector256 indices, ref uint destination) + { + Vector256 alpha = Vector256.Create(0xff000000u); + (Vector256 lower, Vector256 upper) = Vector256.Widen(indices); + (Vector256 pixels0, Vector256 pixels1) = Vector256.Widen(Vector256.ShiftLeft(lower, 8)); + (Vector256 pixels2, Vector256 pixels3) = Vector256.Widen(Vector256.ShiftLeft(upper, 8)); + (pixels0 | alpha).StoreUnsafe(ref destination); + (pixels1 | alpha).StoreUnsafe(ref destination, 8); + (pixels2 | alpha).StoreUnsafe(ref destination, 16); + (pixels3 | alpha).StoreUnsafe(ref destination, 24); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Bundle(Vector512 indices, ref uint destination) + { + Vector512 alpha = Vector512.Create(0xff000000u); + (Vector512 lower, Vector512 upper) = Vector512.Widen(indices); + (Vector512 pixels0, Vector512 pixels1) = Vector512.Widen(Vector512.ShiftLeft(lower, 8)); + (Vector512 pixels2, Vector512 pixels3) = Vector512.Widen(Vector512.ShiftLeft(upper, 8)); + (pixels0 | alpha).StoreUnsafe(ref destination); + (pixels1 | alpha).StoreUnsafe(ref destination, 16); + (pixels2 | alpha).StoreUnsafe(ref destination, 32); + (pixels3 | alpha).StoreUnsafe(ref destination, 48); + } + } + + /// + /// Packs two 4-bit indices into each pixel. + /// + /// + /// Each 16-bit lane holds the indices a (low byte) and b (high byte) of two adjacent pixels. + /// u | (u >> 4) puts a | (b << 4) in the low byte, because a < 16. + /// The left shift by 8 moves this value to the high byte and removes the other bits from the lane. + /// The widen to 32-bit lanes and the OR with the alpha byte give 0xff000000 | ((a | (b << 4)) << 8), as in the scalar form. + /// + private readonly struct Bundle2Operator : IBundleOperator + { + /// + public static int XBits => 1; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Bundle(Vector128 indices, ref uint destination) + { + Vector128 alpha = Vector128.Create(0xff000000u); + Vector128 pairs = indices.AsUInt16(); + Vector128 packed = Vector128.ShiftLeft(pairs | Vector128.ShiftRightLogical(pairs, 4), 8); + (Vector128 pixels0, Vector128 pixels1) = Vector128.Widen(packed); + (pixels0 | alpha).StoreUnsafe(ref destination); + (pixels1 | alpha).StoreUnsafe(ref destination, 4); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Bundle(Vector256 indices, ref uint destination) + { + Vector256 alpha = Vector256.Create(0xff000000u); + Vector256 pairs = indices.AsUInt16(); + Vector256 packed = Vector256.ShiftLeft(pairs | Vector256.ShiftRightLogical(pairs, 4), 8); + (Vector256 pixels0, Vector256 pixels1) = Vector256.Widen(packed); + (pixels0 | alpha).StoreUnsafe(ref destination); + (pixels1 | alpha).StoreUnsafe(ref destination, 8); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Bundle(Vector512 indices, ref uint destination) + { + Vector512 alpha = Vector512.Create(0xff000000u); + Vector512 pairs = indices.AsUInt16(); + Vector512 packed = Vector512.ShiftLeft(pairs | Vector512.ShiftRightLogical(pairs, 4), 8); + (Vector512 pixels0, Vector512 pixels1) = Vector512.Widen(packed); + (pixels0 | alpha).StoreUnsafe(ref destination); + (pixels1 | alpha).StoreUnsafe(ref destination, 16); + } + } + + /// + /// Packs four 2-bit indices into each pixel. + /// + /// + /// Each 32-bit lane holds the indices a, b, c and d of four adjacent pixels in bits 0, 8, 16 and 24. + /// Each index is less than 4. t = u | (u >> 6) puts b in bits 2 to 3, and c and d in bits 16 to 19. + /// t | (t >> 12) moves c and d to bits 4 to 7. Thus the low byte is a | (b << 2) | (c << 4) | (d << 6). + /// The left shift by 8 and the mask keep only this byte in the green byte. The OR sets the alpha byte. + /// + private readonly struct Bundle4Operator : IBundleOperator + { + /// + public static int XBits => 2; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Bundle(Vector128 indices, ref uint destination) + { + Vector128 quads = indices.AsUInt32(); + Vector128 t = quads | Vector128.ShiftRightLogical(quads, 6); + Vector128 packed = Vector128.ShiftLeft(t | Vector128.ShiftRightLogical(t, 12), 8) & Vector128.Create(0x0000ff00u); + (packed | Vector128.Create(0xff000000u)).StoreUnsafe(ref destination); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Bundle(Vector256 indices, ref uint destination) + { + Vector256 quads = indices.AsUInt32(); + Vector256 t = quads | Vector256.ShiftRightLogical(quads, 6); + Vector256 packed = Vector256.ShiftLeft(t | Vector256.ShiftRightLogical(t, 12), 8) & Vector256.Create(0x0000ff00u); + (packed | Vector256.Create(0xff000000u)).StoreUnsafe(ref destination); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Bundle(Vector512 indices, ref uint destination) + { + Vector512 quads = indices.AsUInt32(); + Vector512 t = quads | Vector512.ShiftRightLogical(quads, 6); + Vector512 packed = Vector512.ShiftLeft(t | Vector512.ShiftRightLogical(t, 12), 8) & Vector512.Create(0x0000ff00u); + (packed | Vector512.Create(0xff000000u)).StoreUnsafe(ref destination); + } + } + + /// + /// Packs eight 1-bit indices into each pixel. + /// + /// + /// Each index is 0 or 1. A left shift by 7 moves the index to the most significant bit of its byte lane. + /// The extract of the most significant bits gives one bit for each lane, with lane i in bit i. + /// Thus byte k of the mask holds the eight indices of packed pixel k, the first pixel in the low bit, as in the scalar form. + /// + private readonly struct Bundle8Operator : IBundleOperator + { + /// + public static int XBits => 3; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Bundle(Vector128 indices, ref uint destination) + { + uint mask = Vector128.ExtractMostSignificantBits(Vector128.ShiftLeft(indices, 7)); + destination = 0xff000000u | ((mask & 0xff) << 8); + Unsafe.Add(ref destination, (nuint)1) = 0xff000000u | (mask & 0xff00); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Bundle(Vector256 indices, ref uint destination) + { + uint mask = Vector256.ExtractMostSignificantBits(Vector256.ShiftLeft(indices, 7)); + for (int i = 0; i < 4; i++) + { + Unsafe.Add(ref destination, (uint)i) = 0xff000000u | (((mask >> (8 * i)) & 0xff) << 8); + } + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Bundle(Vector512 indices, ref uint destination) + { + ulong mask = Vector512.ExtractMostSignificantBits(Vector512.ShiftLeft(indices, 7)); + for (int i = 0; i < 8; i++) + { + Unsafe.Add(ref destination, (uint)i) = 0xff000000u | ((uint)((mask >> (8 * i)) & 0xff) << 8); + } + } + } +} diff --git a/src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.PixelTransforms.cs b/src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.PixelTransforms.cs new file mode 100644 index 0000000000..b1891e35ed --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.PixelTransforms.cs @@ -0,0 +1,388 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Common.Helpers; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossless; + +/// +/// Contains the in-place pixel transforms of the subtract green and color transforms, and the driver that runs them. +/// +internal static partial class LosslessUtils +{ + /// + /// Defines an in-place transform of packed ARGB pixels that changes each pixel without reading its neighbors. + /// + /// + /// Each pixel is one little-endian uint: blue in bits 0..7, green in bits 8..15, red in bits 16..23 and alpha in + /// bits 24..31. All forms give the same result for each pixel as the scalar form. + /// + private interface IPixelTransformOperator + { + /// + /// Transforms one pixel. + /// + /// The pixel. + /// The transformed pixel. + public uint Transform(uint argb); + + /// + /// Transforms four pixels. + /// + /// The pixels. + /// The transformed pixels. + public Vector128 Transform(Vector128 argb); + + /// + /// Transforms eight pixels. + /// + /// The pixels. + /// The transformed pixels. + public Vector256 Transform(Vector256 argb); + + /// + /// Transforms sixteen pixels. + /// + /// The pixels. + /// The transformed pixels. + public Vector512 Transform(Vector512 argb); + } + + /// + /// Applies a pixel transform in place to each pixel of a row. + /// + /// The pixel transform. + /// The pixels to transform. + /// The pixel transform and its parameters. + private static void TransformPixels(Span pixels, TOperator operation) + where TOperator : struct, IPixelTransformOperator + { + ref uint pixelBase = ref MemoryMarshal.GetReference(pixels); + nuint length = (uint)pixels.Length; + nuint i = 0; + + // The same offset flows through descending widths, so a row that is not a multiple of the widest register keeps + // a vectorized tail. Each pixel is independent, so the width that transforms a pixel does not change the result. + if (Vector512.IsHardwareAccelerated) + { + for (; i + (uint)Vector512.Count <= length; i += (uint)Vector512.Count) + { + operation.Transform(Vector512.LoadUnsafe(ref pixelBase, i)).StoreUnsafe(ref pixelBase, i); + } + } + + if (Vector256.IsHardwareAccelerated) + { + for (; i + (uint)Vector256.Count <= length; i += (uint)Vector256.Count) + { + operation.Transform(Vector256.LoadUnsafe(ref pixelBase, i)).StoreUnsafe(ref pixelBase, i); + } + } + + if (Vector128.IsHardwareAccelerated) + { + for (; i + (uint)Vector128.Count <= length; i += (uint)Vector128.Count) + { + operation.Transform(Vector128.LoadUnsafe(ref pixelBase, i)).StoreUnsafe(ref pixelBase, i); + } + } + + for (; i < length; i++) + { + ref uint pixel = ref Unsafe.Add(ref pixelBase, i); + pixel = operation.Transform(pixel); + } + } + + /// + /// Gets the byte shuffle that puts the green byte of each pixel in its blue and red bytes, and zero in its green + /// and alpha bytes. Index 255 has the high bit set, so the native shuffle writes zero to that byte. + /// + /// The shuffle indices of one 128-bit lane. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector128 GreenToBlueAndRedIndices() + => Vector128.Create((byte)1, 255, 1, 255, 5, 255, 5, 255, 9, 255, 9, 255, 13, 255, 13, 255); + + /// + /// Adds green to blue and red. This is the inverse of the subtract green transform. + /// + /// + /// The vector forms add byte by byte, so each sum wraps modulo 256 in its own byte, as the masked scalar sum does. + /// + private readonly struct AddGreenOperator : IPixelTransformOperator + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint Transform(uint argb) + { + uint green = (argb >> 8) & 0xff; + uint redBlue = (argb & 0x00ff00ffu) + ((green << 16) | green); + return (argb & 0xff00ff00u) | (redBlue & 0x00ff00ffu); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector128 Transform(Vector128 argb) + => (argb.AsByte() + Vector128.ShuffleNative(argb.AsByte(), GreenToBlueAndRedIndices())).AsUInt32(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector256 Transform(Vector256 argb) + => (argb.AsByte() + Vector256_.ShufflePerLane(argb.AsByte(), GreenToBlueAndRedIndices())).AsUInt32(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector512 Transform(Vector512 argb) + => (argb.AsByte() + Vector512_.ShufflePerLane(argb.AsByte(), GreenToBlueAndRedIndices())).AsUInt32(); + } + + /// + /// Subtracts green from blue and red, the subtract green transform of the encoder. + /// + /// + /// The vector forms subtract byte by byte, so each difference wraps modulo 256 in its own byte, as the masked + /// scalar difference does. + /// + private readonly struct SubtractGreenOperator : IPixelTransformOperator + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint Transform(uint argb) + { + // Bits 8..15 and 24..31 are set to one before the subtraction. Each is at least 255, so a borrow from blue or + // red stops there and does not reach the next channel. The mask then removes them. + uint green = (argb >> 8) & 0xff; + uint redBlue = (argb | 0xff00ff00u) - ((green << 16) | green); + return (argb & 0xff00ff00u) | (redBlue & 0x00ff00ffu); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector128 Transform(Vector128 argb) + => (argb.AsByte() - Vector128.ShuffleNative(argb.AsByte(), GreenToBlueAndRedIndices())).AsUInt32(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector256 Transform(Vector256 argb) + => (argb.AsByte() - Vector256_.ShufflePerLane(argb.AsByte(), GreenToBlueAndRedIndices())).AsUInt32(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector512 Transform(Vector512 argb) + => (argb.AsByte() - Vector512_.ShufflePerLane(argb.AsByte(), GreenToBlueAndRedIndices())).AsUInt32(); + } + + /// + /// Applies the color transform of the encoder: red -= delta(green), blue -= delta(green) + delta(red). + /// + /// + /// + /// A delta is (multiplier * color) >> 5, with both values signed 8-bit. The vector forms compute it with a + /// signed 16-bit high multiply. A color in the high byte of a 16-bit lane is color * 256, and + /// gives multiplier * 8. The high half of the product is thus + /// (color * multiplier * 2048) >> 16 = (color * multiplier) >> 5, and its low byte is the scalar delta. + /// + /// + /// The green multiplier lane holds Cst5b(GreenToRed) in its high 16 bits and Cst5b(GreenToBlue) in its + /// low 16 bits. The red multiplier lane holds Cst5b(RedToBlue) in its high 16 bits and zero in its low 16 bits. + /// + /// + private readonly struct TransformColorOperator : IPixelTransformOperator + { + /// + /// The green-to-red multiplier. + /// + private readonly sbyte greenToRed; + + /// + /// The green-to-blue multiplier. + /// + private readonly sbyte greenToBlue; + + /// + /// The red-to-blue multiplier. + /// + private readonly sbyte redToBlue; + + /// + /// The green multiplier lane for the vector forms: Cst5b(GreenToRed) in the high 16 bits and Cst5b(GreenToBlue) in the low 16 bits. + /// + private readonly int greenMultipliers; + + /// + /// The red multiplier lane for the vector forms: Cst5b(RedToBlue) in the high 16 bits and zero in the low 16 bits. + /// + private readonly int redMultiplier; + + /// + /// Initializes a new instance of the struct. + /// + /// The color transform multipliers. + public TransformColorOperator(Vp8LMultipliers m) + { + this.greenToRed = (sbyte)m.GreenToRed; + this.greenToBlue = (sbyte)m.GreenToBlue; + this.redToBlue = (sbyte)m.RedToBlue; + this.greenMultipliers = (Cst5b(m.GreenToRed) << 16) | (Cst5b(m.GreenToBlue) & 0xffff); + this.redMultiplier = Cst5b(m.RedToBlue) << 16; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint Transform(uint argb) + { + sbyte green = (sbyte)(argb >> 8); + sbyte red = (sbyte)(argb >> 16); + int newRed = (red & 0xff) - ColorTransformDelta(this.greenToRed, green); + int newBlue = (int)(argb & 0xff) - ColorTransformDelta(this.greenToBlue, green) - ColorTransformDelta(this.redToBlue, red); + return (argb & 0xff00ff00u) | ((uint)(newRed & 0xff) << 16) | (uint)(newBlue & 0xff); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector128 Transform(Vector128 argb) + { + // Green goes to the high byte of both 16-bit lanes of each pixel. The low byte of the low lane of the + // product is then the blue delta of green, and of the high lane the red delta of green. + Vector128 green = argb & Vector128.Create(0x0000ff00u); + Vector128 greenDeltas = Vector128_.MultiplyHigh((green | (green << 16)).AsInt16(), Vector128.Create(this.greenMultipliers).AsInt16()); + + // Red goes to the high byte of the high 16-bit lane. The shift moves its blue delta to the blue byte. + Vector128 redDeltas = Vector128_.MultiplyHigh(argb.AsInt16() << 8, Vector128.Create(this.redMultiplier).AsInt16()); + Vector128 deltas = ((redDeltas.AsUInt32() >>> 16).AsByte() + greenDeltas.AsByte()) & Vector128.Create(0x00ff00ffu).AsByte(); + return (argb.AsByte() - deltas).AsUInt32(); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector256 Transform(Vector256 argb) + { + // The same lane layout as the 128-bit form. + Vector256 green = argb & Vector256.Create(0x0000ff00u); + Vector256 greenDeltas = Vector256_.MultiplyHigh((green | (green << 16)).AsInt16(), Vector256.Create(this.greenMultipliers).AsInt16()); + Vector256 redDeltas = Vector256_.MultiplyHigh(argb.AsInt16() << 8, Vector256.Create(this.redMultiplier).AsInt16()); + Vector256 deltas = ((redDeltas.AsUInt32() >>> 16).AsByte() + greenDeltas.AsByte()) & Vector256.Create(0x00ff00ffu).AsByte(); + return (argb.AsByte() - deltas).AsUInt32(); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector512 Transform(Vector512 argb) + { + // The same lane layout as the 128-bit form. + Vector512 green = argb & Vector512.Create(0x0000ff00u); + Vector512 greenDeltas = Vector512_.MultiplyHigh((green | (green << 16)).AsInt16(), Vector512.Create(this.greenMultipliers).AsInt16()); + Vector512 redDeltas = Vector512_.MultiplyHigh(argb.AsInt16() << 8, Vector512.Create(this.redMultiplier).AsInt16()); + Vector512 deltas = ((redDeltas.AsUInt32() >>> 16).AsByte() + greenDeltas.AsByte()) & Vector512.Create(0x00ff00ffu).AsByte(); + return (argb.AsByte() - deltas).AsUInt32(); + } + } + + /// + /// Reverses the color transform: red += delta(green), then blue += delta(green) + delta(new red). + /// + /// + /// The deltas and the multiplier lanes are the same as in . The blue delta of + /// red uses the new red value, so the vector forms add the green deltas first. + /// + private readonly struct TransformColorInverseOperator : IPixelTransformOperator + { + /// + /// The green-to-red multiplier. + /// + private readonly sbyte greenToRed; + + /// + /// The green-to-blue multiplier. + /// + private readonly sbyte greenToBlue; + + /// + /// The red-to-blue multiplier. + /// + private readonly sbyte redToBlue; + + /// + /// The green multiplier lane for the vector forms: Cst5b(GreenToRed) in the high 16 bits and Cst5b(GreenToBlue) in the low 16 bits. + /// + private readonly int greenMultipliers; + + /// + /// The red multiplier lane for the vector forms: Cst5b(RedToBlue) in the high 16 bits and zero in the low 16 bits. + /// + private readonly int redMultiplier; + + /// + /// Initializes a new instance of the struct. + /// + /// The color transform multipliers. + public TransformColorInverseOperator(Vp8LMultipliers m) + { + this.greenToRed = (sbyte)m.GreenToRed; + this.greenToBlue = (sbyte)m.GreenToBlue; + this.redToBlue = (sbyte)m.RedToBlue; + this.greenMultipliers = (Cst5b(m.GreenToRed) << 16) | (Cst5b(m.GreenToBlue) & 0xffff); + this.redMultiplier = Cst5b(m.RedToBlue) << 16; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint Transform(uint argb) + { + sbyte green = (sbyte)(argb >> 8); + int newRed = ((int)(argb >> 16) + ColorTransformDelta(this.greenToRed, green)) & 0xff; + int newBlue = (int)(argb & 0xff) + ColorTransformDelta(this.greenToBlue, green) + ColorTransformDelta(this.redToBlue, (sbyte)newRed); + return (argb & 0xff00ff00u) | ((uint)newRed << 16) | (uint)(newBlue & 0xff); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector128 Transform(Vector128 argb) + { + // Add the green deltas: the blue byte gets the blue delta, and the red byte gets the red delta. + Vector128 green = argb & Vector128.Create(0x0000ff00u); + Vector128 greenDeltas = Vector128_.MultiplyHigh((green | (green << 16)).AsInt16(), Vector128.Create(this.greenMultipliers).AsInt16()); + Vector128 partial = argb.AsByte() + greenDeltas.AsByte(); + + // Move blue and the new red to the high bytes of their 16-bit lanes. The high multiply of the high lane gives + // the blue delta of the new red. The 32-bit shift by 8 moves it under blue, in byte 1. + Vector128 shifted = partial.AsInt16() << 8; + Vector128 redDeltas = Vector128_.MultiplyHigh(shifted, Vector128.Create(this.redMultiplier).AsInt16()); + Vector128 sums = (redDeltas.AsUInt32() >>> 8).AsByte() + shifted.AsByte(); + + // The 16-bit shift by 8 brings the new blue (byte 1) and the new red (byte 3) back to bytes 0 and 2. + return (sums.AsUInt16() >>> 8).AsUInt32() | (argb & Vector128.Create(0xff00ff00u)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector256 Transform(Vector256 argb) + { + // The same lane layout as the 128-bit form. + Vector256 green = argb & Vector256.Create(0x0000ff00u); + Vector256 greenDeltas = Vector256_.MultiplyHigh((green | (green << 16)).AsInt16(), Vector256.Create(this.greenMultipliers).AsInt16()); + Vector256 partial = argb.AsByte() + greenDeltas.AsByte(); + Vector256 shifted = partial.AsInt16() << 8; + Vector256 redDeltas = Vector256_.MultiplyHigh(shifted, Vector256.Create(this.redMultiplier).AsInt16()); + Vector256 sums = (redDeltas.AsUInt32() >>> 8).AsByte() + shifted.AsByte(); + return (sums.AsUInt16() >>> 8).AsUInt32() | (argb & Vector256.Create(0xff00ff00u)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector512 Transform(Vector512 argb) + { + // The same lane layout as the 128-bit form. + Vector512 green = argb & Vector512.Create(0x0000ff00u); + Vector512 greenDeltas = Vector512_.MultiplyHigh((green | (green << 16)).AsInt16(), Vector512.Create(this.greenMultipliers).AsInt16()); + Vector512 partial = argb.AsByte() + greenDeltas.AsByte(); + Vector512 shifted = partial.AsInt16() << 8; + Vector512 redDeltas = Vector512_.MultiplyHigh(shifted, Vector512.Create(this.redMultiplier).AsInt16()); + Vector512 sums = (redDeltas.AsUInt32() >>> 8).AsByte() + shifted.AsByte(); + return (sums.AsUInt16() >>> 8).AsUInt32() | (argb & Vector512.Create(0xff00ff00u)); + } + } +} diff --git a/src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.Predictors.cs b/src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.Predictors.cs new file mode 100644 index 0000000000..1667617196 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.Predictors.cs @@ -0,0 +1,1256 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Common.Helpers; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossless; + +/// +/// Contains the predictor operators of the predictor transform, and the methods that add or subtract their predictions for a run of pixels. +/// +internal static partial class LosslessUtils +{ + /// + /// Defines the prediction of one predictor mode, in scalar and SIMD forms. + /// + /// + /// + /// The encoder writes pixel - prediction, and the decoder writes residual + prediction, each channel modulo 256. See the WebP Lossless Bitstream + /// Specification, section 4.1 "Predictor Transform": https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// Thus one operator serves the encoder and the decoder. + /// + /// + /// Each vector form works lane by lane: each 32-bit lane holds one ARGB pixel, one channel in each byte. The same form predicts one pixel in the low lane, + /// or a whole vector of pixels. + /// + /// + private interface IPredictorOperator + { + /// + /// Gets a value indicating whether the prediction reads the left pixel. + /// + static abstract bool UsesLeft { get; } + + /// + /// Gets a value indicating whether the prediction reads the top pixel. + /// + static abstract bool UsesTop { get; } + + /// + /// Gets a value indicating whether the prediction reads the top-left pixel. + /// + static abstract bool UsesTopLeft { get; } + + /// + /// Gets a value indicating whether the prediction reads the top-right pixel. + /// + static abstract bool UsesTopRight { get; } + + /// + /// Predicts one pixel. + /// + /// The left pixel. + /// The top pixel. The top-left and top-right pixels are at offsets -1 and +1. + /// The prediction. + static abstract uint Predict(uint left, ref uint top); + + /// + /// Predicts the pixels of the 32-bit lanes. + /// + /// The left pixels. + /// The top pixels. + /// The top-left pixels. + /// The top-right pixels. + /// The predictions. + static abstract Vector128 Predict(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight); + + /// + /// Predicts one pixel in 32-bit lane 0. Lanes 1 to 3 of each input are zero. + /// + /// + /// The decoder uses this form only for the modes that read the left pixel. These modes reconstruct one pixel for each step, and the prediction is on + /// the dependency chain of the row. Their predictions of zero lanes are zero, so the next left pixel has zero lanes too. The zero lanes let a mode use + /// a shorter chain than . + /// + /// The left pixel. + /// The top pixel. + /// The top-left pixel. + /// The top-right pixel. + /// The prediction. + static abstract Vector128 PredictPixel(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight); + + /// + /// Predicts the pixels of the 32-bit lanes. + /// + /// The left pixels. + /// The top pixels. + /// The top-left pixels. + /// The top-right pixels. + /// The predictions. + static abstract Vector256 Predict(Vector256 left, Vector256 top, Vector256 topLeft, Vector256 topRight); + + /// + /// Predicts the pixels of the 32-bit lanes. + /// + /// The left pixels. + /// The top pixels. + /// The top-left pixels. + /// The top-right pixels. + /// The predictions. + static abstract Vector512 Predict(Vector512 left, Vector512 top, Vector512 topLeft, Vector512 topRight); + } + + /// + /// Adds the predictions of a predictor mode to a run of residuals, in place. + /// + /// The predictor mode, from 0 to 15. The modes 14 and 15 are not valid, and they use mode 0, as in libwebp. + /// The first residual. The pixel at offset -1 is final when the mode reads the left pixel. + /// The top pixel of the first residual. The pixels at offsets -1 and +1 exist when the mode reads them. + /// The number of pixels. + public static void PredictorAdd(int mode, ref uint pixels, ref uint upper, int count) + { + switch (mode) + { + case 1: + // The left predictor adds the left pixel to each residual. The shared prefix sum reconstructs 4 pixels for each step. + SimdUtils.AddLeft(MemoryMarshal.CreateSpan(ref Unsafe.As(ref pixels), count * 4), 4, Unsafe.Subtract(ref pixels, (nuint)1)); + break; + case 2: + PredictorAdd(ref pixels, ref upper, count); + break; + case 3: + PredictorAdd(ref pixels, ref upper, count); + break; + case 4: + PredictorAdd(ref pixels, ref upper, count); + break; + case 5: + PredictorAdd(ref pixels, ref upper, count); + break; + case 6: + PredictorAdd(ref pixels, ref upper, count); + break; + case 7: + PredictorAdd(ref pixels, ref upper, count); + break; + case 8: + PredictorAdd(ref pixels, ref upper, count); + break; + case 9: + PredictorAdd(ref pixels, ref upper, count); + break; + case 10: + PredictorAdd(ref pixels, ref upper, count); + break; + case 11: + PredictorAdd(ref pixels, ref upper, count); + break; + case 12: + PredictorAdd(ref pixels, ref upper, count); + break; + case 13: + PredictorAdd(ref pixels, ref upper, count); + break; + default: + // Mode 0, and the modes 14 and 15, which are not valid. libwebp uses mode 0 for them. + PredictorAdd(ref pixels, ref upper, count); + break; + } + } + + /// + /// Subtracts the predictions of a predictor mode from a run of pixels. + /// + /// The predictor mode, from 0 to 13. + /// The first pixel. The pixel at offset -1 exists when the mode reads the left pixel. + /// The top pixel of the first pixel. The pixels at offsets -1 and +1 exist when the mode reads them. + /// The number of pixels. + /// The first residual to write. + public static void PredictorSub(int mode, ref uint input, ref uint upper, int count, ref uint output) + { + switch (mode) + { + case 1: + PredictorSub(ref input, ref upper, count, ref output); + break; + case 2: + PredictorSub(ref input, ref upper, count, ref output); + break; + case 3: + PredictorSub(ref input, ref upper, count, ref output); + break; + case 4: + PredictorSub(ref input, ref upper, count, ref output); + break; + case 5: + PredictorSub(ref input, ref upper, count, ref output); + break; + case 6: + PredictorSub(ref input, ref upper, count, ref output); + break; + case 7: + PredictorSub(ref input, ref upper, count, ref output); + break; + case 8: + PredictorSub(ref input, ref upper, count, ref output); + break; + case 9: + PredictorSub(ref input, ref upper, count, ref output); + break; + case 10: + PredictorSub(ref input, ref upper, count, ref output); + break; + case 11: + PredictorSub(ref input, ref upper, count, ref output); + break; + case 12: + PredictorSub(ref input, ref upper, count, ref output); + break; + case 13: + PredictorSub(ref input, ref upper, count, ref output); + break; + default: + PredictorSub(ref input, ref upper, count, ref output); + break; + } + } + + /// + /// Predicts one pixel with a predictor mode. + /// + /// The predictor mode, from 0 to 13. + /// The left pixel. + /// The top pixel. The top-left and top-right pixels are at offsets -1 and +1. + /// The prediction. + public static uint Predict(int mode, uint left, ref uint top) + => mode switch + { + 1 => Predictor1Operator.Predict(left, ref top), + 2 => Predictor2Operator.Predict(left, ref top), + 3 => Predictor3Operator.Predict(left, ref top), + 4 => Predictor4Operator.Predict(left, ref top), + 5 => Predictor5Operator.Predict(left, ref top), + 6 => Predictor6Operator.Predict(left, ref top), + 7 => Predictor7Operator.Predict(left, ref top), + 8 => Predictor8Operator.Predict(left, ref top), + 9 => Predictor9Operator.Predict(left, ref top), + 10 => Predictor10Operator.Predict(left, ref top), + 11 => Predictor11Operator.Predict(left, ref top), + 12 => Predictor12Operator.Predict(left, ref top), + 13 => Predictor13Operator.Predict(left, ref top), + _ => Predictor0Operator.Predict(left, ref top), + }; + + /// + /// Adds the predictions of to a run of residuals, in place. + /// + /// + /// + /// A mode that does not read the left pixel reads only the row above, which is final. Thus each pixel reconstructs on its own, and the run uses the + /// widest vectors, from the same offset in each width, then the scalar form for the remainder. + /// + /// + /// A mode that reads the left pixel must wait for the pixel to its left. One step handles one pixel in the low lane of a , and + /// the reconstructed pixel stays in a register as the next left pixel. Thus the dependency chain has no store and load. A wider vector does not reduce + /// the step count. + /// + /// + /// The predictor operator. + /// The first residual. + /// The top pixel of the first residual. + /// The number of pixels. + private static void PredictorAdd(ref uint pixels, ref uint upper, int count) + where TOperator : struct, IPredictorOperator + { + // The neighbor rows start one pixel before and one pixel after the top pixel. The vector loads use the same offset in each row. + ref uint topLeftRow = ref Unsafe.Subtract(ref upper, (nuint)1); + ref uint topRightRow = ref Unsafe.Add(ref upper, (nuint)1); + nuint length = (uint)count; + nuint x = 0; + if (!TOperator.UsesLeft) + { + if (Vector512.IsHardwareAccelerated) + { + for (; x + (uint)Vector512.Count <= length; x += (uint)Vector512.Count) + { + Vector512 top = TOperator.UsesTop ? Vector512.LoadUnsafe(ref upper, x).AsByte() : default; + Vector512 topLeft = TOperator.UsesTopLeft ? Vector512.LoadUnsafe(ref topLeftRow, x).AsByte() : default; + Vector512 topRight = TOperator.UsesTopRight ? Vector512.LoadUnsafe(ref topRightRow, x).AsByte() : default; + Vector512 prediction = TOperator.Predict(default, top, topLeft, topRight); + (Vector512.LoadUnsafe(ref pixels, x).AsByte() + prediction).AsUInt32().StoreUnsafe(ref pixels, x); + } + } + + if (Vector256.IsHardwareAccelerated) + { + for (; x + (uint)Vector256.Count <= length; x += (uint)Vector256.Count) + { + Vector256 top = TOperator.UsesTop ? Vector256.LoadUnsafe(ref upper, x).AsByte() : default; + Vector256 topLeft = TOperator.UsesTopLeft ? Vector256.LoadUnsafe(ref topLeftRow, x).AsByte() : default; + Vector256 topRight = TOperator.UsesTopRight ? Vector256.LoadUnsafe(ref topRightRow, x).AsByte() : default; + Vector256 prediction = TOperator.Predict(default, top, topLeft, topRight); + (Vector256.LoadUnsafe(ref pixels, x).AsByte() + prediction).AsUInt32().StoreUnsafe(ref pixels, x); + } + } + + if (Vector128.IsHardwareAccelerated) + { + for (; x + (uint)Vector128.Count <= length; x += (uint)Vector128.Count) + { + Vector128 top = TOperator.UsesTop ? Vector128.LoadUnsafe(ref upper, x).AsByte() : default; + Vector128 topLeft = TOperator.UsesTopLeft ? Vector128.LoadUnsafe(ref topLeftRow, x).AsByte() : default; + Vector128 topRight = TOperator.UsesTopRight ? Vector128.LoadUnsafe(ref topRightRow, x).AsByte() : default; + Vector128 prediction = TOperator.Predict(default, top, topLeft, topRight); + (Vector128.LoadUnsafe(ref pixels, x).AsByte() + prediction).AsUInt32().StoreUnsafe(ref pixels, x); + } + } + + for (; x < length; x++) + { + ref uint pixel = ref Unsafe.Add(ref pixels, x); + pixel = AddPixels(pixel, TOperator.Predict(0, ref Unsafe.Add(ref upper, x))); + } + + return; + } + + if (Vector128.IsHardwareAccelerated) + { + // Lane layout: the pixel is the low 32-bit lane, one channel in each byte lane. The byte add wraps each channel modulo 256. + Vector128 left = Vector128.CreateScalar(Unsafe.Subtract(ref pixels, (nuint)1)).AsByte(); + for (; x < length; x++) + { + ref uint top = ref Unsafe.Add(ref upper, x); + Vector128 topPixel = TOperator.UsesTop ? Vector128.CreateScalar(top).AsByte() : default; + Vector128 topLeft = TOperator.UsesTopLeft ? Vector128.CreateScalar(Unsafe.Subtract(ref top, (nuint)1)).AsByte() : default; + Vector128 topRight = TOperator.UsesTopRight ? Vector128.CreateScalar(Unsafe.Add(ref top, (nuint)1)).AsByte() : default; + ref uint pixel = ref Unsafe.Add(ref pixels, x); + left = Vector128.CreateScalar(pixel).AsByte() + TOperator.PredictPixel(left, topPixel, topLeft, topRight); + pixel = left.AsUInt32().ToScalar(); + } + + return; + } + + uint leftPixel = Unsafe.Subtract(ref pixels, (nuint)1); + for (; x < length; x++) + { + ref uint pixel = ref Unsafe.Add(ref pixels, x); + pixel = leftPixel = AddPixels(pixel, TOperator.Predict(leftPixel, ref Unsafe.Add(ref upper, x))); + } + } + + /// + /// Subtracts the predictions of from a run of pixels. + /// + /// + /// Each prediction reads only source pixels, which the method does not change. Thus each residual is on its own for each mode, and the run uses the + /// widest vectors, from the same offset in each width, then the scalar form for the remainder. + /// + /// The predictor operator. + /// The first pixel. + /// The top pixel of the first pixel. + /// The number of pixels. + /// The first residual to write. + private static void PredictorSub(ref uint input, ref uint upper, int count, ref uint output) + where TOperator : struct, IPredictorOperator + { + // The left row starts one pixel before the first pixel, and the neighbor rows one pixel before and one pixel after the top pixel. The vector loads use + // the same offset in each row. + ref uint leftRow = ref Unsafe.Subtract(ref input, (nuint)1); + ref uint topLeftRow = ref Unsafe.Subtract(ref upper, (nuint)1); + ref uint topRightRow = ref Unsafe.Add(ref upper, (nuint)1); + nuint length = (uint)count; + nuint x = 0; + if (Vector512.IsHardwareAccelerated) + { + for (; x + (uint)Vector512.Count <= length; x += (uint)Vector512.Count) + { + Vector512 left = TOperator.UsesLeft ? Vector512.LoadUnsafe(ref leftRow, x).AsByte() : default; + Vector512 top = TOperator.UsesTop ? Vector512.LoadUnsafe(ref upper, x).AsByte() : default; + Vector512 topLeft = TOperator.UsesTopLeft ? Vector512.LoadUnsafe(ref topLeftRow, x).AsByte() : default; + Vector512 topRight = TOperator.UsesTopRight ? Vector512.LoadUnsafe(ref topRightRow, x).AsByte() : default; + Vector512 prediction = TOperator.Predict(left, top, topLeft, topRight); + (Vector512.LoadUnsafe(ref input, x).AsByte() - prediction).AsUInt32().StoreUnsafe(ref output, x); + } + } + + if (Vector256.IsHardwareAccelerated) + { + for (; x + (uint)Vector256.Count <= length; x += (uint)Vector256.Count) + { + Vector256 left = TOperator.UsesLeft ? Vector256.LoadUnsafe(ref leftRow, x).AsByte() : default; + Vector256 top = TOperator.UsesTop ? Vector256.LoadUnsafe(ref upper, x).AsByte() : default; + Vector256 topLeft = TOperator.UsesTopLeft ? Vector256.LoadUnsafe(ref topLeftRow, x).AsByte() : default; + Vector256 topRight = TOperator.UsesTopRight ? Vector256.LoadUnsafe(ref topRightRow, x).AsByte() : default; + Vector256 prediction = TOperator.Predict(left, top, topLeft, topRight); + (Vector256.LoadUnsafe(ref input, x).AsByte() - prediction).AsUInt32().StoreUnsafe(ref output, x); + } + } + + if (Vector128.IsHardwareAccelerated) + { + for (; x + (uint)Vector128.Count <= length; x += (uint)Vector128.Count) + { + Vector128 left = TOperator.UsesLeft ? Vector128.LoadUnsafe(ref leftRow, x).AsByte() : default; + Vector128 top = TOperator.UsesTop ? Vector128.LoadUnsafe(ref upper, x).AsByte() : default; + Vector128 topLeft = TOperator.UsesTopLeft ? Vector128.LoadUnsafe(ref topLeftRow, x).AsByte() : default; + Vector128 topRight = TOperator.UsesTopRight ? Vector128.LoadUnsafe(ref topRightRow, x).AsByte() : default; + Vector128 prediction = TOperator.Predict(left, top, topLeft, topRight); + (Vector128.LoadUnsafe(ref input, x).AsByte() - prediction).AsUInt32().StoreUnsafe(ref output, x); + } + } + + for (; x < length; x++) + { + uint left = TOperator.UsesLeft ? Unsafe.Add(ref leftRow, x) : 0; + Unsafe.Add(ref output, x) = SubPixels(Unsafe.Add(ref input, x), TOperator.Predict(left, ref Unsafe.Add(ref upper, x))); + } + } + + /// + /// Computes clamp(c0 + c1 - c2) in each byte lane, with the clamp to [0, 255]. + /// + /// + /// The bytes widen to 16-bit lanes, so the sum and the difference need no saturation. The narrow with unsigned saturation gives the clamp. Pack keeps the + /// lane order of the 128-bit vector. + /// + /// The first values. + /// The second values. + /// The values to subtract. + /// The clamped results. + [MethodImpl(InliningOptions.AlwaysInline)] + private static Vector128 ClampedAddSubtractFull(Vector128 c0, Vector128 c1, Vector128 c2) + { + (Vector128 c0Low, Vector128 c0High) = Vector128.Widen(c0); + (Vector128 c1Low, Vector128 c1High) = Vector128.Widen(c1); + (Vector128 c2Low, Vector128 c2High) = Vector128.Widen(c2); + Vector128 low = (c0Low + c1Low - c2Low).AsInt16(); + Vector128 high = (c0High + c1High - c2High).AsInt16(); + return Vector128_.PackUnsignedSaturate(low, high); + } + + /// + /// Computes clamp(c0 + c1 - c2) in each byte lane, with the clamp to [0, 255]. + /// + /// + /// The bytes widen to 16-bit lanes, so the sum and the difference need no saturation. The clamp in the 16-bit lanes and the narrow keep the lane order. + /// + /// The first values. + /// The second values. + /// The values to subtract. + /// The clamped results. + [MethodImpl(InliningOptions.AlwaysInline)] + private static Vector256 ClampedAddSubtractFull(Vector256 c0, Vector256 c1, Vector256 c2) + { + (Vector256 c0Low, Vector256 c0High) = Vector256.Widen(c0); + (Vector256 c1Low, Vector256 c1High) = Vector256.Widen(c1); + (Vector256 c2Low, Vector256 c2High) = Vector256.Widen(c2); + Vector256 max = Vector256.Create((short)byte.MaxValue); + Vector256 low = Vector256.Clamp((c0Low + c1Low - c2Low).AsInt16(), Vector256.Zero, max); + Vector256 high = Vector256.Clamp((c0High + c1High - c2High).AsInt16(), Vector256.Zero, max); + return Vector256.Narrow(low.AsUInt16(), high.AsUInt16()); + } + + /// + /// Computes clamp(c0 + c1 - c2) in each byte lane, with the clamp to [0, 255]. + /// + /// + /// The bytes widen to 16-bit lanes, so the sum and the difference need no saturation. The clamp in the 16-bit lanes and the narrow keep the lane order. + /// + /// The first values. + /// The second values. + /// The values to subtract. + /// The clamped results. + [MethodImpl(InliningOptions.AlwaysInline)] + private static Vector512 ClampedAddSubtractFull(Vector512 c0, Vector512 c1, Vector512 c2) + { + (Vector512 c0Low, Vector512 c0High) = Vector512.Widen(c0); + (Vector512 c1Low, Vector512 c1High) = Vector512.Widen(c1); + (Vector512 c2Low, Vector512 c2High) = Vector512.Widen(c2); + Vector512 max = Vector512.Create((short)byte.MaxValue); + Vector512 low = Vector512.Clamp((c0Low + c1Low - c2Low).AsInt16(), Vector512.Zero, max); + Vector512 high = Vector512.Clamp((c0High + c1High - c2High).AsInt16(), Vector512.Zero, max); + return Vector512.Narrow(low.AsUInt16(), high.AsUInt16()); + } + + /// + /// Computes clamp(a + (a - c2) / 2) in each byte lane, with the clamp to [0, 255]. The value a is the average of c0 and c1, rounded down, and the division + /// rounds toward zero. + /// + /// + /// In 16-bit lanes, the arithmetic shift rounds down. The compare mask is -1 when the difference is negative, so the subtraction of the mask adds 1 to a + /// negative difference first. Thus the shift rounds toward zero, as the C division of the specification does. + /// + /// The first values of the average. + /// The second values of the average. + /// The values to move away from. + /// The clamped results. + [MethodImpl(InliningOptions.AlwaysInline)] + private static Vector128 ClampedAddSubtractHalf(Vector128 c0, Vector128 c1, Vector128 c2) + { + (Vector128 aLow, Vector128 aHigh) = Vector128.Widen(Vector128_.AverageRoundDown(c0, c1)); + (Vector128 c2Low, Vector128 c2High) = Vector128.Widen(c2); + Vector128 low = HalfStep(aLow.AsInt16(), c2Low.AsInt16()); + Vector128 high = HalfStep(aHigh.AsInt16(), c2High.AsInt16()); + return Vector128_.PackUnsignedSaturate(low, high); + + static Vector128 HalfStep(Vector128 a, Vector128 c) + => a + Vector128.ShiftRightArithmetic(a - c - Vector128.GreaterThan(c, a), 1); + } + + /// + /// Computes clamp(a + (a - c2) / 2) in each byte lane, with the clamp to [0, 255]. The value a is the average of c0 and c1, rounded down, and the division + /// rounds toward zero. + /// + /// + /// In 16-bit lanes, the arithmetic shift rounds down. The compare mask is -1 when the difference is negative, so the subtraction of the mask adds 1 to a + /// negative difference first. Thus the shift rounds toward zero, as the C division of the specification does. + /// + /// The first values of the average. + /// The second values of the average. + /// The values to move away from. + /// The clamped results. + [MethodImpl(InliningOptions.AlwaysInline)] + private static Vector256 ClampedAddSubtractHalf(Vector256 c0, Vector256 c1, Vector256 c2) + { + (Vector256 aLow, Vector256 aHigh) = Vector256.Widen(Vector256_.AverageRoundDown(c0, c1)); + (Vector256 c2Low, Vector256 c2High) = Vector256.Widen(c2); + Vector256 max = Vector256.Create((short)byte.MaxValue); + Vector256 low = Vector256.Clamp(HalfStep(aLow.AsInt16(), c2Low.AsInt16()), Vector256.Zero, max); + Vector256 high = Vector256.Clamp(HalfStep(aHigh.AsInt16(), c2High.AsInt16()), Vector256.Zero, max); + return Vector256.Narrow(low.AsUInt16(), high.AsUInt16()); + + static Vector256 HalfStep(Vector256 a, Vector256 c) + => a + Vector256.ShiftRightArithmetic(a - c - Vector256.GreaterThan(c, a), 1); + } + + /// + /// Computes clamp(a + (a - c2) / 2) in each byte lane, with the clamp to [0, 255]. The value a is the average of c0 and c1, rounded down, and the division + /// rounds toward zero. + /// + /// + /// In 16-bit lanes, the arithmetic shift rounds down. The compare mask is -1 when the difference is negative, so the subtraction of the mask adds 1 to a + /// negative difference first. Thus the shift rounds toward zero, as the C division of the specification does. + /// + /// The first values of the average. + /// The second values of the average. + /// The values to move away from. + /// The clamped results. + [MethodImpl(InliningOptions.AlwaysInline)] + private static Vector512 ClampedAddSubtractHalf(Vector512 c0, Vector512 c1, Vector512 c2) + { + (Vector512 aLow, Vector512 aHigh) = Vector512.Widen(Vector512_.AverageRoundDown(c0, c1)); + (Vector512 c2Low, Vector512 c2High) = Vector512.Widen(c2); + Vector512 max = Vector512.Create((short)byte.MaxValue); + Vector512 low = Vector512.Clamp(HalfStep(aLow.AsInt16(), c2Low.AsInt16()), Vector512.Zero, max); + Vector512 high = Vector512.Clamp(HalfStep(aHigh.AsInt16(), c2High.AsInt16()), Vector512.Zero, max); + return Vector512.Narrow(low.AsUInt16(), high.AsUInt16()); + + static Vector512 HalfStep(Vector512 a, Vector512 c) + => a + Vector512.ShiftRightArithmetic(a - c - Vector512.GreaterThan(c, a), 1); + } + + /// + /// Selects the top or the left pixel in each 32-bit lane. The result is the left pixel when the channel distances from the top-left pixel to the left + /// pixel sum to more than the distances to the top pixel. Otherwise it is the top pixel. + /// + /// + /// Each absolute difference is the OR of the two saturated subtractions. The sum of the four bytes of a lane uses two steps of masked adds in the 32-bit + /// lane: the first gives two 16-bit partial sums, and the second adds them. Each sum is at most 1020, so the steps have no carry between the sums. + /// + /// The top pixels. + /// The left pixels. + /// The top-left pixels. + /// The selected pixels. + [MethodImpl(InliningOptions.AlwaysInline)] + private static Vector128 Select(Vector128 top, Vector128 left, Vector128 topLeft) + { + Vector128 leftDistance = SumBytes(Vector128.SubtractSaturate(left, topLeft) | Vector128.SubtractSaturate(topLeft, left)); + Vector128 topDistance = SumBytes(Vector128.SubtractSaturate(top, topLeft) | Vector128.SubtractSaturate(topLeft, top)); + return Vector128.ConditionalSelect(Vector128.GreaterThan(leftDistance, topDistance).AsByte(), left, top); + + static Vector128 SumBytes(Vector128 value) + { + Vector128 pairs = Vector128.Create(0x00ff00ffu); + Vector128 sums = (value.AsUInt32() & pairs) + (Vector128.ShiftRightLogical(value.AsUInt32(), 8) & pairs); + return (sums & Vector128.Create(0xffffu)) + Vector128.ShiftRightLogical(sums, 16); + } + } + + /// + /// Selects the top or the left pixel in each 32-bit lane. The result is the left pixel when the channel distances from the top-left pixel to the left + /// pixel sum to more than the distances to the top pixel. Otherwise it is the top pixel. + /// + /// + /// Each absolute difference is the OR of the two saturated subtractions. The sum of the four bytes of a lane uses two steps of masked adds in the 32-bit + /// lane: the first gives two 16-bit partial sums, and the second adds them. Each sum is at most 1020, so the steps have no carry between the sums. + /// + /// The top pixels. + /// The left pixels. + /// The top-left pixels. + /// The selected pixels. + [MethodImpl(InliningOptions.AlwaysInline)] + private static Vector256 Select(Vector256 top, Vector256 left, Vector256 topLeft) + { + Vector256 leftDistance = SumBytes(Vector256.SubtractSaturate(left, topLeft) | Vector256.SubtractSaturate(topLeft, left)); + Vector256 topDistance = SumBytes(Vector256.SubtractSaturate(top, topLeft) | Vector256.SubtractSaturate(topLeft, top)); + return Vector256.ConditionalSelect(Vector256.GreaterThan(leftDistance, topDistance).AsByte(), left, top); + + static Vector256 SumBytes(Vector256 value) + { + Vector256 pairs = Vector256.Create(0x00ff00ffu); + Vector256 sums = (value.AsUInt32() & pairs) + (Vector256.ShiftRightLogical(value.AsUInt32(), 8) & pairs); + return (sums & Vector256.Create(0xffffu)) + Vector256.ShiftRightLogical(sums, 16); + } + } + + /// + /// Selects the top or the left pixel in each 32-bit lane. The result is the left pixel when the channel distances from the top-left pixel to the left + /// pixel sum to more than the distances to the top pixel. Otherwise it is the top pixel. + /// + /// + /// Each absolute difference is the OR of the two saturated subtractions. The sum of the four bytes of a lane uses two steps of masked adds in the 32-bit + /// lane: the first gives two 16-bit partial sums, and the second adds them. Each sum is at most 1020, so the steps have no carry between the sums. + /// + /// The top pixels. + /// The left pixels. + /// The top-left pixels. + /// The selected pixels. + [MethodImpl(InliningOptions.AlwaysInline)] + private static Vector512 Select(Vector512 top, Vector512 left, Vector512 topLeft) + { + Vector512 leftDistance = SumBytes(Vector512.SubtractSaturate(left, topLeft) | Vector512.SubtractSaturate(topLeft, left)); + Vector512 topDistance = SumBytes(Vector512.SubtractSaturate(top, topLeft) | Vector512.SubtractSaturate(topLeft, top)); + return Vector512.ConditionalSelect(Vector512.GreaterThan(leftDistance, topDistance).AsByte(), left, top); + + static Vector512 SumBytes(Vector512 value) + { + Vector512 pairs = Vector512.Create(0x00ff00ffu); + Vector512 sums = (value.AsUInt32() & pairs) + (Vector512.ShiftRightLogical(value.AsUInt32(), 8) & pairs); + return (sums & Vector512.Create(0xffffu)) + Vector512.ShiftRightLogical(sums, 16); + } + } + + /// + /// Mode 0: opaque black, 0xff000000. + /// + private readonly struct Predictor0Operator : IPredictorOperator + { + /// + public static bool UsesLeft => false; + + /// + public static bool UsesTop => false; + + /// + public static bool UsesTopLeft => false; + + /// + public static bool UsesTopRight => false; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static uint Predict(uint left, ref uint top) => WebpConstants.ArgbBlack; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Predict(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Vector128.Create(WebpConstants.ArgbBlack).AsByte(); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PredictPixel(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Predict(left, top, topLeft, topRight); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector256 Predict(Vector256 left, Vector256 top, Vector256 topLeft, Vector256 topRight) + => Vector256.Create(WebpConstants.ArgbBlack).AsByte(); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector512 Predict(Vector512 left, Vector512 top, Vector512 topLeft, Vector512 topRight) + => Vector512.Create(WebpConstants.ArgbBlack).AsByte(); + } + + /// + /// Mode 1: the left pixel, L. + /// + private readonly struct Predictor1Operator : IPredictorOperator + { + /// + public static bool UsesLeft => true; + + /// + public static bool UsesTop => false; + + /// + public static bool UsesTopLeft => false; + + /// + public static bool UsesTopRight => false; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static uint Predict(uint left, ref uint top) => left; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Predict(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) => left; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PredictPixel(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Predict(left, top, topLeft, topRight); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector256 Predict(Vector256 left, Vector256 top, Vector256 topLeft, Vector256 topRight) => left; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector512 Predict(Vector512 left, Vector512 top, Vector512 topLeft, Vector512 topRight) => left; + } + + /// + /// Mode 2: the top pixel, T. + /// + private readonly struct Predictor2Operator : IPredictorOperator + { + /// + public static bool UsesLeft => false; + + /// + public static bool UsesTop => true; + + /// + public static bool UsesTopLeft => false; + + /// + public static bool UsesTopRight => false; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static uint Predict(uint left, ref uint top) => top; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Predict(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) => top; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PredictPixel(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Predict(left, top, topLeft, topRight); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector256 Predict(Vector256 left, Vector256 top, Vector256 topLeft, Vector256 topRight) => top; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector512 Predict(Vector512 left, Vector512 top, Vector512 topLeft, Vector512 topRight) => top; + } + + /// + /// Mode 3: the top-right pixel, TR. + /// + private readonly struct Predictor3Operator : IPredictorOperator + { + /// + public static bool UsesLeft => false; + + /// + public static bool UsesTop => false; + + /// + public static bool UsesTopLeft => false; + + /// + public static bool UsesTopRight => true; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static uint Predict(uint left, ref uint top) => Unsafe.Add(ref top, (nuint)1); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Predict(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) => topRight; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PredictPixel(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Predict(left, top, topLeft, topRight); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector256 Predict(Vector256 left, Vector256 top, Vector256 topLeft, Vector256 topRight) => topRight; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector512 Predict(Vector512 left, Vector512 top, Vector512 topLeft, Vector512 topRight) => topRight; + } + + /// + /// Mode 4: the top-left pixel, TL. + /// + private readonly struct Predictor4Operator : IPredictorOperator + { + /// + public static bool UsesLeft => false; + + /// + public static bool UsesTop => false; + + /// + public static bool UsesTopLeft => true; + + /// + public static bool UsesTopRight => false; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static uint Predict(uint left, ref uint top) => Unsafe.Subtract(ref top, (nuint)1); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Predict(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) => topLeft; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PredictPixel(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Predict(left, top, topLeft, topRight); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector256 Predict(Vector256 left, Vector256 top, Vector256 topLeft, Vector256 topRight) => topLeft; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector512 Predict(Vector512 left, Vector512 top, Vector512 topLeft, Vector512 topRight) => topLeft; + } + + /// + /// Mode 5: Average2(Average2(L, TR), T). + /// + private readonly struct Predictor5Operator : IPredictorOperator + { + /// + public static bool UsesLeft => true; + + /// + public static bool UsesTop => true; + + /// + public static bool UsesTopLeft => false; + + /// + public static bool UsesTopRight => true; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static uint Predict(uint left, ref uint top) => Average2(Average2(left, Unsafe.Add(ref top, (nuint)1)), top); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Predict(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Vector128_.AverageRoundDown(Vector128_.AverageRoundDown(left, topRight), top); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PredictPixel(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Predict(left, top, topLeft, topRight); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector256 Predict(Vector256 left, Vector256 top, Vector256 topLeft, Vector256 topRight) + => Vector256_.AverageRoundDown(Vector256_.AverageRoundDown(left, topRight), top); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector512 Predict(Vector512 left, Vector512 top, Vector512 topLeft, Vector512 topRight) + => Vector512_.AverageRoundDown(Vector512_.AverageRoundDown(left, topRight), top); + } + + /// + /// Mode 6: Average2(L, TL). + /// + private readonly struct Predictor6Operator : IPredictorOperator + { + /// + public static bool UsesLeft => true; + + /// + public static bool UsesTop => false; + + /// + public static bool UsesTopLeft => true; + + /// + public static bool UsesTopRight => false; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static uint Predict(uint left, ref uint top) => Average2(left, Unsafe.Subtract(ref top, (nuint)1)); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Predict(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Vector128_.AverageRoundDown(left, topLeft); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PredictPixel(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Predict(left, top, topLeft, topRight); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector256 Predict(Vector256 left, Vector256 top, Vector256 topLeft, Vector256 topRight) + => Vector256_.AverageRoundDown(left, topLeft); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector512 Predict(Vector512 left, Vector512 top, Vector512 topLeft, Vector512 topRight) + => Vector512_.AverageRoundDown(left, topLeft); + } + + /// + /// Mode 7: Average2(L, T). + /// + private readonly struct Predictor7Operator : IPredictorOperator + { + /// + public static bool UsesLeft => true; + + /// + public static bool UsesTop => true; + + /// + public static bool UsesTopLeft => false; + + /// + public static bool UsesTopRight => false; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static uint Predict(uint left, ref uint top) => Average2(left, top); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Predict(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Vector128_.AverageRoundDown(left, top); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PredictPixel(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Predict(left, top, topLeft, topRight); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector256 Predict(Vector256 left, Vector256 top, Vector256 topLeft, Vector256 topRight) + => Vector256_.AverageRoundDown(left, top); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector512 Predict(Vector512 left, Vector512 top, Vector512 topLeft, Vector512 topRight) + => Vector512_.AverageRoundDown(left, top); + } + + /// + /// Mode 8: Average2(TL, T). + /// + private readonly struct Predictor8Operator : IPredictorOperator + { + /// + public static bool UsesLeft => false; + + /// + public static bool UsesTop => true; + + /// + public static bool UsesTopLeft => true; + + /// + public static bool UsesTopRight => false; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static uint Predict(uint left, ref uint top) => Average2(Unsafe.Subtract(ref top, (nuint)1), top); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Predict(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Vector128_.AverageRoundDown(topLeft, top); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PredictPixel(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Predict(left, top, topLeft, topRight); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector256 Predict(Vector256 left, Vector256 top, Vector256 topLeft, Vector256 topRight) + => Vector256_.AverageRoundDown(topLeft, top); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector512 Predict(Vector512 left, Vector512 top, Vector512 topLeft, Vector512 topRight) + => Vector512_.AverageRoundDown(topLeft, top); + } + + /// + /// Mode 9: Average2(T, TR). + /// + private readonly struct Predictor9Operator : IPredictorOperator + { + /// + public static bool UsesLeft => false; + + /// + public static bool UsesTop => true; + + /// + public static bool UsesTopLeft => false; + + /// + public static bool UsesTopRight => true; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static uint Predict(uint left, ref uint top) => Average2(top, Unsafe.Add(ref top, (nuint)1)); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Predict(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Vector128_.AverageRoundDown(top, topRight); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PredictPixel(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Predict(left, top, topLeft, topRight); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector256 Predict(Vector256 left, Vector256 top, Vector256 topLeft, Vector256 topRight) + => Vector256_.AverageRoundDown(top, topRight); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector512 Predict(Vector512 left, Vector512 top, Vector512 topLeft, Vector512 topRight) + => Vector512_.AverageRoundDown(top, topRight); + } + + /// + /// Mode 10: Average2(Average2(L, TL), Average2(T, TR)). + /// + private readonly struct Predictor10Operator : IPredictorOperator + { + /// + public static bool UsesLeft => true; + + /// + public static bool UsesTop => true; + + /// + public static bool UsesTopLeft => true; + + /// + public static bool UsesTopRight => true; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static uint Predict(uint left, ref uint top) + => Average2(Average2(left, Unsafe.Subtract(ref top, (nuint)1)), Average2(top, Unsafe.Add(ref top, (nuint)1))); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Predict(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Vector128_.AverageRoundDown(Vector128_.AverageRoundDown(left, topLeft), Vector128_.AverageRoundDown(top, topRight)); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PredictPixel(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Predict(left, top, topLeft, topRight); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector256 Predict(Vector256 left, Vector256 top, Vector256 topLeft, Vector256 topRight) + => Vector256_.AverageRoundDown(Vector256_.AverageRoundDown(left, topLeft), Vector256_.AverageRoundDown(top, topRight)); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector512 Predict(Vector512 left, Vector512 top, Vector512 topLeft, Vector512 topRight) + => Vector512_.AverageRoundDown(Vector512_.AverageRoundDown(left, topLeft), Vector512_.AverageRoundDown(top, topRight)); + } + + /// + /// Mode 11: Select(T, L, TL). The scalar form uses the one-pixel vector form when vectors are hardware accelerated. + /// + private readonly struct Predictor11Operator : IPredictorOperator + { + /// + public static bool UsesLeft => true; + + /// + public static bool UsesTop => true; + + /// + public static bool UsesTopLeft => true; + + /// + public static bool UsesTopRight => false; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static uint Predict(uint left, ref uint top) + { + uint topLeft = Unsafe.Subtract(ref top, (nuint)1); + if (Vector128.IsHardwareAccelerated) + { + return Select(Vector128.CreateScalar(top).AsByte(), Vector128.CreateScalar(left).AsByte(), Vector128.CreateScalar(topLeft).AsByte()) + .AsUInt32().ToScalar(); + } + + return Select(top, left, topLeft); + } + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Predict(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Select(top, left, topLeft); + + /// + /// + /// Bytes 4 to 7 are zero in each input, so the sum of absolute differences of bytes 0 to 7 is the distance of the pixel. That is one PSADBW on x64, + /// instead of the two subtractions, the OR and the masked adds of . Only + /// the left distance depends on the left pixel, so the chain is the SAD, the compare, the select and the add. The sums are at most 1020, so a signed + /// compare gives the same order. Lanes 1 to 3 of top and left are zero, so the select gives zero there with any mask. + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PredictPixel(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + { + Vector128 leftDistance = Vector128_.SumAbsoluteDifferencesLow(left, topLeft).AsInt32(); + Vector128 topDistance = Vector128_.SumAbsoluteDifferencesLow(top, topLeft).AsInt32(); + return Vector128.ConditionalSelect(Vector128.GreaterThan(leftDistance, topDistance).AsByte(), left, top); + } + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector256 Predict(Vector256 left, Vector256 top, Vector256 topLeft, Vector256 topRight) + => Select(top, left, topLeft); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector512 Predict(Vector512 left, Vector512 top, Vector512 topLeft, Vector512 topRight) + => Select(top, left, topLeft); + } + + /// + /// Mode 12: ClampAddSubtractFull(L, T, TL). The scalar form uses the one-pixel vector form when vectors are hardware accelerated. + /// + private readonly struct Predictor12Operator : IPredictorOperator + { + /// + public static bool UsesLeft => true; + + /// + public static bool UsesTop => true; + + /// + public static bool UsesTopLeft => true; + + /// + public static bool UsesTopRight => false; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static uint Predict(uint left, ref uint top) + { + uint topLeft = Unsafe.Subtract(ref top, (nuint)1); + if (Vector128.IsHardwareAccelerated) + { + Vector128 leftPixel = Vector128.CreateScalar(left).AsByte(); + Vector128 topPixel = Vector128.CreateScalar(top).AsByte(); + return ClampedAddSubtractFull(leftPixel, topPixel, Vector128.CreateScalar(topLeft).AsByte()).AsUInt32().ToScalar(); + } + + return ClampedAddSubtractFull(left, top, topLeft); + } + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Predict(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => ClampedAddSubtractFull(left, top, topLeft); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PredictPixel(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Predict(left, top, topLeft, topRight); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector256 Predict(Vector256 left, Vector256 top, Vector256 topLeft, Vector256 topRight) + => ClampedAddSubtractFull(left, top, topLeft); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector512 Predict(Vector512 left, Vector512 top, Vector512 topLeft, Vector512 topRight) + => ClampedAddSubtractFull(left, top, topLeft); + } + + /// + /// Mode 13: ClampAddSubtractHalf(Average2(L, T), TL). The scalar form uses the one-pixel vector form when vectors are hardware accelerated. + /// + private readonly struct Predictor13Operator : IPredictorOperator + { + /// + public static bool UsesLeft => true; + + /// + public static bool UsesTop => true; + + /// + public static bool UsesTopLeft => true; + + /// + public static bool UsesTopRight => false; + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static uint Predict(uint left, ref uint top) + { + uint topLeft = Unsafe.Subtract(ref top, (nuint)1); + if (Vector128.IsHardwareAccelerated) + { + Vector128 leftPixel = Vector128.CreateScalar(left).AsByte(); + Vector128 topPixel = Vector128.CreateScalar(top).AsByte(); + return ClampedAddSubtractHalf(leftPixel, topPixel, Vector128.CreateScalar(topLeft).AsByte()).AsUInt32().ToScalar(); + } + + return ClampedAddSubtractHalf(left, top, topLeft); + } + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 Predict(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => ClampedAddSubtractHalf(left, top, topLeft); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector128 PredictPixel(Vector128 left, Vector128 top, Vector128 topLeft, Vector128 topRight) + => Predict(left, top, topLeft, topRight); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector256 Predict(Vector256 left, Vector256 top, Vector256 topLeft, Vector256 topRight) + => ClampedAddSubtractHalf(left, top, topLeft); + + /// + [MethodImpl(InliningOptions.AlwaysInline)] + public static Vector512 Predict(Vector512 left, Vector512 top, Vector512 topLeft, Vector512 topRight) + => ClampedAddSubtractHalf(left, top, topLeft); + } +} diff --git a/src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.cs b/src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.cs index d1681c22f8..7918b30b35 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/LosslessUtils.cs @@ -14,25 +14,44 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; /// /// Utility functions for the lossless decoder. /// -internal static unsafe class LosslessUtils +internal static partial class LosslessUtils { + /// + /// The number of values that the prefix code lookup tables cover. + /// private const int PrefixLookupIdxMax = 512; + /// + /// The number of values that the log2 lookup tables cover. + /// private const int LogLookupIdxMax = 256; + /// + /// The value from which the approximate log2 adds a correction term. + /// private const int ApproxLogMax = 4096; + /// + /// The value from which the log2 functions call in place of the table approximation. + /// private const int ApproxLogWithCorrectionMax = 65536; + /// + /// The value of 1 / ln(2). It converts a natural logarithm to a base 2 logarithm. + /// private const double Log2Reciprocal = 1.44269504088896338700465094007086; /// - /// Returns the exact index where array1 and array2 are different. For an index - /// inferior or equal to bestLenMatch, the return value just has to be strictly - /// inferior to bestLenMatch match. The current behavior is to return 0 if this index - /// is bestLenMatch, and the index itself otherwise. - /// If no two elements are the same, it returns maxLimit. + /// Gets the length of the match between two pixel sequences. A match that is not longer than is of no use + /// to the caller, so the method first compares the values at and returns 0 when they differ. /// + /// The first pixel sequence. It covers at least values. + /// The second pixel sequence. It covers at least values. + /// The length of the best match found so far. + /// The maximum number of values to compare. + /// + /// The number of equal leading values, up to . The result is 0 when the values at differ. + /// public static int FindMatchLength(ReadOnlySpan array1, ReadOnlySpan array2, int bestLenMatch, int maxLimit) { // Before 'expensive' linear match, check if the two arrays match at the @@ -42,309 +61,337 @@ public static int FindMatchLength(ReadOnlySpan array1, ReadOnlySpan return 0; } - return VectorMismatch(array1, array2, maxLimit); + // The runtime compares the sequences with its SIMD prefix scan. Both views end at the limit, so an equal prefix cannot go past it. + return array1[..maxLimit].CommonPrefixLength(array2[..maxLimit]); } /// - /// Counts equal leading values up to the caller's match-length limit. + /// Limits a copy length to the maximum length that a backward reference can store. /// - /// The first candidate sequence, covering at least length values. - /// The second candidate sequence, covering at least length values. - /// The maximum number of values to compare. - /// The first unequal value's index, or length when every compared value matches. + /// The number of pixels available. + /// The smaller of the length and . [MethodImpl(InliningOptions.ShortMethod)] - public static int VectorMismatch(ReadOnlySpan array1, ReadOnlySpan array2, int length) + public static int MaxFindCopyLength(int len) => len < BackwardReferenceEncoder.MaxLength ? len : BackwardReferenceEncoder.MaxLength; + + /// + /// Gets the buffer of a plane that holds a flat position. + /// + /// + /// The LZ77 passes read a plane with flat positions: the position of a value is its row times the row width plus its column. + /// Each buffer of the memory group holds whole rows, so the flat positions of one buffer are contiguous, and all buffers except + /// the last have the same length. The memory group gets the span of a buffer from its memory manager. Thus the callers keep the + /// span and its start position, and call again only when a position is outside the span. + /// + /// The value type of the plane. + /// The plane. + /// The flat position. + /// Receives the flat position of the first value of the buffer. + /// All values of the buffer. + [MethodImpl(MethodImplOptions.NoInlining)] + public static Span GetPlaneBuffer(Buffer2D plane, int position, out int start) + where T : struct { - // The runtime compares uint sequences with its SIMD prefix scan and returns an element count. - // Limit both views so an equal prefix cannot extend beyond the current match candidate. - return MemoryExtensions.CommonPrefixLength(array1[..length], array2[..length]); + MemoryGroup group = plane.FastMemoryGroup; + int index = position / group.BufferLength; + start = index * group.BufferLength; + return group[index].Span; } - [MethodImpl(InliningOptions.ShortMethod)] - public static int MaxFindCopyLength(int len) => len < BackwardReferenceEncoder.MaxLength ? len : BackwardReferenceEncoder.MaxLength; - - public static int PrefixEncodeBits(int distance, ref int extraBits) + /// + /// Gets a value of a plane at a flat position. + /// + /// The value type of the plane. + /// The plane. + /// The flat position. + /// + /// The buffer of the last read and its start position. The method replaces them with the buffer of + /// when the position is outside the buffer. An empty span starts the first read. + /// + /// The flat position of the first value of . + /// A reference to the value. + [MethodImpl(InliningOptions.ShortMethod)] + public static ref T GetPlaneValue(Buffer2D plane, int position, ref Span buffer, ref int start) + where T : struct { - if (distance < PrefixLookupIdxMax) + // A position before the start gives a negative offset, which is a large unsigned value, so one compare tests both ends. + if ((uint)(position - start) >= (uint)buffer.Length) { - (int code, int bits) = WebpLookupTables.PrefixEncodeCode[distance]; - extraBits = bits; - return code; + buffer = GetPlaneBuffer(plane, position, out start); } - return PrefixEncodeBitsNoLut(distance, ref extraBits); + return ref buffer[position - start]; } - public static int PrefixEncode(int distance, ref int extraBits, ref int extraBitsValue) + /// + /// Copies the values of a range of flat positions of a plane. The range can cross the ends of rows and of buffers. + /// + /// The value type of the plane. + /// The plane. + /// The first flat position. + /// Receives the values. Its length is the number of values to copy. + public static void CopyPlaneRun(Buffer2D plane, int position, Span destination) + where T : struct { - if (distance < PrefixLookupIdxMax) + // Copy the part of the range in each buffer with one call. + while (!destination.IsEmpty) { - (int code, int bits) = WebpLookupTables.PrefixEncodeCode[distance]; - extraBits = bits; - extraBitsValue = WebpLookupTables.PrefixEncodeExtraBitsValue[distance]; - - return code; + Span buffer = GetPlaneBuffer(plane, position, out int start); + int count = Math.Min(destination.Length, buffer.Length - (position - start)); + buffer.Slice(position - start, count).CopyTo(destination); + position += count; + destination = destination[count..]; } - - return PrefixEncodeNoLut(distance, ref extraBits, ref extraBitsValue); } /// - /// Add green to blue and red channels (i.e. perform the inverse transform of 'subtract green'). + /// Gets the values of a range of flat positions of a plane as one span, when the range is in one buffer of the plane. /// - /// The pixel data to apply the transformation. - public static void AddGreenToBlueAndRed(Span pixelData) + /// The value type of the plane. + /// The plane. + /// The first flat position. + /// The number of values. + /// Receives the values when the method returns . + /// + /// when the range is in one buffer. Otherwise , and the caller copies the range with + /// . + /// + public static bool TryGetPlaneRun(Buffer2D plane, int position, int length, out Span run) + where T : struct { - if (Vector256.IsHardwareAccelerated && pixelData.Length >= 8) + Span buffer = GetPlaneBuffer(plane, position, out int start); + int offset = position - start; + if (buffer.Length - offset >= length) { - // The `255` values disable the write for alpha (A), since 0x80 is set in the control byte (high bit set). - // Each byte index is within its respective 128-bit lane (0-15 and 16-31), so this is safe for per-lane shuffle. - // The high bits are not set for the index bytes, and the values are always < 16 per lane, satisfying AVX2 lane rules. - Vector256 addGreenToBlueAndRedMask = Vector256.Create( - 1, - 255, - 1, - 255, - 5, - 255, - 5, - 255, - 9, - 255, - 9, - 255, - 13, - 255, - 13, - 255, - 17, - 255, - 17, - 255, - 21, - 255, - 21, - 255, - 25, - 255, - 25, - 255, - 29, - 255, - 29, - 255); - - nuint numPixels = (uint)pixelData.Length; - nuint i = 0; - do - { - ref uint pos = ref Unsafe.Add(ref MemoryMarshal.GetReference(pixelData), i); - Vector256 input = Unsafe.As>(ref pos).AsByte(); - Vector256 in0g0g = Vector256_.ShufflePerLane(input, addGreenToBlueAndRedMask); - Vector256 output = input + in0g0g; - Unsafe.As>(ref pos) = output.AsUInt32(); - i += 8; - } - while (i <= numPixels - 8); - - if (i != numPixels) - { - AddGreenToBlueAndRedScalar(pixelData[(int)i..]); - } + run = buffer.Slice(offset, length); + return true; } - else if (Vector128.IsHardwareAccelerated && pixelData.Length >= 4) - { - Vector128 addGreenToBlueAndRedMask = Vector128.Create(1, 255, 1, 255, 5, 255, 5, 255, 9, 255, 9, 255, 13, 255, 13, 255); - nuint numPixels = (uint)pixelData.Length; - nuint i = 0; - do - { - ref uint pos = ref Unsafe.Add(ref MemoryMarshal.GetReference(pixelData), i); - Vector128 input = Unsafe.As>(ref pos).AsByte(); - Vector128 in0g0g = Vector128.ShuffleNative(input, addGreenToBlueAndRedMask); - Vector128 output = input + in0g0g; - Unsafe.As>(ref pos) = output.AsUInt32(); - i += 4; - } - while (i <= numPixels - 4); - if (i != numPixels) - { - AddGreenToBlueAndRedScalar(pixelData[(int)i..]); - } - } - else + run = default; + return false; + } + + /// + /// Sets a range of flat positions of a plane to one value. + /// + /// The value type of the plane. + /// The plane. + /// The first flat position. + /// The number of values to set. + /// The value. + public static void FillPlane(Buffer2D plane, int position, int length, T value) + where T : struct + { + // Fill the part of the range in each buffer with one call. + while (length > 0) { - AddGreenToBlueAndRedScalar(pixelData); + Span buffer = GetPlaneBuffer(plane, position, out int start); + int count = Math.Min(length, buffer.Length - (position - start)); + buffer.Slice(position - start, count).Fill(value); + position += count; + length -= count; } } - private static void AddGreenToBlueAndRedScalar(Span pixelData) + /// + /// Gets the length of the match between the pixel sequences at two flat positions of a plane. A match that is not longer than + /// is of no use to the caller, so the method first compares the values at + /// and returns 0 when they differ. + /// + /// The pixel plane. + /// The flat position of the first sequence. + /// The flat position of the second sequence. + /// The length of the best match found so far. + /// The maximum match length. Both sequences have at least this number of values in the plane. + /// The buffer of the last read of the first sequence. See . + /// The flat position of the first value of . + /// The buffer of the last read of the second sequence. See . + /// The flat position of the first value of . + /// + /// The number of equal leading values, up to . The result is 0 when the values at differ. + /// + [MethodImpl(InliningOptions.ShortMethod)] + public static int FindMatchLength( + Buffer2D plane, + int position1, + int position2, + int bestLenMatch, + int maxLimit, + ref Span buffer1, + ref int start1, + ref Span buffer2, + ref int start2) { - int numPixels = pixelData.Length; - for (int i = 0; i < numPixels; i++) + if (GetPlaneValue(plane, position1 + bestLenMatch, ref buffer1, ref start1) != GetPlaneValue(plane, position2 + bestLenMatch, ref buffer2, ref start2)) { - uint argb = pixelData[i]; - uint green = (argb >> 8) & 0xff; - uint redBlue = argb & 0x00ff00ffu; - redBlue += (green << 16) | green; - redBlue &= 0x00ff00ffu; - pixelData[i] = (argb & 0xff00ff00u) | redBlue; + return 0; } + + return CommonPrefixLength(plane, position1, position2, maxLimit, ref buffer1, ref start1, ref buffer2, ref start2); } - public static void SubtractGreenFromBlueAndRed(Span pixelData) + /// + /// Gets the number of equal leading values of the pixel sequences at two flat positions of a plane. + /// + /// The pixel plane. + /// The flat position of the first sequence. + /// The flat position of the second sequence. + /// The maximum length. Both sequences have at least this number of values in the plane. + /// The buffer of the last read of the first sequence. See . + /// The flat position of the first value of . + /// The buffer of the last read of the second sequence. See . + /// The flat position of the first value of . + /// The number of equal leading values, up to . + [MethodImpl(InliningOptions.ShortMethod)] + public static int CommonPrefixLength( + Buffer2D plane, + int position1, + int position2, + int maxLimit, + ref Span buffer1, + ref int start1, + ref Span buffer2, + ref int start2) { - if (Vector256.IsHardwareAccelerated && pixelData.Length >= 8) + // Usually both sequences are in the buffers of the last reads. Then one runtime SIMD prefix scan compares them. + int offset1 = position1 - start1; + int offset2 = position2 - start2; + if (offset1 >= 0 && buffer1.Length - offset1 >= maxLimit && offset2 >= 0 && buffer2.Length - offset2 >= maxLimit) { - Vector256 subtractGreenFromBlueAndRedMask = Vector256.Create( - 1, - 255, - 1, - 255, - 5, - 255, - 5, - 255, - 9, - 255, - 9, - 255, - 13, - 255, - 13, - 255, - 17, - 255, - 17, - 255, - 21, - 255, - 21, - 255, - 25, - 255, - 25, - 255, - 29, - 255, - 29, - 255); - - nuint numPixels = (uint)pixelData.Length; - nuint i = 0; - do - { - ref uint pos = ref Unsafe.Add(ref MemoryMarshal.GetReference(pixelData), i); - Vector256 input = Unsafe.As>(ref pos).AsByte(); - Vector256 in0g0g = Vector256_.ShufflePerLane(input, subtractGreenFromBlueAndRedMask); - Vector256 output = input - in0g0g; - Unsafe.As>(ref pos) = output.AsUInt32(); - i += 8; - } - while (i <= numPixels - 8); - - if (i != numPixels) - { - SubtractGreenFromBlueAndRedScalar(pixelData[(int)i..]); - } + return buffer1.Slice(offset1, maxLimit).CommonPrefixLength(buffer2.Slice(offset2, maxLimit)); } - else if (Vector128.IsHardwareAccelerated && pixelData.Length >= 4) - { - Vector128 subtractGreenFromBlueAndRedMask = Vector128.Create(1, 255, 1, 255, 5, 255, 5, 255, 9, 255, 9, 255, 13, 255, 13, 255); - nuint numPixels = (uint)pixelData.Length; - nuint i = 0; - do - { - ref uint pos = ref Unsafe.Add(ref MemoryMarshal.GetReference(pixelData), i); - Vector128 input = Unsafe.As>(ref pos).AsByte(); - Vector128 in0g0g = Vector128.ShuffleNative(input, subtractGreenFromBlueAndRedMask); - Vector128 output = input - in0g0g; - Unsafe.As>(ref pos) = output.AsUInt32(); - i += 4; - } - while (i <= numPixels - 4); - if (i != numPixels) + return CommonPrefixLengthAcrossBuffers(plane, position1, position2, maxLimit, ref buffer1, ref start1, ref buffer2, ref start2); + } + + /// + /// Gets the number of equal leading values of two pixel sequences when a sequence is not in the buffer of its last read, or + /// continues after the end of that buffer. + /// + /// The pixel plane. + /// The flat position of the first sequence. + /// The flat position of the second sequence. + /// The maximum length. Both sequences have at least this number of values in the plane. + /// The buffer of the last read of the first sequence. It receives the buffer of the last compared value. + /// The flat position of the first value of . + /// The buffer of the last read of the second sequence. It receives the buffer of the last compared value. + /// The flat position of the first value of . + /// The number of equal leading values, up to . + [MethodImpl(MethodImplOptions.NoInlining)] + private static int CommonPrefixLengthAcrossBuffers( + Buffer2D plane, + int position1, + int position2, + int maxLimit, + ref Span buffer1, + ref int start1, + ref Span buffer2, + ref int start2) + { + // Compare one segment at a time. A segment ends at the end of a buffer of either sequence or at the limit. + int length = 0; + while (length < maxLimit) + { + GetPlaneValue(plane, position1 + length, ref buffer1, ref start1); + GetPlaneValue(plane, position2 + length, ref buffer2, ref start2); + int offset1 = position1 + length - start1; + int offset2 = position2 + length - start2; + int count = Math.Min(maxLimit - length, Math.Min(buffer1.Length - offset1, buffer2.Length - offset2)); + int equal = buffer1.Slice(offset1, count).CommonPrefixLength(buffer2.Slice(offset2, count)); + length += equal; + if (equal < count) { - SubtractGreenFromBlueAndRedScalar(pixelData[(int)i..]); + break; } } - else + + return length; + } + + /// + /// Gets the prefix code of a distance or length and the number of its extra bits. + /// + /// The distance or length. + /// Receives the number of extra bits. + /// The prefix code. + public static int PrefixEncodeBits(int distance, ref int extraBits) + { + if (distance < PrefixLookupIdxMax) { - SubtractGreenFromBlueAndRedScalar(pixelData); + (int code, int bits) = WebpLookupTables.PrefixEncodeCode[distance]; + extraBits = bits; + return code; } + + return PrefixEncodeBitsNoLut(distance, ref extraBits); } - private static void SubtractGreenFromBlueAndRedScalar(Span pixelData) + /// + /// Gets the prefix code of a distance or length, the number of its extra bits and the value of the extra bits. + /// + /// The distance or length. + /// Receives the number of extra bits. + /// Receives the value of the extra bits. + /// The prefix code. + public static int PrefixEncode(int distance, ref int extraBits, ref int extraBitsValue) { - int numPixels = pixelData.Length; - for (int i = 0; i < numPixels; i++) + if (distance < PrefixLookupIdxMax) { - uint argb = pixelData[i]; - uint green = (argb >> 8) & 0xff; - uint newR = (((argb >> 16) & 0xff) - green) & 0xff; - uint newB = (((argb >> 0) & 0xff) - green) & 0xff; - pixelData[i] = (argb & 0xff00ff00u) | (newR << 16) | newB; + (int code, int bits) = WebpLookupTables.PrefixEncodeCode[distance]; + extraBits = bits; + extraBitsValue = WebpLookupTables.PrefixEncodeExtraBitsValue[distance]; + + return code; } + + return PrefixEncodeNoLut(distance, ref extraBits, ref extraBitsValue); } + /// + /// Add green to blue and red channels (i.e. perform the inverse transform of 'subtract green'). + /// + /// The pixel data to apply the transformation. + public static void AddGreenToBlueAndRed(Span pixelData) => TransformPixels(pixelData, default(AddGreenOperator)); + + /// + /// Subtracts green from blue and red channels, the subtract green transform of the encoder. + /// + /// The pixel data to apply the transformation. + public static void SubtractGreenFromBlueAndRed(Span pixelData) => TransformPixels(pixelData, default(SubtractGreenOperator)); + /// /// If there are not many unique pixel values, it is more efficient to create a color index array and replace the pixel values by the array's indices. - /// This will reverse the color index transform. + /// This will reverse the color index transform for a batch of rows. /// + /// + /// + /// The green channel of each value holds the palette indices. With 16 colors or fewer, each value packs 2, 4 or 8 indices, the first pixel in the + /// low bits. See the WebP Lossless Bitstream Specification, section 4.4 "Color Indexing Transform": + /// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// + /// + /// For each row, copies the green bytes to , and expands + /// them through the palette into the row. The rows expand in place from the last to the first. A packed row is not longer than an expanded row, so + /// expanded row y ends before the expanded row y + 1 starts, and it starts at or after the end of packed row y - 1. Thus each write replaces only + /// values that the transform read before. + /// + /// /// The transform data contains color table size and the entries in the color table. - /// The pixel data to apply the reverse transform on. - /// The resulting pixel data with the reversed transformation data. - public static void ColorIndexInverseTransform( - Vp8LTransform transform, - Span pixelData, - Span outputSpan) + /// The packed rows of the batch, one after the other. On return, the expanded rows. + /// The number of rows in the batch. + /// The scratch for the palette indices of one packed row. + public static void ColorIndexInverseTransform(Vp8LTransform transform, Span pixelData, int rowCount, Span indexRow) { - int bitsPerPixel = 8 >> transform.Bits; + int bitsPerIndex = 8 >> transform.Bits; int width = transform.XSize; - int height = transform.YSize; - Span colorMap = transform.Data.GetSpan(); - int decodedPixels = 0; - if (bitsPerPixel < 8) - { - int pixelsPerByte = 1 << transform.Bits; - int countMask = pixelsPerByte - 1; - int bitMask = (1 << bitsPerPixel) - 1; - - int pixelDataPos = 0; - for (int y = 0; y < height; y++) - { - uint packedPixels = 0; - for (int x = 0; x < width; x++) - { - // We need to load fresh 'packed_pixels' once every - // 'pixelsPerByte' increments of x. Fortunately, pixelsPerByte - // is a power of 2, so we can just use a mask for that, instead of - // decrementing a counter. - if ((x & countMask) == 0) - { - packedPixels = GetArgbIndex(pixelData[pixelDataPos++]); - } - - outputSpan[decodedPixels++] = colorMap[(int)(packedPixels & bitMask)]; - packedPixels >>= bitsPerPixel; - } - } + int packedWidth = SubSampleSize(width, transform.Bits); - outputSpan.CopyTo(pixelData); - } - else + // The palette has 1 << bitsPerIndex entries, one for each value of an index. + ReadOnlySpan colorMap = transform.Data.GetSpan(); + Span indices = indexRow[..packedWidth]; + for (int y = rowCount - 1; y >= 0; y--) { - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - uint colorMapIndex = GetArgbIndex(pixelData[decodedPixels]); - pixelData[decodedPixels] = colorMap[(int)colorMapIndex]; - decodedPixels++; - } - } + SimdUtils.ExtractBytes(pixelData.Slice(y * packedWidth, packedWidth), indices, 1); + PaletteExpander.ExpandLowBitsFirst(indices, bitsPerIndex, colorMap, pixelData.Slice(y * width, width)); } } @@ -353,17 +400,19 @@ public static void ColorIndexInverseTransform( /// Color transform keeps the green (G) value as it is, transforms red (R) based on green and transforms blue (B) based on green and then based on red. /// /// The transform data. - /// The pixel data to apply the inverse transform on. - public static void ColorSpaceInverseTransform(Vp8LTransform transform, Span pixelData) + /// The rows of the batch, one after the other. + /// The image row of the first row of the batch. It selects the tile row of the transform data. + /// The number of rows in the batch. + public static void ColorSpaceInverseTransform(Vp8LTransform transform, Span pixelData, int firstRow, int rowCount) { int width = transform.XSize; - int yEnd = transform.YSize; + int yEnd = firstRow + rowCount; int tileWidth = 1 << transform.Bits; int mask = tileWidth - 1; int safeWidth = width & ~mask; int remainingWidth = width - safeWidth; int tilesPerRow = SubSampleSize(width, transform.Bits); - int y = 0; + int y = firstRow; int predRowIdxStart = (y >> transform.Bits) * tilesPerRow; Span transformData = transform.Data.GetSpan(); @@ -405,430 +454,120 @@ public static void ColorSpaceInverseTransform(Vp8LTransform transform, SpanThe pixel data to transform. /// The number of pixels to process. public static void TransformColor(Vp8LMultipliers m, Span pixelData, int numPixels) - { - if (Avx2.IsSupported && numPixels >= 8) - { - Vector256 transformColorAlphaGreenMask256 = Vector256.Create( - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255); - - Vector256 transformColorRedBlueMask256 = Vector256.Create( - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0); - - Vector256 multsrb = MkCst32(Cst5b(m.GreenToRed), Cst5b(m.GreenToBlue)); - Vector256 multsb2 = MkCst32(Cst5b(m.RedToBlue), 0); - - nuint idx = 0; - do - { - ref uint pos = ref Unsafe.Add(ref MemoryMarshal.GetReference(pixelData), idx); - Vector256 input = Unsafe.As>(ref pos); - Vector256 a = Avx2.And(input.AsByte(), transformColorAlphaGreenMask256); - Vector256 b = Avx2.ShuffleLow(a.AsInt16(), SimdUtils.Shuffle.MMShuffle2200); - Vector256 c = Avx2.ShuffleHigh(b.AsInt16(), SimdUtils.Shuffle.MMShuffle2200); - Vector256 d = Avx2.MultiplyHigh(c.AsInt16(), multsrb.AsInt16()); - Vector256 e = Avx2.ShiftLeftLogical(input.AsInt16(), 8); - Vector256 f = Avx2.MultiplyHigh(e.AsInt16(), multsb2.AsInt16()); - Vector256 g = Avx2.ShiftRightLogical(f.AsInt32(), 16); - Vector256 h = Avx2.Add(g.AsByte(), d.AsByte()); - Vector256 i = Avx2.And(h, transformColorRedBlueMask256); - Vector256 output = Avx2.Subtract(input.AsByte(), i); - Unsafe.As>(ref pos) = output.AsUInt32(); - idx += 8; - } - while (idx <= (uint)numPixels - 8); - - if (idx != (uint)numPixels) - { - TransformColorScalar(m, pixelData[(int)idx..], numPixels - (int)idx); - } - } - else if (Vector128.IsHardwareAccelerated && numPixels >= 4) - { - Vector128 transformColorAlphaGreenMask = Vector128.Create(0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255); - Vector128 transformColorRedBlueMask = Vector128.Create(255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0); - Vector128 multsrb = MkCst16(Cst5b(m.GreenToRed), Cst5b(m.GreenToBlue)); - Vector128 multsb2 = MkCst16(Cst5b(m.RedToBlue), 0); - nuint idx = 0; - do - { - ref uint pos = ref Unsafe.Add(ref MemoryMarshal.GetReference(pixelData), idx); - Vector128 input = Unsafe.As>(ref pos); - Vector128 a = input.AsByte() & transformColorAlphaGreenMask; - Vector128 b = Vector128_.ShuffleLow(a.AsInt16(), SimdUtils.Shuffle.MMShuffle2200); - Vector128 c = Vector128_.ShuffleHigh(b.AsInt16(), SimdUtils.Shuffle.MMShuffle2200); - Vector128 d = Vector128_.MultiplyHigh(c.AsInt16(), multsrb.AsInt16()); - Vector128 e = input.AsInt16() << 8; - Vector128 f = Vector128_.MultiplyHigh(e.AsInt16(), multsb2.AsInt16()); - Vector128 g = Vector128.ShiftRightLogical(f.AsInt32(), 16); - Vector128 h = g.AsByte() + d.AsByte(); - Vector128 i = h & transformColorRedBlueMask; - Vector128 output = input.AsByte() - i; - Unsafe.As>(ref pos) = output.AsUInt32(); - idx += 4; - } - while ((int)idx <= numPixels - 4); - - if ((int)idx != numPixels) - { - TransformColorScalar(m, pixelData[(int)idx..], numPixels - (int)idx); - } - } - else - { - TransformColorScalar(m, pixelData, numPixels); - } - } - - private static void TransformColorScalar(Vp8LMultipliers m, Span data, int numPixels) - { - for (int i = 0; i < numPixels; i++) - { - uint argb = data[i]; - sbyte green = U32ToS8(argb >> 8); - sbyte red = U32ToS8(argb >> 16); - int newRed = red & 0xff; - int newBlue = (int)(argb & 0xff); - newRed -= ColorTransformDelta((sbyte)m.GreenToRed, green); - newRed &= 0xff; - newBlue -= ColorTransformDelta((sbyte)m.GreenToBlue, green); - newBlue -= ColorTransformDelta((sbyte)m.RedToBlue, red); - newBlue &= 0xff; - data[i] = (argb & 0xff00ff00u) | ((uint)newRed << 16) | (uint)newBlue; - } - } + => TransformPixels(pixelData[..numPixels], new TransformColorOperator(m)); /// /// Reverses the color space transform. /// /// The color transform element. /// The pixel data to apply the inverse transform on. - public static void TransformColorInverse(Vp8LMultipliers m, Span pixelData) + public static void TransformColorInverse(Vp8LMultipliers m, Span pixelData) => TransformPixels(pixelData, new TransformColorInverseOperator(m)); + + /// + /// Reverses the predictor transform: each pixel is its residual plus the prediction from the pixels before it in scan-line order. + /// The image is divided into square tiles, and all pixels of a tile use the prediction mode of the tile. + /// See the WebP Lossless Bitstream Specification, section 4.1 "Predictor Transform": + /// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// + /// + /// The method works in place on a batch of rows. A prediction reads the left pixel and the top-left, top and top-right pixels. In scan-line order, these + /// pixels are final before the pixel. The top-right pixel of the last pixel of a row is the first pixel of the current row. That pixel uses + /// the top predictor, so it is final before the other pixels of the row. The specification gives this rule in section 4.1. + /// The row above the batch is the first row of , directly before the batch rows. Thus the top-right read of the last pixel of + /// the first batch row reaches the first pixel of that row. At the end, the method copies the last batch row to that place. The next batch then predicts + /// from the predictor output of this batch, also when later transforms change the batch rows. + /// + /// The transform data. + /// + /// One row of pixels with the predictor output of the row above the batch, then the rows of the batch. + /// The method does not read the first row when is 0. + /// + /// The image row of the first row of the batch. It selects the tile row of the transform data. + /// The number of rows in the batch. It is at least 1. + public static void PredictorInverseTransform(Vp8LTransform transform, Span pixelData, int firstRow, int rowCount) { - if (Avx2.IsSupported && pixelData.Length >= 8) - { - Vector256 transformColorInverseAlphaGreenMask256 = Vector256.Create( - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255, - 0, - 255); - - Vector256 multsrb = MkCst32(Cst5b(m.GreenToRed), Cst5b(m.GreenToBlue)); - Vector256 multsb2 = MkCst32(Cst5b(m.RedToBlue), 0); - nuint idx; - for (idx = 0; idx <= (uint)pixelData.Length - 8; idx += 8) - { - ref uint pos = ref Unsafe.Add(ref MemoryMarshal.GetReference(pixelData), idx); - Vector256 input = Unsafe.As>(ref pos); - Vector256 a = Avx2.And(input.AsByte(), transformColorInverseAlphaGreenMask256); - Vector256 b = Avx2.ShuffleLow(a.AsInt16(), SimdUtils.Shuffle.MMShuffle2200); - Vector256 c = Avx2.ShuffleHigh(b.AsInt16(), SimdUtils.Shuffle.MMShuffle2200); - Vector256 d = Avx2.MultiplyHigh(c.AsInt16(), multsrb.AsInt16()); - Vector256 e = Avx2.Add(input.AsByte(), d.AsByte()); - Vector256 f = Avx2.ShiftLeftLogical(e.AsInt16(), 8); - Vector256 g = Avx2.MultiplyHigh(f, multsb2.AsInt16()); - Vector256 h = Avx2.ShiftRightLogical(g.AsInt32(), 8); - Vector256 i = Avx2.Add(h.AsByte(), f.AsByte()); - Vector256 j = Avx2.ShiftRightLogical(i.AsInt16(), 8); - Vector256 output = Avx2.Or(j.AsByte(), a); - Unsafe.As>(ref pos) = output.AsUInt32(); - } + // The row ref walks one row at a time. The upper row is at offset -width. The predictors read the left pixel at offset -1 and the top-left pixel at + // offset -width - 1. These reads stay inside the pixel data because the first image row and the first column use other predictors. + int width = transform.XSize; + ref uint pixels = ref Unsafe.Add(ref MemoryMarshal.GetReference(pixelData), (uint)width); + Span transformData = transform.Data.GetSpan(); - if (idx != (uint)pixelData.Length) - { - TransformColorInverseScalar(m, pixelData[(int)idx..]); - } + int y = firstRow; + int yEnd = firstRow + rowCount; + if (y == 0) + { + // The first pixel follows the black (mode 0) mode, and the rest of the first row the L (mode 1) mode. These modes do not read the row above. + PredictorAdd(0, ref pixels, ref pixels, 1); + PredictorAdd(1, ref Unsafe.Add(ref pixels, (nuint)1), ref pixels, width - 1); + pixels = ref Unsafe.Add(ref pixels, (uint)width); + y = 1; } - else if (Vector128.IsHardwareAccelerated && pixelData.Length >= 4) + + int tileWidth = 1 << transform.Bits; + int mask = tileWidth - 1; + int tilesPerRow = SubSampleSize(width, transform.Bits); + int predictorModeIdxBase = (y >> transform.Bits) * tilesPerRow; + while (y < yEnd) { - Vector128 transformColorInverseAlphaGreenMask = Vector128.Create(0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255); - Vector128 multsrb = MkCst16(Cst5b(m.GreenToRed), Cst5b(m.GreenToBlue)); - Vector128 multsb2 = MkCst16(Cst5b(m.RedToBlue), 0); + int predictorModeIdx = predictorModeIdxBase; + int x = 1; - nuint idx; - for (idx = 0; idx <= (uint)pixelData.Length - 4; idx += 4) - { - ref uint pos = ref Unsafe.Add(ref MemoryMarshal.GetReference(pixelData), idx); - Vector128 input = Unsafe.As>(ref pos); - Vector128 a = input.AsByte() & transformColorInverseAlphaGreenMask; - Vector128 b = Vector128_.ShuffleLow(a.AsInt16(), SimdUtils.Shuffle.MMShuffle2200); - Vector128 c = Vector128_.ShuffleHigh(b.AsInt16(), SimdUtils.Shuffle.MMShuffle2200); - Vector128 d = Vector128_.MultiplyHigh(c.AsInt16(), multsrb.AsInt16()); - Vector128 e = input.AsByte() + d.AsByte(); - Vector128 f = e.AsInt16() << 8; - Vector128 g = Vector128_.MultiplyHigh(f, multsb2.AsInt16()); - Vector128 h = Vector128.ShiftRightLogical(g.AsInt32(), 8); - Vector128 i = h.AsByte() + f.AsByte(); - Vector128 j = Vector128.ShiftRightLogical(i.AsInt16(), 8); - Vector128 output = j.AsByte() | a; - Unsafe.As>(ref pos) = output.AsUInt32(); - } + // First pixel follows the T (mode=2) mode. + PredictorAdd(2, ref pixels, ref Unsafe.Subtract(ref pixels, (uint)width), 1); - if (idx != (uint)pixelData.Length) + // .. the rest: + while (x < width) { - TransformColorInverseScalar(m, pixelData[(int)idx..]); + int predictorMode = (int)((transformData[predictorModeIdx++] >> 8) & 0xf); + int xEnd = (x & ~mask) + tileWidth; + if (xEnd > width) + { + xEnd = width; + } + + // There are 14 different prediction modes. The mode value has 4 bits. PredictorAdd uses mode 0 for the modes 14 and 15, as libwebp does. + PredictorAdd(predictorMode, ref Unsafe.Add(ref pixels, (uint)x), ref Unsafe.Subtract(ref pixels, (uint)(width - x)), xEnd - x); + x = xEnd; } - } - else - { - TransformColorInverseScalar(m, pixelData); - } - } - private static void TransformColorInverseScalar(Vp8LMultipliers m, Span pixelData) - { - for (int i = 0; i < pixelData.Length; i++) - { - uint argb = pixelData[i]; - sbyte green = (sbyte)(argb >> 8); - uint red = argb >> 16; - int newRed = (int)(red & 0xff); - int newBlue = (int)argb & 0xff; - newRed += ColorTransformDelta((sbyte)m.GreenToRed, green); - newRed &= 0xff; - newBlue += ColorTransformDelta((sbyte)m.GreenToBlue, green); - newBlue += ColorTransformDelta((sbyte)m.RedToBlue, (sbyte)newRed); - newBlue &= 0xff; - - pixelData[i] = (argb & 0xff00ff00u) | ((uint)newRed << 16) | (uint)newBlue; - } - } + pixels = ref Unsafe.Add(ref pixels, (uint)width); + y++; - /// - /// This will reverse the predictor transform. - /// The predictor transform can be used to reduce entropy by exploiting the fact that neighboring pixels are often correlated. - /// In the predictor transform, the current pixel value is predicted from the pixels already decoded (in scan-line order) and only the residual value (actual - predicted) is encoded. - /// The prediction mode determines the type of prediction to use. The image is divided into squares and all the pixels in a square use same prediction mode. - /// - /// The transform data. - /// The pixel data to apply the inverse transform. - /// The resulting pixel data with the reversed transformation data. - public static void PredictorInverseTransform( - Vp8LTransform transform, - Span pixelData, - Span outputSpan) - { - fixed (uint* inputFixed = pixelData) - { - fixed (uint* outputFixed = outputSpan) + if ((y & mask) == 0) { - uint* input = inputFixed; - uint* output = outputFixed; - - int width = transform.XSize; - Span transformData = transform.Data.GetSpan(); - - // First Row follows the L (mode=1) mode. - PredictorAdd0(input, 1, output); - PredictorAdd1(input + 1, width - 1, output + 1); - input += width; - output += width; - - int y = 1; - int yEnd = transform.YSize; - int tileWidth = 1 << transform.Bits; - int mask = tileWidth - 1; - int tilesPerRow = SubSampleSize(width, transform.Bits); - int predictorModeIdxBase = (y >> transform.Bits) * tilesPerRow; - Span scratch = stackalloc short[8]; - while (y < yEnd) - { - int predictorModeIdx = predictorModeIdxBase; - int x = 1; - - // First pixel follows the T (mode=2) mode. - PredictorAdd2(input, output - width, 1, output); - - // .. the rest: - while (x < width) - { - uint predictorMode = (transformData[predictorModeIdx++] >> 8) & 0xf; - int xEnd = (x & ~mask) + tileWidth; - if (xEnd > width) - { - xEnd = width; - } - - // There are 14 different prediction modes. - // In each prediction mode, the current pixel value is predicted from one - // or more neighboring pixels whose values are already known. - switch (predictorMode) - { - case 0: - PredictorAdd0(input + x, xEnd - x, output + x); - break; - case 1: - PredictorAdd1(input + x, xEnd - x, output + x); - break; - case 2: - PredictorAdd2(input + x, output + x - width, xEnd - x, output + x); - break; - case 3: - PredictorAdd3(input + x, output + x - width, xEnd - x, output + x); - break; - case 4: - PredictorAdd4(input + x, output + x - width, xEnd - x, output + x); - break; - case 5: - PredictorAdd5(input + x, output + x - width, xEnd - x, output + x); - break; - case 6: - PredictorAdd6(input + x, output + x - width, xEnd - x, output + x); - break; - case 7: - PredictorAdd7(input + x, output + x - width, xEnd - x, output + x); - break; - case 8: - PredictorAdd8(input + x, output + x - width, xEnd - x, output + x); - break; - case 9: - PredictorAdd9(input + x, output + x - width, xEnd - x, output + x); - break; - case 10: - PredictorAdd10(input + x, output + x - width, xEnd - x, output + x); - break; - case 11: - PredictorAdd11(input + x, output + x - width, xEnd - x, output + x, scratch); - break; - case 12: - PredictorAdd12(input + x, output + x - width, xEnd - x, output + x); - break; - case 13: - PredictorAdd13(input + x, output + x - width, xEnd - x, output + x); - break; - } - - x = xEnd; - } - - input += width; - output += width; - y++; - - if ((y & mask) == 0) - { - // Use the same mask, since tiles are squares. - predictorModeIdxBase += tilesPerRow; - } - } + // Use the same mask, since tiles are squares. + predictorModeIdxBase += tilesPerRow; } } - outputSpan.CopyTo(pixelData); + // Keep the predictor output of the last row for the next batch. + pixelData.Slice(width * rowCount, width).CopyTo(pixelData); } + /// + /// Decodes a delta-coded color table. Each component of a color is the sum, mod 256, of its coded value and the same component + /// of the previous color. + /// + /// + /// The colors are a run of left-predicted 4-byte pixels, the same rule as the left predictor, so decodes them. See the + /// WebP Lossless Bitstream Specification, section 4.4 "Color Indexing Transform". The caller allocates the table clean, so the entries after the + /// last color stay zero. + /// + /// The number of colors in the coded table. + /// The delta-coded colors. + /// Receives the decoded colors. Its entries after are zero. public static void ExpandColorMap(int numColors, Span transformData, Span newColorMap) { - newColorMap[0] = transformData[0]; - Span data = MemoryMarshal.Cast(transformData); - Span newData = MemoryMarshal.Cast(newColorMap); - int numColorsX4 = 4 * numColors; - int i; - for (i = 4; i < numColorsX4; i++) - { - // Equivalent to AddPixelEq(), on a byte-basis. - newData[i] = (byte)((data[i] + newData[i - 4]) & 0xff); - } - - int colorMapLength4 = 4 * newColorMap.Length; - for (; i < colorMapLength4; i++) - { - newData[i] = 0; // black tail. - } + transformData[..numColors].CopyTo(newColorMap); + SimdUtils.AddLeft(MemoryMarshal.AsBytes(newColorMap[1..numColors]), 4, newColorMap[0]); } /// /// Difference of each component, mod 256. /// + /// The ARGB pixel to subtract from. + /// The ARGB pixel to subtract. + /// The ARGB pixel that holds the difference of each component, mod 256. [MethodImpl(InliningOptions.ShortMethod)] public static uint SubPixels(uint a, uint b) { @@ -840,31 +579,96 @@ public static uint SubPixels(uint a, uint b) /// /// Bundles multiple (1, 2, 4 or 8) pixels into a single pixel. /// + /// The palette indices of the row. It has at least values. + /// The number of pixels in the row. + /// The base 2 logarithm of the number of pixels in one packed pixel. The range is 0 to 3. + /// The packed pixels. It has at least SubSampleSize(width, xBits) values. public static void BundleColorMap(ReadOnlySpan row, int width, int xBits, Span dst) { - int x; + switch (xBits) + { + case 0: + BundleColorMap(row, width, dst); + break; + case 1: + BundleColorMap(row, width, dst); + break; + case 2: + BundleColorMap(row, width, dst); + break; + default: + BundleColorMap(row, width, dst); + break; + } + } + + /// + /// Bundles 1 << TOperator.XBits pixels into a single pixel. + /// + /// + /// The vector loops read whole vectors of indices. A vector holds a multiple of 8 indices, so each vector writes whole packed pixels. + /// The scalar loop then starts at the first index of a packed pixel and finishes the row, or does the full row without hardware acceleration. + /// + /// The operator for the number of pixels in one packed pixel. + /// The palette indices of the row. It has at least values. + /// The number of pixels in the row. + /// The packed pixels. It has at least SubSampleSize(width, TOperator.XBits) values. + private static void BundleColorMap(ReadOnlySpan row, int width, Span dst) + where TOperator : IBundleOperator + { + int xBits = TOperator.XBits; + ref byte source = ref MemoryMarshal.GetReference(row); + ref uint destination = ref MemoryMarshal.GetReference(dst); + nuint length = (uint)width; + nuint x = 0; + + if (Vector512.IsHardwareAccelerated) + { + for (; x + (uint)Vector512.Count <= length; x += (uint)Vector512.Count) + { + TOperator.Bundle(Vector512.LoadUnsafe(ref source, x), ref Unsafe.Add(ref destination, x >> xBits)); + } + } + + if (Vector256.IsHardwareAccelerated) + { + for (; x + (uint)Vector256.Count <= length; x += (uint)Vector256.Count) + { + TOperator.Bundle(Vector256.LoadUnsafe(ref source, x), ref Unsafe.Add(ref destination, x >> xBits)); + } + } + + if (Vector128.IsHardwareAccelerated) + { + for (; x + (uint)Vector128.Count <= length; x += (uint)Vector128.Count) + { + TOperator.Bundle(Vector128.LoadUnsafe(ref source, x), ref Unsafe.Add(ref destination, x >> xBits)); + } + } + if (xBits > 0) { + // Each index takes bitDepth bits of the green byte. Index xSub of a packed pixel starts at bit 8 + (bitDepth * xSub). int bitDepth = 1 << (3 - xBits); - int mask = (1 << xBits) - 1; + nuint mask = (1u << xBits) - 1; uint code = 0xff000000; - for (x = 0; x < width; x++) + for (; x < length; x++) { - int xsub = x & mask; - if (xsub == 0) + int xSub = (int)(x & mask); + if (xSub == 0) { code = 0xff000000; } - code |= (uint)(row[x] << (8 + (bitDepth * xsub))); - dst[x >> xBits] = code; + code |= (uint)Unsafe.Add(ref source, x) << (8 + (bitDepth * xSub)); + Unsafe.Add(ref destination, x >> xBits) = code; } } else { - for (x = 0; x < width; x++) + for (; x < length; x++) { - dst[x] = (uint)(0xff000000 | (row[x] << 8)); + Unsafe.Add(ref destination, x) = 0xff000000 | ((uint)Unsafe.Add(ref source, x) << 8); } } } @@ -872,187 +676,130 @@ public static void BundleColorMap(ReadOnlySpan row, int width, int xBits, /// /// Compute the combined Shanon's entropy for distribution {X} and {X+Y}. /// + /// + /// + /// The result is the sum of -FastSLog2 of each non-zero count of X and of X + Y, plus FastSLog2 of the two totals. The counts are not negative, so a + /// zero X + Y means that X is zero too. Thus each index with a non-zero X + Y adds the X + Y term, then the X term when X is not zero. + /// + /// + /// The histograms are sparse. Each vector step adds the counts to the totals and finds the non-zero X + Y lanes with one compare. Only those lanes + /// compute logarithms, in index order. Each width and the scalar form add the terms in the same order, so the double sum, and the encoder + /// decisions that use it, are the same on each platform. + /// + /// + /// The population counts of distribution X. It holds 256 values. + /// The population counts of distribution Y. It holds 256 values. /// Shanon entropy. - public static float CombinedShannonEntropy(Span x, Span y) + public static float CombinedShannonEntropy(ReadOnlySpan x, ReadOnlySpan y) { - if (Avx2.IsSupported) + ref int xRef = ref MemoryMarshal.GetReference(x); + ref int yRef = ref MemoryMarshal.GetReference(y); + double retVal = 0.0d; + uint sumX; + uint sumXY; + + if (Vector512.IsHardwareAccelerated) { - double retVal = 0.0d; - Vector256 tmp = Vector256.Zero; // has the size of the scratch space of sizeof(int) * 8 - ref int xRef = ref MemoryMarshal.GetReference(x); - ref int yRef = ref MemoryMarshal.GetReference(y); - Vector256 sumXY256 = Vector256.Zero; - Vector256 sumX256 = Vector256.Zero; - ref int tmpRef = ref Unsafe.As, int>(ref tmp); - for (nuint i = 0; i < 256; i += 8) + Vector512 sumX512 = Vector512.Zero; + Vector512 sumXY512 = Vector512.Zero; + for (nuint i = 0; i < 256; i += (uint)Vector512.Count) { - Vector256 xVec = Unsafe.As>(ref Unsafe.Add(ref xRef, i)); - Vector256 yVec = Unsafe.As>(ref Unsafe.Add(ref yRef, i)); - - // Check if any X is non-zero: this actually provides a speedup as X is usually sparse. - int mask = Avx2.MoveMask(Avx2.CompareEqual(xVec, Vector256.Zero).AsByte()); - if (mask != -1) - { - Vector256 xy256 = Avx2.Add(xVec, yVec); - sumXY256 = Avx2.Add(sumXY256, xy256); - sumX256 = Avx2.Add(sumX256, xVec); - - // Analyze the different X + Y. - Unsafe.As>(ref tmpRef) = xy256; - if (tmpRef != 0) - { - retVal -= FastSLog2((uint)tmpRef); - if (Unsafe.Add(ref xRef, i) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref xRef, i)); - } - } - - if (Unsafe.Add(ref tmpRef, 1) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref tmpRef, 1)); - if (Unsafe.Add(ref xRef, i + 1) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref xRef, i + 1)); - } - } - - if (Unsafe.Add(ref tmpRef, 2) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref tmpRef, 2)); - if (Unsafe.Add(ref xRef, i + 2) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref xRef, i + 2)); - } - } - - if (Unsafe.Add(ref tmpRef, 3) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref tmpRef, 3)); - if (Unsafe.Add(ref xRef, i + 3) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref xRef, i + 3)); - } - } - - if (Unsafe.Add(ref tmpRef, 4) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref tmpRef, 4)); - if (Unsafe.Add(ref xRef, i + 4) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref xRef, i + 4)); - } - } - - if (Unsafe.Add(ref tmpRef, 5) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref tmpRef, 5)); - if (Unsafe.Add(ref xRef, i + 5) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref xRef, i + 5)); - } - } - - if (Unsafe.Add(ref tmpRef, 6) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref tmpRef, 6)); - if (Unsafe.Add(ref xRef, i + 6) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref xRef, i + 6)); - } - } - - if (Unsafe.Add(ref tmpRef, 7) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref tmpRef, 7)); - if (Unsafe.Add(ref xRef, i + 7) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref xRef, i + 7)); - } - } - } - else - { - // X is fully 0, so only deal with Y. - sumXY256 = Avx2.Add(sumXY256, yVec); - - if (Unsafe.Add(ref yRef, i) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref yRef, i)); - } - - if (Unsafe.Add(ref yRef, i + 1) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref yRef, i + 1)); - } - - if (Unsafe.Add(ref yRef, i + 2) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref yRef, i + 2)); - } - - if (Unsafe.Add(ref yRef, i + 3) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref yRef, i + 3)); - } - - if (Unsafe.Add(ref yRef, i + 4) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref yRef, i + 4)); - } - - if (Unsafe.Add(ref yRef, i + 5) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref yRef, i + 5)); - } - - if (Unsafe.Add(ref yRef, i + 6) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref yRef, i + 6)); - } - - if (Unsafe.Add(ref yRef, i + 7) != 0) - { - retVal -= FastSLog2((uint)Unsafe.Add(ref yRef, i + 7)); - } - } + Vector512 xVec = Vector512.LoadUnsafe(ref xRef, i); + Vector512 xy = xVec + Vector512.LoadUnsafe(ref yRef, i); + sumX512 += xVec; + sumXY512 += xy; + retVal = AddEntropyTerms(ref xRef, ref yRef, i, (~Vector512.Equals(xy, Vector512.Zero)).ExtractMostSignificantBits(), retVal); } - // Sum up sumX256 to get sumX and sum up sumXY256 to get sumXY. - int sumX = Numerics.ReduceSum(sumX256); - int sumXY = Numerics.ReduceSum(sumXY256); + sumX = (uint)Vector512.Sum(sumX512); + sumXY = (uint)Vector512.Sum(sumXY512); + } + else if (Vector256.IsHardwareAccelerated) + { + Vector256 sumX256 = Vector256.Zero; + Vector256 sumXY256 = Vector256.Zero; + for (nuint i = 0; i < 256; i += (uint)Vector256.Count) + { + Vector256 xVec = Vector256.LoadUnsafe(ref xRef, i); + Vector256 xy = xVec + Vector256.LoadUnsafe(ref yRef, i); + sumX256 += xVec; + sumXY256 += xy; + retVal = AddEntropyTerms(ref xRef, ref yRef, i, (~Vector256.Equals(xy, Vector256.Zero)).ExtractMostSignificantBits(), retVal); + } - retVal += FastSLog2((uint)sumX) + FastSLog2((uint)sumXY); + sumX = (uint)Vector256.Sum(sumX256); + sumXY = (uint)Vector256.Sum(sumXY256); + } + else if (Vector128.IsHardwareAccelerated) + { + Vector128 sumX128 = Vector128.Zero; + Vector128 sumXY128 = Vector128.Zero; + for (nuint i = 0; i < 256; i += (uint)Vector128.Count) + { + Vector128 xVec = Vector128.LoadUnsafe(ref xRef, i); + Vector128 xy = xVec + Vector128.LoadUnsafe(ref yRef, i); + sumX128 += xVec; + sumXY128 += xy; + retVal = AddEntropyTerms(ref xRef, ref yRef, i, (~Vector128.Equals(xy, Vector128.Zero)).ExtractMostSignificantBits(), retVal); + } - return (float)retVal; + sumX = (uint)Vector128.Sum(sumX128); + sumXY = (uint)Vector128.Sum(sumXY128); } else { - double retVal = 0.0d; - uint sumX = 0, sumXY = 0; - for (int i = 0; i < 256; i++) + sumX = 0; + sumXY = 0; + for (nuint i = 0; i < 256; i++) { - uint xi = (uint)x[i]; - if (xi != 0) + uint xi = (uint)Unsafe.Add(ref xRef, i); + uint xy = xi + (uint)Unsafe.Add(ref yRef, i); + sumX += xi; + sumXY += xy; + if (xy != 0) { - uint xy = xi + (uint)y[i]; - sumX += xi; - retVal -= FastSLog2(xi); - sumXY += xy; - retVal -= FastSLog2(xy); - } - else if (y[i] != 0) - { - sumXY += (uint)y[i]; - retVal -= FastSLog2((uint)y[i]); + retVal = AddEntropyTerms(ref xRef, ref yRef, i, 1, retVal); } } + } + + retVal += FastSLog2(sumX) + FastSLog2(sumXY); + return (float)retVal; + } - retVal += FastSLog2(sumX) + FastSLog2(sumXY); - return (float)retVal; + /// + /// Subtracts the entropy terms of the non-zero X + Y lanes of one block from , in index order. + /// + /// The first count of X. + /// The first count of Y. + /// The index of the first lane of the block. + /// Bit k is set when X + Y of lane k is not zero. + /// The sum before the block. + /// The sum after the block. + [MethodImpl(InliningOptions.ShortMethod)] + private static double AddEntropyTerms(ref int xRef, ref int yRef, nuint start, ulong nonZero, double retVal) + { + while (nonZero != 0) + { + nuint i = start + (uint)BitOperations.TrailingZeroCount(nonZero); + nonZero &= nonZero - 1; + uint xi = (uint)Unsafe.Add(ref xRef, i); + retVal -= FastSLog2(xi + (uint)Unsafe.Add(ref yRef, i)); + if (xi != 0) + { + retVal -= FastSLog2(xi); + } } + + return retVal; } + /// + /// Applies the forward color transform to the red channel: red - delta(green). + /// + /// The green-to-red multiplier. + /// The ARGB pixel. + /// The transformed red value. [MethodImpl(InliningOptions.ShortMethod)] public static byte TransformColorRed(sbyte greenToRed, uint argb) { @@ -1062,6 +809,13 @@ public static byte TransformColorRed(sbyte greenToRed, uint argb) return (byte)(newRed & 0xff); } + /// + /// Applies the forward color transform to the blue channel: blue - delta(green) - delta(red). + /// + /// The green-to-blue multiplier. + /// The red-to-blue multiplier. + /// The ARGB pixel. + /// The transformed blue value. [MethodImpl(InliningOptions.ShortMethod)] public static byte TransformColorBlue(sbyte greenToBlue, sbyte redToBlue, uint argb) { @@ -1076,15 +830,25 @@ public static byte TransformColorBlue(sbyte greenToBlue, sbyte redToBlue, uint a /// /// Fast calculation of log2(v) for integer input. /// + /// The input value. + /// The approximate base 2 logarithm of . [MethodImpl(InliningOptions.ShortMethod)] - public static float FastLog2(uint v) => v < LogLookupIdxMax ? WebpLookupTables.Log2Table[v] : FastLog2Slow(v); + public static float FastLog2(uint v) => v < LogLookupIdxMax ? WebpLookupTables.Log2Table[(int)v] : FastLog2Slow(v); /// /// Fast calculation of v * log2(v) for integer input. /// + /// The input value. + /// The approximate value of * log2(). [MethodImpl(InliningOptions.ShortMethod)] - public static float FastSLog2(uint v) => v < LogLookupIdxMax ? WebpLookupTables.SLog2Table[v] : FastSLog2Slow(v); + public static float FastSLog2(uint v) => v < LogLookupIdxMax ? WebpLookupTables.SLog2Table[(int)v] : FastSLog2Slow(v); + /// + /// Unpacks the color transform multipliers from a transform image pixel. Bits 0-7 hold green-to-red, bits 8-15 green-to-blue + /// and bits 16-23 red-to-blue. + /// + /// The transform image pixel. + /// Receives the multipliers. [MethodImpl(InliningOptions.ShortMethod)] public static void ColorCodeToMultipliers(uint colorCode, ref Vp8LMultipliers m) { @@ -1093,16 +857,22 @@ public static void ColorCodeToMultipliers(uint colorCode, ref Vp8LMultipliers m) m.RedToBlue = (byte)((colorCode >> 16) & 0xff); } - // Converts near lossless quality into max number of bits shaved off. - // 100 -> 0 - // 80..99 -> 1 - // 60..79 -> 2 - // 40..59 -> 3 - // 20..39 -> 4 - // 0..19 -> 5 + /// + /// Converts a near lossless quality to the maximum number of low bits to remove from each component. + /// + /// + /// Quality 100 gives 0 bits, 80 to 99 give 1, 60 to 79 give 2, 40 to 59 give 3, 20 to 39 give 4, and 0 to 19 give 5. + /// + /// The near lossless quality, from 0 to 100. + /// The number of bits, from 0 to 5. [MethodImpl(InliningOptions.ShortMethod)] public static int NearLosslessBits(int nearLosslessQuality) => 5 - (nearLosslessQuality / 20); + /// + /// Computes an approximation of v * log2(v) for values that the lookup table does not cover. + /// + /// The value. It must be at least . + /// The approximate value of v * log2(v). private static float FastSLog2Slow(uint v) { DebugGuard.MustBeGreaterThanOrEqualTo(v, LogLookupIdxMax, nameof(v)); @@ -1128,12 +898,17 @@ private static float FastSLog2Slow(uint v) // log2(1 + (v % y) / v) ~ LOG_2_RECIPROCAL * (v % y)/v // LOG_2_RECIPROCAL ~ 23/16 int correction = (int)((23 * (origV & (y - 1))) >> 4); - return (vF * (WebpLookupTables.Log2Table[v] + logCnt)) + correction; + return (vF * (WebpLookupTables.Log2Table[(int)v] + logCnt)) + correction; } return (float)(Log2Reciprocal * v * Math.Log(v)); } + /// + /// Computes an approximation of log2(v) for values that the lookup table does not cover. + /// + /// The value. It must be at least . + /// The approximate value of log2(v). private static float FastLog2Slow(uint v) { DebugGuard.MustBeGreaterThanOrEqualTo(v, LogLookupIdxMax, nameof(v)); @@ -1151,7 +926,7 @@ private static float FastLog2Slow(uint v) } while (v >= LogLookupIdxMax); - double log2 = WebpLookupTables.Log2Table[v] + logCnt; + double log2 = WebpLookupTables.Log2Table[(int)v] + logCnt; if (origV >= ApproxLogMax) { // Since the division is still expensive, add this correction factor only @@ -1171,6 +946,9 @@ private static float FastLog2Slow(uint v) /// extra bits. The prefixes are encoded with an entropy code /// while the extra bits are stored just as normal bits. /// + /// The distance or length. The value must be at least 3. + /// Receives the number of extra bits. + /// The prefix code. private static int PrefixEncodeBitsNoLut(int distance, ref int extraBits) { int highestBit = BitOperations.Log2((uint)--distance); @@ -1180,6 +958,14 @@ private static int PrefixEncodeBitsNoLut(int distance, ref int extraBits) return code; } + /// + /// Computes the prefix code of a distance or length, the number of its extra bits and the value of the extra bits without the lookup tables. + /// The code comes from the two highest bits of distance - 1. The extra bits are the bits below them. + /// + /// The distance or length. The value must be at least 3. + /// Receives the number of extra bits. + /// Receives the value of the extra bits. + /// The prefix code. private static int PrefixEncodeNoLut(int distance, ref int extraBits, ref int extraBitsValue) { int highestBit = BitOperations.Log2((uint)--distance); @@ -1190,328 +976,21 @@ private static int PrefixEncodeNoLut(int distance, ref int extraBits, ref int ex return code; } - [MethodImpl(InliningOptions.ShortMethod)] - private static void PredictorAdd0(uint* input, int numberOfPixels, uint* output) - { - for (int x = 0; x < numberOfPixels; x++) - { - output[x] = AddPixels(input[x], WebpConstants.ArgbBlack); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void PredictorAdd1(uint* input, int numberOfPixels, uint* output) - { - uint left = output[-1]; - for (int x = 0; x < numberOfPixels; x++) - { - output[x] = left = AddPixels(input[x], left); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void PredictorAdd2(uint* input, uint* upper, int numberOfPixels, uint* output) - { - for (int x = 0; x < numberOfPixels; x++) - { - uint pred = Predictor2(output[x - 1], upper + x); - output[x] = AddPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void PredictorAdd3(uint* input, uint* upper, int numberOfPixels, uint* output) - { - for (int x = 0; x < numberOfPixels; x++) - { - uint pred = Predictor3(output[x - 1], upper + x); - output[x] = AddPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void PredictorAdd4(uint* input, uint* upper, int numberOfPixels, uint* output) - { - for (int x = 0; x < numberOfPixels; x++) - { - uint pred = Predictor4(output[x - 1], upper + x); - output[x] = AddPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void PredictorAdd5(uint* input, uint* upper, int numberOfPixels, uint* output) - { - for (int x = 0; x < numberOfPixels; x++) - { - uint pred = Predictor5(output[x - 1], upper + x); - output[x] = AddPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void PredictorAdd6(uint* input, uint* upper, int numberOfPixels, uint* output) - { - for (int x = 0; x < numberOfPixels; x++) - { - uint pred = Predictor6(output[x - 1], upper + x); - output[x] = AddPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void PredictorAdd7(uint* input, uint* upper, int numberOfPixels, uint* output) - { - for (int x = 0; x < numberOfPixels; x++) - { - uint pred = Predictor7(output[x - 1], upper + x); - output[x] = AddPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void PredictorAdd8(uint* input, uint* upper, int numberOfPixels, uint* output) - { - for (int x = 0; x < numberOfPixels; x++) - { - uint pred = Predictor8(output[x - 1], upper + x); - output[x] = AddPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void PredictorAdd9(uint* input, uint* upper, int numberOfPixels, uint* output) - { - for (int x = 0; x < numberOfPixels; x++) - { - uint pred = Predictor9(output[x - 1], upper + x); - output[x] = AddPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void PredictorAdd10(uint* input, uint* upper, int numberOfPixels, uint* output) - { - for (int x = 0; x < numberOfPixels; x++) - { - uint pred = Predictor10(output[x - 1], upper + x); - output[x] = AddPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void PredictorAdd11(uint* input, uint* upper, int numberOfPixels, uint* output, Span scratch) - { - for (int x = 0; x < numberOfPixels; x++) - { - uint pred = Predictor11(output[x - 1], upper + x, scratch); - output[x] = AddPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void PredictorAdd12(uint* input, uint* upper, int numberOfPixels, uint* output) - { - for (int x = 0; x < numberOfPixels; x++) - { - uint pred = Predictor12(output[x - 1], upper + x); - output[x] = AddPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void PredictorAdd13(uint* input, uint* upper, int numberOfPixels, uint* output) - { - for (int x = 0; x < numberOfPixels; x++) - { - uint pred = Predictor13(output[x - 1], upper + x); - output[x] = AddPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - public static uint Predictor2(uint left, uint* top) => top[0]; - - [MethodImpl(InliningOptions.ShortMethod)] - public static uint Predictor3(uint left, uint* top) => top[1]; - - [MethodImpl(InliningOptions.ShortMethod)] - public static uint Predictor4(uint left, uint* top) => top[-1]; - - [MethodImpl(InliningOptions.ShortMethod)] - public static uint Predictor5(uint left, uint* top) => Average3(left, top[0], top[1]); - - [MethodImpl(InliningOptions.ShortMethod)] - public static uint Predictor6(uint left, uint* top) => Average2(left, top[-1]); - - [MethodImpl(InliningOptions.ShortMethod)] - public static uint Predictor7(uint left, uint* top) => Average2(left, top[0]); - - [MethodImpl(InliningOptions.ShortMethod)] - public static uint Predictor8(uint left, uint* top) => Average2(top[-1], top[0]); - - [MethodImpl(InliningOptions.ShortMethod)] - public static uint Predictor9(uint left, uint* top) => Average2(top[0], top[1]); - - [MethodImpl(InliningOptions.ShortMethod)] - public static uint Predictor10(uint left, uint* top) => Average4(left, top[-1], top[0], top[1]); - - [MethodImpl(InliningOptions.ShortMethod)] - public static uint Predictor11(uint left, uint* top, Span scratch) => Select(top[0], left, top[-1], scratch); - - [MethodImpl(InliningOptions.ShortMethod)] - public static uint Predictor12(uint left, uint* top) => ClampedAddSubtractFull(left, top[0], top[-1]); - - [MethodImpl(InliningOptions.ShortMethod)] - public static uint Predictor13(uint left, uint* top) => ClampedAddSubtractHalf(left, top[0], top[-1]); - - [MethodImpl(InliningOptions.ShortMethod)] - public static void PredictorSub0(uint* input, int numPixels, uint* output) - { - for (int i = 0; i < numPixels; i++) - { - output[i] = SubPixels(input[i], WebpConstants.ArgbBlack); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - public static void PredictorSub1(uint* input, int numPixels, uint* output) - { - for (int i = 0; i < numPixels; i++) - { - output[i] = SubPixels(input[i], input[i - 1]); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - public static void PredictorSub2(uint* input, uint* upper, int numPixels, uint* output) - { - for (int x = 0; x < numPixels; x++) - { - uint pred = Predictor2(input[x - 1], upper + x); - output[x] = SubPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - public static void PredictorSub3(uint* input, uint* upper, int numPixels, uint* output) - { - for (int x = 0; x < numPixels; x++) - { - uint pred = Predictor3(input[x - 1], upper + x); - output[x] = SubPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - public static void PredictorSub4(uint* input, uint* upper, int numPixels, uint* output) - { - for (int x = 0; x < numPixels; x++) - { - uint pred = Predictor4(input[x - 1], upper + x); - output[x] = SubPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - public static void PredictorSub5(uint* input, uint* upper, int numPixels, uint* output) - { - for (int x = 0; x < numPixels; x++) - { - uint pred = Predictor5(input[x - 1], upper + x); - output[x] = SubPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - public static void PredictorSub6(uint* input, uint* upper, int numPixels, uint* output) - { - for (int x = 0; x < numPixels; x++) - { - uint pred = Predictor6(input[x - 1], upper + x); - output[x] = SubPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - public static void PredictorSub7(uint* input, uint* upper, int numPixels, uint* output) - { - for (int x = 0; x < numPixels; x++) - { - uint pred = Predictor7(input[x - 1], upper + x); - output[x] = SubPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - public static void PredictorSub8(uint* input, uint* upper, int numPixels, uint* output) - { - for (int x = 0; x < numPixels; x++) - { - uint pred = Predictor8(input[x - 1], upper + x); - output[x] = SubPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - public static void PredictorSub9(uint* input, uint* upper, int numPixels, uint* output) - { - for (int x = 0; x < numPixels; x++) - { - uint pred = Predictor9(input[x - 1], upper + x); - output[x] = SubPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - public static void PredictorSub10(uint* input, uint* upper, int numPixels, uint* output) - { - for (int x = 0; x < numPixels; x++) - { - uint pred = Predictor10(input[x - 1], upper + x); - output[x] = SubPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - public static void PredictorSub11(uint* input, uint* upper, int numPixels, uint* output, Span scratch) - { - for (int x = 0; x < numPixels; x++) - { - uint pred = Predictor11(input[x - 1], upper + x, scratch); - output[x] = SubPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - public static void PredictorSub12(uint* input, uint* upper, int numPixels, uint* output) - { - for (int x = 0; x < numPixels; x++) - { - uint pred = Predictor12(input[x - 1], upper + x); - output[x] = SubPixels(input[x], pred); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - public static void PredictorSub13(uint* input, uint* upper, int numPixels, uint* output) - { - for (int x = 0; x < numPixels; x++) - { - uint pred = Predictor13(input[x - 1], upper + x); - output[x] = SubPixels(input[x], pred); - } - } - /// /// Computes sampled size of 'size' when sampling using 'sampling bits'. /// + /// The size in pixels. + /// The base-2 logarithm of the block size in pixels. + /// The number of blocks that cover , rounded up. [MethodImpl(InliningOptions.ShortMethod)] public static int SubSampleSize(int size, int samplingBits) => (size + (1 << samplingBits) - 1) >> samplingBits; /// /// Sum of each component, mod 256. /// + /// The first ARGB pixel. + /// The second ARGB pixel. + /// The ARGB pixel that holds the sum of each component, mod 256. [MethodImpl(InliningOptions.ShortMethod)] public static uint AddPixels(uint a, uint b) { @@ -1520,118 +999,95 @@ public static uint AddPixels(uint a, uint b) return (alphaAndGreen & 0xff00ff00u) | (redAndBlue & 0x00ff00ffu); } - // For sign-extended multiplying constants, pre-shifted by 5: + /// + /// Converts a signed 8-bit color transform multiplier to a 16-bit vector constant. The result is the sign-extended multiplier times 8. + /// + /// + /// The constants are sign-extended multipliers, shifted left by 5 bits. + /// + /// The multiplier. Only the low 8 bits are used. + /// The multiplier times 8. [MethodImpl(InliningOptions.ShortMethod)] public static short Cst5b(int x) => (short)(((short)(x << 8)) >> 5); + /// + /// Computes clamp(c0 + c1 - c2) in each channel, with the clamp to [0, 255]. + /// + /// The first pixel. + /// The second pixel. + /// The pixel to subtract. + /// The clamped result. private static uint ClampedAddSubtractFull(uint c0, uint c1, uint c2) { - if (Vector128.IsHardwareAccelerated) - { - Vector128 c0Vec = Vector128_.UnpackLow(Vector128.CreateScalar(c0).AsByte(), Vector128.Zero); - Vector128 c1Vec = Vector128_.UnpackLow(Vector128.CreateScalar(c1).AsByte(), Vector128.Zero); - Vector128 c2Vec = Vector128_.UnpackLow(Vector128.CreateScalar(c2).AsByte(), Vector128.Zero); - Vector128 v1 = c0Vec.AsInt16() + c1Vec.AsInt16(); - Vector128 v2 = v1 - c2Vec.AsInt16(); - Vector128 b = Vector128_.PackUnsignedSaturate(v2, v2); - return b.AsUInt32().ToScalar(); - } - - { - int a = AddSubtractComponentFull( - (int)(c0 >> 24), - (int)(c1 >> 24), - (int)(c2 >> 24)); - int r = AddSubtractComponentFull( - (int)((c0 >> 16) & 0xff), - (int)((c1 >> 16) & 0xff), - (int)((c2 >> 16) & 0xff)); - int g = AddSubtractComponentFull( - (int)((c0 >> 8) & 0xff), - (int)((c1 >> 8) & 0xff), - (int)((c2 >> 8) & 0xff)); - int b = AddSubtractComponentFull((int)(c0 & 0xff), (int)(c1 & 0xff), (int)(c2 & 0xff)); - return ((uint)a << 24) | ((uint)r << 16) | ((uint)g << 8) | (uint)b; - } + int a = AddSubtractComponentFull((int)(c0 >> 24), (int)(c1 >> 24), (int)(c2 >> 24)); + int r = AddSubtractComponentFull((int)((c0 >> 16) & 0xff), (int)((c1 >> 16) & 0xff), (int)((c2 >> 16) & 0xff)); + int g = AddSubtractComponentFull((int)((c0 >> 8) & 0xff), (int)((c1 >> 8) & 0xff), (int)((c2 >> 8) & 0xff)); + int b = AddSubtractComponentFull((int)(c0 & 0xff), (int)(c1 & 0xff), (int)(c2 & 0xff)); + return ((uint)a << 24) | ((uint)r << 16) | ((uint)g << 8) | (uint)b; } + /// + /// Computes clamp(a + (a - c2) / 2) in each channel, with a = Average2(c0, c1), the division rounded toward zero and the clamp to [0, 255]. + /// + /// The first pixel of the average. + /// The second pixel of the average. + /// The pixel to move away from. + /// The clamped result. private static uint ClampedAddSubtractHalf(uint c0, uint c1, uint c2) { - if (Vector128.IsHardwareAccelerated) - { - Vector128 c0Vec = Vector128_.UnpackLow(Vector128.CreateScalar(c0).AsByte(), Vector128.Zero); - Vector128 c1Vec = Vector128_.UnpackLow(Vector128.CreateScalar(c1).AsByte(), Vector128.Zero); - Vector128 b0 = Vector128_.UnpackLow(Vector128.CreateScalar(c2).AsByte(), Vector128.Zero); - Vector128 avg = c1Vec.AsInt16() + c0Vec.AsInt16(); - Vector128 a0 = Vector128.ShiftRightLogical(avg, 1); - Vector128 a1 = a0 - b0.AsInt16(); - Vector128 bgta = Vector128.GreaterThan(b0.AsInt16(), a0.AsInt16()); - Vector128 a2 = a1 - bgta; - Vector128 a3 = Vector128.ShiftRightArithmetic(a2, 1); - Vector128 a4 = (a0 + a3).AsInt16(); - Vector128 a5 = Vector128_.PackUnsignedSaturate(a4, a4); - return a5.AsUInt32().ToScalar(); - } - - { - uint ave = Average2(c0, c1); - int a = AddSubtractComponentHalf((int)(ave >> 24), (int)(c2 >> 24)); - int r = AddSubtractComponentHalf((int)((ave >> 16) & 0xff), (int)((c2 >> 16) & 0xff)); - int g = AddSubtractComponentHalf((int)((ave >> 8) & 0xff), (int)((c2 >> 8) & 0xff)); - int b = AddSubtractComponentHalf((int)(ave & 0xff), (int)(c2 & 0xff)); - return ((uint)a << 24) | ((uint)r << 16) | ((uint)g << 8) | (uint)b; - } + uint ave = Average2(c0, c1); + int a = AddSubtractComponentHalf((int)(ave >> 24), (int)(c2 >> 24)); + int r = AddSubtractComponentHalf((int)((ave >> 16) & 0xff), (int)((c2 >> 16) & 0xff)); + int g = AddSubtractComponentHalf((int)((ave >> 8) & 0xff), (int)((c2 >> 8) & 0xff)); + int b = AddSubtractComponentHalf((int)(ave & 0xff), (int)(c2 & 0xff)); + return ((uint)a << 24) | ((uint)r << 16) | ((uint)g << 8) | (uint)b; } + /// + /// Computes clamp(a + (a - b) / 2) for one component, with the division rounded toward zero and the clamp to [0, 255]. + /// + /// The average component. + /// The component to move away from. + /// The clamped component. [MethodImpl(InliningOptions.ShortMethod)] - private static int AddSubtractComponentHalf(int a, int b) => (int)Clip255((uint)(a + ((a - b) / 2))); - - [MethodImpl(InliningOptions.ShortMethod)] - private static int AddSubtractComponentFull(int a, int b, int c) => (int)Clip255((uint)(a + b - c)); - - [MethodImpl(InliningOptions.ShortMethod)] - private static uint Clip255(uint a) => a < 256 ? a : ~a >> 24; - - [MethodImpl(InliningOptions.ShortMethod)] - private static Vector128 MkCst16(int hi, int lo) => Vector128.Create((hi << 16) | (lo & 0xffff)); + private static int AddSubtractComponentHalf(int a, int b) => Numerics.ClampToByte(a + ((a - b) / 2)); + /// + /// Computes clamp(a + b - c) for one component, with the clamp to [0, 255]. + /// + /// The first component. + /// The second component. + /// The component to subtract. + /// The clamped component. [MethodImpl(InliningOptions.ShortMethod)] - private static Vector256 MkCst32(int hi, int lo) => Vector256.Create((hi << 16) | (lo & 0xffff)); + private static int AddSubtractComponentFull(int a, int b, int c) => Numerics.ClampToByte(a + b - c); - private static uint Select(uint a, uint b, uint c, Span scratch) + /// + /// Selects the pixel or . The result is when the channel distances from + /// to sum to more than the distances to . Otherwise it is . + /// + /// The top pixel. + /// The left pixel. + /// The top-left pixel. + /// The selected pixel. + private static uint Select(uint a, uint b, uint c) { - if (Vector128.IsHardwareAccelerated) - { - fixed (short* ptr = &MemoryMarshal.GetReference(scratch)) - { - Vector128 a0 = Vector128.CreateScalar(a).AsByte(); - Vector128 b0 = Vector128.CreateScalar(b).AsByte(); - Vector128 c0 = Vector128.CreateScalar(c).AsByte(); - Vector128 ac0 = Vector128.SubtractSaturate(a0, c0); - Vector128 ca0 = Vector128.SubtractSaturate(c0, a0); - Vector128 bc0 = Vector128.SubtractSaturate(b0, c0); - Vector128 cb0 = Vector128.SubtractSaturate(c0, b0); - Vector128 ac = ac0 | ca0; - Vector128 bc = bc0 | cb0; - Vector128 pa = Vector128_.UnpackLow(ac, Vector128.Zero); // |a - c| - Vector128 pb = Vector128_.UnpackLow(bc, Vector128.Zero); // |b - c| - Vector128 diff = pb.AsUInt16() - pa.AsUInt16(); - diff.Store((ushort*)ptr); - int paMinusPb = ptr[3] + ptr[2] + ptr[1] + ptr[0]; - return (paMinusPb <= 0) ? a : b; - } - } - else - { - int paMinusPb = - Sub3((int)(a >> 24), (int)(b >> 24), (int)(c >> 24)) + - Sub3((int)((a >> 16) & 0xff), (int)((b >> 16) & 0xff), (int)((c >> 16) & 0xff)) + - Sub3((int)((a >> 8) & 0xff), (int)((b >> 8) & 0xff), (int)((c >> 8) & 0xff)) + - Sub3((int)(a & 0xff), (int)(b & 0xff), (int)(c & 0xff)); - return paMinusPb <= 0 ? a : b; - } + int paMinusPb = + Sub3((int)(a >> 24), (int)(b >> 24), (int)(c >> 24)) + + Sub3((int)((a >> 16) & 0xff), (int)((b >> 16) & 0xff), (int)((c >> 16) & 0xff)) + + Sub3((int)((a >> 8) & 0xff), (int)((b >> 8) & 0xff), (int)((c >> 8) & 0xff)) + + Sub3((int)(a & 0xff), (int)(b & 0xff), (int)(c & 0xff)); + + return paMinusPb <= 0 ? a : b; } + /// + /// Computes |b - c| - |a - c| for one component. + /// + /// The top component. + /// The left component. + /// The top-left component. + /// The difference of the two distances. [MethodImpl(InliningOptions.ShortMethod)] private static int Sub3(int a, int b, int c) { @@ -1640,21 +1096,51 @@ private static int Sub3(int a, int b, int c) return Math.Abs(pb) - Math.Abs(pa); } + /// + /// Computes the average of two pixels in each channel, rounded down. The shared bits plus half of the different bits give the average + /// with no carry between channels. + /// + /// The first pixel. + /// The second pixel. + /// The average pixel. [MethodImpl(InliningOptions.ShortMethod)] private static uint Average2(uint a0, uint a1) => (((a0 ^ a1) & 0xfefefefeu) >> 1) + (a0 & a1); + /// + /// Computes Average2(Average2(a0, a2), a1) in each channel. + /// + /// The first pixel. + /// The second pixel. + /// The third pixel. + /// The average pixel. [MethodImpl(InliningOptions.ShortMethod)] private static uint Average3(uint a0, uint a1, uint a2) => Average2(Average2(a0, a2), a1); + /// + /// Computes Average2(Average2(a0, a1), Average2(a2, a3)) in each channel. + /// + /// The first pixel. + /// The second pixel. + /// The third pixel. + /// The fourth pixel. + /// The average pixel. [MethodImpl(InliningOptions.ShortMethod)] private static uint Average4(uint a0, uint a1, uint a2, uint a3) => Average2(Average2(a0, a1), Average2(a2, a3)); - [MethodImpl(InliningOptions.ShortMethod)] - private static uint GetArgbIndex(uint idx) => (idx >> 8) & 0xff; - + /// + /// Computes the color transform delta (multiplier * color) >> 5, with both values signed 8-bit. + /// + /// The multiplier. + /// The color component. + /// The delta. [MethodImpl(InliningOptions.ShortMethod)] private static int ColorTransformDelta(sbyte colorPred, sbyte color) => (colorPred * color) >> 5; + /// + /// Reinterprets the low 8 bits of a value as a signed 8-bit value. + /// + /// The value. + /// The signed 8-bit value. [MethodImpl(InliningOptions.ShortMethod)] private static sbyte U32ToS8(uint v) => (sbyte)(v & 0xff); } diff --git a/src/ImageSharp/Formats/Webp/Lossless/NearLosslessEnc.cs b/src/ImageSharp/Formats/Webp/Lossless/NearLosslessEnc.cs deleted file mode 100644 index 54183520b5..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossless/NearLosslessEnc.cs +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossless; - -/// -/// Near-lossless image preprocessing adjusts pixel values to help compressibility with a guarantee -/// of maximum deviation between original and resulting pixel values. -/// -internal static class NearLosslessEnc -{ - private const int MinDimForNearLossless = 64; - - public static void ApplyNearLossless(int xSize, int ySize, int quality, Span argbSrc, Span argbDst, int stride) - { - uint[] copyBuffer = new uint[xSize * 3]; - int limitBits = LosslessUtils.NearLosslessBits(quality); - - // For small icon images, don't attempt to apply near-lossless compression. - if ((xSize < MinDimForNearLossless && ySize < MinDimForNearLossless) || ySize < 3) - { - for (int i = 0; i < ySize; i++) - { - argbSrc.Slice(i * stride, xSize).CopyTo(argbDst.Slice(i * xSize, xSize)); - } - - return; - } - - NearLossless(xSize, ySize, argbSrc, stride, limitBits, copyBuffer, argbDst); - for (int i = limitBits - 1; i != 0; i--) - { - NearLossless(xSize, ySize, argbDst, xSize, i, copyBuffer, argbDst); - } - } - - // Adjusts pixel values of image with given maximum error. - private static void NearLossless(int xSize, int ySize, Span argbSrc, int stride, int limitBits, Span copyBuffer, Span argbDst) - { - int y; - int limit = 1 << limitBits; - Span prevRow = copyBuffer; - Span currRow = copyBuffer.Slice(xSize, xSize); - Span nextRow = copyBuffer.Slice(xSize * 2, xSize); - argbSrc[..xSize].CopyTo(currRow); - argbSrc.Slice(xSize, xSize).CopyTo(nextRow); - - int srcOffset = 0; - int dstOffset = 0; - for (y = 0; y < ySize; y++) - { - if (y == 0 || y == ySize - 1) - { - argbSrc.Slice(srcOffset, xSize).CopyTo(argbDst.Slice(dstOffset, xSize)); - } - else - { - argbSrc.Slice(srcOffset + stride, xSize).CopyTo(nextRow); - argbDst[dstOffset] = argbSrc[srcOffset]; - argbDst[dstOffset + xSize - 1] = argbSrc[srcOffset + xSize - 1]; - for (int x = 1; x < xSize - 1; x++) - { - if (IsSmooth(prevRow, currRow, nextRow, x, limit)) - { - argbDst[dstOffset + x] = currRow[x]; - } - else - { - argbDst[dstOffset + x] = ClosestDiscretizedArgb(currRow[x], limitBits); - } - } - } - - Span temp = prevRow; - prevRow = currRow; - currRow = nextRow; - nextRow = temp; - srcOffset += stride; - dstOffset += xSize; - } - } - - // Applies FindClosestDiscretized to all channels of pixel. - private static uint ClosestDiscretizedArgb(uint a, int bits) => - (FindClosestDiscretized(a >> 24, bits) << 24) | - (FindClosestDiscretized((a >> 16) & 0xff, bits) << 16) | - (FindClosestDiscretized((a >> 8) & 0xff, bits) << 8) | - FindClosestDiscretized(a & 0xff, bits); - - private static uint FindClosestDiscretized(uint a, int bits) - { - uint mask = (1u << bits) - 1; - uint biased = a + (mask >> 1) + ((a >> bits) & 1); - if (biased > 0xff) - { - return 0xff; - } - - return biased & ~mask; - } - - private static bool IsSmooth(ReadOnlySpan prevRow, ReadOnlySpan currRow, ReadOnlySpan nextRow, int ix, int limit) => - IsNear(currRow[ix], currRow[ix - 1], limit) && // Check that all pixels in 4-connected neighborhood are smooth. - IsNear(currRow[ix], currRow[ix + 1], limit) && - IsNear(currRow[ix], prevRow[ix], limit) && - IsNear(currRow[ix], nextRow[ix], limit); - - // Checks if distance between corresponding channel values of pixels a and b is within the given limit. - private static bool IsNear(uint a, uint b, int limit) - { - for (int k = 0; k < 4; ++k) - { - int delta = (int)((a >> (k * 8)) & 0xff) - (int)((b >> (k * 8)) & 0xff); - if (delta >= limit || delta <= -limit) - { - return false; - } - } - - return true; - } -} diff --git a/src/ImageSharp/Formats/Webp/Lossless/NearLosslessEncoder.cs b/src/ImageSharp/Formats/Webp/Lossless/NearLosslessEncoder.cs new file mode 100644 index 0000000000..35fe7a4e33 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossless/NearLosslessEncoder.cs @@ -0,0 +1,427 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Buffers; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Memory; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossless; + +/// +/// Near-lossless image preprocessing adjusts pixel values to help compressibility with a guarantee +/// of maximum deviation between original and resulting pixel values. +/// +internal static class NearLosslessEncoder +{ + /// + /// The image size below which near lossless preprocessing is not applied. Both dimensions must be less than this value to skip it. + /// + private const int MinDimForNearLossless = 64; + + /// + /// Applies near lossless preprocessing. It runs passes with a decreasing number of removed bits, from the quality limit down to 1. + /// Small images and images with fewer than 3 rows are copied without change. + /// + /// The memory allocator for the row scratch buffer. + /// The image width. + /// The image height. + /// The near lossless quality, from 0 to 99. + /// The source pixels. + /// Receives the processed pixels. It has the image size. + public static void ApplyNearLossless(MemoryAllocator memoryAllocator, int xSize, int ySize, int quality, Buffer2D argbSrc, Buffer2D argbDst) + { + int limitBits = LosslessUtils.NearLosslessBits(quality); + + // For small icon images, don't attempt to apply near-lossless compression. + if ((xSize < MinDimForNearLossless && ySize < MinDimForNearLossless) || ySize < 3) + { + for (int y = 0; y < ySize; y++) + { + argbSrc.DangerousGetRowSpan(y)[..xSize].CopyTo(argbDst.DangerousGetRowSpan(y)); + } + + return; + } + + // Three rows: above, current and below. No clear: each pass copies a row into the buffer before it reads it. + using IMemoryOwner copyBuffer = memoryAllocator.Allocate(xSize * 3); + Span rows = copyBuffer.GetSpan(); + NearLossless(xSize, ySize, argbSrc, limitBits, rows, argbDst); + for (int i = limitBits - 1; i != 0; i--) + { + NearLossless(xSize, ySize, argbDst, i, rows, argbDst); + } + } + + /// + /// Runs one near lossless pass. A pixel that differs from one of its 4 neighbors by the limit or more in any channel is rounded + /// to a multiple of 2^limitBits in each channel. The border pixels and smooth pixels do not change. + /// + /// The image width. + /// The image height. It must be at least 2. + /// The source pixels. + /// The number of low bits to remove, from 1 to 5. + /// A scratch buffer for three rows. + /// Receives the processed pixels. It can be the source. + private static void NearLossless(int xSize, int ySize, Buffer2D argbSrc, int limitBits, Span copyBuffer, Buffer2D argbDst) + { + NearLosslessOperator operation = new(limitBits); + Span prevRow = copyBuffer[..xSize]; + Span currRow = copyBuffer.Slice(xSize, xSize); + Span nextRow = copyBuffer.Slice(xSize * 2, xSize); + argbSrc.DangerousGetRowSpan(0)[..xSize].CopyTo(currRow); + argbSrc.DangerousGetRowSpan(1)[..xSize].CopyTo(nextRow); + + for (int y = 0; y < ySize; y++) + { + Span srcRow = argbSrc.DangerousGetRowSpan(y)[..xSize]; + Span dstRow = argbDst.DangerousGetRowSpan(y)[..xSize]; + if (y == 0 || y == ySize - 1) + { + srcRow.CopyTo(dstRow); + } + else + { + // The rows are copies, so the destination can be the source row. The next source row is read before this row is written. + argbSrc.DangerousGetRowSpan(y + 1)[..xSize].CopyTo(nextRow); + dstRow[0] = srcRow[0]; + dstRow[xSize - 1] = srcRow[xSize - 1]; + NearLosslessRow(prevRow, currRow, nextRow, dstRow, operation); + } + + Span temp = prevRow; + prevRow = currRow; + currRow = nextRow; + nextRow = temp; + } + } + + /// + /// Applies the near lossless operator to each pixel of a row except the first and the last. + /// + /// + /// The same column flows through descending vector widths, so a row that is not a multiple of the widest register keeps a + /// vectorized tail. Each pixel depends only on the source rows, so the width that processes a pixel does not change the result. + /// A block reads the left and right neighbors at -1 and +1, so the last block reads at most the last pixel of the row. + /// + /// The row above. + /// The row of the pixels. + /// The row below. + /// Receives the processed pixels. It is not one of the source rows. + /// The near lossless operator for the number of removed bits. + private static void NearLosslessRow( + ReadOnlySpan prevRow, + ReadOnlySpan currRow, + ReadOnlySpan nextRow, + Span dstRow, + NearLosslessOperator operation) + { + ref uint up = ref MemoryMarshal.GetReference(prevRow); + ref uint current = ref MemoryMarshal.GetReference(currRow); + ref uint down = ref MemoryMarshal.GetReference(nextRow); + ref uint dst = ref MemoryMarshal.GetReference(dstRow); + nuint end = (uint)(currRow.Length - 1); + nuint x = 1; + + if (Vector512.IsHardwareAccelerated) + { + for (; x + (uint)Vector512.Count <= end; x += (uint)Vector512.Count) + { + operation.Apply( + Vector512.LoadUnsafe(ref current, x), + Vector512.LoadUnsafe(ref current, x - 1), + Vector512.LoadUnsafe(ref current, x + 1), + Vector512.LoadUnsafe(ref up, x), + Vector512.LoadUnsafe(ref down, x)).StoreUnsafe(ref dst, x); + } + } + + if (Vector256.IsHardwareAccelerated) + { + for (; x + (uint)Vector256.Count <= end; x += (uint)Vector256.Count) + { + operation.Apply( + Vector256.LoadUnsafe(ref current, x), + Vector256.LoadUnsafe(ref current, x - 1), + Vector256.LoadUnsafe(ref current, x + 1), + Vector256.LoadUnsafe(ref up, x), + Vector256.LoadUnsafe(ref down, x)).StoreUnsafe(ref dst, x); + } + } + + if (Vector128.IsHardwareAccelerated) + { + for (; x + (uint)Vector128.Count <= end; x += (uint)Vector128.Count) + { + operation.Apply( + Vector128.LoadUnsafe(ref current, x), + Vector128.LoadUnsafe(ref current, x - 1), + Vector128.LoadUnsafe(ref current, x + 1), + Vector128.LoadUnsafe(ref up, x), + Vector128.LoadUnsafe(ref down, x)).StoreUnsafe(ref dst, x); + } + } + + for (; x < end; x++) + { + Unsafe.Add(ref dst, x) = operation.Apply( + Unsafe.Add(ref current, x), + Unsafe.Add(ref current, x - 1), + Unsafe.Add(ref current, x + 1), + Unsafe.Add(ref up, x), + Unsafe.Add(ref down, x)); + } + } + + /// + /// Rounds each channel of a pixel to the closest multiple of 2^bits. + /// + /// The ARGB pixel. + /// The number of low bits to remove. + /// The rounded pixel. + private static uint ClosestDiscretizedArgb(uint a, int bits) => + (FindClosestDiscretized(a >> 24, bits) << 24) | + (FindClosestDiscretized((a >> 16) & 0xff, bits) << 16) | + (FindClosestDiscretized((a >> 8) & 0xff, bits) << 8) | + FindClosestDiscretized(a & 0xff, bits); + + /// + /// Rounds a channel value to the closest multiple of 2^bits. A tie rounds to the multiple with an even quotient. + /// A result above 255 is clamped to 255. + /// + /// The channel value. + /// The number of low bits to remove. + /// The rounded value. + private static uint FindClosestDiscretized(uint a, int bits) + { + uint mask = (1u << bits) - 1; + uint biased = a + (mask >> 1) + ((a >> bits) & 1); + if (biased > 0xff) + { + return 0xff; + } + + return biased & ~mask; + } + + /// + /// Checks that each channel of two pixels differs by less than the limit. + /// + /// The first pixel. + /// The second pixel. + /// The exclusive limit of the channel difference. + /// if all channel differences are less than the limit; otherwise, . + private static bool IsNear(uint a, uint b, int limit) + { + for (int k = 0; k < 4; ++k) + { + int delta = (int)((a >> (k * 8)) & 0xff) - (int)((b >> (k * 8)) & 0xff); + if (delta >= limit || delta <= -limit) + { + return false; + } + } + + return true; + } + + /// + /// Keeps a pixel that is near each of its left, right, top and bottom neighbors. Rounds each channel of the other pixels to the + /// closest multiple of 2^bits. + /// + /// + /// + /// Each 32-bit lane of the vector forms holds one ARGB pixel. A pixel is near a neighbor when each channel differs by less than + /// 2^bits. The byte lanes give the absolute difference of each channel as max - min. The largest difference to the 4 neighbors + /// is less than 2^bits exactly when it has no bit at or above bit bits, so a pixel is smooth when its four maxima, masked + /// with the high bits of each byte, are zero. + /// + /// + /// The rounding works in 16-bit lanes, so the biased value can exceed 255 without a carry into the next channel. The even + /// bytes (blue and red) and the odd bytes (green and alpha) of each pixel go to the low byte of a 16-bit lane. The vector forms + /// then do the scalar steps: add the bias, select 255 for a sum above 255, else clear the low bits. The odd bytes go back with a + /// 32-bit shift by 8. The vector forms thus give the same pixel as the scalar form. + /// + /// + private readonly struct NearLosslessOperator + { + /// + /// The number of low bits to remove. + /// + private readonly int bits; + + /// + /// The exclusive limit of the channel difference: 2^bits. + /// + private readonly int limit; + + /// + /// The bits of each byte that are at or above bit , in all four bytes. + /// + private readonly uint highBits; + + /// + /// The rounding bias of a channel value: (2^bits - 1) / 2. + /// + private readonly ushort bias; + + /// + /// The mask that clears the low bits of a 16-bit lane. + /// + private readonly ushort roundMask; + + /// + /// Initializes a new instance of the struct. + /// + /// The number of low bits to remove, from 1 to 7. + public NearLosslessOperator(int bits) + { + int mask = (1 << bits) - 1; + this.bits = bits; + this.limit = 1 << bits; + this.highBits = 0x01010101u * (uint)(~mask & 0xff); + this.bias = (ushort)(mask >> 1); + this.roundMask = (ushort)~mask; + } + + /// + /// Processes one pixel. + /// + /// The pixel. + /// The pixel to the left. + /// The pixel to the right. + /// The pixel above. + /// The pixel below. + /// The processed pixel. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint Apply(uint current, uint left, uint right, uint up, uint down) + { + // Check that all pixels in 4-connected neighborhood are smooth. + bool isSmooth = IsNear(current, left, this.limit) && IsNear(current, right, this.limit) && + IsNear(current, up, this.limit) && IsNear(current, down, this.limit); + + return isSmooth ? current : ClosestDiscretizedArgb(current, this.bits); + } + + /// + /// Processes four pixels. + /// + /// The pixels. + /// The pixels to the left. + /// The pixels to the right. + /// The pixels above. + /// The pixels below. + /// The processed pixels. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector128 Apply(Vector128 current, Vector128 left, Vector128 right, Vector128 up, Vector128 down) + { + Vector128 c = current.AsByte(); + Vector128 diffLeft = Vector128.Max(c, left.AsByte()) - Vector128.Min(c, left.AsByte()); + Vector128 diffRight = Vector128.Max(c, right.AsByte()) - Vector128.Min(c, right.AsByte()); + Vector128 diffUp = Vector128.Max(c, up.AsByte()) - Vector128.Min(c, up.AsByte()); + Vector128 diffDown = Vector128.Max(c, down.AsByte()) - Vector128.Min(c, down.AsByte()); + Vector128 maxDiff = Vector128.Max(Vector128.Max(diffLeft, diffRight), Vector128.Max(diffUp, diffDown)); + Vector128 isSmooth = Vector128.Equals(maxDiff.AsUInt32() & Vector128.Create(this.highBits), Vector128.Zero); + + Vector128 even = (current & Vector128.Create(0x00ff00ffu)).AsUInt16(); + Vector128 odd = ((current >>> 8) & Vector128.Create(0x00ff00ffu)).AsUInt16(); + Vector128 rounded = this.Round(even).AsUInt32() | (this.Round(odd).AsUInt32() << 8); + return Vector128.ConditionalSelect(isSmooth, current, rounded); + } + + /// + /// Processes eight pixels. + /// + /// The pixels. + /// The pixels to the left. + /// The pixels to the right. + /// The pixels above. + /// The pixels below. + /// The processed pixels. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector256 Apply(Vector256 current, Vector256 left, Vector256 right, Vector256 up, Vector256 down) + { + // The same lane layout as the 128-bit form. + Vector256 c = current.AsByte(); + Vector256 diffLeft = Vector256.Max(c, left.AsByte()) - Vector256.Min(c, left.AsByte()); + Vector256 diffRight = Vector256.Max(c, right.AsByte()) - Vector256.Min(c, right.AsByte()); + Vector256 diffUp = Vector256.Max(c, up.AsByte()) - Vector256.Min(c, up.AsByte()); + Vector256 diffDown = Vector256.Max(c, down.AsByte()) - Vector256.Min(c, down.AsByte()); + Vector256 maxDiff = Vector256.Max(Vector256.Max(diffLeft, diffRight), Vector256.Max(diffUp, diffDown)); + Vector256 isSmooth = Vector256.Equals(maxDiff.AsUInt32() & Vector256.Create(this.highBits), Vector256.Zero); + + Vector256 even = (current & Vector256.Create(0x00ff00ffu)).AsUInt16(); + Vector256 odd = ((current >>> 8) & Vector256.Create(0x00ff00ffu)).AsUInt16(); + Vector256 rounded = this.Round(even).AsUInt32() | (this.Round(odd).AsUInt32() << 8); + return Vector256.ConditionalSelect(isSmooth, current, rounded); + } + + /// + /// Processes sixteen pixels. + /// + /// The pixels. + /// The pixels to the left. + /// The pixels to the right. + /// The pixels above. + /// The pixels below. + /// The processed pixels. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector512 Apply(Vector512 current, Vector512 left, Vector512 right, Vector512 up, Vector512 down) + { + // The same lane layout as the 128-bit form. + Vector512 c = current.AsByte(); + Vector512 diffLeft = Vector512.Max(c, left.AsByte()) - Vector512.Min(c, left.AsByte()); + Vector512 diffRight = Vector512.Max(c, right.AsByte()) - Vector512.Min(c, right.AsByte()); + Vector512 diffUp = Vector512.Max(c, up.AsByte()) - Vector512.Min(c, up.AsByte()); + Vector512 diffDown = Vector512.Max(c, down.AsByte()) - Vector512.Min(c, down.AsByte()); + Vector512 maxDiff = Vector512.Max(Vector512.Max(diffLeft, diffRight), Vector512.Max(diffUp, diffDown)); + Vector512 isSmooth = Vector512.Equals(maxDiff.AsUInt32() & Vector512.Create(this.highBits), Vector512.Zero); + + Vector512 even = (current & Vector512.Create(0x00ff00ffu)).AsUInt16(); + Vector512 odd = ((current >>> 8) & Vector512.Create(0x00ff00ffu)).AsUInt16(); + Vector512 rounded = this.Round(even).AsUInt32() | (this.Round(odd).AsUInt32() << 8); + return Vector512.ConditionalSelect(isSmooth, current, rounded); + } + + /// + /// Rounds the channel value in each 16-bit lane, as does. + /// + /// The channel values, from 0 to 255. + /// The rounded values, from 0 to 255. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private Vector128 Round(Vector128 values) + { + Vector128 biased = values + Vector128.Create(this.bias) + ((values >>> this.bits) & Vector128.One); + Vector128 isAbove = Vector128.GreaterThan(biased, Vector128.Create((ushort)0xff)); + return Vector128.ConditionalSelect(isAbove, Vector128.Create((ushort)0xff), biased & Vector128.Create(this.roundMask)); + } + + /// + /// Rounds the channel value in each 16-bit lane, as does. + /// + /// The channel values, from 0 to 255. + /// The rounded values, from 0 to 255. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private Vector256 Round(Vector256 values) + { + Vector256 biased = values + Vector256.Create(this.bias) + ((values >>> this.bits) & Vector256.One); + Vector256 isAbove = Vector256.GreaterThan(biased, Vector256.Create((ushort)0xff)); + return Vector256.ConditionalSelect(isAbove, Vector256.Create((ushort)0xff), biased & Vector256.Create(this.roundMask)); + } + + /// + /// Rounds the channel value in each 16-bit lane, as does. + /// + /// The channel values, from 0 to 255. + /// The rounded values, from 0 to 255. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private Vector512 Round(Vector512 values) + { + Vector512 biased = values + Vector512.Create(this.bias) + ((values >>> this.bits) & Vector512.One); + Vector512 isAbove = Vector512.GreaterThan(biased, Vector512.Create((ushort)0xff)); + return Vector512.ConditionalSelect(isAbove, Vector512.Create((ushort)0xff), biased & Vector512.Create(this.roundMask)); + } + } +} diff --git a/src/ImageSharp/Formats/Webp/Lossless/PixOrCopy.cs b/src/ImageSharp/Formats/Webp/Lossless/PixOrCopy.cs deleted file mode 100644 index bb8ce18aad..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossless/PixOrCopy.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -using System.Diagnostics; - -namespace SixLabors.ImageSharp.Formats.Webp.Lossless; - -[DebuggerDisplay("Mode: {Mode}, Len: {Len}, BgraOrDistance: {BgraOrDistance}")] -internal readonly struct PixOrCopy -{ - public readonly PixOrCopyMode Mode; - public readonly ushort Len; - public readonly uint BgraOrDistance; - - private PixOrCopy(PixOrCopyMode mode, ushort len, uint bgraOrDistance) - { - this.Mode = mode; - this.Len = len; - this.BgraOrDistance = bgraOrDistance; - } - - public static PixOrCopy CreateCacheIdx(int idx) => new(PixOrCopyMode.CacheIdx, 1, (uint)idx); - - public static PixOrCopy CreateLiteral(uint bgra) => new(PixOrCopyMode.Literal, 1, bgra); - - public static PixOrCopy CreateCopy(uint distance, ushort len) => new(PixOrCopyMode.Copy, len, distance); - - public int Literal(int component) => (int)(this.BgraOrDistance >> (component * 8)) & 0xFF; - - public uint CacheIdx() => this.BgraOrDistance; - - public ushort Length() => this.Len; - - public uint Distance() => this.BgraOrDistance; - - public bool IsLiteral() => this.Mode == PixOrCopyMode.Literal; - - public bool IsCacheIdx() => this.Mode == PixOrCopyMode.CacheIdx; - - public bool IsCopy() => this.Mode == PixOrCopyMode.Copy; -} diff --git a/src/ImageSharp/Formats/Webp/Lossless/PixOrCopyMode.cs b/src/ImageSharp/Formats/Webp/Lossless/PixOrCopyMode.cs deleted file mode 100644 index 78da2d1a52..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossless/PixOrCopyMode.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossless; - -internal enum PixOrCopyMode : byte -{ - Literal, - - CacheIdx, - - Copy, - - None -} diff --git a/src/ImageSharp/Formats/Webp/Lossless/PixelOrCopy.cs b/src/ImageSharp/Formats/Webp/Lossless/PixelOrCopy.cs new file mode 100644 index 0000000000..eb1276b282 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossless/PixelOrCopy.cs @@ -0,0 +1,106 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Diagnostics; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossless; + +/// +/// One lossless backward reference token: a literal pixel, a color cache index or a copy. +/// +[DebuggerDisplay("Mode: {Mode}, Len: {Len}, BgraOrDistance: {BgraOrDistance}")] +internal readonly struct PixelOrCopy +{ + /// + /// The kind of the token. + /// + public readonly PixelOrCopyMode Mode; + + /// + /// The number of pixels that the token covers. Literals and cache indices cover one pixel. + /// + public readonly ushort Len; + + /// + /// The BGRA pixel of a literal, the cache index of a cache token, or the distance of a copy. + /// + public readonly uint BgraOrDistance; + + /// + /// Initializes a new instance of the struct. + /// + /// The kind of the token. + /// The number of pixels that the token covers. + /// The pixel, cache index or distance. + private PixelOrCopy(PixelOrCopyMode mode, ushort len, uint bgraOrDistance) + { + this.Mode = mode; + this.Len = len; + this.BgraOrDistance = bgraOrDistance; + } + + /// + /// Creates a token that refers to one pixel in the color cache. + /// + /// The color cache index. + /// The cache index token. + public static PixelOrCopy CreateCacheIdx(int idx) => new(PixelOrCopyMode.CacheIdx, 1, (uint)idx); + + /// + /// Creates a token that stores one pixel. + /// + /// The BGRA pixel. + /// The literal token. + public static PixelOrCopy CreateLiteral(uint bgra) => new(PixelOrCopyMode.Literal, 1, bgra); + + /// + /// Creates a token that copies pixels from a backward distance. + /// + /// The backward distance in pixels, or its plane code after the 2D locality conversion. + /// The number of pixels to copy. + /// The copy token. + public static PixelOrCopy CreateCopy(uint distance, ushort len) => new(PixelOrCopyMode.Copy, len, distance); + + /// + /// Gets one component of a literal pixel. + /// + /// The component index: 0 is blue, 1 is green, 2 is red and 3 is alpha. + /// The 8-bit component value. + public int Literal(int component) => (int)(this.BgraOrDistance >> (component * 8)) & 0xFF; + + /// + /// Gets the color cache index of a cache token. + /// + /// The color cache index. + public uint CacheIdx() => this.BgraOrDistance; + + /// + /// Gets the number of pixels that the token covers. + /// + /// The number of pixels. + public ushort Length() => this.Len; + + /// + /// Gets the distance of a copy token. + /// + /// The distance. + public uint Distance() => this.BgraOrDistance; + + /// + /// Gets a value indicating whether the token is a literal. + /// + /// if the token is a literal; otherwise, . + public bool IsLiteral() => this.Mode == PixelOrCopyMode.Literal; + + /// + /// Gets a value indicating whether the token is a color cache index. + /// + /// if the token is a color cache index; otherwise, . + public bool IsCacheIdx() => this.Mode == PixelOrCopyMode.CacheIdx; + + /// + /// Gets a value indicating whether the token is a copy. + /// + /// if the token is a copy; otherwise, . + public bool IsCopy() => this.Mode == PixelOrCopyMode.Copy; +} diff --git a/src/ImageSharp/Formats/Webp/Lossless/PixelOrCopyMode.cs b/src/ImageSharp/Formats/Webp/Lossless/PixelOrCopyMode.cs new file mode 100644 index 0000000000..cf40d9fd21 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossless/PixelOrCopyMode.cs @@ -0,0 +1,30 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.ImageSharp.Formats.Webp.Lossless; + +/// +/// Identifies the kind of a lossless backward reference token. +/// +internal enum PixelOrCopyMode : byte +{ + /// + /// The token stores one BGRA pixel. + /// + Literal, + + /// + /// The token stores the index of one pixel in the color cache. + /// + CacheIdx, + + /// + /// The token copies a run of pixels from a backward distance. + /// + Copy, + + /// + /// The token has no kind. + /// + None +} diff --git a/src/ImageSharp/Formats/Webp/Lossless/PredictorEncoder.cs b/src/ImageSharp/Formats/Webp/Lossless/PredictorEncoder.cs index e7e608c4de..80af67fa0b 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/PredictorEncoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/PredictorEncoder.cs @@ -1,50 +1,103 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +using System.Buffers; +using System.Numerics.Tensors; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Memory; namespace SixLabors.ImageSharp.Formats.Webp.Lossless; /// /// Image transform methods for the lossless webp encoder. /// -internal static unsafe class PredictorEncoder +internal static class PredictorEncoder { - private static readonly sbyte[][] Offset = - [ - [0, -1], [0, 1], [-1, 0], [1, 0], [-1, -1], [-1, 1], [1, -1], [1, 1] - ]; + /// + /// The number of counts of one histogram group: the alpha, red, green and blue histograms of 256 counts each, in this order. + /// + public const int HistogramGroupSize = 4 * 256; + /// + /// The number of search directions in . + /// private const int GreenRedToBlueNumAxis = 8; + /// + /// The maximum number of iterations of the green-to-blue and red-to-blue multiplier search. + /// private const int GreenRedToBlueMaxIters = 7; + /// + /// The start value of a predictor cost search. It is larger than any real cost. + /// private const float MaxDiffCost = 1e30f; + /// + /// The mask of the alpha channel of an ARGB pixel. + /// private const uint MaskAlpha = 0xff000000; + /// + /// The cost bonus of a predictor that the tile to the left or above also uses. It keeps nearby tiles on the same predictor. + /// private const float SpatialPredictorBias = 15.0f; + /// + /// The predictor mode that all tiles use at low effort: the select predictor. + /// private const int PredLowEffort = 11; - // This uses C#'s compiler optimization to refer to assembly's static data directly. + /// + /// Gets the step size of each iteration of the green-to-blue and red-to-blue multiplier search. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates no memory. + /// private static ReadOnlySpan DeltaLut => [16, 16, 8, 4, 2, 2, 2]; + /// + /// Gets the search directions of the green-to-blue and red-to-blue multiplier search. Direction i is the green-to-blue step at 2 * i and the + /// red-to-blue step at 2 * i + 1. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates no memory. + /// + private static ReadOnlySpan Offset => [0, -1, 0, 1, -1, 0, 1, 0, -1, -1, -1, 1, 1, -1, 1, 1]; + /// /// Finds the best predictor for each tile, and converts the image to residuals /// with respect to predictions. If nearLosslessQuality < 100, applies /// near lossless processing, shaving off more bits of residuals for lower qualities. /// + /// The image width in pixels. + /// The image height in pixels. + /// The log2 of the tile size. + /// The pixels. On return, the prediction residuals. The plane has the image size. + /// + /// The scratch buffer: two rows of + 1 pixels, then 2 * bytes rounded up to whole + /// pixels, then three rows of pixels. + /// + /// Receives the predictor mode of each tile in bits 8-15 of a transform image pixel. The plane has the tile grid size. + /// + /// The scratch histograms: 12 arrays of 256 counts. The first four arrays get the accumulated alpha, red, green and blue residual + /// histograms and must be zero. The next four are for the current mode, and the last four for the best mode. + /// + /// Whether near-lossless processing is enabled. + /// The near-lossless quality, from 0 to 100. A lower quality quantizes the residuals more. + /// The handling of transparent pixels. keeps all residuals exact. + /// Whether the pixels use the subtract green transform. + /// Whether all tiles use the select predictor without a search. public static void ResidualImage( int width, int height, int bits, - Span bgra, + Buffer2D bgra, Span bgraScratch, - Span image, - int[][] histoArgb, - int[][] bestHisto, + Buffer2D image, + Span histograms, bool nearLossless, int nearLosslessQuality, TransparentColorMode transparentColorMode, @@ -54,22 +107,17 @@ public static void ResidualImage( int tilesPerRow = LosslessUtils.SubSampleSize(width, bits); int tilesPerCol = LosslessUtils.SubSampleSize(height, bits); int maxQuantization = 1 << LosslessUtils.NearLosslessBits(nearLosslessQuality); - Span scratch = stackalloc short[8]; - // TODO: Can we optimize this? - int[][] histo = - [ - new int[256], - new int[256], - new int[256], - new int[256] - ]; + // Each group holds the alpha, red, green and blue histograms of 256 counts, one after the other. + Span histo = histograms[..HistogramGroupSize]; + Span histoArgb = histograms.Slice(HistogramGroupSize, HistogramGroupSize); + Span bestHisto = histograms.Slice(2 * HistogramGroupSize, HistogramGroupSize); if (lowEffort) { - for (int i = 0; i < tilesPerRow * tilesPerCol; i++) + for (int tileY = 0; tileY < tilesPerCol; tileY++) { - image[i] = WebpConstants.ArgbBlack | (PredLowEffort << 8); + image.DangerousGetRowSpan(tileY).Fill(WebpConstants.ArgbBlack | (PredLowEffort << 8)); } } else @@ -93,10 +141,9 @@ public static void ResidualImage( transparentColorMode, usedSubtractGreen, nearLossless, - image, - scratch); + image); - image[(tileY * tilesPerRow) + tileX] = (uint)(WebpConstants.ArgbBlack | (pred << 8)); + image.DangerousGetRowSpan(tileY)[tileX] = (uint)(WebpConstants.ArgbBlack | (pred << 8)); } } } @@ -115,73 +162,170 @@ public static void ResidualImage( lowEffort); } - public static void ColorSpaceTransform(int width, int height, int bits, uint quality, Span bgra, Span image, Span scratch) + /// + /// Finds the best color transform multipliers for each tile, stores them in the transform image and applies the transform to the pixels in place. + /// + /// The memory allocator of the scratch copy of a tile that crosses the end of a plane buffer. + /// The image width. + /// The image height. + /// The log2 of the tile size. + /// The encoding quality, from 0 to 100. A higher quality searches more multipliers. + /// The pixels. On return, the transformed pixels. The plane has the image size. + /// Receives the multipliers of each tile as a transform image pixel. The plane has the tile grid size. + /// + /// The scratch histograms: 3 arrays of 256 counts. The first two arrays get the accumulated red and blue histograms and must be zero. + /// The last array is for the tile that is evaluated. + /// + public static void ColorSpaceTransform( + MemoryAllocator memoryAllocator, + int width, + int height, + int bits, + uint quality, + Buffer2D bgra, + Buffer2D image, + Span histograms) { int maxTileSize = 1 << bits; int tileXSize = LosslessUtils.SubSampleSize(width, bits); int tileYSize = LosslessUtils.SubSampleSize(height, bits); - int[] accumulatedRedHisto = new int[256]; - int[] accumulatedBlueHisto = new int[256]; + Span accumulatedRedHisto = histograms[..256]; + Span accumulatedBlueHisto = histograms.Slice(256, 256); + Span scratch = histograms.Slice(512, 256); Vp8LMultipliers prevX = default(Vp8LMultipliers); Vp8LMultipliers prevY = default(Vp8LMultipliers); + + // The search reads a tile as one run of flat positions with the image width as the stride. A tile that crosses the end of a + // plane buffer is copied to a scratch run with the same layout first. Only a plane of several buffers has such tiles. + using IMemoryOwner? tileCopyOwner = bgra.FastMemoryGroup.Count > 1 + ? memoryAllocator.Allocate(((maxTileSize - 1) * width) + maxTileSize) + : null; + + // The histogram scan reads the neighbors of the first two columns at their flat positions, each with its own plane buffer. + Span pixels = default; + int pixelsStart = 0; + Span above = default; + int aboveStart = 0; for (int tileY = 0; tileY < tileYSize; tileY++) { for (int tileX = 0; tileX < tileXSize; tileX++) { int tileXOffset = tileX * maxTileSize; int tileYOffset = tileY * maxTileSize; - int allXMax = GetMin(tileXOffset + maxTileSize, width); - int allYMax = GetMin(tileYOffset + maxTileSize, height); - int offset = (tileY * tileXSize) + tileX; + int allXMax = Math.Min(tileXOffset + maxTileSize, width); + int allYMax = Math.Min(tileYOffset + maxTileSize, height); if (tileY != 0) { - LosslessUtils.ColorCodeToMultipliers(image[offset - tileXSize], ref prevY); + LosslessUtils.ColorCodeToMultipliers(image.DangerousGetRowSpan(tileY - 1)[tileX], ref prevY); + } + + // The tile as one run: its rows at the image width stride, from the first pixel to the last pixel of the tile. + int tileStart = (tileYOffset * width) + tileXOffset; + int tileLength = ((allYMax - tileYOffset - 1) * width) + (allXMax - tileXOffset); + if (!LosslessUtils.TryGetPlaneRun(bgra, tileStart, tileLength, out Span tileArgb)) + { + tileArgb = tileCopyOwner!.GetSpan()[..tileLength]; + LosslessUtils.CopyPlaneRun(bgra, tileStart, tileArgb); } prevX = GetBestColorTransformForTile( - tileX, - tileY, - bits, + allXMax - tileXOffset, + allYMax - tileYOffset, prevX, prevY, quality, width, - height, accumulatedRedHisto, accumulatedBlueHisto, - bgra, + tileArgb, scratch); - image[offset] = MultipliersToColorCode(prevX); + image.DangerousGetRowSpan(tileY)[tileX] = MultipliersToColorCode(prevX); CopyTileWithColorTransform(width, height, tileXOffset, tileYOffset, maxTileSize, prevX, bgra); - // Gather accumulated histogram data. + // Gather accumulated histogram data. The two pixels before a pixel and the three pixels above them are its neighbors at + // flat positions. From column 2, they are in the row of the pixel and in the row above, so the scan reads the two rows. + // The first two columns read the neighbors at their flat positions, which are at the end of the rows before. for (int y = tileYOffset; y < allYMax; y++) { - int ix = (y * width) + tileXOffset; - int ixEnd = ix + allXMax - tileXOffset; - - for (; ix < ixEnd; ix++) + ReadOnlySpan row = bgra.DangerousGetRowSpan(y); + ReadOnlySpan aboveRow = y > 0 ? bgra.DangerousGetRowSpan(y - 1) : default; + for (int x = tileXOffset; x < allXMax; x++) { - uint pix = bgra[ix]; - if (ix >= 2 && pix == bgra[ix - 2] && pix == bgra[ix - 1]) + uint pix = row[x]; + uint left2; + uint left1; + bool sameAsAbove; + if (x >= 2) + { + left2 = row[x - 2]; + left1 = row[x - 1]; + sameAsAbove = y > 0 && left2 == aboveRow[x - 2] && left1 == aboveRow[x - 1] && pix == aboveRow[x]; + } + else { - continue; // Repeated pixels are handled by backward references. + int ix = (y * width) + x; + if (ix < 2) + { + accumulatedRedHisto[(int)((pix >> 16) & 0xff)]++; + accumulatedBlueHisto[(int)(pix & 0xff)]++; + continue; + } + + left2 = LosslessUtils.GetPlaneValue(bgra, ix - 2, ref pixels, ref pixelsStart); + left1 = LosslessUtils.GetPlaneValue(bgra, ix - 1, ref pixels, ref pixelsStart); + sameAsAbove = ix >= width + 2 + && left2 == LosslessUtils.GetPlaneValue(bgra, ix - width - 2, ref above, ref aboveStart) + && left1 == LosslessUtils.GetPlaneValue(bgra, ix - width - 1, ref above, ref aboveStart) + && pix == LosslessUtils.GetPlaneValue(bgra, ix - width, ref above, ref aboveStart); } - if (ix >= width + 2 && bgra[ix - 2] == bgra[ix - width - 2] && bgra[ix - 1] == bgra[ix - width - 1] && pix == bgra[ix - width]) + // Repeated pixels are handled by backward references. + if ((pix == left2 && pix == left1) || sameAsAbove) { - continue; // Repeated pixels are handled by backward references. + continue; } - accumulatedRedHisto[(pix >> 16) & 0xff]++; - accumulatedBlueHisto[(pix >> 0) & 0xff]++; + accumulatedRedHisto[(int)((pix >> 16) & 0xff)]++; + accumulatedBlueHisto[(int)(pix & 0xff)]++; } } } } } + /// + /// Gets the number of pixels of the scratch buffer of . + /// + /// + /// The buffer holds two rows of + 1 pixels for the prediction context, then the maximum differences of two rows, + /// bytes each, rounded up to whole pixels, then three rows of pixels. The near-lossless + /// step restores the rows around a row there when the pixels use the subtract green transform. + /// + /// The image width in pixels. + /// The number of pixels. + public static int GetScratchSize(int width) => (2 * (width + 1)) + GetMaxDiffsScratchSize(width) + (3 * width); + + /// + /// Adds the four channels of a pixel to the alpha, red, green and blue histograms. + /// + /// + /// Each channel value is less than 256, so each reference must have at least 256 counts after it. + /// + /// The first count of the alpha histogram. + /// The first count of the red histogram. + /// The first count of the green histogram. + /// The first count of the blue histogram. + /// The ARGB pixel. + [MethodImpl(InliningOptions.ShortMethod)] + public static void UpdateHisto(ref uint alpha, ref uint red, ref uint green, ref uint blue, uint argb) + { + Unsafe.Add(ref alpha, argb >> 24)++; + Unsafe.Add(ref red, (argb >> 16) & 0xff)++; + Unsafe.Add(ref green, (argb >> 8) & 0xff)++; + Unsafe.Add(ref blue, argb & 0xff)++; + } + /// /// Returns best predictor and updates the accumulated histogram. /// If maxQuantization > 1, assumes that near lossless processing will be @@ -189,6 +333,21 @@ public static void ColorSpaceTransform(int width, int height, int bits, uint qua /// maxQuantization (the actual quantization level depends on smoothness near /// the given pixel). /// + /// The image width in pixels. + /// The image height in pixels. + /// The column of the tile. + /// The row of the tile. + /// The log2 of the tile size. + /// The residual histograms of the previous tiles: four arrays of 256 counts. Receives the counts of the best predictor. + /// The scratch buffer with pixels. + /// The pixels. The plane has the image size. + /// The scratch histograms of the current mode: four arrays of 256 counts. + /// The scratch histograms of the best mode: four arrays of 256 counts. + /// The largest near-lossless quantization step, a power of 2. A value of 1 keeps all residuals exact. + /// The handling of transparent pixels. keeps all residuals exact. + /// Whether the pixels use the subtract green transform. + /// Whether near-lossless processing is enabled. + /// The transform image. The method reads the predictor modes of the left and above tiles. /// Best predictor. private static int GetBestPredictorForTile( int width, @@ -196,63 +355,70 @@ private static int GetBestPredictorForTile( int tileX, int tileY, int bits, - int[][] accumulated, + Span accumulated, Span argbScratch, - Span argb, - int[][] histoArgb, - int[][] bestHisto, + Buffer2D argb, + Span histoArgb, + Span bestHisto, int maxQuantization, TransparentColorMode transparentColorMode, bool usedSubtractGreen, bool nearLossless, - ReadOnlySpan modes, - Span scratch) + Buffer2D modes) { const int numPredModes = 14; int startX = tileX << bits; int startY = tileY << bits; int tileSize = 1 << bits; - int maxY = GetMin(tileSize, height - startY); - int maxX = GetMin(tileSize, width - startX); + int maxY = Math.Min(tileSize, height - startY); + int maxX = Math.Min(tileSize, width - startX); // Whether there exist columns just outside the tile. int haveLeft = startX > 0 ? 1 : 0; - // Position and size of the strip covering the tile and adjacent columns if they exist. + // Position and size of the strip covering the tile and adjacent columns if they exist. The strip has the tile columns, the column to the left + // when the tile is not in the first column, and the column to the right when the tile does not end at the right edge of the image. int contextStartX = startX - haveLeft; - int contextWidth = maxX + haveLeft + (maxX < width ? 1 : 0) - startX; - int tilesPerRow = LosslessUtils.SubSampleSize(width, bits); + int contextWidth = maxX + haveLeft + (maxX < width - startX ? 1 : 0); // Prediction modes of the left and above neighbor tiles. - int leftMode = (int)(tileX > 0 ? (modes[(tileY * tilesPerRow) + tileX - 1] >> 8) & 0xff : 0xff); - int aboveMode = (int)(tileY > 0 ? (modes[((tileY - 1) * tilesPerRow) + tileX] >> 8) & 0xff : 0xff); + int leftMode = (int)(tileX > 0 ? (modes.DangerousGetRowSpan(tileY)[tileX - 1] >> 8) & 0xff : 0xff); + int aboveMode = (int)(tileY > 0 ? (modes.DangerousGetRowSpan(tileY - 1)[tileX] >> 8) & 0xff : 0xff); // The width of upper_row and current_row is one pixel larger than image width // to allow the top right pixel to point to the leftmost pixel of the next row // when at the right edge. - Span upperRow = argbScratch; - Span currentRow = upperRow[(width + 1)..]; - Span maxDiffs = MemoryMarshal.Cast(currentRow[(width + 1)..]); + int maxDiffsSize = GetMaxDiffsScratchSize(width); + Span upperRow = argbScratch[..(width + 1)]; + Span currentRow = argbScratch.Slice(width + 1, width + 1); + Span maxDiffs = MemoryMarshal.Cast(argbScratch.Slice(2 * (width + 1), maxDiffsSize))[..width]; + Span restoredRows = argbScratch.Slice((2 * (width + 1)) + maxDiffsSize, 3 * width); float bestDiff = MaxDiffCost; int bestMode = 0; - Span residuals = stackalloc uint[1 << WebpConstants.MaxTransformBits]; // 256 bytes - for (int i = 0; i < 4; i++) - { - histoArgb[i].AsSpan().Clear(); - bestHisto[i].AsSpan().Clear(); - } + + // A row of a tile has at most 1 << MaxTransformBits pixels. MaxTransformBits is 6, so the residuals fit in 64 entries. + InlineArray64 residualsStorage = default; + Span residuals = residualsStorage; + histoArgb.Clear(); + bestHisto.Clear(); for (int mode = 0; mode < numPredModes; mode++) { + // The histograms swap after a better mode, so the channel references are taken for each mode. + // The counts are never negative, so the same bits as unsigned values give the same increments. + ref uint histoBase = ref MemoryMarshal.GetReference(MemoryMarshal.Cast(histoArgb)); + ref uint histoAlpha = ref histoBase; + ref uint histoRed = ref Unsafe.Add(ref histoBase, 256u); + ref uint histoGreen = ref Unsafe.Add(ref histoBase, 512u); + ref uint histoBlue = ref Unsafe.Add(ref histoBase, 768u); + if (startY > 0) { // Read the row above the tile which will become the first upper_row. // Include a pixel to the left if it exists; include a pixel to the right // in all cases (wrapping to the leftmost pixel of the next row if it does - // not exist). - Span src = argb.Slice(((startY - 1) * width) + contextStartX, maxX + haveLeft + 1); - Span dst = currentRow[contextStartX..]; - src.CopyTo(dst); + // not exist). The copy reads flat positions, so the pixel after the row is the first pixel of the next row. + LosslessUtils.CopyPlaneRun(argb, ((startY - 1) * width) + contextStartX, currentRow.Slice(contextStartX, maxX + haveLeft + 1)); } for (int relativeY = 0; relativeY < maxY; relativeY++) @@ -267,15 +433,19 @@ private static int GetBestPredictorForTile( // the image (wrapping to the leftmost pixel of the next row if it does // not exist in the currentRow). int offset = (y * width) + contextStartX; - Span src = argb.Slice(offset, maxX + haveLeft + (y + 1 < height ? 1 : 0)); - Span dst = currentRow[contextStartX..]; - src.CopyTo(dst); + LosslessUtils.CopyPlaneRun(argb, offset, currentRow.Slice(contextStartX, maxX + haveLeft + (y + 1 < height ? 1 : 0))); if (nearLossless) { if (maxQuantization > 1 && y >= 1 && y + 1 < height) { - MaxDiffsForRow(contextWidth, width, argb, offset, maxDiffs[contextStartX..], usedSubtractGreen); + MaxDiffsForRow( + argb.DangerousGetRowSpan(y - 1).Slice(contextStartX, contextWidth), + argb.DangerousGetRowSpan(y).Slice(contextStartX, contextWidth), + argb.DangerousGetRowSpan(y + 1).Slice(contextStartX, contextWidth), + maxDiffs[contextStartX..], + usedSubtractGreen, + restoredRows); } } @@ -293,12 +463,11 @@ private static int GetBestPredictorForTile( transparentColorMode, usedSubtractGreen, nearLossless, - residuals, - scratch); + residuals); for (int relativeX = 0; relativeX < maxX; ++relativeX) { - UpdateHisto(histoArgb, residuals[relativeX]); + UpdateHisto(ref histoAlpha, ref histoRed, ref histoGreen, ref histoBlue, residuals[relativeX]); } } @@ -317,34 +486,47 @@ private static int GetBestPredictorForTile( if (curDiff < bestDiff) { - (bestHisto, histoArgb) = (histoArgb, bestHisto); + Span tmp = bestHisto; + bestHisto = histoArgb; + histoArgb = tmp; bestDiff = curDiff; bestMode = mode; } - for (int i = 0; i < 4; i++) - { - histoArgb[i].AsSpan().Clear(); - } + histoArgb.Clear(); } - for (int i = 0; i < 4; i++) - { - for (int j = 0; j < 256; j++) - { - accumulated[i][j] += bestHisto[i][j]; - } - } + // The four histograms are one after the other in both groups, so one add covers all of them. + TensorPrimitives.Add(accumulated, bestHisto, accumulated); return bestMode; } /// - /// Stores the difference between the pixel and its prediction in "output". - /// In case of a lossy encoding, updates the source image to avoid propagating - /// the deviation further to pixels which depend on the current pixel for their - /// predictions. + /// Stores the difference between each pixel and its prediction in . + /// A near-lossless encode also writes each quantized pixel back to the source row, so the pixels that are + /// predicted from it see the value that the decoder sees. /// + /// + /// keeps every residual exact, also in a near-lossless encode. With + /// , the caller has already set all components of each pixel with zero alpha + /// to zero, before the conversion to Bgra32. Near-lossless does not quantize a pixel with zero alpha, so the decoded + /// pixel stays zero, as the clear contract requires. + /// + /// The image width in pixels. + /// The image height in pixels. + /// The row above. It is one pixel wider than the image. + /// The current row. It is one pixel wider than the image. + /// The maximum difference of each pixel of the current row to its neighbors. + /// The predictor mode. + /// The column of the first pixel. + /// The column after the last pixel. + /// The row. + /// The largest near-lossless quantization step, a power of 2. A value of 1 keeps all residuals exact. + /// The handling of transparent pixels. keeps all residuals exact. + /// Whether the pixels use the subtract green transform. + /// Whether near-lossless processing is enabled. + /// Receives the residuals. Index 0 holds the residual of the pixel at . private static void GetResidual( int width, int height, @@ -359,132 +541,57 @@ private static void GetResidual( TransparentColorMode transparentColorMode, bool usedSubtractGreen, bool nearLossless, - Span output, - Span scratch) + Span output) { - if (transparentColorMode == TransparentColorMode.Preserve) + // Without near-lossless quantization every residual is exact, so the batch predictor gives the full row. + if (transparentColorMode == TransparentColorMode.Preserve || !nearLossless) { - PredictBatch(mode, xStart, y, xEnd - xStart, currentRowSpan, upperRowSpan, output, scratch); + PredictBatch(mode, xStart, y, xEnd - xStart, currentRowSpan, upperRowSpan, output); } else { -#pragma warning disable SA1503 // Braces should not be omitted -#pragma warning disable RCS1001 // Add braces (when expression spans over multiple lines) - fixed (uint* currentRow = currentRowSpan) - fixed (uint* upperRow = upperRowSpan) + // Both rows are one pixel wider than the image. The predictors read the left pixel at + // offset -1 of the current row. They read the top-left, top and top-right pixels at + // offsets -1, 0 and +1 of the upper row. The code uses these predictors only when x is not 0. + ref uint currentRow = ref MemoryMarshal.GetReference(currentRowSpan); + ref uint upperRow = ref MemoryMarshal.GetReference(upperRowSpan); + for (int x = xStart; x < xEnd; x++) { - for (int x = xStart; x < xEnd; x++) + ref uint current = ref Unsafe.Add(ref currentRow, (uint)x); + ref uint upper = ref Unsafe.Add(ref upperRow, (uint)x); + uint predict; + uint residual; + if (y == 0) { - uint predict = 0; - uint residual; - if (y == 0) - { - predict = x == 0 ? WebpConstants.ArgbBlack : currentRow[x - 1]; // Left. - } - else if (x == 0) - { - predict = upperRow[x]; // Top. - } - else - { - switch (mode) - { - case 0: - predict = WebpConstants.ArgbBlack; - break; - case 1: - predict = currentRow[x - 1]; - break; - case 2: - predict = LosslessUtils.Predictor2(currentRow[x - 1], upperRow + x); - break; - case 3: - predict = LosslessUtils.Predictor3(currentRow[x - 1], upperRow + x); - break; - case 4: - predict = LosslessUtils.Predictor4(currentRow[x - 1], upperRow + x); - break; - case 5: - predict = LosslessUtils.Predictor5(currentRow[x - 1], upperRow + x); - break; - case 6: - predict = LosslessUtils.Predictor6(currentRow[x - 1], upperRow + x); - break; - case 7: - predict = LosslessUtils.Predictor7(currentRow[x - 1], upperRow + x); - break; - case 8: - predict = LosslessUtils.Predictor8(currentRow[x - 1], upperRow + x); - break; - case 9: - predict = LosslessUtils.Predictor9(currentRow[x - 1], upperRow + x); - break; - case 10: - predict = LosslessUtils.Predictor10(currentRow[x - 1], upperRow + x); - break; - case 11: - predict = LosslessUtils.Predictor11(currentRow[x - 1], upperRow + x, scratch); - break; - case 12: - predict = LosslessUtils.Predictor12(currentRow[x - 1], upperRow + x); - break; - case 13: - predict = LosslessUtils.Predictor13(currentRow[x - 1], upperRow + x); - break; - } - } - - if (nearLossless) - { - if (maxQuantization == 1 || mode == 0 || y == 0 || y == height - 1 || x == 0 || x == width - 1) - { - residual = LosslessUtils.SubPixels(currentRow[x], predict); - } - else - { - residual = NearLossless(currentRow[x], predict, maxQuantization, maxDiffs[x], usedSubtractGreen); - - // Update the source image. - currentRow[x] = LosslessUtils.AddPixels(predict, residual); - - // x is never 0 here so we do not need to update upperRow like below. - } - } - else - { - residual = LosslessUtils.SubPixels(currentRow[x], predict); - } + predict = x == 0 ? WebpConstants.ArgbBlack : Unsafe.Subtract(ref current, (nuint)1); // Left. + } + else if (x == 0) + { + predict = upper; // Top. + } + else + { + predict = LosslessUtils.Predict(mode, Unsafe.Subtract(ref current, (nuint)1), ref upper); + } - if ((currentRow[x] & MaskAlpha) == 0) - { - // If alpha is 0, cleanup RGB. We can choose the RGB values of the - // residual for best compression. The prediction of alpha itself can be - // non-zero and must be kept though. We choose RGB of the residual to be - // 0. - residual &= MaskAlpha; - - // Update the source image. - currentRow[x] = predict & ~MaskAlpha; - - // The prediction for the rightmost pixel in a row uses the leftmost - // pixel - // in that row as its top-right context pixel. Hence if we change the - // leftmost pixel of current_row, the corresponding change must be - // applied - // to upperRow as well where top-right context is being read from. - if (x == 0 && y != 0) - { - upperRow[width] = currentRow[0]; - } - } + // The border pixels, mode 0 and a pixel with zero alpha keep the exact residual. Near-lossless never + // quantizes x == 0, so the top-right context copy of the leftmost pixel at upperRow[width] stays valid. + if (maxQuantization == 1 || mode == 0 || y == 0 || y == height - 1 || x == 0 || x == width - 1 || (current & MaskAlpha) == 0) + { + residual = LosslessUtils.SubPixels(current, predict); + } + else + { + residual = NearLossless(current, predict, maxQuantization, maxDiffs[x], usedSubtractGreen); - output[x - xStart] = residual; + // Write the decoded value back, so the pixels that are predicted from this pixel use it. + current = LosslessUtils.AddPixels(predict, residual); } + + output[x - xStart] = residual; } } } -#pragma warning restore RCS1001 // Add braces (when expression spans over multiple lines) -#pragma warning restore SA1503 // Braces should not be omitted /// /// Quantize every component of the difference between the actual pixel value and @@ -493,6 +600,12 @@ private static void GetResidual( /// value and predict have undergone subtract green, which means that red and /// blue are represented as offsets from green. /// + /// The actual ARGB pixel. + /// The predicted ARGB pixel. + /// The largest quantization step, a power of 2. + /// The maximum difference of the pixel to its neighbors. A value of 2 or less keeps the residual exact. + /// Whether the pixels use the subtract green transform. + /// The quantized ARGB residual. private static uint NearLossless(uint value, uint predict, int maxQuantization, int maxDiff, bool usedSubtractGreen) { byte newGreen = 0; @@ -549,6 +662,11 @@ private static uint NearLossless(uint value, uint predict, int maxQuantization, /// to a multiple of quantization, working modulo 256, taking care not to cross /// a boundary (inclusive upper limit). /// + /// The actual component value. + /// The predicted component value. + /// The inclusive upper limit of the decoded component value. + /// The quantization step, a power of 2. + /// The quantized residual, mod 256. private static byte NearLosslessComponent(byte value, byte predict, byte boundary, int quantization) { int residual = (value - predict) & 0xff; @@ -592,41 +710,53 @@ private static byte NearLosslessComponent(byte value, byte predict, byte boundar /// residuals to multiples of quantization levels up to max_quantization /// (the actual quantization level depends on smoothness near the given pixel). /// + /// The image width in pixels. + /// The image height in pixels. + /// The log2 of the tile size. + /// The transform image with the predictor mode of each tile in bits 8-15. + /// The scratch buffer with pixels. + /// The pixels. On return, the prediction residuals. The plane has the image size. + /// The largest near-lossless quantization step, a power of 2. A value of 1 keeps all residuals exact. + /// The handling of transparent pixels. keeps all residuals exact. + /// Whether the pixels use the subtract green transform. + /// Whether near-lossless processing is enabled. + /// Whether all pixels use the select predictor, without the modes of the tiles. private static void CopyImageWithPrediction( int width, int height, int bits, - ReadOnlySpan modes, + Buffer2D modes, Span argbScratch, - Span argb, + Buffer2D argb, int maxQuantization, TransparentColorMode transparentColorMode, bool usedSubtractGreen, bool nearLossless, bool lowEffort) { - int tilesPerRow = LosslessUtils.SubSampleSize(width, bits); - // The width of upperRow and currentRow is one pixel larger than image width // to allow the top right pixel to point to the leftmost pixel of the next row - // when at the right edge. - Span upperRow = argbScratch; - Span currentRow = upperRow[(width + 1)..]; - Span currentMaxDiffs = MemoryMarshal.Cast(currentRow[(width + 1)..]); - - Span lowerMaxDiffs = currentMaxDiffs[width..]; - Span scratch = stackalloc short[8]; + // when at the right edge. The maximum differences of two rows follow, then the restored rows of the near-lossless step. + int maxDiffsSize = GetMaxDiffsScratchSize(width); + Span upperRow = argbScratch[..(width + 1)]; + Span currentRow = argbScratch.Slice(width + 1, width + 1); + Span maxDiffs = MemoryMarshal.Cast(argbScratch.Slice(2 * (width + 1), maxDiffsSize)); + Span restoredRows = argbScratch.Slice((2 * (width + 1)) + maxDiffsSize, 3 * width); + Span currentMaxDiffs = maxDiffs[..width]; + Span lowerMaxDiffs = maxDiffs.Slice(width, width); for (int y = 0; y < height; y++) { Span tmp32 = upperRow; upperRow = currentRow; currentRow = tmp32; - Span src = argb.Slice(y * width, width + (y + 1 < height ? 1 : 0)); - src.CopyTo(currentRow); + + // The copy reads flat positions, so the pixel after the row is the first pixel of the next row. + LosslessUtils.CopyPlaneRun(argb, y * width, currentRow[..(width + (y + 1 < height ? 1 : 0))]); + Span residualRow = argb.DangerousGetRowSpan(y); if (lowEffort) { - PredictBatch(PredLowEffort, 0, y, width, currentRow, upperRow, argb[(y * width)..], scratch); + PredictBatch(PredLowEffort, 0, y, width, currentRow, upperRow, residualRow); } else { @@ -640,13 +770,20 @@ private static void CopyImageWithPrediction( lowerMaxDiffs = tmp8; if (y + 2 < height) { - MaxDiffsForRow(width, width, argb, (y + 1) * width, lowerMaxDiffs, usedSubtractGreen); + MaxDiffsForRow( + argb.DangerousGetRowSpan(y), + argb.DangerousGetRowSpan(y + 1), + argb.DangerousGetRowSpan(y + 2), + lowerMaxDiffs, + usedSubtractGreen, + restoredRows); } } + ReadOnlySpan modesRow = modes.DangerousGetRowSpan(y >> bits); for (int x = 0; x < width;) { - int mode = (int)((modes[((y >> bits) * tilesPerRow) + (x >> bits)] >> 8) & 0xff); + int mode = (int)((modesRow[x >> bits] >> 8) & 0xff); int xEnd = x + (1 << bits); if (xEnd > width) { @@ -667,8 +804,7 @@ private static void CopyImageWithPrediction( transparentColorMode, usedSubtractGreen, nearLossless, - argb[((y * width) + x)..], - scratch); + residualRow[x..]); x = xEnd; } @@ -676,6 +812,17 @@ private static void CopyImageWithPrediction( } } + /// + /// Computes the prediction residuals of a run of pixels in one row. The first pixel of a row and all pixels of the first row + /// use fixed predictors, because their neighbors are not available. + /// + /// The predictor mode. + /// The column of the first pixel. + /// The row. + /// The number of pixels. + /// The current row. + /// The row above. + /// Receives the residuals. private static void PredictBatch( int mode, int xStart, @@ -683,123 +830,218 @@ private static void PredictBatch( int numPixels, Span currentSpan, Span upperSpan, - Span outputSpan, - Span scratch) + Span outputSpan) { -#pragma warning disable SA1503 // Braces should not be omitted - fixed (uint* current = currentSpan) - fixed (uint* upper = upperSpan) - fixed (uint* outputFixed = outputSpan) + ref uint current = ref MemoryMarshal.GetReference(currentSpan); + ref uint upper = ref MemoryMarshal.GetReference(upperSpan); + ref uint output = ref MemoryMarshal.GetReference(outputSpan); + if (xStart == 0) { - uint* output = outputFixed; - if (xStart == 0) - { - if (y == 0) - { - // ARGB_BLACK. - LosslessUtils.PredictorSub0(current, 1, output); - } - else - { - // Top one. - LosslessUtils.PredictorSub2(current, upper, 1, output); - } - - ++xStart; - ++output; - --numPixels; - } - - if (y == 0) - { - // Left one. - LosslessUtils.PredictorSub1(current + xStart, numPixels, output); - } - else - { - switch (mode) - { - case 0: - LosslessUtils.PredictorSub0(current + xStart, numPixels, output); - break; - case 1: - LosslessUtils.PredictorSub1(current + xStart, numPixels, output); - break; - case 2: - LosslessUtils.PredictorSub2(current + xStart, upper + xStart, numPixels, output); - break; - case 3: - LosslessUtils.PredictorSub3(current + xStart, upper + xStart, numPixels, output); - break; - case 4: - LosslessUtils.PredictorSub4(current + xStart, upper + xStart, numPixels, output); - break; - case 5: - LosslessUtils.PredictorSub5(current + xStart, upper + xStart, numPixels, output); - break; - case 6: - LosslessUtils.PredictorSub6(current + xStart, upper + xStart, numPixels, output); - break; - case 7: - LosslessUtils.PredictorSub7(current + xStart, upper + xStart, numPixels, output); - break; - case 8: - LosslessUtils.PredictorSub8(current + xStart, upper + xStart, numPixels, output); - break; - case 9: - LosslessUtils.PredictorSub9(current + xStart, upper + xStart, numPixels, output); - break; - case 10: - LosslessUtils.PredictorSub10(current + xStart, upper + xStart, numPixels, output); - break; - case 11: - LosslessUtils.PredictorSub11(current + xStart, upper + xStart, numPixels, output, scratch); - break; - case 12: - LosslessUtils.PredictorSub12(current + xStart, upper + xStart, numPixels, output); - break; - case 13: - LosslessUtils.PredictorSub13(current + xStart, upper + xStart, numPixels, output); - break; - } - } + // The first pixel of the image uses black (mode 0), and the first pixel of the other rows the top pixel (mode 2). Neither mode reads the left + // pixel, which is before the start of the row. + LosslessUtils.PredictorSub(y == 0 ? 0 : 2, ref current, ref upper, 1, ref output); + ++xStart; + output = ref Unsafe.Add(ref output, (nuint)1); + --numPixels; } + + // The first row has no row above. It uses the left predictor, which does not read the upper row. + ref uint currentX = ref Unsafe.Add(ref current, (uint)xStart); + ref uint upperX = ref Unsafe.Add(ref upper, (uint)xStart); + LosslessUtils.PredictorSub(y == 0 ? 1 : mode, ref currentX, ref upperX, numPixels, ref output); } -#pragma warning restore SA1503 // Braces should not be omitted - private static void MaxDiffsForRow(int width, int stride, ReadOnlySpan argb, int offset, Span maxDiffs, bool usedSubtractGreen) + /// + /// Gets the number of pixels that hold the maximum differences of two rows: 2 * bytes, rounded up to whole pixels. + /// + /// The image width in pixels. + /// The number of pixels. + private static int GetMaxDiffsScratchSize(int width) => ((2 * width) + 3) / 4; + + /// + /// Computes, for each pixel of a row except the first and the last, the largest channel difference to its 4 neighbors. + /// When the subtract green transform was applied, the pixels are restored before the comparison. + /// + /// The pixels of the row above. + /// The pixels of the row. The three rows have the same length. + /// The pixels of the row below. + /// Receives the largest difference of each pixel. + /// Whether the subtract green transform was applied to the pixels. + /// A scratch buffer of three rows of at least the row length for the restored pixels. + private static void MaxDiffsForRow( + ReadOnlySpan upRow, + ReadOnlySpan currentRow, + ReadOnlySpan downRow, + Span maxDiffs, + bool usedSubtractGreen, + Span restoredRows) { + int width = currentRow.Length; if (width <= 2) { return; } - uint current = argb[offset]; - uint right = argb[offset + 1]; if (usedSubtractGreen) { - current = AddGreenToBlueAndRed(current); - right = AddGreenToBlueAndRed(right); + // The owner transform restores copies of the three rows. Thus each pixel is restored one time, and not once for each neighbor. + Span restored = restoredRows[..(3 * width)]; + upRow.CopyTo(restored); + currentRow.CopyTo(restored[width..]); + downRow.CopyTo(restored[(2 * width)..]); + LosslessUtils.AddGreenToBlueAndRed(restored); + upRow = restored[..width]; + currentRow = restored.Slice(width, width); + downRow = restored.Slice(2 * width, width); + } + + ref uint up = ref MemoryMarshal.GetReference(upRow); + ref uint current = ref MemoryMarshal.GetReference(currentRow); + ref uint down = ref MemoryMarshal.GetReference(downRow); + ref byte diffs = ref MemoryMarshal.GetReference(maxDiffs); + + // The outputs are the pixels 1 to width - 2. A block reads the left and right neighbors at -1 and +1, so the last block reads at + // most the pixel width - 1. A block computes four vectors of pixels, one pixel in each 32-bit lane, and narrows them in order to + // one vector of bytes. The same column flows through descending widths, and the scalar form computes the remainder. + nuint end = (uint)(width - 1); + nuint x = 1; + if (Vector512.IsHardwareAccelerated) + { + nuint lanes = (uint)Vector512.Count; + for (; x + (4 * lanes) <= end; x += 4 * lanes) + { + Vector512 d0 = MaxDiffAroundPixel( + Vector512.LoadUnsafe(ref current, x), + Vector512.LoadUnsafe(ref up, x), + Vector512.LoadUnsafe(ref down, x), + Vector512.LoadUnsafe(ref current, x - 1), + Vector512.LoadUnsafe(ref current, x + 1)); + + nuint x1 = x + lanes; + Vector512 d1 = MaxDiffAroundPixel( + Vector512.LoadUnsafe(ref current, x1), + Vector512.LoadUnsafe(ref up, x1), + Vector512.LoadUnsafe(ref down, x1), + Vector512.LoadUnsafe(ref current, x1 - 1), + Vector512.LoadUnsafe(ref current, x1 + 1)); + + nuint x2 = x1 + lanes; + Vector512 d2 = MaxDiffAroundPixel( + Vector512.LoadUnsafe(ref current, x2), + Vector512.LoadUnsafe(ref up, x2), + Vector512.LoadUnsafe(ref down, x2), + Vector512.LoadUnsafe(ref current, x2 - 1), + Vector512.LoadUnsafe(ref current, x2 + 1)); + + nuint x3 = x2 + lanes; + Vector512 d3 = MaxDiffAroundPixel( + Vector512.LoadUnsafe(ref current, x3), + Vector512.LoadUnsafe(ref up, x3), + Vector512.LoadUnsafe(ref down, x3), + Vector512.LoadUnsafe(ref current, x3 - 1), + Vector512.LoadUnsafe(ref current, x3 + 1)); + + // Each lane holds a value from 0 to 255, so the truncating narrows keep each value. + Vector512.Narrow(Vector512.Narrow(d0, d1), Vector512.Narrow(d2, d3)).StoreUnsafe(ref diffs, x); + } + } + + if (Vector256.IsHardwareAccelerated) + { + nuint lanes = (uint)Vector256.Count; + for (; x + (4 * lanes) <= end; x += 4 * lanes) + { + Vector256 d0 = MaxDiffAroundPixel( + Vector256.LoadUnsafe(ref current, x), + Vector256.LoadUnsafe(ref up, x), + Vector256.LoadUnsafe(ref down, x), + Vector256.LoadUnsafe(ref current, x - 1), + Vector256.LoadUnsafe(ref current, x + 1)); + + nuint x1 = x + lanes; + Vector256 d1 = MaxDiffAroundPixel( + Vector256.LoadUnsafe(ref current, x1), + Vector256.LoadUnsafe(ref up, x1), + Vector256.LoadUnsafe(ref down, x1), + Vector256.LoadUnsafe(ref current, x1 - 1), + Vector256.LoadUnsafe(ref current, x1 + 1)); + + nuint x2 = x1 + lanes; + Vector256 d2 = MaxDiffAroundPixel( + Vector256.LoadUnsafe(ref current, x2), + Vector256.LoadUnsafe(ref up, x2), + Vector256.LoadUnsafe(ref down, x2), + Vector256.LoadUnsafe(ref current, x2 - 1), + Vector256.LoadUnsafe(ref current, x2 + 1)); + + nuint x3 = x2 + lanes; + Vector256 d3 = MaxDiffAroundPixel( + Vector256.LoadUnsafe(ref current, x3), + Vector256.LoadUnsafe(ref up, x3), + Vector256.LoadUnsafe(ref down, x3), + Vector256.LoadUnsafe(ref current, x3 - 1), + Vector256.LoadUnsafe(ref current, x3 + 1)); + + // Each lane holds a value from 0 to 255, so the truncating narrows keep each value. + Vector256.Narrow(Vector256.Narrow(d0, d1), Vector256.Narrow(d2, d3)).StoreUnsafe(ref diffs, x); + } } - for (int x = 1; x < width - 1; x++) + if (Vector128.IsHardwareAccelerated) { - uint up = argb[offset - stride + x]; - uint down = argb[offset + stride + x]; - uint left = current; - current = right; - right = argb[offset + x + 1]; - if (usedSubtractGreen) + nuint lanes = (uint)Vector128.Count; + for (; x + (4 * lanes) <= end; x += 4 * lanes) { - up = AddGreenToBlueAndRed(up); - down = AddGreenToBlueAndRed(down); - right = AddGreenToBlueAndRed(right); + Vector128 d0 = MaxDiffAroundPixel( + Vector128.LoadUnsafe(ref current, x), + Vector128.LoadUnsafe(ref up, x), + Vector128.LoadUnsafe(ref down, x), + Vector128.LoadUnsafe(ref current, x - 1), + Vector128.LoadUnsafe(ref current, x + 1)); + + nuint x1 = x + lanes; + Vector128 d1 = MaxDiffAroundPixel( + Vector128.LoadUnsafe(ref current, x1), + Vector128.LoadUnsafe(ref up, x1), + Vector128.LoadUnsafe(ref down, x1), + Vector128.LoadUnsafe(ref current, x1 - 1), + Vector128.LoadUnsafe(ref current, x1 + 1)); + + nuint x2 = x1 + lanes; + Vector128 d2 = MaxDiffAroundPixel( + Vector128.LoadUnsafe(ref current, x2), + Vector128.LoadUnsafe(ref up, x2), + Vector128.LoadUnsafe(ref down, x2), + Vector128.LoadUnsafe(ref current, x2 - 1), + Vector128.LoadUnsafe(ref current, x2 + 1)); + + nuint x3 = x2 + lanes; + Vector128 d3 = MaxDiffAroundPixel( + Vector128.LoadUnsafe(ref current, x3), + Vector128.LoadUnsafe(ref up, x3), + Vector128.LoadUnsafe(ref down, x3), + Vector128.LoadUnsafe(ref current, x3 - 1), + Vector128.LoadUnsafe(ref current, x3 + 1)); + + // Each lane holds a value from 0 to 255, so the truncating narrows keep each value. + Vector128.Narrow(Vector128.Narrow(d0, d1), Vector128.Narrow(d2, d3)).StoreUnsafe(ref diffs, x); } + } - maxDiffs[x] = (byte)MaxDiffAroundPixel(current, up, down, left, right); + for (; x < end; x++) + { + uint left = Unsafe.Add(ref current, x - 1); + uint right = Unsafe.Add(ref current, x + 1); + Unsafe.Add(ref diffs, x) = (byte)MaxDiffAroundPixel(Unsafe.Add(ref current, x), Unsafe.Add(ref up, x), Unsafe.Add(ref down, x), left, right); } } + /// + /// Gets the largest absolute channel difference of two pixels. + /// + /// The first pixel. + /// The second pixel. + /// The largest difference. [MethodImpl(InliningOptions.ShortMethod)] private static int MaxDiffBetweenPixels(uint p1, uint p2) { @@ -807,9 +1049,18 @@ private static int MaxDiffBetweenPixels(uint p1, uint p2) int diffR = Math.Abs((int)((p1 >> 16) & 0xff) - (int)((p2 >> 16) & 0xff)); int diffG = Math.Abs((int)((p1 >> 8) & 0xff) - (int)((p2 >> 8) & 0xff)); int diffB = Math.Abs((int)(p1 & 0xff) - (int)(p2 & 0xff)); - return GetMax(GetMax(diffA, diffR), GetMax(diffG, diffB)); + return Math.Max(Math.Max(diffA, diffR), Math.Max(diffG, diffB)); } + /// + /// Gets the largest absolute channel difference of a pixel to its 4 neighbors. + /// + /// The pixel. + /// The pixel above. + /// The pixel below. + /// The pixel to the left. + /// The pixel to the right. + /// The largest difference. [MethodImpl(InliningOptions.ShortMethod)] private static int MaxDiffAroundPixel(uint current, uint up, uint down, uint left, uint right) { @@ -817,66 +1068,158 @@ private static int MaxDiffAroundPixel(uint current, uint up, uint down, uint lef int diffDown = MaxDiffBetweenPixels(current, down); int diffLeft = MaxDiffBetweenPixels(current, left); int diffRight = MaxDiffBetweenPixels(current, right); - return GetMax(GetMax(diffUp, diffDown), GetMax(diffLeft, diffRight)); + return Math.Max(Math.Max(diffUp, diffDown), Math.Max(diffLeft, diffRight)); } - [MethodImpl(InliningOptions.ShortMethod)] - private static void UpdateHisto(int[][] histoArgb, uint argb) + /// + /// Gets the largest absolute channel difference of each of four pixels to its 4 neighbors. + /// + /// + /// Each 32-bit lane holds one pixel. The byte lanes give each channel difference as max - min, which is the absolute difference of + /// the scalar form. The maxima then fold into byte 0 of each pixel: a 32-bit shift by 16 brings bytes 2 and 3 under bytes 0 and 1, + /// and a shift by 8 brings byte 1 under byte 0. The mask keeps byte 0, so each lane holds the scalar result, from 0 to 255. + /// + /// The pixels. + /// The pixels above. + /// The pixels below. + /// The pixels to the left. + /// The pixels to the right. + /// The largest difference of each pixel, one in each lane. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector128 MaxDiffAroundPixel( + Vector128 current, + Vector128 up, + Vector128 down, + Vector128 left, + Vector128 right) { - ++histoArgb[0][argb >> 24]; - ++histoArgb[1][(argb >> 16) & 0xff]; - ++histoArgb[2][(argb >> 8) & 0xff]; - ++histoArgb[3][argb & 0xff]; + Vector128 c = current.AsByte(); + Vector128 diffUp = Vector128.Max(c, up.AsByte()) - Vector128.Min(c, up.AsByte()); + Vector128 diffDown = Vector128.Max(c, down.AsByte()) - Vector128.Min(c, down.AsByte()); + Vector128 diffLeft = Vector128.Max(c, left.AsByte()) - Vector128.Min(c, left.AsByte()); + Vector128 diffRight = Vector128.Max(c, right.AsByte()) - Vector128.Min(c, right.AsByte()); + Vector128 max = Vector128.Max(Vector128.Max(diffUp, diffDown), Vector128.Max(diffLeft, diffRight)); + max = Vector128.Max(max, (max.AsUInt32() >>> 16).AsByte()); + max = Vector128.Max(max, (max.AsUInt32() >>> 8).AsByte()); + return max.AsUInt32() & Vector128.Create(0xffu); } - private static uint AddGreenToBlueAndRed(uint argb) + /// + /// Gets the largest absolute channel difference of each of eight pixels to its 4 neighbors. + /// + /// + /// The same lane layout as the 128-bit form. + /// + /// The pixels. + /// The pixels above. + /// The pixels below. + /// The pixels to the left. + /// The pixels to the right. + /// The largest difference of each pixel, one in each lane. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector256 MaxDiffAroundPixel( + Vector256 current, + Vector256 up, + Vector256 down, + Vector256 left, + Vector256 right) { - uint green = (argb >> 8) & 0xff; - uint redBlue = argb & 0x00ff00ffu; - redBlue += (green << 16) | green; - redBlue &= 0x00ff00ffu; - return (argb & 0xff00ff00u) | redBlue; + Vector256 c = current.AsByte(); + Vector256 diffUp = Vector256.Max(c, up.AsByte()) - Vector256.Min(c, up.AsByte()); + Vector256 diffDown = Vector256.Max(c, down.AsByte()) - Vector256.Min(c, down.AsByte()); + Vector256 diffLeft = Vector256.Max(c, left.AsByte()) - Vector256.Min(c, left.AsByte()); + Vector256 diffRight = Vector256.Max(c, right.AsByte()) - Vector256.Min(c, right.AsByte()); + Vector256 max = Vector256.Max(Vector256.Max(diffUp, diffDown), Vector256.Max(diffLeft, diffRight)); + max = Vector256.Max(max, (max.AsUInt32() >>> 16).AsByte()); + max = Vector256.Max(max, (max.AsUInt32() >>> 8).AsByte()); + return max.AsUInt32() & Vector256.Create(0xffu); } - private static void CopyTileWithColorTransform(int xSize, int ySize, int tileX, int tileY, int maxTileSize, Vp8LMultipliers colorTransform, Span argb) + /// + /// Gets the largest absolute channel difference of each of sixteen pixels to its 4 neighbors. + /// + /// + /// The same lane layout as the 128-bit form. + /// + /// The pixels. + /// The pixels above. + /// The pixels below. + /// The pixels to the left. + /// The pixels to the right. + /// The largest difference of each pixel, one in each lane. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector512 MaxDiffAroundPixel( + Vector512 current, + Vector512 up, + Vector512 down, + Vector512 left, + Vector512 right) { - int xScan = GetMin(maxTileSize, xSize - tileX); - int yScan = GetMin(maxTileSize, ySize - tileY); - argb = argb[((tileY * xSize) + tileX)..]; - while (yScan-- > 0) - { - LosslessUtils.TransformColor(colorTransform, argb, xScan); + Vector512 c = current.AsByte(); + Vector512 diffUp = Vector512.Max(c, up.AsByte()) - Vector512.Min(c, up.AsByte()); + Vector512 diffDown = Vector512.Max(c, down.AsByte()) - Vector512.Min(c, down.AsByte()); + Vector512 diffLeft = Vector512.Max(c, left.AsByte()) - Vector512.Min(c, left.AsByte()); + Vector512 diffRight = Vector512.Max(c, right.AsByte()) - Vector512.Min(c, right.AsByte()); + Vector512 max = Vector512.Max(Vector512.Max(diffUp, diffDown), Vector512.Max(diffLeft, diffRight)); + max = Vector512.Max(max, (max.AsUInt32() >>> 16).AsByte()); + max = Vector512.Max(max, (max.AsUInt32() >>> 8).AsByte()); + return max.AsUInt32() & Vector512.Create(0xffu); + } - if (argb.Length > xSize) - { - argb = argb[xSize..]; - } + /// + /// Applies the color transform to the pixels of one tile in place. A tile at the right or bottom edge can be smaller than the tile size. + /// + /// The image width. + /// The image height. + /// The column of the first pixel of the tile. + /// The row of the first pixel of the tile. + /// The tile size. + /// The color transform multipliers. + /// The image pixels. The plane has the image size. + private static void CopyTileWithColorTransform( + int xSize, + int ySize, + int tileX, + int tileY, + int maxTileSize, + Vp8LMultipliers colorTransform, + Buffer2D argb) + { + int xScan = Math.Min(maxTileSize, xSize - tileX); + int yEnd = Math.Min(tileY + maxTileSize, ySize); + for (int y = tileY; y < yEnd; y++) + { + LosslessUtils.TransformColor(colorTransform, argb.DangerousGetRowSpan(y)[tileX..], xScan); } } + /// + /// Finds the color transform multipliers with the lowest estimated cost for one tile. The search first finds green-to-red, then green-to-blue + /// and red-to-blue. + /// + /// The tile width. A tile at the right edge can be smaller than the tile size. + /// The tile height. A tile at the bottom edge can be smaller than the tile size. + /// The multipliers of the tile to the left. + /// The multipliers of the tile above. + /// The encoding quality, from 0 to 100. + /// The image width. It is the stride of the tile rows. + /// The histogram of the transformed red values of the tiles done before. + /// The histogram of the transformed blue values of the tiles done before. + /// The pixels of the tile, from its first pixel, with as the stride. + /// A scratch buffer with at least 256 entries. + /// The best multipliers. private static Vp8LMultipliers GetBestColorTransformForTile( - int tileX, - int tileY, - int bits, + int tileWidth, + int tileHeight, Vp8LMultipliers prevX, Vp8LMultipliers prevY, uint quality, int xSize, - int ySize, - int[] accumulatedRedHisto, - int[] accumulatedBlueHisto, - Span argb, + ReadOnlySpan accumulatedRedHisto, + ReadOnlySpan accumulatedBlueHisto, + Span tileArgb, Span scratch) { - int maxTileSize = 1 << bits; - int tileYOffset = tileY * maxTileSize; - int tileXOffset = tileX * maxTileSize; - int allXMax = GetMin(tileXOffset + maxTileSize, xSize); - int allYMax = GetMin(tileYOffset + maxTileSize, ySize); - int tileWidth = allXMax - tileXOffset; - int tileHeight = allYMax - tileYOffset; - Span tileArgb = argb[((tileYOffset * xSize) + tileXOffset)..]; - Vp8LMultipliers bestTx = default(Vp8LMultipliers); GetBestGreenToRed(tileArgb, xSize, scratch, tileWidth, tileHeight, prevX, prevY, quality, accumulatedRedHisto, ref bestTx); @@ -886,6 +1229,20 @@ private static Vp8LMultipliers GetBestColorTransformForTile( return bestTx; } + /// + /// Searches the green-to-red multiplier with the lowest estimated cost. Each iteration tries the best value plus and minus a step, + /// and the step halves after each iteration. A higher quality runs more iterations. + /// + /// The pixels of the tile, starting at its first pixel. + /// The number of pixels between rows. + /// A scratch buffer with at least 256 entries. + /// The tile width. + /// The tile height. + /// The multipliers of the tile to the left. + /// The multipliers of the tile above. + /// The encoding quality, from 0 to 100. + /// The histogram of the transformed red values of the tiles done before. + /// Receives the green-to-red multiplier. private static void GetBestGreenToRed( Span argb, int stride, @@ -895,7 +1252,7 @@ private static void GetBestGreenToRed( Vp8LMultipliers prevX, Vp8LMultipliers prevY, uint quality, - int[] accumulatedRedHisto, + ReadOnlySpan accumulatedRedHisto, ref Vp8LMultipliers bestTx) { uint maxIters = 4 + ((7 * quality) / 256); // in range [4..6] @@ -924,6 +1281,20 @@ private static void GetBestGreenToRed( bestTx.GreenToRed = (byte)(greenToRedBest & 0xff); } + /// + /// Searches the green-to-blue and red-to-blue multipliers with the lowest estimated cost. Each iteration tries a step in each + /// direction of from the best pair, with the step sizes of . + /// + /// The pixels of the tile, starting at its first pixel. + /// The number of pixels between rows. + /// A scratch buffer with at least 256 entries. + /// The tile width. + /// The tile height. + /// The multipliers of the tile to the left. + /// The multipliers of the tile above. + /// The encoding quality, from 0 to 100. + /// The histogram of the transformed blue values of the tiles done before. + /// Receives the green-to-blue and red-to-blue multipliers. private static void GetBestGreenRedToBlue( Span argb, int stride, @@ -933,7 +1304,7 @@ private static void GetBestGreenRedToBlue( Vp8LMultipliers prevX, Vp8LMultipliers prevY, uint quality, - int[] accumulatedBlueHisto, + ReadOnlySpan accumulatedBlueHisto, ref Vp8LMultipliers bestTx) { int iters = (quality < 25) ? 1 : (quality > 50) ? GreenRedToBlueMaxIters : 4; @@ -958,8 +1329,8 @@ private static void GetBestGreenRedToBlue( int delta = DeltaLut[iter]; for (int axis = 0; axis < GreenRedToBlueNumAxis; axis++) { - int greenToBlueCur = (Offset[axis][0] * delta) + greenToBlueBest; - int redToBlueCur = (Offset[axis][1] * delta) + redToBlueBest; + int greenToBlueCur = (Offset[2 * axis] * delta) + greenToBlueBest; + int redToBlueCur = (Offset[(2 * axis) + 1] * delta) + redToBlueBest; double curDiff = GetPredictionCostCrossColorBlue( argb, stride, @@ -997,6 +1368,20 @@ private static void GetBestGreenRedToBlue( bestTx.RedToBlue = (byte)(redToBlueBest & 0xff); } + /// + /// Estimates the cost of the transformed red values of a tile for one green-to-red multiplier. A multiplier that equals the left or the + /// top neighbor, or that is zero, gets a cost bonus. + /// + /// The pixels of the tile, starting at its first pixel. + /// The number of pixels between rows. + /// A scratch buffer with at least 256 entries. + /// The tile width. + /// The tile height. + /// The multipliers of the tile to the left. + /// The multipliers of the tile above. + /// The green-to-red multiplier to test. + /// The histogram of the transformed red values of the tiles done before. + /// The estimated cost. A lower value is better. private static double GetPredictionCostCrossColorRed( Span argb, int stride, @@ -1006,7 +1391,7 @@ private static double GetPredictionCostCrossColorRed( Vp8LMultipliers prevX, Vp8LMultipliers prevY, int greenToRed, - int[] accumulatedRedHisto) + ReadOnlySpan accumulatedRedHisto) { Span histo = scratch[..256]; histo.Clear(); @@ -1034,6 +1419,21 @@ private static double GetPredictionCostCrossColorRed( return curDiff; } + /// + /// Estimates the cost of the transformed blue values of a tile for one pair of green-to-blue and red-to-blue multipliers. + /// A multiplier that equals the left or the top neighbor, or that is zero, gets a cost bonus. + /// + /// The pixels of the tile, starting at its first pixel. + /// The number of pixels between rows. + /// A scratch buffer with at least 256 entries. + /// The tile width. + /// The tile height. + /// The multipliers of the tile to the left. + /// The multipliers of the tile above. + /// The green-to-blue multiplier to test. + /// The red-to-blue multiplier to test. + /// The histogram of the transformed blue values of the tiles done before. + /// The estimated cost. A lower value is better. private static double GetPredictionCostCrossColorBlue( Span argb, int stride, @@ -1044,7 +1444,7 @@ private static double GetPredictionCostCrossColorBlue( Vp8LMultipliers prevY, int greenToBlue, int redToBlue, - int[] accumulatedBlueHisto) + ReadOnlySpan accumulatedBlueHisto) { Span histo = scratch[..256]; histo.Clear(); @@ -1088,21 +1488,34 @@ private static double GetPredictionCostCrossColorBlue( return curDiff; } - private static float PredictionCostSpatialHistogram(int[][] accumulated, int[][] tile) + /// + /// Estimates the cost of the residual histograms of a tile. The cost favors small residuals and a low entropy of the tile and the accumulated histograms. + /// + /// The alpha, red, green and blue residual histograms of the tiles done before. + /// The alpha, red, green and blue residual histograms of the tile. + /// The estimated cost. A lower value is better. + private static float PredictionCostSpatialHistogram(ReadOnlySpan accumulated, ReadOnlySpan tile) { double retVal = 0.0d; for (int i = 0; i < 4; i++) { double kExpValue = 0.94; - retVal += PredictionCostSpatial(tile[i], 1, kExpValue); - retVal += LosslessUtils.CombinedShannonEntropy(tile[i], accumulated[i]); + ReadOnlySpan tileChannel = tile.Slice(i * 256, 256); + retVal += PredictionCostSpatial(tileChannel, 1, kExpValue); + retVal += LosslessUtils.CombinedShannonEntropy(tileChannel, accumulated.Slice(i * 256, 256)); } return (float)retVal; } + /// + /// Estimates the cost of a transformed channel histogram. The cost favors small values and a low entropy of the tile and the accumulated histograms. + /// + /// The histogram of the tiles done before. + /// The histogram of the tile. + /// The estimated cost. A lower value is better. [MethodImpl(InliningOptions.ShortMethod)] - private static double PredictionCostCrossColor(int[] accumulated, Span counts) + private static double PredictionCostCrossColor(ReadOnlySpan accumulated, ReadOnlySpan counts) { // Favor low entropy, locally and globally. // Favor small absolute values for PredictionCostSpatial. @@ -1110,6 +1523,14 @@ private static double PredictionCostCrossColor(int[] accumulated, Span coun return LosslessUtils.CombinedShannonEntropy(counts, accumulated) + PredictionCostSpatial(counts, 3, expValue); } + /// + /// Computes a negative cost bonus for values near zero. Zero adds its count with its own weight. The values from 1 to 15 and from -1 to -15 + /// add their counts with a weight that decays by 0.6 for each step away from zero. + /// + /// The histogram of 256 values. The value 256 - i holds the count of -i. + /// The weight of the zero value. + /// The weight of the values -1 and 1. + /// The cost bonus. It is zero or negative. [MethodImpl(InliningOptions.ShortMethod)] private static float PredictionCostSpatial(ReadOnlySpan counts, int weight0, double expVal) { @@ -1125,15 +1546,21 @@ private static float PredictionCostSpatial(ReadOnlySpan counts, int weight0 return (float)(-0.1 * bits); } + /// + /// Computes the difference of two channel values, mod 256. + /// + /// The first value. + /// The value to subtract. + /// The difference. [MethodImpl(InliningOptions.ShortMethod)] private static byte NearLosslessDiff(byte a, byte b) => (byte)((a - b) & 0xff); + /// + /// Packs the color transform multipliers into a transform image pixel. The alpha is 255, bits 0-7 hold green-to-red, bits 8-15 + /// green-to-blue and bits 16-23 red-to-blue. + /// + /// The multipliers. + /// The transform image pixel. [MethodImpl(InliningOptions.ShortMethod)] private static uint MultipliersToColorCode(Vp8LMultipliers m) => 0xff000000u | ((uint)m.RedToBlue << 16) | ((uint)m.GreenToBlue << 8) | m.GreenToRed; - - [MethodImpl(InliningOptions.ShortMethod)] - private static int GetMin(int a, int b) => a > b ? b : a; - - [MethodImpl(InliningOptions.ShortMethod)] - private static int GetMax(int a, int b) => (a < b) ? b : a; } diff --git a/src/ImageSharp/Formats/Webp/Lossless/Vp8LBackwardReferences.cs b/src/ImageSharp/Formats/Webp/Lossless/Vp8LBackwardReferences.cs new file mode 100644 index 0000000000..0fb29e7792 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossless/Vp8LBackwardReferences.cs @@ -0,0 +1,148 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Buffers; +using System.Runtime.CompilerServices; +using SixLabors.ImageSharp.Memory; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossless; + +/// +/// A list of tokens (literals, cache indices and copies) for one image. +/// +/// +/// The tokens are stored in blocks of the same size. A block is allocated when the list first grows into it, and it stays for the next +/// pass, so the memory follows the number of tokens, not the number of pixels. No block is larger than a buffer of the allocator pool, so +/// the blocks of a large image come from the pool and do not cause unpooled memory. +/// +internal sealed class Vp8LBackwardReferences : IDisposable +{ + /// + /// The allocator of the blocks. + /// + private readonly MemoryAllocator memoryAllocator; + + /// + /// The allocated blocks, in list order. Each block holds tokens. + /// + private readonly List> blocks = []; + + /// + /// The number of tokens in each block. + /// + private readonly int blockSize; + + /// + /// The number of stored tokens. While a pass writes, it is the number of tokens in the full blocks. + /// + private int count; + + /// + /// Initializes a new instance of the class. + /// + /// The memory allocator. + /// The number of pixels. Each token covers at least one pixel, so this is the maximum number of tokens. + public Vp8LBackwardReferences(MemoryAllocator memoryAllocator, int pixels) + { + this.memoryAllocator = memoryAllocator; + + // The pool gives a full buffer for each allocation over the shared array pool limit, and the shared array pool keeps only a few + // arrays of one size. Thus a block of a large image has the pool buffer size. A small image needs one block of one token for + // each pixel at most. + this.blockSize = Math.Min(pixels, memoryAllocator.GetBufferCapacityInBytes() / Unsafe.SizeOf()); + } + + /// + /// Gets the number of blocks that hold the stored tokens. + /// + public int BlockCount => (this.count + this.blockSize - 1) / this.blockSize; + + /// + /// Gets the stored tokens of one block. + /// + /// The block index, from 0 to - 1. + /// The tokens. Only the last block can have fewer than the block size. + public Span GetBlock(int index) + { + int start = index * this.blockSize; + return this.blocks[index].GetSpan()[..Math.Min(this.blockSize, this.count - start)]; + } + + /// + /// Removes all tokens and starts a pass that writes new tokens. + /// + /// + /// The pass writes its tokens to the returned block from index 0. When the block is full, the pass calls + /// and continues at index 0 of the new block. At the end, the pass calls with the number of tokens in the last + /// block. Thus the pass gets the pooled memory one time for each block, not for each token. + /// + /// The first block. + public Span BeginWrite() + { + this.count = 0; + return this.GetOrAllocateBlock(0); + } + + /// + /// Keeps the full write block of a pass and gets the next block. + /// + /// The next block. + [MethodImpl(MethodImplOptions.NoInlining)] + public Span NextBlock() + { + this.count += this.blockSize; + return this.GetOrAllocateBlock(this.count / this.blockSize); + } + + /// + /// Ends a pass that writes new tokens. + /// + /// The number of tokens that the pass wrote to the last block. + public void EndWrite(int lastBlockCount) => this.count += lastBlockCount; + + /// + /// Removes all tokens. The blocks stay for the next pass. + /// + public void Clear() => this.count = 0; + + /// + /// Replaces the tokens of with a copy of the tokens of this list. + /// + /// The list that gets the tokens. It has the same block size. + public void CopyTo(Vp8LBackwardReferences destination) + { + int blockCount = this.BlockCount; + for (int i = 0; i < blockCount; i++) + { + this.GetBlock(i).CopyTo(destination.GetOrAllocateBlock(i)); + } + + destination.count = this.count; + } + + /// + public void Dispose() + { + foreach (IMemoryOwner block in this.blocks) + { + block.Dispose(); + } + + this.blocks.Clear(); + } + + /// + /// Gets a block, and allocates it when the list did not grow into it before. + /// + /// The block index. It is at most the number of allocated blocks, because the list grows one block at a time. + /// All tokens of the block. + private Span GetOrAllocateBlock(int index) + { + if (index == this.blocks.Count) + { + this.blocks.Add(this.memoryAllocator.Allocate(this.blockSize)); + } + + return this.blocks[index].GetSpan(); + } +} diff --git a/src/ImageSharp/Formats/Webp/Lossless/Vp8LBackwardRefs.cs b/src/ImageSharp/Formats/Webp/Lossless/Vp8LBackwardRefs.cs deleted file mode 100644 index 634fac5e82..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossless/Vp8LBackwardRefs.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -using System.Buffers; -using SixLabors.ImageSharp.Memory; - -namespace SixLabors.ImageSharp.Formats.Webp.Lossless; - -internal class Vp8LBackwardRefs : IDisposable -{ - private readonly IMemoryOwner refs; - private int count; - - public Vp8LBackwardRefs(MemoryAllocator memoryAllocator, int pixels) - { - this.refs = memoryAllocator.Allocate(pixels); - this.count = 0; - } - - public void Add(PixOrCopy pixOrCopy) => this.refs.Memory.Span[this.count++] = pixOrCopy; - - public void Clear() => this.count = 0; - - public Span.Enumerator GetEnumerator() => this.refs.Slice(0, this.count).GetEnumerator(); - - /// - public void Dispose() => this.refs.Dispose(); -} diff --git a/src/ImageSharp/Formats/Webp/Lossless/Vp8LBitEntropy.cs b/src/ImageSharp/Formats/Webp/Lossless/Vp8LBitEntropy.cs index 2ef8a75f56..a6257a54d7 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/Vp8LBitEntropy.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/Vp8LBitEntropy.cs @@ -6,25 +6,17 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; /// /// Holds bit entropy results and entropy-related functions. /// -internal class Vp8LBitEntropy +/// +/// The type is a value type, so a cost estimate keeps it on the stack. Each method that collects a population calls +/// first, so the default value is a valid start state. +/// +internal struct Vp8LBitEntropy { /// /// Not a trivial literal symbol. /// private const uint NonTrivialSym = 0xffffffff; - /// - /// Initializes a new instance of the class. - /// - public Vp8LBitEntropy() - { - this.Entropy = 0.0d; - this.Sum = 0; - this.NoneZeros = 0; - this.MaxVal = 0; - this.NoneZeroCode = NonTrivialSym; - } - /// /// Gets or sets the entropy. /// @@ -50,6 +42,9 @@ public Vp8LBitEntropy() /// public uint NoneZeroCode { get; set; } + /// + /// Sets all results to zero and the index of the last nonzero to the value for no trivial symbol. + /// public void Init() { this.Entropy = 0.0d; @@ -59,7 +54,12 @@ public void Init() this.NoneZeroCode = NonTrivialSym; } - public double BitsEntropyRefine() + /// + /// Mixes the entropy with the minimum cost of a Huffman code for the population. A population with at most one nonzero + /// value costs nothing. + /// + /// The refined entropy in bits. + public readonly double BitsEntropyRefine() { double mix; if (this.NoneZeros < 5) @@ -100,6 +100,11 @@ public double BitsEntropyRefine() return this.Entropy < minLimit ? minLimit : this.Entropy; } + /// + /// Gets the entropy for the distribution 'array', without the streak statistics. + /// + /// The population. + /// The number of entries to read. public void BitsEntropyUnrefined(ReadOnlySpan array, int n) { this.Init(); @@ -125,7 +130,10 @@ public void BitsEntropyUnrefined(ReadOnlySpan array, int n) /// /// Get the entropy for the distribution 'X'. /// - public void BitsEntropyUnrefined(ReadOnlySpan x, int length, Vp8LStreaks stats) + /// The population. + /// The number of entries to read. + /// Receives the streak statistics. It must start with zero counts. + public void BitsEntropyUnrefined(ReadOnlySpan x, int length, ref Vp8LStreaks stats) { int i; int iPrev = 0; @@ -138,16 +146,23 @@ public void BitsEntropyUnrefined(ReadOnlySpan x, int length, Vp8LStreaks s uint xi = x[i]; if (xi != xPrev) { - this.GetEntropyUnrefined(xi, i, ref xPrev, ref iPrev, stats); + this.GetEntropyUnrefined(xi, i, ref xPrev, ref iPrev, ref stats); } } - this.GetEntropyUnrefined(0, i, ref xPrev, ref iPrev, stats); + this.GetEntropyUnrefined(0, i, ref xPrev, ref iPrev, ref stats); this.Entropy += LosslessUtils.FastSLog2(this.Sum); } - public void GetCombinedEntropyUnrefined(ReadOnlySpan x, ReadOnlySpan y, int length, Vp8LStreaks stats) + /// + /// Gets the entropy for the sum of the distributions 'X' and 'Y', without computing the sum. + /// + /// The first population. + /// The second population. + /// The number of entries to read. + /// Receives the streak statistics. It must start with zero counts. + public void GetCombinedEntropyUnrefined(ReadOnlySpan x, ReadOnlySpan y, int length, ref Vp8LStreaks stats) { int i; int iPrev = 0; @@ -160,38 +175,24 @@ public void GetCombinedEntropyUnrefined(ReadOnlySpan x, ReadOnlySpan uint xy = x[i] + y[i]; if (xy != xyPrev) { - this.GetEntropyUnrefined(xy, i, ref xyPrev, ref iPrev, stats); + this.GetEntropyUnrefined(xy, i, ref xyPrev, ref iPrev, ref stats); } } - this.GetEntropyUnrefined(0, i, ref xyPrev, ref iPrev, stats); + this.GetEntropyUnrefined(0, i, ref xyPrev, ref iPrev, ref stats); this.Entropy += LosslessUtils.FastSLog2(this.Sum); } - public void GetEntropyUnrefined(ReadOnlySpan x, int length, Vp8LStreaks stats) - { - int i; - int iPrev = 0; - uint xPrev = x[0]; - - this.Init(); - - for (i = 1; i < length; i++) - { - uint xi = x[i]; - if (xi != xPrev) - { - this.GetEntropyUnrefined(xi, i, ref xPrev, ref iPrev, stats); - } - } - - this.GetEntropyUnrefined(0, i, ref xPrev, ref iPrev, stats); - - this.Entropy += LosslessUtils.FastSLog2(this.Sum); - } - - private void GetEntropyUnrefined(uint val, int i, ref uint valPrev, ref int iPrev, Vp8LStreaks stats) + /// + /// Adds the streak of equal values that ends before index to the entropy and the streak statistics. + /// + /// The value at index . It starts the next streak. + /// The index after the streak. + /// The value of the streak. Receives . + /// The first index of the streak. Receives . + /// The streak statistics to update. + private void GetEntropyUnrefined(uint val, int i, ref uint valPrev, ref int iPrev, ref Vp8LStreaks stats) { int streak = i - iPrev; @@ -209,8 +210,10 @@ private void GetEntropyUnrefined(uint val, int i, ref uint valPrev, ref int iPre } // Gather info for the Huffman cost. - stats.Counts[valPrev != 0 ? 1 : 0] += streak > 3 ? 1 : 0; - stats.Streaks[valPrev != 0 ? 1 : 0][streak > 3 ? 1 : 0] += streak; + int isNonZero = valPrev != 0 ? 1 : 0; + int isLong = streak > 3 ? 1 : 0; + stats.Counts[isNonZero] += isLong; + stats.Streaks[(isNonZero * 2) + isLong] += streak; valPrev = val; iPrev = i; diff --git a/src/ImageSharp/Formats/Webp/Lossless/Vp8LDecoder.cs b/src/ImageSharp/Formats/Webp/Lossless/Vp8LDecoder.cs index eae73054d8..b8d8ebe0c9 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/Vp8LDecoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/Vp8LDecoder.cs @@ -12,9 +12,6 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; /// internal class Vp8LDecoder : IDisposable { - // The header parse changes Width to the packed width of a color-indexed image. The pixel data needs the full image size. - private readonly int pixelCount; - /// /// Initializes a new instance of the class. /// @@ -24,7 +21,6 @@ public Vp8LDecoder(int width, int height) { this.Width = width; this.Height = height; - this.pixelCount = width * height; this.Metadata = new Vp8LMetadata(); } @@ -49,27 +45,56 @@ public Vp8LDecoder(int width, int height) public List Transforms { get; set; } /// - /// Gets the pixel data. + /// Gets the decoded ARGB values of the image stream, one row for each image row. A row has values. /// - public IMemoryOwner Pixels { get; private set; } + public Buffer2D Pixels { get; private set; } /// - /// Allocates the pixel data for the decode of the image stream. + /// Gets the palette index bytes of the paletted alpha path, one row for each image row. A row has bytes. + /// + public Buffer2D PaletteIndices { get; private set; } + + /// + /// Allocates the pixel data for the decode of the image stream. The headers set and before this call. /// /// - /// The header parse needs no pixel data, and it runs before the decoder creates the image. The decoder calls this method after it creates - /// the image. Thus the pixel data comes after the image buffer. + /// + /// As in the JPEG decoder, the rows are a from the pool. The pool serves it in blocks of whole rows, so a decode reuses the + /// memory of the decode before it. A contiguous buffer of a large image is larger than a pool block, and the allocator then gets new memory for each + /// decode. + /// + /// + /// The color indexing transform packs several pixels in one value, so can be less than the image width. The transforms expand the + /// rows in the batch cache, so the pixel data needs only the stream size. + /// + /// + /// The allocation is not clean. The decode writes each pixel of the rows that it keeps, and the transforms of a row read only that row and the rows + /// above it. Thus no value of the other rows reaches the image. + /// /// /// The memory allocator. public void AllocatePixels(MemoryAllocator memoryAllocator) - => this.Pixels = memoryAllocator.Allocate(this.pixelCount, AllocationOptions.Clean); + => this.Pixels = memoryAllocator.Allocate2D(this.Width, this.Height); + + /// + /// Allocates the palette index bytes of the paletted alpha path. The headers set and before this call. + /// + /// + /// The paletted path stores one palette index byte for each value, so it needs a quarter of the size of the ARGB pixel data. As for + /// , the rows come from the pool in blocks of whole rows. The allocation is not clean, because the decode writes each value of the + /// rows that it keeps. + /// + /// The memory allocator. + public void AllocatePaletteIndices(MemoryAllocator memoryAllocator) + => this.PaletteIndices = memoryAllocator.Allocate2D(this.Width, this.Height); /// public void Dispose() { - // A damaged image can stop after the header parse, before AllocatePixels runs. Then the pixel data does not exist. + // A damaged image can stop after the header parse, before the allocation runs. Then the pixel data does not exist. this.Pixels?.Dispose(); - this.Metadata?.HuffmanImage?.Dispose(); + this.PaletteIndices?.Dispose(); + this.Metadata?.Dispose(); if (this.Transforms != null) { diff --git a/src/ImageSharp/Formats/Webp/Lossless/Vp8LEncoder.cs b/src/ImageSharp/Formats/Webp/Lossless/Vp8LEncoder.cs index cee93b8abf..b52b91b302 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/Vp8LEncoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/Vp8LEncoder.cs @@ -6,7 +6,9 @@ using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; using SixLabors.ImageSharp.ColorProfiles; +using SixLabors.ImageSharp.Compression; using SixLabors.ImageSharp.Formats.Webp.BitWriter; using SixLabors.ImageSharp.Formats.Webp.Chunks; using SixLabors.ImageSharp.Formats.Webp.ColorConverters; @@ -25,13 +27,19 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; internal class Vp8LEncoder : IDisposable { /// - /// Scratch buffer to reduce allocations. + /// The code lengths of the Huffman code that stores the code lengths of a full Huffman code. /// - private InlineArray256 scratch; // mutable struct, don't make readonly + private readonly byte[] codeLengthBitDepth = new byte[WebpConstants.CodeLengthCodes]; - private readonly int[][] histoArgb = [new int[256], new int[256], new int[256], new int[256]]; + /// + /// The codes of the Huffman code that stores the code lengths of a full Huffman code. + /// + private readonly short[] codeLengthBitDepthSymbols = new short[WebpConstants.CodeLengthCodes]; - private readonly int[][] bestHisto = [new int[256], new int[256], new int[256], new int[256]]; + /// + /// The histogram of the code length tokens of a full Huffman code. + /// + private readonly uint[] codeLengthHistogram = new uint[WebpConstants.CodeLengthCodes + 1]; /// /// The to use for buffer allocations. @@ -44,9 +52,10 @@ internal class Vp8LEncoder : IDisposable private readonly Configuration configuration; /// - /// Maximum number of reference blocks the image will be segmented into. + /// The working copy of the input. A config that maps the palette, applies the near-lossless step, or is one of several configs + /// writes its working image here, because the input must stay unchanged for the next config. /// - private const int MaxRefsBlockPerImage = 16; + private Buffer2D workingCopy; /// /// A bit writer for writing lossless webp streams. @@ -64,8 +73,8 @@ internal class Vp8LEncoder : IDisposable private readonly WebpEncodingMethod method; /// - /// Flag indicating whether to preserve the exact RGB values under transparent area. Otherwise, discard this invisible - /// RGB information for better compression. + /// The mode for the RGB values of transparent pixels. sets all components + /// of each source pixel with zero alpha to zero before the encode. /// private readonly TransparentColorMode transparentColorMode; @@ -84,10 +93,19 @@ internal class Vp8LEncoder : IDisposable /// private readonly int nearLosslessQuality; + /// + /// A palette with fewer colors than this value maps the pixels with a linear search. A larger palette uses a hash table. + /// private const int ApplyPaletteGreedyMax = 4; + /// + /// The log2 of the number of entries in the hash table that maps a color to its palette index. + /// private const int PaletteInvSizeBits = 11; + /// + /// The number of entries in the hash table that maps a color to its palette index. + /// private const int PaletteInvSize = 1 << PaletteInvSizeBits; /// @@ -100,8 +118,7 @@ internal class Vp8LEncoder : IDisposable /// The encoding quality. /// Whether to skip metadata encoding. /// Quality/speed trade-off (0=fast, 6=slower-better). - /// Flag indicating whether to preserve the exact RGB values under transparent area. - /// Otherwise, discard this invisible RGB information for better compression. + /// The mode for the RGB values of transparent pixels. /// Indicating whether near lossless mode should be used. /// The near lossless quality. The range is 0 (maximum preprocessing) to 100 (no preprocessing, the default). public Vp8LEncoder( @@ -117,7 +134,6 @@ public Vp8LEncoder( int nearLosslessQuality) { int pixelCount = width * height; - int initialSize = pixelCount * 2; this.memoryAllocator = memoryAllocator; this.configuration = configuration; @@ -127,37 +143,67 @@ public Vp8LEncoder( this.transparentColorMode = transparentColorMode; this.nearLossless = nearLossless; this.nearLosslessQuality = Math.Clamp(nearLosslessQuality, 0, 100); - this.bitWriter = new Vp8LBitWriter(initialSize); - this.Bgra = memoryAllocator.Allocate(pixelCount); - this.EncodedData = memoryAllocator.Allocate(pixelCount); + + // The image planes come from the pool in buffers of whole rows, so a large image causes no unpooled memory. + this.Bgra = memoryAllocator.Allocate2D(width, height); + this.EncodedData = this.Bgra; this.Palette = memoryAllocator.Allocate(WebpConstants.MaxPaletteSize); - this.Refs = new Vp8LBackwardRefs[3]; - this.HashChain = new Vp8LHashChain(memoryAllocator, pixelCount); + this.Refs = new Vp8LBackwardReferences[4]; + this.HashChain = new Vp8LHashChain(memoryAllocator, width, height); for (int i = 0; i < this.Refs.Length; i++) { - this.Refs[i] = new Vp8LBackwardRefs(memoryAllocator, pixelCount); + this.Refs[i] = new Vp8LBackwardReferences(memoryAllocator, pixelCount); } } - // RFC 1951 will calm you down if you are worried about this funny sequence. - // This sequence is tuned from that, but more weighted for lower symbol count, - // and more spiking histograms. - // This uses C#'s compiler optimization to refer to assembly's static data directly. + /// + /// Defines a hash of a palette color for the table that maps a color to its palette index. + /// + private interface IPaletteHashOperator + { + /// + /// Hashes a color. + /// + /// The ARGB color. + /// The hash, less than . + public static abstract uint Hash(uint color); + } + + /// + /// Gets the order in which the code lengths of the code length code are stored. + /// + /// + /// The order starts from the code length code order of RFC 1951. It gives more weight to low symbol counts and to histograms with peaks. + /// private static ReadOnlySpan StorageOrder => [17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; - // This uses C#'s compiler optimization to refer to assembly's static data directly. - private static ReadOnlySpan Order => [1, 2, 0, 3]; + /// + /// Gets the histogram indices of the red and blue histograms of each entropy mode, from to + /// . Entry 2 * k is the red histogram of mode k, and entry 2 * k + 1 its blue histogram. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates no memory. + /// + private static ReadOnlySpan RedAndBlueHistogramPairs => + [ + (byte)HistogramIndex.HistoRed, (byte)HistogramIndex.HistoBlue, + (byte)HistogramIndex.HistoRedPred, (byte)HistogramIndex.HistoBluePred, + (byte)HistogramIndex.HistoRedSubGreen, (byte)HistogramIndex.HistoBlueSubGreen, + (byte)HistogramIndex.HistoRedPredSubGreen, (byte)HistogramIndex.HistoBluePredSubGreen, + (byte)HistogramIndex.HistoRed, (byte)HistogramIndex.HistoBlue + ]; /// - /// Gets the memory for the image data as packed bgra values. + /// Gets the input image as packed bgra values. The plane has the size of the current image. /// - public IMemoryOwner Bgra { get; } + public Buffer2D Bgra { get; private set; } /// - /// Gets the memory for the encoded output image data. + /// Gets the working image that the transforms change and the entropy coding reads. It has the current width. + /// It is when the transforms can change the input in place. Otherwise it is . /// - public IMemoryOwner EncodedData { get; } + public Buffer2D EncodedData { get; private set; } /// /// Gets or sets the scratch memory for bgra rows used for predictions. @@ -180,9 +226,9 @@ public Vp8LEncoder( public int TransformBits { get; set; } /// - /// Gets or sets the transform data. + /// Gets or sets the transform image of the predictor or the cross color transform. It has the size of the transform image. /// - public IMemoryOwner TransformData { get; set; } + public Buffer2D TransformData { get; set; } /// /// Gets or sets the cache bits. If equal to 0, don't use color cache. @@ -220,9 +266,10 @@ public Vp8LEncoder( public IMemoryOwner Palette { get; } /// - /// Gets the backward references. + /// Gets the four backward reference buffers. uses slot 0 for the references with a color cache, slot 1 for the + /// references without one, and slots 2 and 3 as working buffers and for the histogram image. /// - public Vp8LBackwardRefs[] Refs { get; } + public Vp8LBackwardReferences[] Refs { get; } /// /// Gets the hash chain. @@ -267,6 +314,16 @@ public WebpVp8X EncodeHeader(Image image, Stream stream, bool ha return vp8x; } + /// + /// Writes the chunks after the image data: the EXIF and XMP metadata, unless metadata is skipped. When the image has alpha and a VP8X header + /// was written, the method updates the alpha flag of that header. + /// + /// The pixel format. + /// The image that holds the metadata. + /// The VP8X header that was written, or the default value when no VP8X header was written. + /// Whether the encoded image has alpha. + /// The output stream. + /// The stream position before the encode started. public void EncodeFooter(Image image, in WebpVp8X vp8x, bool hasAlpha, Stream stream, long initialPosition) where TPixel : unmanaged, IPixel { @@ -292,7 +349,6 @@ public void EncodeFooter(Image image, in WebpVp8X vp8x, bool has /// Flag indicating, if an animation parameter is present. /// The return transform from sRGB to the encoded profile, or null. /// Reusable straight RGBA row scratch. - /// Reusable RGB transform scratch. /// A indicating whether the frame contains an alpha channel. public bool Encode( ImageFrame frame, @@ -301,12 +357,16 @@ public bool Encode( Stream stream, bool hasAnimation, ColorProfileConverter converter, - Span vectors, - Span rgb) + Span vectors) where TPixel : unmanaged, IPixel { // Convert image pixels to bgra array. - bool hasAlpha = this.ConvertPixelsToBgra(frame.PixelBuffer.GetRegion(bounds), converter, vectors, rgb); + bool hasAlpha = this.ConvertPixelsToBgra(frame.PixelBuffer.GetRegion(bounds), converter, vectors); + + // Start with room for 16 bits for each pixel, so most images need no growth. An animation encodes each frame with the same encoder, + // so the writer of the previous frame goes back to the pool first. + this.bitWriter?.Dispose(); + this.bitWriter = new Vp8LBitWriter(this.memoryAllocator, bounds.Width * bounds.Height * 2); // Write the image size. this.WriteImageSize(bounds.Width, bounds.Height); @@ -348,35 +408,40 @@ public bool Encode( /// /// Encodes the alpha image data using the webp lossless compression. /// - /// The type of the pixel. - /// The alpha-pixel data to encode from. - /// The destination buffer to write the encoded alpha data to. - /// The size of the compressed data in bytes. - /// If the size of the data is the same as the pixel count, the compression would not yield in smaller data and is left uncompressed. + /// + /// The caller fills with one packed pixel for each alpha value before the call. + /// Each pixel holds the alpha value in the green channel, and the other channels are zero. + /// ALPH stores coverage only, so no RGB profile applies to these pixels. + /// + /// The image width. + /// The image height. + /// Receives the size of the compressed data in bytes, or 0 when the method returns null. + /// + /// The compressed data, or null when the compressed data is not smaller than the pixel count. The caller owns and disposes the data. /// - public int EncodeAlphaImageData(Buffer2DRegion frame, IMemoryOwner alphaData) - where TPixel : unmanaged, IPixel + public IMemoryOwner EncodeAlphaImageData(int width, int height, out int size) { - int width = frame.Width; - int height = frame.Height; int pixelCount = width * height; - // Convert image pixels to bgra array. - // ALPH stores coverage only; its lossless compression must not apply the image's RGB profile. - this.ConvertPixelsToBgra(frame, null, [], []); + // Start with room for 1 bit for each alpha value. Alpha planes usually compress well, and the writer grows when necessary. + // A writer of an earlier encode goes back to the pool first. + this.bitWriter?.Dispose(); + this.bitWriter = new Vp8LBitWriter(this.memoryAllocator, pixelCount >> 3); // The image-stream will NOT contain any headers describing the image dimension, the dimension is already known. this.EncodeStream(width, height); this.bitWriter.Finish(); - int size = this.bitWriter.NumBytes; + size = this.bitWriter.NumBytes; if (size >= pixelCount) { // Compressing would not yield in smaller data -> leave the data uncompressed. - return pixelCount; + size = 0; + return null; } - this.bitWriter.WriteToBuffer(alphaData.GetSpan()); - return size; + IMemoryOwner data = this.memoryAllocator.Allocate(size); + this.bitWriter.WriteToBuffer(data.GetSpan()); + return data; } /// @@ -410,109 +475,137 @@ private void WriteAlphaAndVersion(bool hasAlpha) /// The image frame height. private void EncodeStream(int width, int height) { - Span bgra = this.Bgra.GetSpan(); - Span encodedData = this.EncodedData.GetSpan(); + Buffer2D bgra = this.Bgra; bool lowEffort = this.method == 0; // Analyze image (entropy, numPalettes etc). - CrunchConfig[] crunchConfigs = this.EncoderAnalyze(bgra, width, height, out bool redAndBlueAlwaysZero); + CrunchConfiguration[] crunchConfigs = this.EncoderAnalyze(bgra, width, height, out bool redAndBlueAlwaysZero); int bestSize = 0; - Vp8LBitWriter bitWriterInit = this.bitWriter; - Vp8LBitWriter bitWriterBest = this.bitWriter.Clone(); - bool isFirstConfig = true; - foreach (CrunchConfig crunchConfig in crunchConfigs) - { - bgra.CopyTo(encodedData); - const bool useCache = true; - this.UsePalette = crunchConfig.EntropyIdx is EntropyIx.Palette or EntropyIx.PaletteAndSpatial; - this.UseSubtractGreenTransform = crunchConfig.EntropyIdx is EntropyIx.SubGreen or EntropyIx.SpatialSubGreen; - this.UsePredictorTransform = crunchConfig.EntropyIdx is EntropyIx.Spatial or EntropyIx.SpatialSubGreen; - if (lowEffort) - { - this.UseCrossColorTransform = false; - } - else - { - this.UseCrossColorTransform = !redAndBlueAlwaysZero && this.UsePredictorTransform; - } - this.AllocateTransformBuffer(width, height); + // Each config restarts at the same write position. A clone has the same bytes before that position, so the position is valid for both writers. + (ulong Bits, int Used, int Cur) bitWriterInit = this.bitWriter.Position; - // Reset any parameter in the encoder that is set in the previous iteration. - this.CacheBits = 0; - this.ClearRefs(); + // A second writer keeps the best result only when more than one config is encoded. + // With one config, the result stays in the current writer, so no clone is necessary. + bool multipleConfigs = crunchConfigs.Length > 1; + Vp8LBitWriter bitWriterBest = multipleConfigs ? this.bitWriter.Clone() : null; - if (this.nearLossless) + // The encoder disposes its current writer. The second writer is released here, also when an encode throws. + try + { + bool isFirstConfig = true; + foreach (CrunchConfiguration crunchConfig in crunchConfigs) { + const bool useCache = true; + this.UsePalette = crunchConfig.EntropyIdx is EntropyIndex.Palette or EntropyIndex.PaletteAndSpatial; + this.UseSubtractGreenTransform = crunchConfig.EntropyIdx is EntropyIndex.SubGreen or EntropyIndex.SpatialSubGreen; + this.UsePredictorTransform = crunchConfig.EntropyIdx is EntropyIndex.Spatial or EntropyIndex.SpatialSubGreen; + if (lowEffort) + { + this.UseCrossColorTransform = false; + } + else + { + this.UseCrossColorTransform = !redAndBlueAlwaysZero && this.UsePredictorTransform; + } + + this.AllocateTransformBuffer(width, height); + + // Reset any parameter in the encoder that is set in the previous iteration. + this.CacheBits = 0; + this.ClearRefs(); + // Apply near-lossless preprocessing. - bool useNearLossless = this.nearLosslessQuality < 100 && !this.UsePalette && !this.UsePredictorTransform; + bool useNearLossless = this.nearLossless && this.nearLosslessQuality < 100 && !this.UsePalette && !this.UsePredictorTransform; if (useNearLossless) { - this.AllocateTransformBuffer(width, height); - // The encoder reads the working copy, so the adjusted pixels go there. - NearLosslessEnc.ApplyNearLossless(width, height, this.nearLosslessQuality, bgra, encodedData, width); + this.EncodedData = this.GetWorkingCopy(width, height); + NearLosslessEncoder.ApplyNearLossless(this.memoryAllocator, width, height, this.nearLosslessQuality, bgra, this.EncodedData); } - } - // Encode palette. - if (this.UsePalette) - { - this.EncodePalette(lowEffort); - this.MapImageFromPalette(width, height); + // Encode palette. + if (this.UsePalette) + { + this.EncodePalette(lowEffort); + this.MapImageFromPalette(width, height); - // If using a color cache, do not have it bigger than the number of colors. - if (useCache && this.PaletteSize < 1 << WebpConstants.MaxColorCacheBits) + // If using a color cache, do not have it bigger than the number of colors. + if (useCache && this.PaletteSize < 1 << WebpConstants.MaxColorCacheBits) + { + this.CacheBits = BitOperations.Log2((uint)this.PaletteSize) + 1; + } + } + else if (!useNearLossless) { - this.CacheBits = BitOperations.Log2((uint)this.PaletteSize) + 1; + // The transforms change the working image in place. With several configs, each config starts from a copy of the input. + // With one config, no later step reads the input, so the transforms change the input itself and no copy is necessary. + // The palette mapping and the near-lossless step read the input and write each pixel of the working copy, so they need no copy. + if (multipleConfigs) + { + this.EncodedData = this.GetWorkingCopy(width, height); + bgra.FastMemoryGroup.CopyTo(width, this.EncodedData.FastMemoryGroup, width, width, height); + } + else + { + this.EncodedData = bgra; + } } - } - // Apply transforms and write transform data. - if (this.UseSubtractGreenTransform) - { - this.ApplySubtractGreen(); - } + // Apply transforms and write transform data. + if (this.UseSubtractGreenTransform) + { + this.ApplySubtractGreen(); + } - if (this.UsePredictorTransform) - { - this.ApplyPredictFilter(this.CurrentWidth, height, lowEffort); - } + if (this.UsePredictorTransform) + { + this.ApplyPredictFilter(this.CurrentWidth, height, lowEffort); + } - if (this.UseCrossColorTransform) - { - this.ApplyCrossColorFilter(this.CurrentWidth, height, lowEffort); - } + if (this.UseCrossColorTransform) + { + this.ApplyCrossColorFilter(this.CurrentWidth, height, lowEffort); + } - this.bitWriter.PutBits(0, 1); // No more transforms. + this.bitWriter.PutBits(0, 1); // No more transforms. - // Encode and write the transformed image. - this.EncodeImage( - this.CurrentWidth, - height, - useCache, - crunchConfig, - this.CacheBits, - lowEffort); + // Encode and write the transformed image. + this.EncodeImage( + this.CurrentWidth, + height, + useCache, + crunchConfig, + this.CacheBits, + lowEffort); - // If we are better than what we already have. - if (isFirstConfig || this.bitWriter.NumBytes < bestSize) - { - bestSize = this.bitWriter.NumBytes; - BitWriterSwap(ref this.bitWriter, ref bitWriterBest); + if (multipleConfigs) + { + // If we are better than what we already have. + if (isFirstConfig || this.bitWriter.NumBytes < bestSize) + { + bestSize = this.bitWriter.NumBytes; + BitWriterSwap(ref this.bitWriter, ref bitWriterBest); + } + + // Reset the bit writer for the following iteration. + this.bitWriter.Reset(bitWriterInit); + } + + isFirstConfig = false; } - // Reset the bit writer for the following iteration if any. - if (crunchConfigs.Length > 1) + if (multipleConfigs) { - this.bitWriter.Reset(bitWriterInit); + // Keep the best result. The finally block releases the other writer. + BitWriterSwap(ref bitWriterBest, ref this.bitWriter); } - - isFirstConfig = false; } - - BitWriterSwap(ref bitWriterBest, ref this.bitWriter); + finally + { + bitWriterBest?.Dispose(); + } } /// @@ -521,36 +614,23 @@ private void EncodeStream(int width, int height) /// The type of the pixels. /// The frame pixel buffer to convert. /// The return transform from sRGB to the encoded profile, or null. - /// Reusable straight RGBA row scratch. - /// Reusable RGB transform scratch. + /// + /// Reusable straight RGBA row scratch. It is not empty when a profile transform or the clear of transparent pixels is required. + /// /// true, if the image is non opaque. - public bool ConvertPixelsToBgra(Buffer2DRegion pixels, ColorProfileConverter converter, Span vectors, Span rgb) + public bool ConvertPixelsToBgra(Buffer2DRegion pixels, ColorProfileConverter converter, Span vectors) where TPixel : unmanaged, IPixel { bool nonOpaque = false; - Span bgra = this.Bgra.GetSpan(); - Span bgraBytes = MemoryMarshal.Cast(bgra); - int widthBytes = pixels.Width * 4; - WebpColorConverterBase colorConverter = converter is null ? null : WebpColorConverterBase.GetConverter(WebpColorType.Rgba); + bool clearTransparentPixels = EncodingUtilities.ShouldReplaceTransparentPixels(this.transparentColorMode); + this.SetImageSize(pixels.Width, pixels.Height); for (int y = 0; y < pixels.Height; y++) { - Span rowSpan = pixels.DangerousGetRowSpan(y); - Span rowBytes = bgraBytes.Slice(y * widthBytes, widthBytes); - if (converter is null) - { - // Keep the direct byte conversion when no profile transform is required. - PixelOperations.Instance.ToBgra32Bytes(this.configuration, rowSpan, rowBytes, pixels.Width); - } - else - { - // Transform the source precision before final BGRA byte packing; alpha uses the pixel API. - colorConverter.ConvertRgbRow(this.configuration, rowSpan, converter, vectors, rgb, MemoryMarshal.Cast(rowBytes)); - } - + Span rowBgra = MemoryMarshal.Cast(this.Bgra.DangerousGetRowSpan(y)); + WebpColorConverterBase.ConvertSourceToBgra(this.configuration, pixels.DangerousGetRowSpan(y), converter, clearTransparentPixels, vectors, rowBgra); if (!nonOpaque) { - Span rowBgra = MemoryMarshal.Cast(rowBytes); nonOpaque = WebpCommonUtils.CheckNonOpaque(rowBgra); } } @@ -565,7 +645,8 @@ public bool ConvertPixelsToBgra(Buffer2DRegion pixels, ColorProf /// The image width. /// The image height. /// Indicates if red and blue are always zero. - private CrunchConfig[] EncoderAnalyze(ReadOnlySpan bgra, int width, int height, out bool redAndBlueAlwaysZero) + /// The configurations to try, each with its backward reference settings. + private CrunchConfiguration[] EncoderAnalyze(Buffer2D bgra, int width, int height, out bool redAndBlueAlwaysZero) { // Check if we only deal with a small number of colors and should use a palette. bool usePalette = this.AnalyzeAndCreatePalette(bgra, width, height); @@ -576,48 +657,48 @@ private CrunchConfig[] EncoderAnalyze(ReadOnlySpan bgra, int width, int he // Try out multiple LZ77 on images with few colors. int nlz77s = this.PaletteSize is > 0 and <= 16 ? 2 : 1; - EntropyIx entropyIdx = this.AnalyzeEntropy(bgra, width, height, usePalette, this.PaletteSize, this.TransformBits, out redAndBlueAlwaysZero); + EntropyIndex entropyIdx = this.AnalyzeEntropy(bgra, width, height, usePalette, this.PaletteSize, this.TransformBits, out redAndBlueAlwaysZero); bool doNotCache = false; - List crunchConfigs = []; + List crunchConfigs = []; if (this.method == WebpEncodingMethod.BestQuality && this.quality == 100) { doNotCache = true; // Go brute force on all transforms. - foreach (EntropyIx entropyIx in Enum.GetValues()) + for (EntropyIndex entropyIx = EntropyIndex.Direct; entropyIx < EntropyIndex.NumEntropyIx; entropyIx++) { // We can only apply kPalette or kPaletteAndSpatial if we can indeed use a palette. - if ((entropyIx != EntropyIx.Palette && entropyIx != EntropyIx.PaletteAndSpatial) || usePalette) + if ((entropyIx != EntropyIndex.Palette && entropyIx != EntropyIndex.PaletteAndSpatial) || usePalette) { - crunchConfigs.Add(new CrunchConfig { EntropyIdx = entropyIx }); + crunchConfigs.Add(new CrunchConfiguration { EntropyIdx = entropyIx }); } } } else { // Only choose the guessed best transform. - crunchConfigs.Add(new CrunchConfig { EntropyIdx = entropyIdx }); + crunchConfigs.Add(new CrunchConfiguration { EntropyIdx = entropyIdx }); if (this.quality >= 75 && this.method == WebpEncodingMethod.Level5) { // Test with and without color cache. doNotCache = true; // If we have a palette, also check in combination with spatial. - if (entropyIdx == EntropyIx.Palette) + if (entropyIdx == EntropyIndex.Palette) { - crunchConfigs.Add(new CrunchConfig { EntropyIdx = EntropyIx.PaletteAndSpatial }); + crunchConfigs.Add(new CrunchConfiguration { EntropyIdx = EntropyIndex.PaletteAndSpatial }); } } } // Fill in the different LZ77s. - foreach (CrunchConfig crunchConfig in crunchConfigs) + foreach (CrunchConfiguration crunchConfig in crunchConfigs) { for (int j = 0; j < nlz77s; j++) { - crunchConfig.SubConfigs.Add(new CrunchSubConfig + crunchConfig.SubConfigs.Add(new CrunchSubConfiguration { Lz77 = j == 0 ? (int)Vp8LLz77Type.Lz77Standard | (int)Vp8LLz77Type.Lz77Rle : (int)Vp8LLz77Type.Lz77Box, DoNotCache = doNotCache @@ -628,13 +709,25 @@ private CrunchConfig[] EncoderAnalyze(ReadOnlySpan bgra, int width, int he return [.. crunchConfigs]; } - private void EncodeImage(int width, int height, bool useCache, CrunchConfig config, int cacheBits, bool lowEffort) + /// + /// Encodes the transformed pixels with entropy coding: the color cache, the entropy image, the Huffman codes and the coded pixels. + /// When the configuration has more than one backward reference setting, the method keeps the smallest result. + /// + /// The image width. + /// The image height. + /// Whether a color cache can be used. + /// The configuration with the backward reference settings to try. + /// The maximum number of color cache bits. 0 selects the largest cache size. + /// Whether to use the fast, low effort search. + private void EncodeImage(int width, int height, bool useCache, CrunchConfiguration config, int cacheBits, bool lowEffort) { // bgra data with transformations applied. - Span bgra = this.EncodedData.GetSpan(); + Buffer2D bgra = this.EncodedData; int histogramImageXySize = LosslessUtils.SubSampleSize(width, this.HistoBits) * LosslessUtils.SubSampleSize(height, this.HistoBits); - Span histogramSymbols = histogramImageXySize <= 64 ? stackalloc ushort[histogramImageXySize] : new ushort[histogramImageXySize]; - Span huffTree = stackalloc HuffmanTree[3 * WebpConstants.CodeLengthCodes]; + + // No clear: the histogram analysis writes the symbol of each histogram tile before any read. + using IMemoryOwner histogramSymbolsBuffer = this.memoryAllocator.Allocate(histogramImageXySize); + Span histogramSymbols = histogramSymbolsBuffer.GetSpan(); if (useCache) { @@ -651,140 +744,189 @@ private void EncodeImage(int width, int height, bool useCache, CrunchConfig conf // Calculate backward references from BGRA image. this.HashChain.Fill(bgra, this.quality, width, height, lowEffort); - Vp8LBitWriter bitWriterBest = config.SubConfigs.Count > 1 ? this.bitWriter.Clone() : this.bitWriter; - Vp8LBitWriter bwInit = this.bitWriter; - bool isFirstIteration = true; - foreach (CrunchSubConfig subConfig in config.SubConfigs) - { - Vp8LBackwardRefs refsBest = BackwardReferenceEncoder.GetBackwardReferences( - width, - height, - bgra, - this.quality, - subConfig.Lz77, - ref cacheBits, - this.memoryAllocator, - this.HashChain, - this.Refs[0], - this.Refs[1]); - - // Keep the best references aside and use the other element from the first - // two as a temporary for later usage. - Vp8LBackwardRefs refsTmp = this.Refs[refsBest.Equals(this.Refs[0]) ? 1 : 0]; - - this.bitWriter.Reset(bwInit); - using OwnedVp8LHistogram tmpHisto = OwnedVp8LHistogram.Create(this.memoryAllocator, cacheBits); - using Vp8LHistogramSet histogramImage = new(this.memoryAllocator, histogramImageXySize, cacheBits); - - // Build histogram image and symbols from backward references. - HistogramEncoder.GetHistoImageSymbols( - this.memoryAllocator, - width, - height, - refsBest, - this.quality, - this.HistoBits, - cacheBits, - histogramImage, - tmpHisto, - histogramSymbols); - - // Create Huffman bit lengths and codes for each histogram image. - int histogramImageSize = histogramImage.Count; - int bitArraySize = 5 * histogramImageSize; - HuffmanTreeCode[] huffmanCodes = new HuffmanTreeCode[bitArraySize]; - - GetHuffBitLengthsAndCodes(histogramImage, huffmanCodes); - - // Color Cache parameters. - if (cacheBits > 0) - { - this.bitWriter.PutBits(1, 1); - this.bitWriter.PutBits((uint)cacheBits, 4); - } - else - { - this.bitWriter.PutBits(0, 1); - } + // The histogram image has its own hash chain, so the hash chain of the image stays valid for the next settings. + int histogramWidth = LosslessUtils.SubSampleSize(width, this.HistoBits); + int histogramHeight = LosslessUtils.SubSampleSize(height, this.HistoBits); + using Vp8LHashChain histogramHashChain = new(this.memoryAllocator, histogramWidth, histogramHeight); + + // Several results are compared when there are several settings, or when a setting also tries no color cache. + bool multipleResults = config.SubConfigs.Count > 1 || config.SubConfigs[0].DoNotCache; + Vp8LBitWriter bitWriterBest = multipleResults ? this.bitWriter.Clone() : this.bitWriter; + (ulong Bits, int Used, int Cur) bwInit = this.bitWriter.Position; - // Huffman image + meta huffman. - bool writeHistogramImage = histogramImageSize > 1; - this.bitWriter.PutBits((uint)(writeHistogramImage ? 1 : 0), 1); - if (writeHistogramImage) + // With several results, the two writers are different objects. The encoder disposes its current writer, so the second writer is + // released here when an encode throws. + try + { + bool isFirstIteration = true; + foreach (CrunchSubConfiguration subConfig in config.SubConfigs) { - using IMemoryOwner histogramBgraBuffer = this.memoryAllocator.Allocate(histogramImageXySize); - Span histogramBgra = histogramBgraBuffer.GetSpan(); - int maxIndex = 0; - for (int i = 0; i < histogramImageXySize; i++) + // Each setting starts from the same maximum cache size. Slot 0 gets the references with the best color cache, and slot 1 the + // references without a color cache. + BackwardReferenceEncoder.GetBackwardReferences( + width, + height, + bgra, + this.quality, + subConfig.Lz77, + cacheBits, + subConfig.DoNotCache, + this.memoryAllocator, + this.HashChain, + this.Refs, + out int cacheBitsBest); + + for (int iCache = 0; iCache < (subConfig.DoNotCache ? 2 : 1); iCache++) { - int symbolIndex = histogramSymbols[i] & 0xffff; - histogramBgra[i] = (uint)(symbolIndex << 8); - if (symbolIndex >= maxIndex) + // When the best cache size is 0, the first pass already encoded the references without a color cache. + if (iCache == 1 && cacheBitsBest == 0) { - maxIndex = symbolIndex + 1; + break; } - } - - histogramImageSize = maxIndex; - this.bitWriter.PutBits((uint)(this.HistoBits - 2), 3); - this.EncodeImageNoHuffman( - histogramBgra, - this.HashChain, - refsTmp, - this.Refs[2], - LosslessUtils.SubSampleSize(width, this.HistoBits), - LosslessUtils.SubSampleSize(height, this.HistoBits), - this.quality, - lowEffort); - } + int cacheBitsTmp = iCache == 0 ? cacheBitsBest : 0; + Vp8LBackwardReferences refsBest = this.Refs[iCache]; + + this.bitWriter.Reset(bwInit); + using OwnedVp8LHistogram tmpHisto = OwnedVp8LHistogram.Create(this.memoryAllocator, cacheBitsTmp); + using Vp8LHistogramSet histogramImage = new(this.memoryAllocator, histogramImageXySize, cacheBitsTmp, AllocationOptions.None, false); + + // Build histogram image and symbols from backward references. + HistogramEncoder.GetHistoImageSymbols( + this.memoryAllocator, + width, + height, + refsBest, + this.quality, + this.HistoBits, + cacheBitsTmp, + histogramImage, + tmpHisto, + histogramSymbols); + + // Create Huffman bit lengths and codes for each histogram image. + // The histogram image is written while these codes are in use. The sub-image encode creates its own code set. + int histogramImageSize = histogramImage.Count; + int codeCount = 5 * histogramImageSize; + using IMemoryOwner codeOffsetsBuffer = this.memoryAllocator.Allocate(codeCount + 1); + Span codeOffsets = codeOffsetsBuffer.GetSpan()[..(codeCount + 1)]; + int symbolCount = GetHuffmanCodeOffsets(histogramImage, codeOffsets, out int maxNumSymbols); + + // The tree creation leaves the code length of an unused symbol unchanged, so the code lengths start at zero. + // No clear for the codes: the tree creation writes the code of each symbol. + using IMemoryOwner codeLengthsBuffer = this.memoryAllocator.Allocate(symbolCount, AllocationOptions.Clean); + using IMemoryOwner codesBuffer = this.memoryAllocator.Allocate(symbolCount); + Span codeLengths = codeLengthsBuffer.GetSpan()[..symbolCount]; + Span codes = codesBuffer.GetSpan()[..symbolCount]; + + // The tree creation scratch serves the image codes and the code length codes. A code never has more tokens than symbols. + // No clear: the tree creation clears the RLE flags it uses and writes each tree node and token before it reads it. + using IMemoryOwner bufRleBuffer = this.memoryAllocator.Allocate(maxNumSymbols); + using IMemoryOwner huffTreeBuffer = this.memoryAllocator.Allocate(3 * maxNumSymbols); + using IMemoryOwner tokensBuffer = this.memoryAllocator.Allocate(maxNumSymbols); + Span bufRle = bufRleBuffer.GetSpan(); + Span huffTree = huffTreeBuffer.GetSpan(); + Span tokens = tokensBuffer.GetSpan(); + + GetHuffBitLengthsAndCodes(histogramImage, codeOffsets, codeLengths, codes, bufRle, huffTree); + + // Color Cache parameters. + if (cacheBitsTmp > 0) + { + this.bitWriter.PutBits(1, 1); + this.bitWriter.PutBits((uint)cacheBitsTmp, 4); + } + else + { + this.bitWriter.PutBits(0, 1); + } - // Store Huffman codes. - // Find maximum number of symbols for the huffman tree-set. - int maxTokens = 0; - for (int i = 0; i < 5 * histogramImageSize; i++) - { - HuffmanTreeCode codes = huffmanCodes[i]; - if (maxTokens < codes.NumSymbols) - { - maxTokens = codes.NumSymbols; - } - } + // Huffman image + meta huffman. + bool writeHistogramImage = histogramImageSize > 1; + this.bitWriter.PutBits((uint)(writeHistogramImage ? 1 : 0), 1); + if (writeHistogramImage) + { + using Buffer2D histogramBgra = this.memoryAllocator.Allocate2D(histogramWidth, histogramHeight); + int maxIndex = 0; + for (int y = 0; y < histogramHeight; y++) + { + Span histogramRow = histogramBgra.DangerousGetRowSpan(y); + ReadOnlySpan symbolRow = histogramSymbols.Slice(y * histogramWidth, histogramWidth); + for (int x = 0; x < histogramWidth; x++) + { + int symbolIndex = symbolRow[x] & 0xffff; + histogramRow[x] = (uint)(symbolIndex << 8); + if (symbolIndex >= maxIndex) + { + maxIndex = symbolIndex + 1; + } + } + } + + histogramImageSize = maxIndex; + + this.bitWriter.PutBits((uint)(this.HistoBits - 2), 3); + this.EncodeImageNoHuffman( + histogramBgra, + histogramHashChain, + this.Refs.AsSpan(2, 2), + histogramWidth, + histogramHeight, + this.quality, + lowEffort); + } - HuffmanTreeToken[] tokens = new HuffmanTreeToken[maxTokens]; - for (int i = 0; i < tokens.Length; i++) - { - tokens[i] = new HuffmanTreeToken(); - } + // Store Huffman codes. + for (int i = 0; i < 5 * histogramImageSize; i++) + { + int start = codeOffsets[i]; + int length = codeOffsets[i + 1] - start; + Span codeLengthsOfCode = codeLengths.Slice(start, length); + this.StoreHuffmanCode(huffTree, bufRle, tokens, codeLengthsOfCode); + ClearHuffmanTreeIfOnlyOneSymbol(codeLengthsOfCode, codes.Slice(start, length)); + } - for (int i = 0; i < 5 * histogramImageSize; i++) - { - HuffmanTreeCode codes = huffmanCodes[i]; - this.StoreHuffmanCode(huffTree, tokens, codes); - ClearHuffmanTreeIfOnlyOneSymbol(codes); - } + // Store actual literals. + this.StoreImageToBitMask(width, this.HistoBits, refsBest, histogramSymbols, codeOffsets, codeLengths, codes); - // Store actual literals. - this.StoreImageToBitMask(width, this.HistoBits, refsBest, histogramSymbols, huffmanCodes); + // Keep track of the smallest image so far. + if (isFirstIteration || (bitWriterBest != null && this.bitWriter.NumBytes < bitWriterBest.NumBytes)) + { + (bitWriterBest, this.bitWriter) = (this.bitWriter, bitWriterBest); + } - // Keep track of the smallest image so far. - if (isFirstIteration || (bitWriterBest != null && this.bitWriter.NumBytes < bitWriterBest.NumBytes)) + isFirstIteration = false; + } + } + } + catch + { + if (multipleResults) { - (bitWriterBest, this.bitWriter) = (this.bitWriter, bitWriterBest); + bitWriterBest.Dispose(); } - isFirstIteration = false; + throw; + } + + if (multipleResults) + { + // The writers are different objects here. Release the writer that does not hold the best result. + this.bitWriter.Dispose(); } this.bitWriter = bitWriterBest; } /// - /// Save the palette to the bitstream. + /// Writes the palette to the bitstream as a sub-image of the differences between consecutive palette entries. /// + /// Whether to use the fast, low effort search. private void EncodePalette(bool lowEffort) { - Span tmpPalette = stackalloc uint[WebpConstants.MaxPaletteSize]; + // The differences of up to 256 colors take 1 KB, so they come from the allocator. The clear keeps the entries after the palette at zero. + using IMemoryOwner tmpPaletteBuffer = this.memoryAllocator.Allocate(WebpConstants.MaxPaletteSize, AllocationOptions.Clean); + Span tmpPalette = tmpPaletteBuffer.GetSpan(); int paletteSize = this.PaletteSize; Span palette = this.Palette.Memory.Span; this.bitWriter.PutBits(WebpConstants.TransformPresent, 1); @@ -796,7 +938,10 @@ private void EncodePalette(bool lowEffort) } tmpPalette[0] = palette[0]; - this.EncodeImageNoHuffman(tmpPalette, this.HashChain, this.Refs[0], this.Refs[1], width: paletteSize, height: 1, quality: 20, lowEffort); + + // The palette sub-image is one row of paletteSize pixels, encoded with quality 20. The plane wraps the pooled row. + using Buffer2D paletteImage = Buffer2D.WrapMemory(tmpPaletteBuffer.Memory[..paletteSize], paletteSize, 1); + this.EncodeImageNoHuffman(paletteImage, this.HashChain, this.Refs.AsSpan(0, 2), paletteSize, 1, 20, lowEffort); } /// @@ -806,9 +951,22 @@ private void ApplySubtractGreen() { this.bitWriter.PutBits(WebpConstants.TransformPresent, 1); this.bitWriter.PutBits((uint)Vp8LTransformType.SubtractGreen, 2); - LosslessUtils.SubtractGreenFromBlueAndRed(this.EncodedData.GetSpan()); + + // The transform changes each pixel on its own, so each buffer of the plane is one call. The plane has the image size. + MemoryGroup group = this.EncodedData.FastMemoryGroup; + for (int i = 0; i < group.Count; i++) + { + LosslessUtils.SubtractGreenFromBlueAndRed(group[i].Span); + } } + /// + /// Applies the predictor transform to the pixel data and writes the transform with its predictor image to the bitstream. + /// Near lossless quantization of the residuals is disabled when a palette is used. + /// + /// The image width. + /// The image height. + /// Whether to use one fixed predictor for all tiles. private void ApplyPredictFilter(int width, int height, bool lowEffort) { // We disable near-lossless quantization if palette is used. @@ -816,16 +974,20 @@ private void ApplyPredictFilter(int width, int height, bool lowEffort) int predBits = this.TransformBits; int transformWidth = LosslessUtils.SubSampleSize(width, predBits); int transformHeight = LosslessUtils.SubSampleSize(height, predBits); + this.SetTransformImageSize(transformWidth, transformHeight); + + // Three groups of alpha, red, green and blue histograms: the accumulated counts, which start at zero, the counts of the current mode + // and the counts of the best mode. + using IMemoryOwner histogramsBuffer = this.memoryAllocator.Allocate(3 * PredictorEncoder.HistogramGroupSize, AllocationOptions.Clean); PredictorEncoder.ResidualImage( width, height, predBits, - this.EncodedData.GetSpan(), + this.EncodedData, this.BgraScratch.GetSpan(), - this.TransformData.GetSpan(), - this.histoArgb, - this.bestHisto, + this.TransformData, + histogramsBuffer.GetSpan(), this.nearLossless, nearLosslessStrength, this.transparentColorMode, @@ -837,127 +999,159 @@ private void ApplyPredictFilter(int width, int height, bool lowEffort) this.bitWriter.PutBits((uint)(predBits - 2), 3); this.EncodeImageNoHuffman( - this.TransformData.GetSpan(), + this.TransformData, this.HashChain, - this.Refs[0], - this.Refs[1], + this.Refs.AsSpan(0, 2), transformWidth, transformHeight, this.quality, lowEffort); } + /// + /// Applies the color transform to the pixel data and writes the transform with its multiplier image to the bitstream. + /// + /// The image width. + /// The image height. + /// Whether to use the fast, low effort search for the multiplier image. private void ApplyCrossColorFilter(int width, int height, bool lowEffort) { int colorTransformBits = this.TransformBits; int transformWidth = LosslessUtils.SubSampleSize(width, colorTransformBits); int transformHeight = LosslessUtils.SubSampleSize(height, colorTransformBits); + this.SetTransformImageSize(transformWidth, transformHeight); + + // The accumulated red and blue histograms, which start at zero, and the histogram of the tile that is evaluated. + using IMemoryOwner histogramsBuffer = this.memoryAllocator.Allocate(3 * 256, AllocationOptions.Clean); PredictorEncoder.ColorSpaceTransform( + this.memoryAllocator, width, height, colorTransformBits, this.quality, - this.EncodedData.GetSpan(), - this.TransformData.GetSpan(), - this.scratch); + this.EncodedData, + this.TransformData, + histogramsBuffer.GetSpan()); this.bitWriter.PutBits(WebpConstants.TransformPresent, 1); this.bitWriter.PutBits((uint)Vp8LTransformType.CrossColorTransform, 2); this.bitWriter.PutBits((uint)(colorTransformBits - 2), 3); this.EncodeImageNoHuffman( - this.TransformData.GetSpan(), + this.TransformData, this.HashChain, - this.Refs[0], - this.Refs[1], + this.Refs.AsSpan(0, 2), transformWidth, transformHeight, this.quality, lowEffort); } + /// + /// Encodes a sub-image, such as a transform image or the entropy image, with one set of Huffman codes, no color cache and no entropy image. + /// + /// The pixels of the sub-image. + /// The hash chain to fill for the sub-image. + /// Two backward reference buffers. Slot 0 gets the references of the sub-image. + /// The sub-image width. + /// The sub-image height. + /// The encoding quality, from 0 to 100. + /// Whether to use the fast, low effort search. private void EncodeImageNoHuffman( - ReadOnlySpan bgra, + Buffer2D bgra, Vp8LHashChain hashChain, - Vp8LBackwardRefs refsTmp1, - Vp8LBackwardRefs refsTmp2, + Span refs, int width, int height, uint quality, bool lowEffort) { int cacheBits = 0; - ushort[] histogramSymbols = new ushort[1]; // Only one tree, one symbol. - - HuffmanTreeCode[] huffmanCodes = new HuffmanTreeCode[5]; - Span huffTree = stackalloc HuffmanTree[3 * WebpConstants.CodeLengthCodes]; + ReadOnlySpan histogramSymbols = [0]; // Only one tree, one symbol. // Calculate backward references from the image pixels. hashChain.Fill(bgra, quality, width, height, lowEffort); - Vp8LBackwardRefs refs = BackwardReferenceEncoder.GetBackwardReferences( + BackwardReferenceEncoder.GetBackwardReferences( width, height, bgra, quality, (int)Vp8LLz77Type.Lz77Standard | (int)Vp8LLz77Type.Lz77Rle, - ref cacheBits, + cacheBits, + false, this.memoryAllocator, hashChain, - refsTmp1, - refsTmp2); + refs, + out cacheBits); // Build histogram image and symbols from backward references. - using Vp8LHistogramSet histogramImage = new(this.memoryAllocator, refs, 1, cacheBits); - - // Create Huffman bit lengths and codes for each histogram image. - GetHuffBitLengthsAndCodes(histogramImage, huffmanCodes); + using Vp8LHistogramSet histogramImage = new(this.memoryAllocator, refs[0], 1, cacheBits); + + // Create Huffman bit lengths and codes for each histogram image. The sub-image has its own codes, so the histogram image can be + // written while the codes of the main image are in use. + int codeCount = 5 * histogramImage.Count; + using IMemoryOwner codeOffsetsBuffer = this.memoryAllocator.Allocate(codeCount + 1); + Span codeOffsets = codeOffsetsBuffer.GetSpan()[..(codeCount + 1)]; + int symbolCount = GetHuffmanCodeOffsets(histogramImage, codeOffsets, out int maxNumSymbols); + + // The tree creation leaves the code length of an unused symbol unchanged, so the code lengths start at zero. + // No clear for the codes: the tree creation writes the code of each symbol. + using IMemoryOwner codeLengthsBuffer = this.memoryAllocator.Allocate(symbolCount, AllocationOptions.Clean); + using IMemoryOwner codesBuffer = this.memoryAllocator.Allocate(symbolCount); + Span codeLengths = codeLengthsBuffer.GetSpan()[..symbolCount]; + Span codes = codesBuffer.GetSpan()[..symbolCount]; + + // The tree creation scratch serves the image codes and the code length codes. A code never has more tokens than symbols. + // No clear: the tree creation clears the RLE flags it uses and writes each tree node and token before it reads it. + using IMemoryOwner bufRleBuffer = this.memoryAllocator.Allocate(maxNumSymbols); + using IMemoryOwner huffTreeBuffer = this.memoryAllocator.Allocate(3 * maxNumSymbols); + using IMemoryOwner tokensBuffer = this.memoryAllocator.Allocate(maxNumSymbols); + Span bufRle = bufRleBuffer.GetSpan(); + Span huffTree = huffTreeBuffer.GetSpan(); + Span tokens = tokensBuffer.GetSpan(); + + GetHuffBitLengthsAndCodes(histogramImage, codeOffsets, codeLengths, codes, bufRle, huffTree); // No color cache, no Huffman image. this.bitWriter.PutBits(0, 1); - // Find maximum number of symbols for the huffman tree-set. - int maxTokens = 0; - for (int i = 0; i < 5; i++) - { - HuffmanTreeCode codes = huffmanCodes[i]; - if (maxTokens < codes.NumSymbols) - { - maxTokens = codes.NumSymbols; - } - } - - HuffmanTreeToken[] tokens = new HuffmanTreeToken[maxTokens]; - for (int i = 0; i < tokens.Length; i++) - { - tokens[i] = new HuffmanTreeToken(); - } - // Store Huffman codes. - for (int i = 0; i < 5; i++) + for (int i = 0; i < codeCount; i++) { - HuffmanTreeCode codes = huffmanCodes[i]; - this.StoreHuffmanCode(huffTree, tokens, codes); - ClearHuffmanTreeIfOnlyOneSymbol(codes); + int start = codeOffsets[i]; + int length = codeOffsets[i + 1] - start; + Span codeLengthsOfCode = codeLengths.Slice(start, length); + this.StoreHuffmanCode(huffTree, bufRle, tokens, codeLengthsOfCode); + ClearHuffmanTreeIfOnlyOneSymbol(codeLengthsOfCode, codes.Slice(start, length)); } // Store actual literals. - this.StoreImageToBitMask(width, 0, refs, histogramSymbols, huffmanCodes); + this.StoreImageToBitMask(width, 0, refs[0], histogramSymbols, codeOffsets, codeLengths, codes); } - private void StoreHuffmanCode(Span huffTree, HuffmanTreeToken[] tokens, HuffmanTreeCode huffmanCode) + /// + /// Writes one Huffman code to the bitstream. A code with at most two used symbols, each less than 256, uses the simple code form. + /// Other codes use the normal code form. + /// + /// A scratch buffer for the tree nodes of the code length code, with at least 57 entries. + /// A scratch buffer for the RLE flags of the code length code, with at least 19 entries. + /// A scratch buffer for the code length tokens, with at least one entry for each symbol of the code. + /// The code lengths of the Huffman code to write. The decoder makes the codes from the code lengths. + private void StoreHuffmanCode(Span huffTree, Span bufRle, Span tokens, ReadOnlySpan codeLengths) { + // The first two used symbols. The simple code form needs only those. A new local is zero. int count = 0; - Span symbols = this.scratch[..2]; - symbols.Clear(); + InlineArray2 symbolsBuffer = default; + Span symbols = symbolsBuffer; const int maxBits = 8; const int maxSymbol = 1 << maxBits; // Check whether it's a small tree. - for (int i = 0; i < huffmanCode.NumSymbols && count < 3; i++) + for (int i = 0; i < codeLengths.Length && count < 3; i++) { - if (huffmanCode.CodeLengths[i] != 0) + if (codeLengths[i] != 0) { if (count < 2) { @@ -996,35 +1190,39 @@ private void StoreHuffmanCode(Span huffTree, HuffmanTreeToken[] tok } else { - this.StoreFullHuffmanCode(huffTree, tokens, huffmanCode); + this.StoreFullHuffmanCode(huffTree, bufRle, tokens, codeLengths); } } - private void StoreFullHuffmanCode(Span huffTree, HuffmanTreeToken[] tokens, HuffmanTreeCode tree) + /// + /// Writes one Huffman code in the normal code form. The code lengths become tokens, and the tokens are coded with a code length code. + /// When the trailing zero tokens cost more than 12 bits, the method writes the token count and omits them. + /// + /// A scratch buffer for the tree nodes of the code length code, with at least 57 entries. + /// A scratch buffer for the RLE flags of the code length code, with at least 19 entries. + /// A scratch buffer for the code length tokens, with at least one entry for each symbol of the code. + /// The code lengths of the Huffman code to write. + private void StoreFullHuffmanCode(Span huffTree, Span bufRle, Span tokens, ReadOnlySpan codeLengths) { - // TODO: Allocations. This method is called in a loop. + // The scratch arrays are reused for each code. The tree creation reads zero code lengths for unused symbols, + // and the histogram counts from zero, so both are cleared first. The tree creation clears the RLE flags and writes all codes. int i; - byte[] codeLengthBitDepth = new byte[WebpConstants.CodeLengthCodes]; - short[] codeLengthBitDepthSymbols = new short[WebpConstants.CodeLengthCodes]; - HuffmanTreeCode huffmanCode = new() - { - NumSymbols = WebpConstants.CodeLengthCodes, - CodeLengths = codeLengthBitDepth, - Codes = codeLengthBitDepthSymbols - }; + byte[] codeLengthBitDepth = this.codeLengthBitDepth; + uint[] histogram = this.codeLengthHistogram; + Array.Clear(codeLengthBitDepth); + Array.Clear(histogram); + short[] codeLengthBitDepthSymbols = this.codeLengthBitDepthSymbols; this.bitWriter.PutBits(0, 1); - int numTokens = HuffmanUtils.CreateCompressedHuffmanTree(tree, tokens); - uint[] histogram = new uint[WebpConstants.CodeLengthCodes + 1]; - bool[] bufRle = new bool[WebpConstants.CodeLengthCodes + 1]; + int numTokens = HuffmanUtils.CreateCompressedHuffmanTree(codeLengths, tokens); for (i = 0; i < numTokens; i++) { histogram[tokens[i].Code]++; } - HuffmanUtils.CreateHuffmanTree(histogram, 7, bufRle, huffTree, huffmanCode); + HuffmanUtils.CreateHuffmanTree(histogram, 7, bufRle, huffTree, codeLengthBitDepth, codeLengthBitDepthSymbols); this.StoreHuffmanTreeOfHuffmanTreeToBitMask(codeLengthBitDepth); - ClearHuffmanTreeIfOnlyOneSymbol(huffmanCode); + ClearHuffmanTreeIfOnlyOneSymbol(codeLengthBitDepth, codeLengthBitDepthSymbols); int trailingZeroBits = 0; int trimmedLength = numTokens; @@ -1069,16 +1267,23 @@ private void StoreFullHuffmanCode(Span huffTree, HuffmanTreeToken[] } } - this.StoreHuffmanTreeToBitMask(tokens, length, huffmanCode); + this.StoreHuffmanTreeToBitMask(tokens, length, codeLengthBitDepth, codeLengthBitDepthSymbols); } - private void StoreHuffmanTreeToBitMask(HuffmanTreeToken[] tokens, int numTokens, HuffmanTreeCode huffmanCode) + /// + /// Writes the code length tokens with the code length code. Codes 16, 17 and 18 are followed by 2, 3 and 7 extra bits. + /// + /// The code length tokens. + /// The number of tokens to write. + /// The code lengths of the code length code. + /// The bit-reversed codes of the code length code. + private void StoreHuffmanTreeToBitMask(ReadOnlySpan tokens, int numTokens, ReadOnlySpan codeLengths, ReadOnlySpan codes) { for (int i = 0; i < numTokens; i++) { int ix = tokens[i].Code; int extraBits = tokens[i].ExtraBits; - this.bitWriter.PutBits((uint)huffmanCode.Codes[ix], huffmanCode.CodeLengths[ix]); + this.bitWriter.PutBits((uint)codes[ix], codeLengths[ix]); switch (ix) { case 16: @@ -1094,6 +1299,11 @@ private void StoreHuffmanTreeToBitMask(HuffmanTreeToken[] tokens, int numTokens, } } + /// + /// Writes the code lengths of the code length code in , with 3 bits each. Trailing zero lengths are omitted, + /// but at least 4 lengths are written. + /// + /// The code lengths of the code length code. private void StoreHuffmanTreeOfHuffmanTreeToBitMask(byte[] codeLengthBitDepth) { // Throw away trailing zeros: @@ -1113,12 +1323,26 @@ private void StoreHuffmanTreeOfHuffmanTreeToBitMask(byte[] codeLengthBitDepth) } } + /// + /// Writes the backward references with the Huffman codes of the tile of each token. + /// + /// The image width. + /// The log2 of the entropy image tile size. 0 means that the image has one set of Huffman codes. + /// The backward references to write. + /// The Huffman code set index of each tile. + /// + /// The first symbol of each Huffman code, five codes for each set: green, red, blue, alpha and distance. The next offset ends the code. + /// + /// The code lengths of all codes. + /// The bit-reversed codes of all codes. private void StoreImageToBitMask( int width, int histoBits, - Vp8LBackwardRefs backwardRefs, + Vp8LBackwardReferences backwardRefs, ReadOnlySpan histogramSymbols, - HuffmanTreeCode[] huffmanCodes) + ReadOnlySpan codeOffsets, + ReadOnlySpan codeLengths, + ReadOnlySpan codes) { int histoXSize = histoBits > 0 ? LosslessUtils.SubSampleSize(width, histoBits) : 1; int tileMask = histoBits == 0 ? 0 : -(1 << histoBits); @@ -1129,53 +1353,68 @@ private void StoreImageToBitMask( int tileX = x & tileMask; int tileY = y & tileMask; int histogramIx = histogramSymbols[0]; - Span codes = huffmanCodes.AsSpan(5 * histogramIx); - foreach (PixOrCopy v in backwardRefs) + // The first symbol of each of the five codes of the current tile. They change only at a tile change, not for each token. A write + // indexes the spans of all codes at the first symbol of its code plus the symbol. + int greenStart = codeOffsets[5 * histogramIx]; + int redStart = codeOffsets[(5 * histogramIx) + 1]; + int blueStart = codeOffsets[(5 * histogramIx) + 2]; + int alphaStart = codeOffsets[(5 * histogramIx) + 3]; + int distanceStart = codeOffsets[(5 * histogramIx) + 4]; + + int blockCount = backwardRefs.BlockCount; + for (int block = 0; block < blockCount; block++) { - if (tileX != (x & tileMask) || tileY != (y & tileMask)) + foreach (PixelOrCopy v in backwardRefs.GetBlock(block)) { - tileX = x & tileMask; - tileY = y & tileMask; - histogramIx = histogramSymbols[((y >> histoBits) * histoXSize) + (x >> histoBits)]; - codes = huffmanCodes.AsSpan(5 * histogramIx); - } + if (tileX != (x & tileMask) || tileY != (y & tileMask)) + { + tileX = x & tileMask; + tileY = y & tileMask; + histogramIx = histogramSymbols[((y >> histoBits) * histoXSize) + (x >> histoBits)]; + greenStart = codeOffsets[5 * histogramIx]; + redStart = codeOffsets[(5 * histogramIx) + 1]; + blueStart = codeOffsets[(5 * histogramIx) + 2]; + alphaStart = codeOffsets[(5 * histogramIx) + 3]; + distanceStart = codeOffsets[(5 * histogramIx) + 4]; + } - if (v.IsLiteral()) - { - for (int k = 0; k < 4; k++) + if (v.IsLiteral()) { - int code = v.Literal(Order[k]); - this.bitWriter.WriteHuffmanCode(codes[k], code); + // The stream order is green, red, blue, then alpha. Literal(n) gives blue for 0, green for 1, red for 2 and alpha for 3. + this.bitWriter.WriteHuffmanCode(codeLengths, codes, greenStart + v.Literal(1)); + this.bitWriter.WriteHuffmanCode(codeLengths, codes, redStart + v.Literal(2)); + this.bitWriter.WriteHuffmanCode(codeLengths, codes, blueStart + v.Literal(0)); + this.bitWriter.WriteHuffmanCode(codeLengths, codes, alphaStart + v.Literal(3)); + } + else if (v.IsCacheIdx()) + { + int code = (int)v.CacheIdx(); + int literalIx = 256 + WebpConstants.NumLengthCodes + code; + this.bitWriter.WriteHuffmanCode(codeLengths, codes, greenStart + literalIx); + } + else + { + int bits = 0; + int nBits = 0; + int distance = (int)v.Distance(); + int code = LosslessUtils.PrefixEncode(v.Len, ref nBits, ref bits); + this.bitWriter.WriteHuffmanCodeWithExtraBits(codeLengths, codes, greenStart + 256 + code, bits, nBits); + + // Don't write the distance with the extra bits code since + // the distance can be up to 18 bits of extra bits, and the prefix + // 15 bits, totaling to 33, and our PutBits only supports up to 32 bits. + code = LosslessUtils.PrefixEncode(distance, ref nBits, ref bits); + this.bitWriter.WriteHuffmanCode(codeLengths, codes, distanceStart + code); + this.bitWriter.PutBits((uint)bits, nBits); } - } - else if (v.IsCacheIdx()) - { - int code = (int)v.CacheIdx(); - int literalIx = 256 + WebpConstants.NumLengthCodes + code; - this.bitWriter.WriteHuffmanCode(codes[0], literalIx); - } - else - { - int bits = 0; - int nBits = 0; - int distance = (int)v.Distance(); - int code = LosslessUtils.PrefixEncode(v.Len, ref nBits, ref bits); - this.bitWriter.WriteHuffmanCodeWithExtraBits(codes[0], 256 + code, bits, nBits); - - // Don't write the distance with the extra bits code since - // the distance can be up to 18 bits of extra bits, and the prefix - // 15 bits, totaling to 33, and our PutBits only supports up to 32 bits. - code = LosslessUtils.PrefixEncode(distance, ref nBits, ref bits); - this.bitWriter.WriteHuffmanCode(codes[4], code); - this.bitWriter.PutBits((uint)bits, nBits); - } - x += v.Length(); - while (x >= width) - { - x -= width; - y++; + x += v.Length(); + while (x >= width) + { + x -= width; + y++; + } } } } @@ -1191,8 +1430,8 @@ private void StoreImageToBitMask( /// The transformation bits. /// Indicates if red and blue are always zero. /// The entropy mode to use. - private EntropyIx AnalyzeEntropy( - ReadOnlySpan bgra, + private EntropyIndex AnalyzeEntropy( + Buffer2D bgra, int width, int height, bool usePalette, @@ -1205,110 +1444,101 @@ private EntropyIx AnalyzeEntropy( // In the case of small palettes, we pack 2, 4 or 8 pixels together. In // practice, small palettes are better than any other transform. redAndBlueAlwaysZero = true; - return EntropyIx.Palette; + return EntropyIndex.Palette; } - using IMemoryOwner histoBuffer = this.memoryAllocator.Allocate((int)HistoIx.HistoTotal * 256, AllocationOptions.Clean); + using IMemoryOwner histoBuffer = this.memoryAllocator.Allocate((int)HistogramIndex.HistoTotal * 256, AllocationOptions.Clean); Span histo = histoBuffer.Memory.Span; - uint pixPrev = bgra[0]; // Skip the first pixel. - ReadOnlySpan prevRow = null; - for (int y = 0; y < height; y++) - { - ReadOnlySpan currentRow = bgra.Slice(y * width, width); - for (int x = 0; x < width; x++) - { - uint pix = currentRow[x]; - uint pixDiff = LosslessUtils.SubPixels(pix, pixPrev); - pixPrev = pix; - if (pixDiff == 0 || (prevRow.Length > 0 && pix == prevRow[x])) - { - continue; - } - - AddSingle( - pix, - histo[..], - histo[((int)HistoIx.HistoRed * 256)..], - histo[((int)HistoIx.HistoGreen * 256)..], - histo[((int)HistoIx.HistoBlue * 256)..]); - AddSingle( - pixDiff, - histo[((int)HistoIx.HistoAlphaPred * 256)..], - histo[((int)HistoIx.HistoRedPred * 256)..], - histo[((int)HistoIx.HistoGreenPred * 256)..], - histo[((int)HistoIx.HistoBluePred * 256)..]); - AddSingleSubGreen( - pix, - histo[((int)HistoIx.HistoRedSubGreen * 256)..], - histo[((int)HistoIx.HistoBlueSubGreen * 256)..]); - AddSingleSubGreen( - pixDiff, - histo[((int)HistoIx.HistoRedPredSubGreen * 256)..], - histo[((int)HistoIx.HistoBluePredSubGreen * 256)..]); - // Approximate the palette by the entropy of the multiplicative hash. - uint hash = HashPix(pix); - histo[((int)HistoIx.HistoPalette * 256) + (int)hash]++; + // The left neighbor of each pixel is the pixel before it at its flat position, also at the start of a row. Each buffer of the + // plane holds whole rows, so inside a buffer the scan reads the flat run of the buffer. The first row of a buffer reads the last + // row of the buffer before it, so the two rows go to a scratch run first. The counts do not depend on the order of the pixels. + // The first pixel differs from itself by zero, so the scan skips it. The pixels of the first row have no top neighbor. + using IMemoryOwner seamBuffer = this.memoryAllocator.Allocate(2 * width); + Span seam = seamBuffer.GetSpan()[..(2 * width)]; + MemoryGroup group = bgra.FastMemoryGroup; + int rowsPerBuffer = group.BufferLength / width; + for (int i = 0; i < group.Count; i++) + { + Span rows = group[i].Span; + int firstRow = i * rowsPerBuffer; + int rowCount = Math.Min(rowsPerBuffer, height - firstRow); + if (i == 0) + { + CollectEntropyHistograms(rows, 1, width, width, false, histo); + } + else + { + bgra.DangerousGetRowSpan(firstRow - 1).CopyTo(seam); + rows[..width].CopyTo(seam[width..]); + CollectEntropyHistograms(seam, width, 2 * width, width, true, histo); } - prevRow = currentRow; + CollectEntropyHistograms(rows, width, rowCount * width, width, true, histo); } - Span entropyComp = stackalloc double[(int)HistoIx.HistoTotal]; - Span entropy = stackalloc double[(int)EntropyIx.NumEntropyIx]; - int lastModeToAnalyze = usePalette ? (int)EntropyIx.Palette : (int)EntropyIx.SpatialSubGreen; + // HistoTotal is 13 and NumEntropyIx is 6. + InlineArray13 entropyCompStorage = default; + InlineArray6 entropyStorage = default; + Span entropyComp = entropyCompStorage; + Span entropy = entropyStorage; + int lastModeToAnalyze = usePalette ? (int)EntropyIndex.Palette : (int)EntropyIndex.SpatialSubGreen; // Let's add one zero to the predicted histograms. The zeros are removed // too efficiently by the pixDiff == 0 comparison, at least one of the // zeros is likely to exist. - histo[(int)HistoIx.HistoRedPredSubGreen * 256]++; - histo[(int)HistoIx.HistoBluePredSubGreen * 256]++; - histo[(int)HistoIx.HistoRedPred * 256]++; - histo[(int)HistoIx.HistoGreenPred * 256]++; - histo[(int)HistoIx.HistoBluePred * 256]++; - histo[(int)HistoIx.HistoAlphaPred * 256]++; + histo[(int)HistogramIndex.HistoRedPredSubGreen * 256]++; + histo[(int)HistogramIndex.HistoBluePredSubGreen * 256]++; + histo[(int)HistogramIndex.HistoRedPred * 256]++; + histo[(int)HistogramIndex.HistoGreenPred * 256]++; + histo[(int)HistogramIndex.HistoBluePred * 256]++; + histo[(int)HistogramIndex.HistoAlphaPred * 256]++; - Vp8LBitEntropy bitEntropy = new(); - for (int j = 0; j < (int)HistoIx.HistoTotal; j++) + // The entropy method sets its own start state for each histogram. + Vp8LBitEntropy bitEntropy = default; + for (int j = 0; j < (int)HistogramIndex.HistoTotal; j++) { - bitEntropy.Init(); Span curHisto = histo.Slice(j * 256, 256); bitEntropy.BitsEntropyUnrefined(curHisto, 256); entropyComp[j] = bitEntropy.BitsEntropyRefine(); } - entropy[(int)EntropyIx.Direct] = - entropyComp[(int)HistoIx.HistoAlpha] + - entropyComp[(int)HistoIx.HistoRed] + - entropyComp[(int)HistoIx.HistoGreen] + - entropyComp[(int)HistoIx.HistoBlue]; - entropy[(int)EntropyIx.Spatial] = - entropyComp[(int)HistoIx.HistoAlphaPred] + - entropyComp[(int)HistoIx.HistoRedPred] + - entropyComp[(int)HistoIx.HistoGreenPred] + - entropyComp[(int)HistoIx.HistoBluePred]; - entropy[(int)EntropyIx.SubGreen] = - entropyComp[(int)HistoIx.HistoAlpha] + - entropyComp[(int)HistoIx.HistoRedSubGreen] + - entropyComp[(int)HistoIx.HistoGreen] + - entropyComp[(int)HistoIx.HistoBlueSubGreen]; - entropy[(int)EntropyIx.SpatialSubGreen] = - entropyComp[(int)HistoIx.HistoAlphaPred] + - entropyComp[(int)HistoIx.HistoRedPredSubGreen] + - entropyComp[(int)HistoIx.HistoGreenPred] + - entropyComp[(int)HistoIx.HistoBluePredSubGreen]; - entropy[(int)EntropyIx.Palette] = entropyComp[(int)HistoIx.HistoPalette]; + entropy[(int)EntropyIndex.Direct] = + entropyComp[(int)HistogramIndex.HistoAlpha] + + entropyComp[(int)HistogramIndex.HistoRed] + + entropyComp[(int)HistogramIndex.HistoGreen] + + entropyComp[(int)HistogramIndex.HistoBlue]; + + entropy[(int)EntropyIndex.Spatial] = + entropyComp[(int)HistogramIndex.HistoAlphaPred] + + entropyComp[(int)HistogramIndex.HistoRedPred] + + entropyComp[(int)HistogramIndex.HistoGreenPred] + + entropyComp[(int)HistogramIndex.HistoBluePred]; + + entropy[(int)EntropyIndex.SubGreen] = + entropyComp[(int)HistogramIndex.HistoAlpha] + + entropyComp[(int)HistogramIndex.HistoRedSubGreen] + + entropyComp[(int)HistogramIndex.HistoGreen] + + entropyComp[(int)HistogramIndex.HistoBlueSubGreen]; + + entropy[(int)EntropyIndex.SpatialSubGreen] = + entropyComp[(int)HistogramIndex.HistoAlphaPred] + + entropyComp[(int)HistogramIndex.HistoRedPredSubGreen] + + entropyComp[(int)HistogramIndex.HistoGreenPred] + + entropyComp[(int)HistogramIndex.HistoBluePredSubGreen]; + + entropy[(int)EntropyIndex.Palette] = entropyComp[(int)HistogramIndex.HistoPalette]; // When including transforms, there is an overhead in bits from // storing them. This overhead is small but matters for small images. // For spatial, there are 14 transformations. - entropy[(int)EntropyIx.Spatial] += + entropy[(int)EntropyIndex.Spatial] += LosslessUtils.SubSampleSize(width, transformBits) * LosslessUtils.SubSampleSize(height, transformBits) * LosslessUtils.FastLog2(14); // For color transforms: 24 as only 3 channels are considered in a ColorTransformElement. - entropy[(int)EntropyIx.SpatialSubGreen] += + entropy[(int)EntropyIndex.SpatialSubGreen] += LosslessUtils.SubSampleSize(width, transformBits) * LosslessUtils.SubSampleSize(height, transformBits) * LosslessUtils.FastLog2(24); @@ -1317,42 +1547,173 @@ private EntropyIx AnalyzeEntropy( // We empirically estimate the cost of a compressed entry as 8 bits. // The palette is differential-coded when compressed hence a much // lower cost than sizeof(uint32_t)*8. - entropy[(int)EntropyIx.Palette] += paletteSize * 8; + entropy[(int)EntropyIndex.Palette] += paletteSize * 8; - EntropyIx minEntropyIx = EntropyIx.Direct; - for (int k = (int)EntropyIx.Direct + 1; k <= lastModeToAnalyze; k++) + EntropyIndex minEntropyIx = EntropyIndex.Direct; + for (int k = (int)EntropyIndex.Direct + 1; k <= lastModeToAnalyze; k++) { if (entropy[(int)minEntropyIx] > entropy[k]) { - minEntropyIx = (EntropyIx)k; + minEntropyIx = (EntropyIndex)k; } } - redAndBlueAlwaysZero = true; - // Let's check if the histogram of the chosen entropy mode has // non-zero red and blue values. If all are zero, we can later skip - // the cross color optimization. - byte[][] histoPairs = - [ - [(byte)HistoIx.HistoRed, (byte)HistoIx.HistoBlue], - [(byte)HistoIx.HistoRedPred, (byte)HistoIx.HistoBluePred], - [(byte)HistoIx.HistoRedSubGreen, (byte)HistoIx.HistoBlueSubGreen], - [(byte)HistoIx.HistoRedPredSubGreen, (byte)HistoIx.HistoBluePredSubGreen], - [(byte)HistoIx.HistoRed, (byte)HistoIx.HistoBlue] - ]; - Span redHisto = histo[(256 * histoPairs[(int)minEntropyIx][0])..]; - Span blueHisto = histo[(256 * histoPairs[(int)minEntropyIx][1])..]; - for (int i = 1; i < 256; i++) - { - if ((redHisto[i] | blueHisto[i]) != 0) + // the cross color optimization. The count of value 0 does not matter. + ReadOnlySpan histoPairs = RedAndBlueHistogramPairs; + ReadOnlySpan redHisto = histo.Slice((256 * histoPairs[2 * (int)minEntropyIx]) + 1, 255); + ReadOnlySpan blueHisto = histo.Slice((256 * histoPairs[(2 * (int)minEntropyIx) + 1]) + 1, 255); + redAndBlueAlwaysZero = !redHisto.ContainsAnyExcept(0u) && !blueHisto.ContainsAnyExcept(0u); + + return minEntropyIx; + } + + /// + /// Adds the pixels of a run to the entropy analysis histograms. A pixel that equals its left neighbor, or its top neighbor when + /// is set, is skipped, because backward references code such pixels. + /// + /// + /// + /// The vector forms hold one ARGB pixel in each 32-bit lane. The difference to the left neighbor subtracts byte by byte, so each + /// channel wraps mod 256, as in . The skip test compares whole lanes. + /// + /// + /// The bin increments are scalar, so a vector block stores its pixels, differences and hashes in inline arrays first. A bit mask of the + /// kept lanes then drives the increments. The bins count each pixel once, in any order, so the vector width does not change the counts. + /// The single pixel form fills the first entry of each inline array, so all forms share the increments. + /// + /// + /// The image pixels, without row padding. + /// The index of the first pixel of the run. It is at least 1. + /// The index after the last pixel of the run. + /// The image width. + /// Whether the pixels of the run have a top neighbor. Then is at least . + /// The histograms of 256 counts, at 256 times their index. + private static void CollectEntropyHistograms(ReadOnlySpan bgra, int start, int end, int width, bool hasTop, Span histo) + { + // The staging buffers hold one block of the widest vector, 16 lanes. + InlineArray16 pixelsStorage = default; + InlineArray16 diffsStorage = default; + InlineArray16 hashesStorage = default; + ref uint pixels = ref pixelsStorage[0]; + ref uint diffs = ref diffsStorage[0]; + ref uint hashes = ref hashesStorage[0]; + + // Each channel index is less than 256, so each increment stays in its histogram. + ref uint histoBase = ref MemoryMarshal.GetReference(histo); + ref uint alpha = ref Unsafe.Add(ref histoBase, (uint)HistogramIndex.HistoAlpha * 256); + ref uint red = ref Unsafe.Add(ref histoBase, (uint)HistogramIndex.HistoRed * 256); + ref uint green = ref Unsafe.Add(ref histoBase, (uint)HistogramIndex.HistoGreen * 256); + ref uint blue = ref Unsafe.Add(ref histoBase, (uint)HistogramIndex.HistoBlue * 256); + ref uint alphaPred = ref Unsafe.Add(ref histoBase, (uint)HistogramIndex.HistoAlphaPred * 256); + ref uint redPred = ref Unsafe.Add(ref histoBase, (uint)HistogramIndex.HistoRedPred * 256); + ref uint greenPred = ref Unsafe.Add(ref histoBase, (uint)HistogramIndex.HistoGreenPred * 256); + ref uint bluePred = ref Unsafe.Add(ref histoBase, (uint)HistogramIndex.HistoBluePred * 256); + ref uint redSubGreen = ref Unsafe.Add(ref histoBase, (uint)HistogramIndex.HistoRedSubGreen * 256); + ref uint blueSubGreen = ref Unsafe.Add(ref histoBase, (uint)HistogramIndex.HistoBlueSubGreen * 256); + ref uint redPredSubGreen = ref Unsafe.Add(ref histoBase, (uint)HistogramIndex.HistoRedPredSubGreen * 256); + ref uint bluePredSubGreen = ref Unsafe.Add(ref histoBase, (uint)HistogramIndex.HistoBluePredSubGreen * 256); + ref uint palette = ref Unsafe.Add(ref histoBase, (uint)HistogramIndex.HistoPalette * 256); + + ref uint bgraBase = ref MemoryMarshal.GetReference(bgra); + nuint top = (uint)width; + nuint i = (uint)start; + nuint n = (uint)end; + while (i < n) + { + // Bit k of keep is set when lane k is not skipped. + uint keep; + nuint count; + if (Vector512.IsHardwareAccelerated && i + (uint)Vector512.Count <= n) { - redAndBlueAlwaysZero = false; - break; + Vector512 pix = Vector512.LoadUnsafe(ref bgraBase, i); + Vector512 diff = (pix.AsByte() - Vector512.LoadUnsafe(ref bgraBase, i - 1).AsByte()).AsUInt32(); + Vector512 skip = Vector512.Equals(diff, Vector512.Zero); + if (hasTop) + { + skip |= Vector512.Equals(pix, Vector512.LoadUnsafe(ref bgraBase, i - top)); + } + + keep = ~(uint)skip.ExtractMostSignificantBits() & 0xffffu; + if (keep != 0) + { + pix.StoreUnsafe(ref pixels); + diff.StoreUnsafe(ref diffs); + HashPix(pix).StoreUnsafe(ref hashes); + } + + count = (uint)Vector512.Count; } - } + else if (Vector256.IsHardwareAccelerated && i + (uint)Vector256.Count <= n) + { + Vector256 pix = Vector256.LoadUnsafe(ref bgraBase, i); + Vector256 diff = (pix.AsByte() - Vector256.LoadUnsafe(ref bgraBase, i - 1).AsByte()).AsUInt32(); + Vector256 skip = Vector256.Equals(diff, Vector256.Zero); + if (hasTop) + { + skip |= Vector256.Equals(pix, Vector256.LoadUnsafe(ref bgraBase, i - top)); + } - return minEntropyIx; + keep = ~skip.ExtractMostSignificantBits() & 0xffu; + if (keep != 0) + { + pix.StoreUnsafe(ref pixels); + diff.StoreUnsafe(ref diffs); + HashPix(pix).StoreUnsafe(ref hashes); + } + + count = (uint)Vector256.Count; + } + else if (Vector128.IsHardwareAccelerated && i + (uint)Vector128.Count <= n) + { + Vector128 pix = Vector128.LoadUnsafe(ref bgraBase, i); + Vector128 diff = (pix.AsByte() - Vector128.LoadUnsafe(ref bgraBase, i - 1).AsByte()).AsUInt32(); + Vector128 skip = Vector128.Equals(diff, Vector128.Zero); + if (hasTop) + { + skip |= Vector128.Equals(pix, Vector128.LoadUnsafe(ref bgraBase, i - top)); + } + + keep = ~skip.ExtractMostSignificantBits() & 0xfu; + if (keep != 0) + { + pix.StoreUnsafe(ref pixels); + diff.StoreUnsafe(ref diffs); + HashPix(pix).StoreUnsafe(ref hashes); + } + + count = (uint)Vector128.Count; + } + else + { + uint pix = Unsafe.Add(ref bgraBase, i); + uint diff = LosslessUtils.SubPixels(pix, Unsafe.Add(ref bgraBase, i - 1)); + bool skip = diff == 0 || (hasTop && pix == Unsafe.Add(ref bgraBase, i - top)); + keep = skip ? 0u : 1u; + pixels = pix; + diffs = diff; + hashes = HashPix(pix); + count = 1; + } + + while (keep != 0) + { + nuint k = (uint)BitOperations.TrailingZeroCount(keep); + keep &= keep - 1; + uint pix = Unsafe.Add(ref pixels, k); + uint diff = Unsafe.Add(ref diffs, k); + PredictorEncoder.UpdateHisto(ref alpha, ref red, ref green, ref blue, pix); + PredictorEncoder.UpdateHisto(ref alphaPred, ref redPred, ref greenPred, ref bluePred, diff); + AddSingleSubGreen(pix, ref redSubGreen, ref blueSubGreen); + AddSingleSubGreen(diff, ref redPredSubGreen, ref bluePredSubGreen); + + // Approximate the palette by the entropy of the multiplicative hash. + Unsafe.Add(ref palette, Unsafe.Add(ref hashes, k))++; + } + + i += count; + } } /// @@ -1363,10 +1724,10 @@ private EntropyIx AnalyzeEntropy( /// The image width. /// The image height. /// true, if a palette should be used. - private bool AnalyzeAndCreatePalette(ReadOnlySpan bgra, int width, int height) + private bool AnalyzeAndCreatePalette(Buffer2D bgra, int width, int height) { Span palette = this.Palette.Memory.Span; - this.PaletteSize = GetColorPalette(bgra, width, height, palette); + this.PaletteSize = this.GetColorPalette(bgra, palette); if (this.PaletteSize > WebpConstants.MaxPaletteSize) { this.PaletteSize = 0; @@ -1387,44 +1748,100 @@ private bool AnalyzeAndCreatePalette(ReadOnlySpan bgra, int width, int hei /// /// Gets the color palette. /// - /// The image to get the palette from as packed bgra values. - /// The image width. - /// The image height. + /// + /// The colors go into a hash table with 4 slots for each possible palette entry and linear probing. + /// A run of equal pixels needs only one table lookup, because the scan skips each pixel that is equal to the pixel before it. + /// The caller sorts the palette, so the order of the colors here has no effect on the output. + /// + /// The image to get the palette from as packed bgra values, without row padding. /// The span to store the palette into. - /// The number of palette entries. - private static int GetColorPalette(ReadOnlySpan bgra, int width, int height, Span palette) + /// The number of palette entries, or + 1 if the image has more colors. + private int GetColorPalette(Buffer2D bgra, Span palette) { - HashSet colors = []; - for (int y = 0; y < height; y++) + const int colorHashSize = WebpConstants.MaxPaletteSize * 4; + + // The hash uses the top 10 bits of the product, which index the 1024 slots: 32 - log2(1024) = 22. + const int colorHashRightShift = 22; + + // The first half holds the colors. The second half holds 1 for each slot in use, so only that half needs a clear. + using IMemoryOwner hashBuffer = this.memoryAllocator.Allocate(colorHashSize * 2); + Span colors = hashBuffer.GetSpan()[..colorHashSize]; + Span inUse = hashBuffer.GetSpan().Slice(colorHashSize, colorHashSize); + inUse.Clear(); + + int numColors = 0; + + // The scan reads each buffer of the plane as one run. The plane has the image size, and the last pixel of a buffer is the pixel + // before the first pixel of the next buffer, so the runs give the same scan as one run of the image. + MemoryGroup group = bgra.FastMemoryGroup; + uint lastPix = ~group[0].Span[0]; // Not equal to the first pixel, so the scan adds the first pixel. + for (int i = 0; i < group.Count; i++) { - ReadOnlySpan bgraRow = bgra.Slice(y * width, width); - for (int x = 0; x < width; x++) + ReadOnlySpan run = group[i].Span; + int x = 0; + while (true) { - colors.Add(bgraRow[x]); - if (colors.Count > WebpConstants.MaxPaletteSize) + // Find the next pixel that is not equal to the pixel before it. + int skip = run[x..].IndexOfAnyExcept(lastPix); + if (skip < 0) + { + break; + } + + x += skip; + lastPix = run[x++]; + int key = ColorCache.HashPix(lastPix, colorHashRightShift); + while (true) { - // Exact count is not needed, because a palette will not be used then anyway. - return WebpConstants.MaxPaletteSize + 1; + if (inUse[key] == 0) + { + colors[key] = lastPix; + inUse[key] = 1; + if (++numColors > WebpConstants.MaxPaletteSize) + { + // Exact count is not needed, because a palette will not be used then anyway. + return WebpConstants.MaxPaletteSize + 1; + } + + break; + } + + if (colors[key] == lastPix) + { + // The color is already in the table. + break; + } + + // Another color uses this slot, so try the next slot. + key = (key + 1) & (colorHashSize - 1); } } } // Fill the colors into the palette. - using HashSet.Enumerator colorEnumerator = colors.GetEnumerator(); int idx = 0; - while (colorEnumerator.MoveNext()) + for (int i = 0; i < colorHashSize; i++) { - palette[idx++] = colorEnumerator.Current; + if (inUse[i] != 0) + { + palette[idx++] = colors[i]; + } } - return colors.Count; + return numColors; } + /// + /// Replaces each input pixel with its palette index and packs the indices into the working pixel data. + /// A palette of at most 2, 4 or 16 colors packs 8, 4 or 2 indices into each pixel. The current width becomes the packed width. + /// + /// The image width. + /// The image height. private void MapImageFromPalette(int width, int height) { - Span src = this.EncodedData.GetSpan(); - int srcStride = this.CurrentWidth; - Span dst = this.EncodedData.GetSpan(); // Applying the palette will be done in place. + // The mapping reads the input pixels and writes the packed indices to the working copy. + // Thus the working copy needs no copy of the input first. + Buffer2D src = this.Bgra; Span palette = this.Palette.GetSpan(); int paletteSize = this.PaletteSize; int xBits; @@ -1441,21 +1858,25 @@ private void MapImageFromPalette(int width, int height) } this.CurrentWidth = LosslessUtils.SubSampleSize(width, xBits); - this.ApplyPalette(src, srcStride, dst, this.CurrentWidth, palette, paletteSize, width, height, xBits); + this.EncodedData = this.GetWorkingCopy(this.CurrentWidth, height); + this.ApplyPalette(src, this.EncodedData, palette, paletteSize, width, height, xBits); } /// - /// Remap bgra values in src[] to packed palettes entries in dst[] - /// using 'row' as a temporary buffer of size 'width'. - /// We assume that all src[] values have a corresponding entry in the palette. - /// Note: src[] can be the same as dst[] + /// Replaces each pixel with its palette index and packs the indices, 1 << indices in each pixel. + /// Each pixel of the source has an entry in the palette. /// + /// The source pixels. + /// The destination pixels. A row has the packed width. + /// The palette. + /// The number of palette entries. + /// The image width. + /// The image height. + /// The base 2 logarithm of the number of indices in each packed pixel. private void ApplyPalette( - Span src, - int srcStride, - Span dst, - int dstStride, - Span palette, + Buffer2D src, + Buffer2D dst, + ReadOnlySpan palette, int paletteSize, int width, int height, @@ -1470,9 +1891,10 @@ private void ApplyPalette( uint prevIdx = 0; for (int y = 0; y < height; y++) { + Span srcRow = src.DangerousGetRowSpan(y); for (int x = 0; x < width; x++) { - uint pix = src[x]; + uint pix = srcRow[x]; if (pix != prevPix) { prevIdx = SearchColorGreedy(palette, pix); @@ -1482,139 +1904,147 @@ private void ApplyPalette( tmpRow[x] = (byte)prevIdx; } - BundleColorMap(tmpRow, width, xBits, dst); - src = src[srcStride..]; - dst = dst[dstStride..]; + LosslessUtils.BundleColorMap(tmpRow, width, xBits, dst.DangerousGetRowSpan(y)); } } else { - uint[] buffer = new uint[PaletteInvSize]; + // No clear: each hash attempt fills the full table first. + using IMemoryOwner bufferOwner = this.memoryAllocator.Allocate(PaletteInvSize); + Span buffer = bufferOwner.GetSpan(); // Try to find a perfect hash function able to go from a color to an index // within 1 << PaletteInvSize in order to build a hash map to go from color to index in palette. - int i; - for (i = 0; i < 3; i++) + // The hash is chosen once here, so the pixel loop has no switch. + if (TryCreatePaletteHashTable(palette, paletteSize, buffer)) { - bool useLut = true; - - // Set each element in buffer to max value. - buffer.AsSpan().Fill(uint.MaxValue); - - for (int j = 0; j < paletteSize; j++) - { - uint ind = 0; - switch (i) - { - case 0: - ind = ApplyPaletteHash0(palette[j]); - break; - case 1: - ind = ApplyPaletteHash1(palette[j]); - break; - case 2: - ind = ApplyPaletteHash2(palette[j]); - break; - } - - if (buffer[ind] != uint.MaxValue) - { - useLut = false; - break; - } - - buffer[ind] = (uint)j; - } - - if (useLut) - { - break; - } + ApplyPaletteFor(width, height, palette, src, dst, tmpRow, buffer, xBits); } - - if (i is 0 or 1 or 2) + else if (TryCreatePaletteHashTable(palette, paletteSize, buffer)) { - ApplyPaletteFor(width, height, palette, i, src, srcStride, dst, dstStride, tmpRow, buffer, xBits); + ApplyPaletteFor(width, height, palette, src, dst, tmpRow, buffer, xBits); + } + else if (TryCreatePaletteHashTable(palette, paletteSize, buffer)) + { + ApplyPaletteFor(width, height, palette, src, dst, tmpRow, buffer, xBits); } else { - uint[] idxMap = new uint[paletteSize]; - uint[] paletteSorted = new uint[paletteSize]; + // The sorted palette and the map from a sorted entry to its palette index. No clear: the preparation writes each entry. + using IMemoryOwner mapBuffer = this.memoryAllocator.Allocate(2 * paletteSize); + Span paletteSorted = mapBuffer.GetSpan()[..paletteSize]; + Span idxMap = mapBuffer.GetSpan().Slice(paletteSize, paletteSize); PrepareMapToPalette(palette, paletteSize, paletteSorted, idxMap); - ApplyPaletteForWithIdxMap(width, height, palette, src, srcStride, dst, dstStride, tmpRow, idxMap, xBits, paletteSorted, paletteSize); + ApplyPaletteForWithIdxMap(width, height, palette, src, dst, tmpRow, idxMap, xBits, paletteSorted, paletteSize); } } } - private static void ApplyPaletteFor( + /// + /// Fills a hash table that maps each palette color to its palette index, when the hash maps each color to its own entry. + /// + /// The hash of the table. + /// The palette. + /// The number of palette colors. + /// The hash table with entries. On return, the entries of the palette colors. + /// if no two colors have the same hash; otherwise, . + private static bool TryCreatePaletteHashTable(ReadOnlySpan palette, int paletteSize, Span buffer) + where THash : struct, IPaletteHashOperator + { + // Set each element in buffer to max value. + buffer.Fill(uint.MaxValue); + + for (int j = 0; j < paletteSize; j++) + { + int ind = (int)THash.Hash(palette[j]); + if (buffer[ind] != uint.MaxValue) + { + return false; + } + + buffer[ind] = (uint)j; + } + + return true; + } + + /// + /// Maps each pixel to its palette index with a perfect hash table and packs the indices of each row. + /// + /// The hash that the table uses. + /// The image width. + /// The image height. + /// The palette. + /// The input pixels. + /// Receives the packed indices. A row has the packed width. + /// A scratch buffer for the indices of one row. + /// The hash table. Each entry holds the palette index of the color with that hash. + /// The log2 of the number of indices in each packed pixel. + private static void ApplyPaletteFor( int width, int height, ReadOnlySpan palette, - int hashIdx, - Span src, - int srcStride, - Span dst, - int dstStride, + Buffer2D src, + Buffer2D dst, Span tmpRow, - uint[] buffer, + ReadOnlySpan buffer, int xBits) + where THash : struct, IPaletteHashOperator { uint prevPix = palette[0]; uint prevIdx = 0; for (int y = 0; y < height; y++) { + Span srcRow = src.DangerousGetRowSpan(y); for (int x = 0; x < width; x++) { - uint pix = src[x]; + uint pix = srcRow[x]; if (pix != prevPix) { - switch (hashIdx) - { - case 0: - prevIdx = buffer[ApplyPaletteHash0(pix)]; - break; - case 1: - prevIdx = buffer[ApplyPaletteHash1(pix)]; - break; - case 2: - prevIdx = buffer[ApplyPaletteHash2(pix)]; - break; - } - + prevIdx = buffer[(int)THash.Hash(pix)]; prevPix = pix; } tmpRow[x] = (byte)prevIdx; } - LosslessUtils.BundleColorMap(tmpRow, width, xBits, dst); - - src = src[srcStride..]; - dst = dst[dstStride..]; + LosslessUtils.BundleColorMap(tmpRow, width, xBits, dst.DangerousGetRowSpan(y)); } } + /// + /// Maps each pixel to its palette index with a binary search in the sorted palette and packs the indices of each row. + /// + /// The image width. + /// The image height. + /// The palette. + /// The input pixels. + /// Receives the packed indices. A row has the packed width. + /// A scratch buffer for the indices of one row. + /// The palette index of each entry of the sorted palette. + /// The log2 of the number of indices in each packed pixel. + /// The palette in increasing order. + /// The number of palette colors. private static void ApplyPaletteForWithIdxMap( int width, int height, ReadOnlySpan palette, - Span src, - int srcStride, - Span dst, - int dstStride, + Buffer2D src, + Buffer2D dst, Span tmpRow, - uint[] idxMap, + ReadOnlySpan idxMap, int xBits, - uint[] paletteSorted, + ReadOnlySpan paletteSorted, int paletteSize) { uint prevPix = palette[0]; uint prevIdx = 0; for (int y = 0; y < height; y++) { + Span srcRow = src.DangerousGetRowSpan(y); for (int x = 0; x < width; x++) { - uint pix = src[x]; + uint pix = srcRow[x]; if (pix != prevPix) { prevIdx = idxMap[SearchColorNoIdx(paletteSorted, pix, paletteSize)]; @@ -1624,27 +2054,36 @@ private static void ApplyPaletteForWithIdxMap( tmpRow[x] = (byte)prevIdx; } - LosslessUtils.BundleColorMap(tmpRow, width, xBits, dst); - - src = src[srcStride..]; - dst = dst[dstStride..]; + LosslessUtils.BundleColorMap(tmpRow, width, xBits, dst.DangerousGetRowSpan(y)); } } /// - /// Sort palette in increasing order and prepare an inverse mapping array. + /// Sorts the palette in increasing order and makes the map from each sorted entry to its palette index. /// - private static void PrepareMapToPalette(Span palette, int numColors, uint[] sorted, uint[] idxMap) + /// The palette. + /// The number of palette entries. + /// Gets the sorted palette entries. It has entries. + /// Gets the palette index of each sorted entry. + private static void PrepareMapToPalette(ReadOnlySpan palette, int numColors, Span sorted, Span idxMap) { + // The palette colors are unique, so the ascending order is the only sorted order of the colors. palette[..numColors].CopyTo(sorted); - Array.Sort(sorted, PaletteCompareColorsForSort); + sorted[..numColors].Sort(); for (int i = 0; i < numColors; i++) { idxMap[SearchColorNoIdx(sorted, palette[i], numColors)] = (uint)i; } } - private static int SearchColorNoIdx(uint[] sorted, uint color, int hi) + /// + /// Finds a color in a sorted palette with a binary search. The palette must contain the color. + /// + /// The palette in increasing order. + /// The color to find. + /// The number of palette colors. + /// The index of the color in the sorted palette. + private static int SearchColorNoIdx(ReadOnlySpan sorted, uint color, int hi) { int low = 0; if (sorted[low] == color) @@ -1671,26 +2110,22 @@ private static int SearchColorNoIdx(uint[] sorted, uint color, int hi) } } - private static void ClearHuffmanTreeIfOnlyOneSymbol(HuffmanTreeCode huffmanCode) + /// + /// Sets all code lengths and codes to zero when the code has at most one used symbol. Such a symbol then takes no bits in the coded pixels. + /// + /// The code lengths of the Huffman code. + /// The bit-reversed codes of the Huffman code. + private static void ClearHuffmanTreeIfOnlyOneSymbol(Span codeLengths, Span codes) { - int count = 0; - for (int k = 0; k < huffmanCode.NumSymbols; k++) + // Find the first used symbol, then look for a second one after it. Both searches are vectorized. + int first = codeLengths.IndexOfAnyExcept((byte)0); + if (first >= 0 && codeLengths[(first + 1)..].ContainsAnyExcept((byte)0)) { - if (huffmanCode.CodeLengths[k] != 0) - { - count++; - if (count > 1) - { - return; - } - } + return; } - for (int k = 0; k < huffmanCode.NumSymbols; k++) - { - huffmanCode.CodeLengths[k] = 0; - huffmanCode.Codes[k] = 0; - } + codeLengths.Clear(); + codes.Clear(); } /// @@ -1762,62 +2197,73 @@ private static void GreedyMinimizeDeltas(Span palette, int numColors) } #pragma warning restore CA1517 - private static void GetHuffBitLengthsAndCodes(Vp8LHistogramSet histogramImage, HuffmanTreeCode[] huffmanCodes) + /// + /// Sets the first symbol of each Huffman code of a set of histograms. Each histogram has five codes, in this order: the green and length + /// prefix code (with the color cache codes), the red code, the blue code, the alpha code and the distance code. + /// + /// + /// The codes are stored one after the other in one code length span and one code span. The next offset ends a code, so the table has one + /// more entry than codes. + /// + /// The histograms. The literal code of a histogram has the number of literal codes of its palette code bits. + /// Receives the offsets: 5 entries for each histogram, and one more entry with the total number of symbols. + /// Receives the largest number of symbols of a code. + /// The total number of symbols of all codes. + private static int GetHuffmanCodeOffsets(Vp8LHistogramSet histograms, Span offsets, out int maxNumSymbols) { - int maxNumSymbols = 0; - - // Iterate over all histograms and get the aggregate number of codes used. - for (int i = 0; i < histogramImage.Count; i++) - { - Vp8LHistogram histo = histogramImage[i]; - int startIdx = 5 * i; - for (int k = 0; k < 5; k++) - { - int numSymbols; - if (k == 0) - { - numSymbols = histo.NumCodes(); - } - else if (k == 4) - { - numSymbols = WebpConstants.NumDistanceCodes; - } - else - { - numSymbols = 256; - } - - huffmanCodes[startIdx + k].NumSymbols = numSymbols; - } - } - - // TODO: Allocations. - int end = 5 * histogramImage.Count; - for (int i = 0; i < end; i++) - { - int bitLength = huffmanCodes[i].NumSymbols; - huffmanCodes[i].Codes = new short[bitLength]; - huffmanCodes[i].CodeLengths = new byte[bitLength]; - if (maxNumSymbols < bitLength) - { - maxNumSymbols = bitLength; - } - } - - // Create Huffman trees. - // TODO: Allocations. - bool[] bufRle = new bool[maxNumSymbols]; - HuffmanTree[] huffTree = new HuffmanTree[3 * maxNumSymbols]; + int total = 0; + int maxLiteralSymbols = 0; + for (int i = 0; i < histograms.Count; i++) + { + // The literal code size is the only size that changes from one histogram to the next. + // The red, blue and alpha codes have 256 symbols each, and the distance code 40. + int literalSymbols = histograms[i].NumCodes(); + Span histogramOffsets = offsets.Slice(5 * i, 5); + histogramOffsets[0] = total; + histogramOffsets[1] = total + literalSymbols; + histogramOffsets[2] = histogramOffsets[1] + WebpConstants.NumLiteralCodes; + histogramOffsets[3] = histogramOffsets[2] + WebpConstants.NumLiteralCodes; + histogramOffsets[4] = histogramOffsets[3] + WebpConstants.NumLiteralCodes; + total = histogramOffsets[4] + WebpConstants.NumDistanceCodes; + maxLiteralSymbols = Math.Max(maxLiteralSymbols, literalSymbols); + } + + offsets[5 * histograms.Count] = total; + maxNumSymbols = Math.Max(maxLiteralSymbols, WebpConstants.NumLiteralCodes); + return total; + } + /// + /// Creates the Huffman code lengths and codes of each histogram. + /// + /// + /// The offsets give each code its number of symbols. The code lengths start at zero. The tree creation leaves the code length of an + /// unused symbol unchanged and writes all codes. + /// + /// The histograms. The method changes the counts. + /// The first symbol of each code, 5 codes for each histogram, from . + /// Receives the code lengths of all codes. The values must be zero. + /// Receives the bit-reversed codes of all codes. + /// A scratch buffer with at least one entry for each symbol of the largest code. + /// A scratch buffer with at least three entries for each symbol of the largest code. + private static void GetHuffBitLengthsAndCodes( + Vp8LHistogramSet histogramImage, + ReadOnlySpan codeOffsets, + Span codeLengths, + Span codes, + Span bufRle, + Span huffTree) + { for (int i = 0; i < histogramImage.Count; i++) { - int codesStartIdx = 5 * i; + // Code k of the histogram is the symbols from offsets[k] to offsets[k + 1] of the spans of all codes. + ReadOnlySpan offsets = codeOffsets.Slice(5 * i, 6); Vp8LHistogram histo = histogramImage[i]; - HuffmanUtils.CreateHuffmanTree(histo.Literal, 15, bufRle, huffTree, huffmanCodes[codesStartIdx]); - HuffmanUtils.CreateHuffmanTree(histo.Red, 15, bufRle, huffTree, huffmanCodes[codesStartIdx + 1]); - HuffmanUtils.CreateHuffmanTree(histo.Blue, 15, bufRle, huffTree, huffmanCodes[codesStartIdx + 2]); - HuffmanUtils.CreateHuffmanTree(histo.Alpha, 15, bufRle, huffTree, huffmanCodes[codesStartIdx + 3]); - HuffmanUtils.CreateHuffmanTree(histo.Distance, 15, bufRle, huffTree, huffmanCodes[codesStartIdx + 4]); + HuffmanUtils.CreateHuffmanTree(histo.Literal, 15, bufRle, huffTree, codeLengths[offsets[0]..offsets[1]], codes[offsets[0]..offsets[1]]); + HuffmanUtils.CreateHuffmanTree(histo.Red, 15, bufRle, huffTree, codeLengths[offsets[1]..offsets[2]], codes[offsets[1]..offsets[2]]); + HuffmanUtils.CreateHuffmanTree(histo.Blue, 15, bufRle, huffTree, codeLengths[offsets[2]..offsets[3]], codes[offsets[2]..offsets[3]]); + HuffmanUtils.CreateHuffmanTree(histo.Alpha, 15, bufRle, huffTree, codeLengths[offsets[3]..offsets[4]], codes[offsets[3]..offsets[4]]); + HuffmanUtils.CreateHuffmanTree(histo.Distance, 15, bufRle, huffTree, codeLengths[offsets[4]..offsets[5]], codes[offsets[4]..offsets[5]]); } } @@ -1842,8 +2288,13 @@ private static uint PaletteColorDistance(uint col1, uint col2) } /// - /// Calculates the huffman image bits. + /// Gets the base 2 logarithm of the tile size of the entropy image. /// + /// The encoding method. A slower method gives smaller tiles. + /// Whether the image uses a palette, which gives larger tiles. + /// The image width. + /// The image height. + /// The number of tile bits, limited so that the entropy image stays small. private static int GetHistoBits(WebpEncodingMethod method, bool usePalette, int width, int height) { // Make tile size a function of encoding method (Range: 0 to 6). @@ -1874,44 +2325,20 @@ private static int GetHistoBits(WebpEncodingMethod method, bool usePalette, int } /// - /// Bundles multiple (1, 2, 4 or 8) pixels into a single pixel. + /// Swaps two bit writers. /// - private static void BundleColorMap(ReadOnlySpan row, int width, int xBits, Span dst) - { - int x; - if (xBits > 0) - { - int bitDepth = 1 << (3 - xBits); - int mask = (1 << xBits) - 1; - uint code = 0xff000000; - for (x = 0; x < width; x++) - { - int xSub = x & mask; - if (xSub == 0) - { - code = 0xff000000; - } - - code |= (uint)(row[x] << (8 + (bitDepth * xSub))); - dst[x >> xBits] = code; - } - } - else - { - for (x = 0; x < width; x++) - { - dst[x] = (uint)(0xff000000 | (row[x] << 8)); - } - } - } - + /// The first bit writer. On return, the second bit writer. + /// The second bit writer. On return, the first bit writer. [MethodImpl(InliningOptions.ShortMethod)] private static void BitWriterSwap(ref Vp8LBitWriter src, ref Vp8LBitWriter dst) => (dst, src) = (src, dst); /// - /// Calculates the bits used for the transformation. + /// Gets the base 2 logarithm of the tile size of the predictor and color transforms. /// + /// The encoding method. A slower method allows smaller tiles. + /// The tile bits of the entropy image. + /// The number of tile bits of the transforms. [MethodImpl(InliningOptions.ShortMethod)] private static int GetTransformBits(WebpEncodingMethod method, int histoBits) { @@ -1932,23 +2359,27 @@ private static int GetTransformBits(WebpEncodingMethod method, int histoBits) return histoBits > maxTransformBits ? maxTransformBits : histoBits; } + /// + /// Adds the red and blue channels of a pixel after the subtract green transform to the red and blue histograms. + /// + /// The ARGB pixel. + /// The first count of the histogram of red minus green, mod 256. It has 256 counts. + /// The first count of the histogram of blue minus green, mod 256. It has 256 counts. [MethodImpl(InliningOptions.ShortMethod)] - private static void AddSingle(uint p, Span a, Span r, Span g, Span b) - { - a[(int)(p >> 24) & 0xff]++; - r[(int)(p >> 16) & 0xff]++; - g[(int)(p >> 8) & 0xff]++; - b[(int)(p >> 0) & 0xff]++; - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void AddSingleSubGreen(uint p, Span r, Span b) + private static void AddSingleSubGreen(uint p, ref uint r, ref uint b) { - int green = (int)p >> 8; // The upper bits are masked away later. - r[(int)((p >> 16) - green) & 0xff]++; - b[(int)((p >> 0) - green) & 0xff]++; + // The differences wrap mod 2^32. The mask keeps the low 8 bits, so each index is the channel difference mod 256. + uint green = p >> 8; + Unsafe.Add(ref r, ((p >> 16) - green) & 0xff)++; + Unsafe.Add(ref b, (p - green) & 0xff)++; } + /// + /// Finds the index of a color in a palette of at most 4 colors with a linear search. The palette must contain the color. + /// + /// The palette. + /// The color to find. + /// The palette index. A color that is not one of the first three entries gets index 3. [MethodImpl(InliningOptions.ShortMethod)] private static uint SearchColorGreedy(ReadOnlySpan palette, uint color) { @@ -1970,46 +2401,127 @@ private static uint SearchColorGreedy(ReadOnlySpan palette, uint color) return 3; } + /// + /// Hashes a pixel to 8 bits. The entropy of a histogram of these hashes approximates the cost of a palette. + /// + /// The ARGB pixel. + /// The hash, from 0 to 255. [MethodImpl(InliningOptions.ShortMethod)] - private static uint ApplyPaletteHash0(uint color) => (color >> 8) & 0xff; // Focus on the green color. - - [MethodImpl(InliningOptions.ShortMethod)] - private static uint ApplyPaletteHash1(uint color) => (uint)((color & 0x00ffffffu) * 4222244071ul) >> (32 - PaletteInvSizeBits); // Forget about alpha. + private static uint HashPix(uint pix) => (uint)((((long)pix + (pix >> 19)) * 0x39c5fba7L) & 0xffffffffu) >> 24; + /// + /// Hashes four pixels to 8 bits each, as does. + /// + /// + /// The scalar form keeps the low 32 bits of the product. These bits depend only on the low 32 bits of the factors, so the sum and + /// the product can wrap in each 32-bit lane, and the lanes give the same hashes. + /// + /// The ARGB pixels, one in each lane. + /// The hashes, from 0 to 255, one in each lane. [MethodImpl(InliningOptions.ShortMethod)] - private static uint ApplyPaletteHash2(uint color) => (uint)((color & 0x00ffffffu) * ((1ul << 31) - 1)) >> (32 - PaletteInvSizeBits); // Forget about alpha. + private static Vector128 HashPix(Vector128 pix) => ((pix + (pix >>> 19)) * Vector128.Create(0x39c5fba7u)) >>> 24; - // Note that masking with 0xffffffffu is for preventing an - // 'unsigned int overflow' warning. Doesn't impact the compiled code. + /// + /// Hashes eight pixels to 8 bits each, as does. The lanes wrap as in the 128-bit form. + /// + /// The ARGB pixels, one in each lane. + /// The hashes, from 0 to 255, one in each lane. [MethodImpl(InliningOptions.ShortMethod)] - private static uint HashPix(uint pix) => (uint)((((long)pix + (pix >> 19)) * 0x39c5fba7L) & 0xffffffffu) >> 24; + private static Vector256 HashPix(Vector256 pix) => ((pix + (pix >>> 19)) * Vector256.Create(0x39c5fba7u)) >>> 24; + /// + /// Hashes sixteen pixels to 8 bits each, as does. The lanes wrap as in the 128-bit form. + /// + /// The ARGB pixels, one in each lane. + /// The hashes, from 0 to 255, one in each lane. [MethodImpl(InliningOptions.ShortMethod)] - private static int PaletteCompareColorsForSort(uint p1, uint p2) => p1 < p2 ? -1 : 1; + private static Vector512 HashPix(Vector512 pix) => ((pix + (pix >>> 19)) * Vector512.Create(0x39c5fba7u)) >>> 24; + /// + /// Gets the distance of a component difference from zero, mod 256. + /// + /// The component difference, from 0 to 255. + /// The distance, from 0 to 128. [MethodImpl(InliningOptions.ShortMethod)] private static uint PaletteComponentDistance(uint v) => (v <= 128) ? v : (256 - v); + /// + /// Makes sure that the scratch buffer of the predictor transform is large enough for the current transforms. The buffer is allocated + /// again only when it is too small. The current width is set to the image width. + /// + /// The image width. + /// The image height. public void AllocateTransformBuffer(int width, int height) { - // VP8LResidualImage needs room for 2 scanlines of uint32 pixels with an extra - // pixel in each, plus 2 regular scanlines of bytes. - int bgraScratchSize = this.UsePredictorTransform ? ((width + 1) * 2) + (((width * 2) + 4 - 1) / 4) : 0; - int transformDataSize = this.UsePredictorTransform || this.UseCrossColorTransform - ? LosslessUtils.SubSampleSize(width, this.TransformBits) * LosslessUtils.SubSampleSize(height, this.TransformBits) - : 0; - - this.BgraScratch = this.memoryAllocator.Allocate(bgraScratchSize); - this.TransformData = this.memoryAllocator.Allocate(transformDataSize); + // The predictor transform owns the layout of its scratch buffer. + int bgraScratchSize = this.UsePredictorTransform ? PredictorEncoder.GetScratchSize(width) : 0; + + // Keep a buffer that is large enough for this config. The users take only the part that the config needs, + // so a larger buffer from an earlier config is correct. Replace a buffer only when it is too small. + if (this.BgraScratch is null || this.BgraScratch.Memory.Length < bgraScratchSize) + { + this.BgraScratch?.Dispose(); + this.BgraScratch = this.memoryAllocator.Allocate(bgraScratchSize); + } + this.CurrentWidth = width; } + /// + /// Makes sure that has the size of the transform image of the current transform. The transforms read the + /// plane by rows, so it has the exact size: the palette mapping can make the working image narrower than the input image. + /// The plane is allocated again only when its size changes. + /// + /// The width of the transform image. + /// The height of the transform image. + private void SetTransformImageSize(int transformWidth, int transformHeight) + { + if (this.TransformData is null || this.TransformData.Width != transformWidth || this.TransformData.Height != transformHeight) + { + this.TransformData?.Dispose(); + this.TransformData = this.memoryAllocator.Allocate2D(transformWidth, transformHeight); + } + } + + /// + /// Sets the size of the input image. The input plane is allocated again only when its size changes, as for the frames of an animation. + /// + /// The image width. + /// The image height. + public void SetImageSize(int width, int height) + { + if (this.Bgra.Width != width || this.Bgra.Height != height) + { + this.Bgra.Dispose(); + this.Bgra = this.memoryAllocator.Allocate2D(width, height); + } + + this.EncodedData = this.Bgra; + } + + /// + /// Gets the working copy with a size. The plane is allocated again only when its size changes. No clear: the caller writes each pixel. + /// + /// The width of the working image. + /// The height of the working image. + /// The working copy. + private Buffer2D GetWorkingCopy(int width, int height) + { + if (this.workingCopy is null || this.workingCopy.Width != width || this.workingCopy.Height != height) + { + this.workingCopy?.Dispose(); + this.workingCopy = this.memoryAllocator.Allocate2D(width, height); + } + + return this.workingCopy; + } + /// /// Clears the backward references. /// public void ClearRefs() { - foreach (Vp8LBackwardRefs refs in this.Refs) + foreach (Vp8LBackwardReferences refs in this.Refs) { refs.Clear(); } @@ -2018,17 +2530,50 @@ public void ClearRefs() /// public void Dispose() { + this.bitWriter?.Dispose(); this.Bgra.Dispose(); - this.EncodedData.Dispose(); + this.workingCopy?.Dispose(); this.BgraScratch?.Dispose(); this.Palette.Dispose(); this.TransformData?.Dispose(); - foreach (Vp8LBackwardRefs refs in this.Refs) + foreach (Vp8LBackwardReferences refs in this.Refs) { refs.Dispose(); } this.HashChain.Dispose(); } + + /// + /// Hashes a color to its green channel. + /// + private readonly struct PaletteHashGreen : IPaletteHashOperator + { + /// + [MethodImpl(InliningOptions.ShortMethod)] + public static uint Hash(uint color) => (color >> 8) & 0xff; // Focus on the green color. + } + + /// + /// Hashes the RGB channels of a color with a multiplicative hash. + /// The hash is the top bits of the low 32 bits of the product. + /// + private readonly struct PaletteHashRgb : IPaletteHashOperator + { + /// + [MethodImpl(InliningOptions.ShortMethod)] + public static uint Hash(uint color) => (uint)((color & 0x00ffffffu) * 4222244071ul) >> (32 - PaletteInvSizeBits); // Forget about alpha. + } + + /// + /// Hashes the RGB channels of a color with a second multiplicative hash, with the multiplier 2^31 - 1. + /// The hash is the top bits of the low 32 bits of the product. + /// + private readonly struct PaletteHashRgbMersenne : IPaletteHashOperator + { + /// + [MethodImpl(InliningOptions.ShortMethod)] + public static uint Hash(uint color) => (uint)((color & 0x00ffffffu) * ((1ul << 31) - 1)) >> (32 - PaletteInvSizeBits); // Forget about alpha. + } } diff --git a/src/ImageSharp/Formats/Webp/Lossless/Vp8LHashChain.cs b/src/ImageSharp/Formats/Webp/Lossless/Vp8LHashChain.cs index 45cd027655..e47215a799 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/Vp8LHashChain.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/Vp8LHashChain.cs @@ -3,18 +3,34 @@ using System.Buffers; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using SixLabors.ImageSharp.Memory; namespace SixLabors.ImageSharp.Formats.Webp.Lossless; +/// +/// Finds the best backward match at each pixel of an image. Each entry stores the offset and the length of the match. +/// internal sealed class Vp8LHashChain : IDisposable { + /// + /// The hash multiplier of the second pixel of a pixel pair. + /// private const uint HashMultiplierHi = 0xc6a4a793u; + /// + /// The hash multiplier of the first pixel of a pixel pair. + /// private const uint HashMultiplierLo = 0x5bd1e996u; + /// + /// The number of bits of a pixel pair hash. + /// private const int HashBits = 18; + /// + /// The number of entries in the table from a hash to the last pixel with that hash. + /// private const int HashSize = 1 << HashBits; /// @@ -27,27 +43,35 @@ internal sealed class Vp8LHashChain : IDisposable /// private const int WindowSize = (1 << WindowSizeBits) - 120; + /// + /// The memory allocator for the temporary hash table. + /// private readonly MemoryAllocator memoryAllocator; /// /// Initializes a new instance of the class. /// /// The memory allocator. - /// The size off the chain. - public Vp8LHashChain(MemoryAllocator memoryAllocator, int size) + /// The width of the largest image of the chain. + /// The height of the largest image of the chain. + public Vp8LHashChain(MemoryAllocator memoryAllocator, int width, int height) { this.memoryAllocator = memoryAllocator; - this.OffsetLength = this.memoryAllocator.Allocate(size, AllocationOptions.Clean); - this.Size = size; + + // No clear: Fill and the box LZ77 search write each entry they use before it is read. The plane comes from the pool in buffers + // of whole rows, so a large image causes no unpooled memory. An image of the chain can be smaller than the plane. It uses the + // flat positions from 0. + this.OffsetLength = this.memoryAllocator.Allocate2D(width, height); + this.Size = width * height; } /// - /// Gets the offset length. + /// Gets the offset length of each pixel, at the flat position of the pixel. /// The 20 most significant bits contain the offset at which the best match is found. /// These 20 bits are the limit defined by GetWindowSizeForHashChain (through WindowSize = 1 << 20). /// The lower 12 bits contain the length of the match. /// - public IMemoryOwner OffsetLength { get; } + public Buffer2D OffsetLength { get; } /// /// Gets the size of the hash chain. @@ -56,46 +80,70 @@ public Vp8LHashChain(MemoryAllocator memoryAllocator, int size) /// public int Size { get; } - public void Fill(ReadOnlySpan bgra, uint quality, int xSize, int ySize, bool lowEffort) + /// + /// Finds the best backward match at each pixel and stores it in . The first and the last pixel get no match. + /// A higher quality searches more candidates in a larger window. + /// + /// The BGRA pixels, at their flat positions. + /// The encoding quality, from 0 to 100. + /// The image width. + /// The image height. + /// Whether to skip the first checks of the pixel above and the previous pixel. + public void Fill(Buffer2D bgra, uint quality, int xSize, int ySize, bool lowEffort) { int size = xSize * ySize; int iterMax = GetMaxItersForQuality(quality); int windowSize = GetWindowSizeForHashChain(quality, xSize); int pos; + Buffer2D offsetLength = this.OffsetLength; + + // Each plane read keeps the buffer of its last position, so it gets a new buffer only at a buffer end. The reads of the current + // search pixel, of the match candidates, of the chain links and of the entries of the current search pixel go to different + // places, so each has its own buffer. + Span pixels = default; + int pixelsStart = 0; + Span candidates = default; + int candidatesStart = 0; + Span links = default; + int linksStart = 0; + Span entries = default; + int entriesStart = 0; if (size <= 2) { - this.OffsetLength.GetSpan()[0] = 0; + LosslessUtils.GetPlaneValue(offsetLength, 0, ref entries, ref entriesStart) = 0; + LosslessUtils.GetPlaneValue(offsetLength, size - 1, ref entries, ref entriesStart) = 0; return; } using IMemoryOwner hashToFirstIndexBuffer = this.memoryAllocator.Allocate(HashSize); - using IMemoryOwner chainBuffer = this.memoryAllocator.Allocate(size, AllocationOptions.Clean); Span hashToFirstIndex = hashToFirstIndexBuffer.GetSpan(); - Span chain = chainBuffer.GetSpan(); - // Initialize hashToFirstIndex array to -1. + // The chain links each pixel to the previous pixel with the same hash. It uses the offset length memory, with each link stored + // as the unsigned value of the signed position, so -1 ends the chain. The match search below goes from the last pixel to the + // first. It reads chain entries only at the current search pixel and below. It writes entries only from the current search + // pixel down to, but not including, the next search pixel. Thus the search never reads a chain entry after it writes an + // offset length to it. hashToFirstIndex.Fill(-1); // Fill the chain linking pixels with the same hash. - bool bgraComp = bgra.Length > 1 && bgra[0] == bgra[1]; - Span tmp = stackalloc uint[2]; + bool bgraComp = LosslessUtils.GetPlaneValue(bgra, 0, ref pixels, ref pixelsStart) == LosslessUtils.GetPlaneValue(bgra, 1, ref pixels, ref pixelsStart); for (pos = 0; pos < size - 2;) { uint hashCode; - bool bgraCompNext = bgra[pos + 1] == bgra[pos + 2]; + uint pixel = LosslessUtils.GetPlaneValue(bgra, pos, ref pixels, ref pixelsStart); + uint nextPixel = LosslessUtils.GetPlaneValue(bgra, pos + 1, ref pixels, ref pixelsStart); + bool bgraCompNext = nextPixel == LosslessUtils.GetPlaneValue(bgra, pos + 2, ref pixels, ref pixelsStart); if (bgraComp && bgraCompNext) { // Consecutive pixels with the same color will share the same hash. // We therefore use a different hash: the color and its repetition length. - tmp.Clear(); uint len = 1; - tmp[0] = bgra[pos]; // Figure out how far the pixels are the same. The last pixel has a different 64 bit hash, // as its next pixel does not have the same color, so we just need to get to // the last pixel equal to its follower. - while (pos + (int)len + 2 < size && bgra[(int)(pos + len + 2)] == bgra[pos]) + while (pos + (int)len + 2 < size && LosslessUtils.GetPlaneValue(bgra, (int)(pos + len + 2), ref pixels, ref pixelsStart) == pixel) { ++len; } @@ -104,8 +152,8 @@ public void Fill(ReadOnlySpan bgra, uint quality, int xSize, int ySize, bo { // Skip the pixels that match for distance=1 and length>MaxLength // because they are linked to their predecessor and we automatically - // check that in the main for loop below. Skipping means setting no - // predecessor in the chain, hence -1. + // check that in the main for loop below. A skipped pixel has no predecessor in the chain, so its entry is -1. + LosslessUtils.FillPlane(offsetLength, pos, (int)(len - BackwardReferenceEncoder.MaxLength), uint.MaxValue); pos += (int)(len - BackwardReferenceEncoder.MaxLength); len = BackwardReferenceEncoder.MaxLength; } @@ -113,9 +161,8 @@ public void Fill(ReadOnlySpan bgra, uint quality, int xSize, int ySize, bo // Process the rest of the hash chain. while (len > 0) { - tmp[1] = len--; - hashCode = GetPixPairHash64(tmp); - chain[pos] = hashToFirstIndex[(int)hashCode]; + hashCode = GetPixPairHash64(pixel, len--); + LosslessUtils.GetPlaneValue(offsetLength, pos, ref links, ref linksStart) = (uint)hashToFirstIndex[(int)hashCode]; hashToFirstIndex[(int)hashCode] = pos++; } @@ -124,21 +171,25 @@ public void Fill(ReadOnlySpan bgra, uint quality, int xSize, int ySize, bo else { // Just move one pixel forward. - hashCode = GetPixPairHash64(bgra[pos..]); - chain[pos] = hashToFirstIndex[(int)hashCode]; + hashCode = GetPixPairHash64(pixel, nextPixel); + LosslessUtils.GetPlaneValue(offsetLength, pos, ref links, ref linksStart) = (uint)hashToFirstIndex[(int)hashCode]; hashToFirstIndex[(int)hashCode] = pos++; bgraComp = bgraCompNext; } } // Process the penultimate pixel. - chain[pos] = hashToFirstIndex[(int)GetPixPairHash64(bgra[pos..])]; + uint penultimateHash = GetPixPairHash64( + LosslessUtils.GetPlaneValue(bgra, pos, ref pixels, ref pixelsStart), + LosslessUtils.GetPlaneValue(bgra, pos + 1, ref pixels, ref pixelsStart)); + + LosslessUtils.GetPlaneValue(offsetLength, pos, ref links, ref linksStart) = (uint)hashToFirstIndex[(int)penultimateHash]; // Find the best match interval at each pixel, defined by an offset to the // pixel and a length. The right-most pixel cannot match anything to the right // (hence a best length of 0) and the left-most pixel nothing to the left (hence an offset of 0). - Span offsetLength = this.OffsetLength.GetSpan(); - offsetLength[0] = offsetLength[size - 1] = 0; + // The entry of pixel 0 is written after the search, because the search can still read the chain entry of pixel 0. + LosslessUtils.GetPlaneValue(offsetLength, size - 1, ref entries, ref entriesStart) = 0; for (int basePosition = size - 2; basePosition > 0;) { int maxLen = LosslessUtils.MaxFindCopyLength(size - 1 - basePosition); @@ -148,7 +199,7 @@ public void Fill(ReadOnlySpan bgra, uint quality, int xSize, int ySize, bo uint bestDistance = 0; int minPos = basePosition > windowSize ? basePosition - windowSize : 0; int lengthMax = maxLen < 256 ? maxLen : 256; - pos = chain[basePosition]; + pos = (int)LosslessUtils.GetPlaneValue(offsetLength, basePosition, ref entries, ref entriesStart); int currLength; if (!lowEffort) @@ -156,7 +207,17 @@ public void Fill(ReadOnlySpan bgra, uint quality, int xSize, int ySize, bo // Heuristic: use the comparison with the above line as an initialization. if (basePosition >= (uint)xSize) { - currLength = LosslessUtils.FindMatchLength(bgra[(bgraStart - xSize)..], bgra[bgraStart..], bestLength, maxLen); + currLength = LosslessUtils.FindMatchLength( + bgra, + bgraStart - xSize, + bgraStart, + bestLength, + maxLen, + ref candidates, + ref candidatesStart, + ref pixels, + ref pixelsStart); + if (currLength > bestLength) { bestLength = currLength; @@ -167,7 +228,17 @@ public void Fill(ReadOnlySpan bgra, uint quality, int xSize, int ySize, bo } // Heuristic: compare to the previous pixel. - currLength = LosslessUtils.FindMatchLength(bgra[(bgraStart - 1)..], bgra[bgraStart..], bestLength, maxLen); + currLength = LosslessUtils.FindMatchLength( + bgra, + bgraStart - 1, + bgraStart, + bestLength, + maxLen, + ref candidates, + ref candidatesStart, + ref pixels, + ref pixelsStart); + if (currLength > bestLength) { bestLength = currLength; @@ -183,21 +254,21 @@ public void Fill(ReadOnlySpan bgra, uint quality, int xSize, int ySize, bo } } - uint bestBgra = bgra[bgraStart..][bestLength]; + uint bestBgra = LosslessUtils.GetPlaneValue(bgra, bgraStart + bestLength, ref pixels, ref pixelsStart); - for (; pos >= minPos && (--iter > 0); pos = chain[pos]) + for (; pos >= minPos && (--iter > 0); pos = (int)LosslessUtils.GetPlaneValue(offsetLength, pos, ref links, ref linksStart)) { - if (bgra[pos + bestLength] != bestBgra) + if (LosslessUtils.GetPlaneValue(bgra, pos + bestLength, ref candidates, ref candidatesStart) != bestBgra) { continue; } - currLength = LosslessUtils.VectorMismatch(bgra[pos..], bgra[bgraStart..], maxLen); + currLength = LosslessUtils.CommonPrefixLength(bgra, pos, bgraStart, maxLen, ref candidates, ref candidatesStart, ref pixels, ref pixelsStart); if (bestLength < currLength) { bestLength = currLength; bestDistance = (uint)(basePosition - pos); - bestBgra = bgra[bgraStart..][bestLength]; + bestBgra = LosslessUtils.GetPlaneValue(bgra, bgraStart + bestLength, ref pixels, ref pixelsStart); // Stop if we have reached a good enough length. if (bestLength >= lengthMax) @@ -212,7 +283,9 @@ public void Fill(ReadOnlySpan bgra, uint quality, int xSize, int ySize, bo uint maxBasePosition = (uint)basePosition; while (true) { - offsetLength[basePosition] = (bestDistance << BackwardReferenceEncoder.MaxLengthBits) | (uint)bestLength; + LosslessUtils.GetPlaneValue(offsetLength, basePosition, ref entries, ref entriesStart) = + (bestDistance << BackwardReferenceEncoder.MaxLengthBits) | (uint)bestLength; + --basePosition; // Stop if we don't have a match or if we are out of bounds. @@ -222,7 +295,9 @@ public void Fill(ReadOnlySpan bgra, uint quality, int xSize, int ySize, bo } // Stop if we cannot extend the matching intervals to the left. - if (basePosition < bestDistance || bgra[(int)(basePosition - bestDistance)] != bgra[basePosition]) + if (basePosition < bestDistance + || LosslessUtils.GetPlaneValue(bgra, (int)(basePosition - bestDistance), ref candidates, ref candidatesStart) + != LosslessUtils.GetPlaneValue(bgra, basePosition, ref pixels, ref pixelsStart)) { break; } @@ -244,24 +319,37 @@ public void Fill(ReadOnlySpan bgra, uint quality, int xSize, int ySize, bo } } } + + LosslessUtils.GetPlaneValue(offsetLength, 0, ref entries, ref entriesStart) = 0; } + /// + /// Gets the length of the best match from an entry of . + /// + /// The entry with the offset and the length of the match. + /// The match length. [MethodImpl(InliningOptions.ShortMethod)] - public int FindLength(int basePosition) => (int)(this.OffsetLength.GetSpan()[basePosition] & ((1U << BackwardReferenceEncoder.MaxLengthBits) - 1)); + public static int FindLength(uint offsetLength) => (int)(offsetLength & ((1U << BackwardReferenceEncoder.MaxLengthBits) - 1)); + /// + /// Gets the offset of the best match from an entry of . + /// + /// The entry with the offset and the length of the match. + /// The match offset. [MethodImpl(InliningOptions.ShortMethod)] - public int FindOffset(int basePosition) => (int)(this.OffsetLength.GetSpan()[basePosition] >> BackwardReferenceEncoder.MaxLengthBits); + public static int FindOffset(uint offsetLength) => (int)(offsetLength >> BackwardReferenceEncoder.MaxLengthBits); /// - /// Calculates the hash for a pixel pair. + /// Calculates the hash for a pixel pair. A run of equal pixels uses the pair of its color and its repetition length. /// - /// An Span with two pixels. + /// The first value of the pair. + /// The second value of the pair. /// The hash. [MethodImpl(InliningOptions.ShortMethod)] - private static uint GetPixPairHash64(ReadOnlySpan bgra) + private static uint GetPixPairHash64(uint first, uint second) { - uint key = bgra[1] * HashMultiplierHi; - key += bgra[0] * HashMultiplierLo; + uint key = second * HashMultiplierHi; + key += first * HashMultiplierLo; key >>= 32 - HashBits; return key; } @@ -275,6 +363,13 @@ private static uint GetPixPairHash64(ReadOnlySpan bgra) [MethodImpl(InliningOptions.ShortMethod)] private static int GetMaxItersForQuality(uint quality) => (int)(8 + (quality * quality / 128)); + /// + /// Gets the maximum match distance for a quality. Above quality 75, it is . + /// Lower qualities use 256, 64 or 16 rows, but never more than . + /// + /// The encoding quality, from 0 to 100. + /// The image width. + /// The maximum match distance in pixels. [MethodImpl(InliningOptions.ShortMethod)] private static int GetWindowSizeForHashChain(uint quality, int xSize) { diff --git a/src/ImageSharp/Formats/Webp/Lossless/Vp8LHistogram.cs b/src/ImageSharp/Formats/Webp/Lossless/Vp8LHistogram.cs index 937f3e32bd..86e0ffd66e 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/Vp8LHistogram.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/Vp8LHistogram.cs @@ -4,56 +4,122 @@ using System.Buffers; using System.Numerics.Tensors; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; using SixLabors.ImageSharp.Common.Helpers; using SixLabors.ImageSharp.Memory; namespace SixLabors.ImageSharp.Formats.Webp.Lossless; -internal abstract unsafe class Vp8LHistogram +/// +/// Counts the symbols of the five lossless Huffman codes (literal, red, blue, alpha and distance) and caches their estimated costs. +/// The counts are in a backing memory that the derived type provides. +/// +internal abstract class Vp8LHistogram { + /// + /// The trivial symbol value of a histogram that has no single trivial symbol. + /// private const uint NonTrivialSym = 0xffffffff; - private readonly uint* red; - private readonly uint* blue; - private readonly uint* alpha; - private readonly uint* distance; - private readonly uint* literal; - private readonly uint* isUsed; + /// + /// The number of entries of the red histogram. + /// private const int RedSize = WebpConstants.NumLiteralCodes; + + /// + /// The number of entries of the blue histogram. + /// private const int BlueSize = WebpConstants.NumLiteralCodes; + + /// + /// The number of entries of the alpha histogram. + /// private const int AlphaSize = WebpConstants.NumLiteralCodes; + + /// + /// The number of entries of the distance histogram. + /// private const int DistanceSize = WebpConstants.NumDistanceCodes; - public const int LiteralSize = WebpConstants.NumLiteralCodes + WebpConstants.NumLengthCodes + (1 << WebpConstants.MaxColorCacheBits) + 1; + + /// + /// The number of used flags. + /// private const int UsedSize = 5; // 5 for literal, red, blue, alpha, distance - public const int BufferSize = RedSize + BlueSize + AlphaSize + DistanceSize + LiteralSize + UsedSize; + + // The channels are stored one after the other in the backing memory: + // red, blue, alpha, distance, literal, then the used flags. + // The literal size changes with the palette code bits, so the used flags have an offset for each instance. + // The offsets are public, so a caller that walks many histograms of one set can index one span of the set's memory. + + /// + /// The offset of the red channel in the backing memory. + /// + public const int RedOffset = 0; + + /// + /// The offset of the blue channel in the backing memory. + /// + public const int BlueOffset = RedOffset + RedSize; + + /// + /// The offset of the alpha channel in the backing memory. + /// + public const int AlphaOffset = BlueOffset + BlueSize; + + /// + /// The offset of the distance channel in the backing memory. + /// + public const int DistanceOffset = AlphaOffset + AlphaSize; + + /// + /// The offset of the literal channel in the backing memory. + /// + public const int LiteralOffset = DistanceOffset + DistanceSize; + + /// + /// The backing memory of entries. The histogram does not own this memory. + /// + private readonly Memory buffer; + + /// + /// The number of literal entries in the backing memory. It is the number of codes for the palette code bits + /// given at construction. + /// + private readonly int literalSize; + + /// + /// The offset of the used flags in the backing memory. The flags come after the literal entries. + /// + private readonly int isUsedOffset; /// /// Initializes a new instance of the class. /// - /// The base pointer to the backing memory. + /// The backing memory of entries. /// The backward references to initialize the histogram with. /// The palette code bits. - protected Vp8LHistogram(uint* basePointer, Vp8LBackwardRefs refs, int paletteCodeBits) - : this(basePointer, paletteCodeBits) => this.StoreRefs(refs); + protected Vp8LHistogram(Memory buffer, Vp8LBackwardReferences refs, int paletteCodeBits) + : this(buffer, paletteCodeBits) => this.StoreRefs(refs, false, 0); /// /// Initializes a new instance of the class. /// - /// The base pointer to the backing memory. - /// The palette code bits. - protected Vp8LHistogram(uint* basePointer, int paletteCodeBits) + /// + /// The backing memory of entries. The caller owns this memory and keeps it alive while the histogram is used. + /// + /// The palette code bits. It also sets the size of the literal histogram. + protected Vp8LHistogram(Memory buffer, int paletteCodeBits) { this.PaletteCodeBits = paletteCodeBits; - this.red = basePointer; - this.blue = this.red + RedSize; - this.alpha = this.blue + BlueSize; - this.distance = this.alpha + AlphaSize; - this.literal = this.distance + DistanceSize; - this.isUsed = this.literal + LiteralSize; + this.literalSize = NumCodes(paletteCodeBits); + this.isUsedOffset = LiteralOffset + this.literalSize; + this.buffer = buffer; } /// /// Gets or sets the palette code bits. + /// The value must not be more than the palette code bits given at construction, because these set the literal size. /// public int PaletteCodeBits { get; set; } @@ -77,25 +143,78 @@ protected Vp8LHistogram(uint* basePointer, int paletteCodeBits) /// public double BlueCost { get; set; } - public Span Red => new(this.red, RedSize); + /// + /// Gets the red histogram. + /// + public Span Red => this.buffer.Span.Slice(RedOffset, RedSize); - public Span Blue => new(this.blue, BlueSize); + /// + /// Gets the blue histogram. + /// + public Span Blue => this.buffer.Span.Slice(BlueOffset, BlueSize); - public Span Alpha => new(this.alpha, AlphaSize); + /// + /// Gets the alpha histogram. + /// + public Span Alpha => this.buffer.Span.Slice(AlphaOffset, AlphaSize); - public Span Distance => new(this.distance, DistanceSize); + /// + /// Gets the distance histogram. + /// + public Span Distance => this.buffer.Span.Slice(DistanceOffset, DistanceSize); - public Span Literal => new(this.literal, LiteralSize); + /// + /// Gets the literal histogram. Its length is the number of codes for the palette code bits given at construction. + /// + public Span Literal => this.buffer.Span.Slice(LiteralOffset, this.literalSize); + /// + /// Gets or sets the trivial symbol: the alpha, red and blue values packed as an ARGB pixel with zero green, when each of these + /// histograms has exactly one nonzero symbol. Otherwise, the value is 0xffffffff. + /// public uint TrivialSymbol { get; set; } - private Span IsUsedSpan => new(this.isUsed, UsedSize); + /// + /// Gets the extra bit weights of 16 consecutive prefix code terms, from an even term: lane k has the weight 1 + (k / 2). + /// + /// + /// The data comes from the static data of the assembly, so the property allocates no memory. + /// + private static ReadOnlySpan ExtraBitsWeights => [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8]; - private Span TotalSpan => new(this.red, BufferSize); + /// + /// Gets the used flags of the literal, red, blue, alpha and distance histograms, in this order. + /// + private Span IsUsedSpan => this.buffer.Span.Slice(this.isUsedOffset, UsedSize); + + /// + /// Gets the number of entries of the backing memory of one histogram. + /// + /// The palette code bits. These set the size of the literal histogram. + /// The number of entries. + public static int GetBufferSize(int paletteCodeBits) => RedSize + BlueSize + AlphaSize + DistanceSize + NumCodes(paletteCodeBits) + UsedSize; + /// + /// Gets the number of literal codes: the literals, the length prefix codes and the color cache codes. + /// + /// The palette code bits. Zero means no color cache. + /// The number of literal codes. + public static int NumCodes(int paletteCodeBits) + => WebpConstants.NumLiteralCodes + WebpConstants.NumLengthCodes + (paletteCodeBits > 0 ? 1 << paletteCodeBits : 0); + + /// + /// Gets a value indicating whether a histogram has at least one nonzero count. + /// + /// The histogram index: 0 is literal, 1 is red, 2 is blue, 3 is alpha and 4 is distance. + /// if the histogram is used; otherwise, . [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsUsed(int index) => this.IsUsedSpan[index] == 1u; + /// + /// Sets the used flag of a histogram. + /// + /// The histogram index: 0 is literal, 1 is red, 2 is blue, 3 is alpha and 4 is distance. + /// Whether the histogram is used. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void IsUsed(int index, bool value) => this.IsUsedSpan[index] = value ? 1u : 0; @@ -105,12 +224,14 @@ protected Vp8LHistogram(uint* basePointer, int paletteCodeBits) /// The histogram to copy to. public void CopyTo(Vp8LHistogram other) { - this.Red.CopyTo(other.Red); - this.Blue.CopyTo(other.Blue); - this.Alpha.CopyTo(other.Alpha); - this.Literal.CopyTo(other.Literal); - this.Distance.CopyTo(other.Distance); - this.IsUsedSpan.CopyTo(other.IsUsedSpan); + // Memory.Span can call the memory manager. Get each backing span one time. + ReadOnlySpan source = this.buffer.Span; + Span destination = other.buffer.Span; + + // Red, blue, alpha and distance have fixed sizes and come first, so one copy moves all of them. + source[..LiteralOffset].CopyTo(destination); + source.Slice(LiteralOffset, this.literalSize).CopyTo(destination.Slice(LiteralOffset, other.literalSize)); + source.Slice(this.isUsedOffset, UsedSize).CopyTo(destination.Slice(other.isUsedOffset, UsedSize)); other.LiteralCost = this.LiteralCost; other.RedCost = this.RedCost; @@ -120,9 +241,12 @@ public void CopyTo(Vp8LHistogram other) other.PaletteCodeBits = this.PaletteCodeBits; } + /// + /// Sets all counts, used flags, cached costs, the trivial symbol and the palette code bits to zero. + /// public void Clear() { - this.TotalSpan.Clear(); + this.buffer.Span.Clear(); this.PaletteCodeBits = 0; this.BitCost = 0; this.LiteralCost = 0; @@ -135,39 +259,51 @@ public void Clear() /// Collect all the references into a histogram (without reset). /// /// The backward references. - public void StoreRefs(Vp8LBackwardRefs refs) + /// Indicates whether to use the distance modifier. + /// The image width. It is only used when is true. + public void StoreRefs(Vp8LBackwardReferences refs, bool useDistanceModifier, int xSize) { - foreach (PixOrCopy v in refs) + // Memory.Span can call the memory manager, so get the backing span once for all tokens. + Span histogram = this.buffer.Span; + int blockCount = refs.BlockCount; + for (int block = 0; block < blockCount; block++) { - this.AddSinglePixOrCopy(in v, false); + foreach (PixelOrCopy v in refs.GetBlock(block)) + { + AddToken(histogram, in v, useDistanceModifier, xSize); + } } } /// /// Accumulate a token 'v' into a histogram. /// + /// The backing memory of one histogram, with the channels at their offsets. /// The token to add. /// Indicates whether to use the distance modifier. - /// xSize is only used when useDistanceModifier is true. - public void AddSinglePixOrCopy(in PixOrCopy v, bool useDistanceModifier, int xSize = 0) + /// The image width. It is only used when is true. + public static void AddToken(Span histogram, in PixelOrCopy v, bool useDistanceModifier, int xSize) { if (v.IsLiteral()) { - this.Alpha[v.Literal(3)]++; - this.Red[v.Literal(2)]++; - this.Literal[v.Literal(1)]++; - this.Blue[v.Literal(0)]++; + // Literal(n) masks the component to 8 bits. Each index is less than 256, so it stays in its channel. + // The red, blue and alpha channels have 256 entries. The literal channel has more than 256 entries. + ref uint histogramRef = ref MemoryMarshal.GetReference(histogram); + Unsafe.Add(ref histogramRef, (uint)(AlphaOffset + v.Literal(3)))++; + Unsafe.Add(ref histogramRef, (uint)(RedOffset + v.Literal(2)))++; + Unsafe.Add(ref histogramRef, (uint)(LiteralOffset + v.Literal(1)))++; + Unsafe.Add(ref histogramRef, (uint)(BlueOffset + v.Literal(0)))++; } else if (v.IsCacheIdx()) { int literalIx = (int)(WebpConstants.NumLiteralCodes + WebpConstants.NumLengthCodes + v.CacheIdx()); - this.Literal[literalIx]++; + histogram[LiteralOffset + literalIx]++; } else { int extraBits = 0; int code = LosslessUtils.PrefixEncodeBits(v.Length(), ref extraBits); - this.Literal[WebpConstants.NumLiteralCodes + code]++; + histogram[LiteralOffset + WebpConstants.NumLiteralCodes + code]++; if (!useDistanceModifier) { code = LosslessUtils.PrefixEncodeBits((int)v.Distance(), ref extraBits); @@ -177,44 +313,62 @@ public void AddSinglePixOrCopy(in PixOrCopy v, bool useDistanceModifier, int xSi code = LosslessUtils.PrefixEncodeBits(BackwardReferenceEncoder.DistanceToPlaneCode(xSize, (int)v.Distance()), ref extraBits); } - this.Distance[code]++; + histogram[DistanceOffset + code]++; } } - public int NumCodes() => WebpConstants.NumLiteralCodes + WebpConstants.NumLengthCodes + (this.PaletteCodeBits > 0 ? 1 << this.PaletteCodeBits : 0); + /// + /// Gets the number of literal codes for the current palette code bits. + /// + /// The number of literal codes. + public int NumCodes() => NumCodes(this.PaletteCodeBits); /// /// Estimate how many bits the combined entropy of literals and distance approximately maps to. /// /// Estimated bits. - public double EstimateBits(Vp8LStreaks stats, Vp8LBitEntropy bitsEntropy) + public double EstimateBits() { + // Memory.Span can call the memory manager. Get the backing span one time. + Span histogram = this.buffer.Span; + Span isUsed = histogram.Slice(this.isUsedOffset, UsedSize); + ReadOnlySpan literal = histogram.Slice(LiteralOffset, this.literalSize); + ReadOnlySpan distance = histogram.Slice(DistanceOffset, DistanceSize); uint notUsed = 0; return - this.PopulationCost(this.Literal, this.NumCodes(), ref notUsed, 0, stats, bitsEntropy) - + this.PopulationCost(this.Red, WebpConstants.NumLiteralCodes, ref notUsed, 1, stats, bitsEntropy) - + this.PopulationCost(this.Blue, WebpConstants.NumLiteralCodes, ref notUsed, 2, stats, bitsEntropy) - + this.PopulationCost(this.Alpha, WebpConstants.NumLiteralCodes, ref notUsed, 3, stats, bitsEntropy) - + this.PopulationCost(this.Distance, WebpConstants.NumDistanceCodes, ref notUsed, 4, stats, bitsEntropy) - + ExtraCost(this.Literal[WebpConstants.NumLiteralCodes..], WebpConstants.NumLengthCodes) - + ExtraCost(this.Distance, WebpConstants.NumDistanceCodes); + PopulationCost(literal, this.NumCodes(), ref notUsed, out isUsed[0]) + + PopulationCost(histogram.Slice(RedOffset, RedSize), WebpConstants.NumLiteralCodes, ref notUsed, out isUsed[1]) + + PopulationCost(histogram.Slice(BlueOffset, BlueSize), WebpConstants.NumLiteralCodes, ref notUsed, out isUsed[2]) + + PopulationCost(histogram.Slice(AlphaOffset, AlphaSize), WebpConstants.NumLiteralCodes, ref notUsed, out isUsed[3]) + + PopulationCost(distance, WebpConstants.NumDistanceCodes, ref notUsed, out isUsed[4]) + + ExtraCost(literal[WebpConstants.NumLiteralCodes..], WebpConstants.NumLengthCodes) + + ExtraCost(distance, WebpConstants.NumDistanceCodes); } - public void UpdateHistogramCost(Vp8LStreaks stats, Vp8LBitEntropy bitsEntropy) + /// + /// Computes and caches the estimated costs of the histograms, the used flags and the trivial symbol. + /// + public void UpdateHistogramCost() { + // Memory.Span can call the memory manager. Get the backing span one time. + Span histogram = this.buffer.Span; + Span isUsed = histogram.Slice(this.isUsedOffset, UsedSize); + ReadOnlySpan literal = histogram.Slice(LiteralOffset, this.literalSize); + ReadOnlySpan distance = histogram.Slice(DistanceOffset, DistanceSize); uint alphaSym = 0, redSym = 0, blueSym = 0; uint notUsed = 0; - double alphaCost = this.PopulationCost(this.Alpha, WebpConstants.NumLiteralCodes, ref alphaSym, 3, stats, bitsEntropy); - double distanceCost = this.PopulationCost(this.Distance, WebpConstants.NumDistanceCodes, ref notUsed, 4, stats, bitsEntropy) - + ExtraCost(this.Distance, WebpConstants.NumDistanceCodes); + ReadOnlySpan alpha = histogram.Slice(AlphaOffset, AlphaSize); + double alphaCost = PopulationCost(alpha, WebpConstants.NumLiteralCodes, ref alphaSym, out isUsed[3]); + double distanceCost = PopulationCost(distance, WebpConstants.NumDistanceCodes, ref notUsed, out isUsed[4]) + + ExtraCost(distance, WebpConstants.NumDistanceCodes); int numCodes = this.NumCodes(); - this.LiteralCost = this.PopulationCost(this.Literal, numCodes, ref notUsed, 0, stats, bitsEntropy) - + ExtraCost(this.Literal[WebpConstants.NumLiteralCodes..], WebpConstants.NumLengthCodes); + this.LiteralCost = PopulationCost(literal, numCodes, ref notUsed, out isUsed[0]) + + ExtraCost(literal[WebpConstants.NumLiteralCodes..], WebpConstants.NumLengthCodes); - this.RedCost = this.PopulationCost(this.Red, WebpConstants.NumLiteralCodes, ref redSym, 1, stats, bitsEntropy); - this.BlueCost = this.PopulationCost(this.Blue, WebpConstants.NumLiteralCodes, ref blueSym, 2, stats, bitsEntropy); + this.RedCost = PopulationCost(histogram.Slice(RedOffset, RedSize), WebpConstants.NumLiteralCodes, ref redSym, out isUsed[1]); + this.BlueCost = PopulationCost(histogram.Slice(BlueOffset, BlueSize), WebpConstants.NumLiteralCodes, ref blueSym, out isUsed[2]); this.BitCost = this.LiteralCost + this.RedCost + this.BlueCost + alphaCost + distanceCost; if ((alphaSym | redSym | blueSym) == NonTrivialSym) { @@ -233,11 +387,15 @@ public void UpdateHistogramCost(Vp8LStreaks stats, Vp8LBitEntropy bitsEntropy) /// Since the previous score passed is 'costThreshold', we only need to compare /// the partial cost against 'costThreshold + C(a) + C(b)' to possibly bail-out early. /// - public double AddEval(Vp8LHistogram b, Vp8LStreaks stats, Vp8LBitEntropy bitsEntropy, double costThreshold, Vp8LHistogram output) + /// The histogram to add. + /// The score from which the estimate can stop. + /// Receives the sum and its cost when the score is at most the threshold. It can be this histogram or . + /// The score C(a+b) - C(a) - C(b). When the estimate stops early, the value is a partial score above the threshold. + public double AddEval(Vp8LHistogram b, double costThreshold, Vp8LHistogram output) { double sumCost = this.BitCost + b.BitCost; costThreshold += sumCost; - if (this.GetCombinedHistogramEntropy(b, stats, bitsEntropy, costThreshold, costInitial: 0, out double cost)) + if (this.GetCombinedHistogramEntropy(b, costThreshold, 0, out double cost)) { this.Add(b, output); output.BitCost = cost; @@ -247,47 +405,77 @@ public double AddEval(Vp8LHistogram b, Vp8LStreaks stats, Vp8LBitEntropy bitsEnt return cost - sumCost; } - public double AddThresh(Vp8LHistogram b, Vp8LStreaks stats, Vp8LBitEntropy bitsEntropy, double costThreshold) + /// + /// Estimates the extra cost to add a histogram to this histogram: C(a+b) - C(a). The estimate can stop early when it exceeds the threshold. + /// + /// The histogram to add. + /// The cost from which the estimate can stop. + /// The extra cost. When the estimate stops early, the value is a partial cost above the threshold. + public double AddThresh(Vp8LHistogram b, double costThreshold) { double costInitial = -this.BitCost; - this.GetCombinedHistogramEntropy(b, stats, bitsEntropy, costThreshold, costInitial, out double cost); + this.GetCombinedHistogramEntropy(b, costThreshold, costInitial, out double cost); return cost; } + /// + /// Adds the counts of two histograms and writes the sum to the output. The output is used where an input is used. + /// The output keeps the trivial symbol only when both inputs have the same trivial symbol. + /// + /// The second histogram. + /// Receives the sum. It can be this histogram or . public void Add(Vp8LHistogram b, Vp8LHistogram output) { + // Memory.Span can call the memory manager. Get each backing span one time. + ReadOnlySpan aHistogram = this.buffer.Span; + ReadOnlySpan bHistogram = b.buffer.Span; + Span outputHistogram = output.buffer.Span; + ReadOnlySpan aIsUsed = aHistogram.Slice(this.isUsedOffset, UsedSize); + ReadOnlySpan bIsUsed = bHistogram.Slice(b.isUsedOffset, UsedSize); + Span outputIsUsed = outputHistogram.Slice(output.isUsedOffset, UsedSize); + + // The number of literal codes comes from the current palette code bits. + // It can be less than the literal size given at construction. int literalSize = this.NumCodes(); - this.AddLiteral(b, output, literalSize); - this.AddRed(b, output, WebpConstants.NumLiteralCodes); - this.AddBlue(b, output, WebpConstants.NumLiteralCodes); - this.AddAlpha(b, output, WebpConstants.NumLiteralCodes); - this.AddDistance(b, output, WebpConstants.NumDistanceCodes); + AddChannel(aHistogram, bHistogram, outputHistogram, LiteralOffset, literalSize, aIsUsed[0] == 1u, bIsUsed[0] == 1u); + AddChannel(aHistogram, bHistogram, outputHistogram, RedOffset, WebpConstants.NumLiteralCodes, aIsUsed[1] == 1u, bIsUsed[1] == 1u); + AddChannel(aHistogram, bHistogram, outputHistogram, BlueOffset, WebpConstants.NumLiteralCodes, aIsUsed[2] == 1u, bIsUsed[2] == 1u); + AddChannel(aHistogram, bHistogram, outputHistogram, AlphaOffset, WebpConstants.NumLiteralCodes, aIsUsed[3] == 1u, bIsUsed[3] == 1u); + AddChannel(aHistogram, bHistogram, outputHistogram, DistanceOffset, WebpConstants.NumDistanceCodes, aIsUsed[4] == 1u, bIsUsed[4] == 1u); - for (int i = 0; i < 5; i++) + for (int i = 0; i < UsedSize; i++) { - output.IsUsed(i, this.IsUsed(i) | b.IsUsed(i)); + outputIsUsed[i] = (aIsUsed[i] == 1u) | (bIsUsed[i] == 1u) ? 1u : 0; } - output.TrivialSymbol = this.TrivialSymbol == b.TrivialSymbol - ? this.TrivialSymbol - : NonTrivialSym; + output.TrivialSymbol = this.TrivialSymbol == b.TrivialSymbol ? this.TrivialSymbol : NonTrivialSym; } - public bool GetCombinedHistogramEntropy( - Vp8LHistogram b, - Vp8LStreaks stats, - Vp8LBitEntropy bitEntropy, - double costThreshold, - double costInitial, - out double cost) + /// + /// Estimates the cost of the sum of this histogram and another histogram, without computing the sum. The method adds the cost of + /// each code to the initial cost and stops when the cost exceeds the threshold. + /// + /// The second histogram. + /// The cost from which the method stops. + /// The start value of the cost. + /// Receives the cost. When the method stops early, the value is a partial cost above the threshold. + /// if the cost is at most the threshold; otherwise, . + public bool GetCombinedHistogramEntropy(Vp8LHistogram b, double costThreshold, double costInitial, out double cost) { + // Memory.Span can call the memory manager. Get each backing span one time. + ReadOnlySpan aHistogram = this.buffer.Span; + ReadOnlySpan bHistogram = b.buffer.Span; + ReadOnlySpan aIsUsed = aHistogram.Slice(this.isUsedOffset, UsedSize); + ReadOnlySpan bIsUsed = bHistogram.Slice(b.isUsedOffset, UsedSize); + ReadOnlySpan aLiteral = aHistogram.Slice(LiteralOffset, this.literalSize); + ReadOnlySpan bLiteral = bHistogram.Slice(LiteralOffset, b.literalSize); bool trivialAtEnd = false; cost = costInitial; - cost += GetCombinedEntropy(this.Literal, b.Literal, this.NumCodes(), this.IsUsed(0), b.IsUsed(0), false, stats, bitEntropy); + cost += GetCombinedEntropy(aLiteral, bLiteral, this.NumCodes(), aIsUsed[0] == 1u, bIsUsed[0] == 1u, false); - cost += ExtraCostCombined(this.Literal[WebpConstants.NumLiteralCodes..], b.Literal[WebpConstants.NumLiteralCodes..], WebpConstants.NumLengthCodes); + cost += ExtraCostCombined(aLiteral[WebpConstants.NumLiteralCodes..], bLiteral[WebpConstants.NumLiteralCodes..], WebpConstants.NumLengthCodes); if (cost > costThreshold) { @@ -308,161 +496,102 @@ public bool GetCombinedHistogramEntropy( } } - cost += GetCombinedEntropy(this.Red, b.Red, WebpConstants.NumLiteralCodes, this.IsUsed(1), b.IsUsed(1), trivialAtEnd, stats, bitEntropy); + ReadOnlySpan aRed = aHistogram.Slice(RedOffset, RedSize); + ReadOnlySpan bRed = bHistogram.Slice(RedOffset, RedSize); + cost += GetCombinedEntropy(aRed, bRed, WebpConstants.NumLiteralCodes, aIsUsed[1] == 1u, bIsUsed[1] == 1u, trivialAtEnd); + if (cost > costThreshold) { return false; } - cost += GetCombinedEntropy(this.Blue, b.Blue, WebpConstants.NumLiteralCodes, this.IsUsed(2), b.IsUsed(2), trivialAtEnd, stats, bitEntropy); + ReadOnlySpan aBlue = aHistogram.Slice(BlueOffset, BlueSize); + ReadOnlySpan bBlue = bHistogram.Slice(BlueOffset, BlueSize); + cost += GetCombinedEntropy(aBlue, bBlue, WebpConstants.NumLiteralCodes, aIsUsed[2] == 1u, bIsUsed[2] == 1u, trivialAtEnd); + if (cost > costThreshold) { return false; } - cost += GetCombinedEntropy(this.Alpha, b.Alpha, WebpConstants.NumLiteralCodes, this.IsUsed(3), b.IsUsed(3), trivialAtEnd, stats, bitEntropy); + ReadOnlySpan aAlpha = aHistogram.Slice(AlphaOffset, AlphaSize); + ReadOnlySpan bAlpha = bHistogram.Slice(AlphaOffset, AlphaSize); + cost += GetCombinedEntropy(aAlpha, bAlpha, WebpConstants.NumLiteralCodes, aIsUsed[3] == 1u, bIsUsed[3] == 1u, trivialAtEnd); + if (cost > costThreshold) { return false; } - cost += GetCombinedEntropy(this.Distance, b.Distance, WebpConstants.NumDistanceCodes, this.IsUsed(4), b.IsUsed(4), false, stats, bitEntropy); + ReadOnlySpan aDistance = aHistogram.Slice(DistanceOffset, DistanceSize); + ReadOnlySpan bDistance = bHistogram.Slice(DistanceOffset, DistanceSize); + cost += GetCombinedEntropy(aDistance, bDistance, WebpConstants.NumDistanceCodes, aIsUsed[4] == 1u, bIsUsed[4] == 1u, false); if (cost > costThreshold) { return false; } - cost += ExtraCostCombined(this.Distance, b.Distance, WebpConstants.NumDistanceCodes); + cost += ExtraCostCombined(aDistance, bDistance, WebpConstants.NumDistanceCodes); return cost <= costThreshold; } - private void AddLiteral(Vp8LHistogram b, Vp8LHistogram output, int literalSize) - { - if (this.IsUsed(0)) - { - if (b.IsUsed(0)) - { - TensorPrimitives.Add(this.Literal[..literalSize], b.Literal[..literalSize], output.Literal[..literalSize]); - } - else - { - this.Literal[..literalSize].CopyTo(output.Literal); - } - } - else if (b.IsUsed(0)) - { - b.Literal[..literalSize].CopyTo(output.Literal); - } - else - { - output.Literal[..literalSize].Clear(); - } - } - - private void AddRed(Vp8LHistogram b, Vp8LHistogram output, int size) - { - if (this.IsUsed(1)) - { - if (b.IsUsed(1)) - { - TensorPrimitives.Add(this.Red[..size], b.Red[..size], output.Red[..size]); - } - else - { - this.Red[..size].CopyTo(output.Red); - } - } - else if (b.IsUsed(1)) - { - b.Red[..size].CopyTo(output.Red); - } - else - { - output.Red[..size].Clear(); - } - } - - private void AddBlue(Vp8LHistogram b, Vp8LHistogram output, int size) - { - if (this.IsUsed(2)) - { - if (b.IsUsed(2)) - { - TensorPrimitives.Add(this.Blue[..size], b.Blue[..size], output.Blue[..size]); - } - else - { - this.Blue[..size].CopyTo(output.Blue); - } - } - else if (b.IsUsed(2)) - { - b.Blue[..size].CopyTo(output.Blue); - } - else - { - output.Blue[..size].Clear(); - } - } - - private void AddAlpha(Vp8LHistogram b, Vp8LHistogram output, int size) + /// + /// Adds one channel of two histograms into the same channel of the output histogram. + /// + /// The backing span of the first histogram. + /// The backing span of the second histogram. + /// The backing span of the output histogram. It can be the same memory as or . + /// The offset of the channel in each backing span. + /// The number of channel entries to add. + /// The used flag of the channel in the first histogram. + /// The used flag of the channel in the second histogram. + private static void AddChannel(ReadOnlySpan a, ReadOnlySpan b, Span output, int offset, int length, bool isAUsed, bool isBUsed) { - if (this.IsUsed(3)) - { - if (b.IsUsed(3)) - { - TensorPrimitives.Add(this.Alpha[..size], b.Alpha[..size], output.Alpha[..size]); - } - else - { - this.Alpha[..size].CopyTo(output.Alpha); - } - } - else if (b.IsUsed(3)) - { - b.Alpha[..size].CopyTo(output.Alpha); - } - else - { - output.Alpha[..size].Clear(); - } - } + ReadOnlySpan aChannel = a.Slice(offset, length); + ReadOnlySpan bChannel = b.Slice(offset, length); + Span outputChannel = output.Slice(offset, length); - private void AddDistance(Vp8LHistogram b, Vp8LHistogram output, int size) - { - if (this.IsUsed(4)) + // Add only when both channels are used. When one channel is used, copy it. + // When no channel is used, clear the output. + if (isAUsed) { - if (b.IsUsed(4)) + if (isBUsed) { - TensorPrimitives.Add(this.Distance[..size], b.Distance[..size], output.Distance[..size]); + TensorPrimitives.Add(aChannel, bChannel, outputChannel); } else { - this.Distance[..size].CopyTo(output.Distance); + aChannel.CopyTo(outputChannel); } } - else if (b.IsUsed(4)) + else if (isBUsed) { - b.Distance[..size].CopyTo(output.Distance); + bChannel.CopyTo(outputChannel); } else { - output.Distance[..size].Clear(); + outputChannel.Clear(); } } - private static double GetCombinedEntropy( - ReadOnlySpan x, - ReadOnlySpan y, - int length, - bool isXUsed, - bool isYUsed, - bool trivialAtEnd, - Vp8LStreaks stats, - Vp8LBitEntropy bitEntropy) + /// + /// Estimates the cost of the sum of one histogram channel of two histograms, without computing the sum. + /// + /// The channel of the first histogram. + /// The channel of the second histogram. + /// The number of entries. + /// Whether the first channel is used. + /// Whether the second channel is used. + /// + /// Whether the sum has one nonzero entry, at index 0 or at the last index. Then only the Huffman cost of the code lengths counts. + /// + /// The estimated cost in bits. + private static double GetCombinedEntropy(ReadOnlySpan x, ReadOnlySpan y, int length, bool isXUsed, bool isYUsed, bool trivialAtEnd) { - stats.Clear(); - bitEntropy.Init(); + // The statistics are small value types, so each estimate starts from zero values on the stack. + // The entropy methods set their own start state. With no used channel, the zero entropy refines to 0. + Vp8LStreaks stats = default; + Vp8LBitEntropy bitEntropy = default; if (trivialAtEnd) { // This configuration is due to palettization that transforms an indexed @@ -470,12 +599,12 @@ private static double GetCombinedEntropy( // BitsEntropyRefine is 0 for histograms with only one non-zero value. // Only FinalHuffmanCost needs to be evaluated. - // Deal with the non-zero value at index 0 or length-1. - stats.Streaks[1][0] = 1; + // Deal with the non-zero value at index 0 or length-1: one short streak of a nonzero value. + stats.Streaks[2] = 1; - // Deal with the following/previous zero streak. + // Deal with the following/previous zero streak: one long streak of zeros. stats.Counts[0] = 1; - stats.Streaks[0][1] = length - 1; + stats.Streaks[1] = length - 1; return stats.FinalHuffmanCost(); } @@ -484,34 +613,103 @@ private static double GetCombinedEntropy( { if (isYUsed) { - bitEntropy.GetCombinedEntropyUnrefined(x, y, length, stats); + bitEntropy.GetCombinedEntropyUnrefined(x, y, length, ref stats); } else { - bitEntropy.GetEntropyUnrefined(x, length, stats); + bitEntropy.BitsEntropyUnrefined(x, length, ref stats); } } else if (isYUsed) { - bitEntropy.GetEntropyUnrefined(y, length, stats); + bitEntropy.BitsEntropyUnrefined(y, length, ref stats); } else { + // One streak of zeros covers the channel. It is long when it has more than 3 entries. stats.Counts[0] = 1; - stats.Streaks[0][length > 3 ? 1 : 0] = length; - bitEntropy.Init(); + stats.Streaks[length > 3 ? 1 : 0] = length; } return bitEntropy.BitsEntropyRefine() + stats.FinalHuffmanCost(); } + /// + /// Computes the extra bits of the prefix codes of the sum of two histograms, without computing the sum. + /// Prefix code c, from 4, has (c - 2) / 2 extra bits. + /// + /// + /// + /// Term j, from 0, reads code j + 4 and has the weight (j + 2) / 2. As in the scalar form, each count sum + /// wraps to 32 bits and each product wraps to a signed 32-bit value. + /// + /// + /// The vector forms hold one term in each 32-bit lane. They widen the products to 64-bit lanes before the + /// sums, so no sum wraps. Each term and each partial sum is an integer below 2^53, so each double addition of the + /// scalar form is exact. Thus the order of the additions does not change the result. + /// + /// + /// The prefix code counts of the first histogram. + /// The prefix code counts of the second histogram. + /// The number of prefix codes. It is more than 4. + /// The number of extra bits. private static double ExtraCostCombined(ReadOnlySpan x, ReadOnlySpan y, int length) { - double cost = 0.0d; - for (int i = 2; i < length - 2; i++) + ref uint xBase = ref MemoryMarshal.GetReference(x[4..length]); + ref uint yBase = ref MemoryMarshal.GetReference(y[4..length]); + ref int weightBase = ref MemoryMarshal.GetReference(ExtraBitsWeights); + nuint count = (uint)(length - 4); + nuint j = 0; + long cost = 0; + + // The same term index flows through descending widths. Each width starts at an even term, so the weights of a + // block are the base weights plus j / 2. + if (Vector512.IsHardwareAccelerated) + { + Vector512 sum = Vector512.Zero; + for (; j + (uint)Vector512.Count <= count; j += (uint)Vector512.Count) + { + Vector512 weights = Vector512.LoadUnsafe(ref weightBase) + Vector512.Create((int)(j >> 1)); + Vector512 xy = (Vector512.LoadUnsafe(ref xBase, j) + Vector512.LoadUnsafe(ref yBase, j)).AsInt32(); + (Vector512 lower, Vector512 upper) = Vector512.Widen(xy * weights); + sum += lower + upper; + } + + cost += Vector512.Sum(sum); + } + + if (Vector256.IsHardwareAccelerated) { - int xy = (int)(x[i + 2] + y[i + 2]); - cost += (i >> 1) * xy; + Vector256 sum = Vector256.Zero; + for (; j + (uint)Vector256.Count <= count; j += (uint)Vector256.Count) + { + Vector256 weights = Vector256.LoadUnsafe(ref weightBase) + Vector256.Create((int)(j >> 1)); + Vector256 xy = (Vector256.LoadUnsafe(ref xBase, j) + Vector256.LoadUnsafe(ref yBase, j)).AsInt32(); + (Vector256 lower, Vector256 upper) = Vector256.Widen(xy * weights); + sum += lower + upper; + } + + cost += Vector256.Sum(sum); + } + + if (Vector128.IsHardwareAccelerated) + { + Vector128 sum = Vector128.Zero; + for (; j + (uint)Vector128.Count <= count; j += (uint)Vector128.Count) + { + Vector128 weights = Vector128.LoadUnsafe(ref weightBase) + Vector128.Create((int)(j >> 1)); + Vector128 xy = (Vector128.LoadUnsafe(ref xBase, j) + Vector128.LoadUnsafe(ref yBase, j)).AsInt32(); + (Vector128 lower, Vector128 upper) = Vector128.Widen(xy * weights); + sum += lower + upper; + } + + cost += Vector128.Sum(sum); + } + + for (; j < count; j++) + { + int xy = (int)(Unsafe.Add(ref xBase, j) + Unsafe.Add(ref yBase, j)); + cost += (int)((j + 2) >> 1) * xy; } return cost; @@ -520,59 +718,145 @@ private static double ExtraCostCombined(ReadOnlySpan x, ReadOnlySpan /// /// Get the symbol entropy for the distribution 'population'. /// - private double PopulationCost(ReadOnlySpan population, int length, ref uint trivialSym, int isUsedIndex, Vp8LStreaks stats, Vp8LBitEntropy bitEntropy) + /// The histogram channel. + /// The number of entries to read from . + /// Receives the only non-zero code, or when there is not exactly one. + /// Receives the used flag of the channel: 1 when there is at least one non-zero streak, else 0. + /// The estimated cost in bits. + private static double PopulationCost(ReadOnlySpan population, int length, ref uint trivialSym, out uint isUsed) { - bitEntropy.Init(); - stats.Clear(); - bitEntropy.BitsEntropyUnrefined(population, length, stats); + // The statistics are small value types, so each estimate starts from zero values on the stack. + // The entropy method sets its own start state. + Vp8LStreaks stats = default; + Vp8LBitEntropy bitEntropy = default; + bitEntropy.BitsEntropyUnrefined(population, length, ref stats); trivialSym = (bitEntropy.NoneZeros == 1) ? bitEntropy.NoneZeroCode : NonTrivialSym; - // The histogram is used if there is at least one non-zero streak. - this.IsUsed(isUsedIndex, stats.Streaks[1][0] != 0 || stats.Streaks[1][1] != 0); + // The histogram is used if there is at least one non-zero streak, short or long. + isUsed = stats.Streaks[2] != 0 || stats.Streaks[3] != 0 ? 1u : 0; return bitEntropy.BitsEntropyRefine() + stats.FinalHuffmanCost(); } + /// + /// Computes the extra bits of the prefix codes of a histogram. Prefix code c, from 4, has (c - 2) / 2 extra bits. + /// + /// + /// + /// Term j, from 0, reads code j + 4 and has the weight (j + 2) / 2. As in the scalar form, each product is exact: + /// the weight is less than 2^5 and the count less than 2^32. + /// + /// + /// The vector forms hold one count in each 32-bit lane. They split the count into its low and high 16 bits and + /// multiply each half by the weight, so no lane wraps: each half product is less than 2^21, and a lane adds fewer + /// than 2^6 of them. The scalar sum then adds the low sums and the high sums shifted left by 16. Each term and each + /// partial sum is an integer below 2^53, so each double addition of the scalar form is exact. Thus the order of + /// the additions does not change the result. + /// + /// + /// The prefix code counts. + /// The number of prefix codes. It is more than 4. + /// The number of extra bits. private static double ExtraCost(ReadOnlySpan population, int length) { - double cost = 0.0d; - for (int i = 2; i < length - 2; i++) + ref uint countBase = ref MemoryMarshal.GetReference(population[4..length]); + ref uint weightBase = ref Unsafe.As(ref MemoryMarshal.GetReference(ExtraBitsWeights)); + nuint count = (uint)(length - 4); + nuint j = 0; + ulong cost = 0; + + // The same term index flows through descending widths. Each width starts at an even term, so the weights of a + // block are the base weights plus j / 2. + if (Vector512.IsHardwareAccelerated) + { + Vector512 lowSum = Vector512.Zero; + Vector512 highSum = Vector512.Zero; + for (; j + (uint)Vector512.Count <= count; j += (uint)Vector512.Count) + { + Vector512 weights = Vector512.LoadUnsafe(ref weightBase) + Vector512.Create((uint)(j >> 1)); + Vector512 counts = Vector512.LoadUnsafe(ref countBase, j); + lowSum += (counts & Vector512.Create(0xffffu)) * weights; + highSum += (counts >>> 16) * weights; + } + + cost += Vector512.Sum(lowSum) + ((ulong)Vector512.Sum(highSum) << 16); + } + + if (Vector256.IsHardwareAccelerated) + { + Vector256 lowSum = Vector256.Zero; + Vector256 highSum = Vector256.Zero; + for (; j + (uint)Vector256.Count <= count; j += (uint)Vector256.Count) + { + Vector256 weights = Vector256.LoadUnsafe(ref weightBase) + Vector256.Create((uint)(j >> 1)); + Vector256 counts = Vector256.LoadUnsafe(ref countBase, j); + lowSum += (counts & Vector256.Create(0xffffu)) * weights; + highSum += (counts >>> 16) * weights; + } + + cost += Vector256.Sum(lowSum) + ((ulong)Vector256.Sum(highSum) << 16); + } + + if (Vector128.IsHardwareAccelerated) + { + Vector128 lowSum = Vector128.Zero; + Vector128 highSum = Vector128.Zero; + for (; j + (uint)Vector128.Count <= count; j += (uint)Vector128.Count) + { + Vector128 weights = Vector128.LoadUnsafe(ref weightBase) + Vector128.Create((uint)(j >> 1)); + Vector128 counts = Vector128.LoadUnsafe(ref countBase, j); + lowSum += (counts & Vector128.Create(0xffffu)) * weights; + highSum += (counts >>> 16) * weights; + } + + cost += Vector128.Sum(lowSum) + ((ulong)Vector128.Sum(highSum) << 16); + } + + for (; j < count; j++) { - cost += (i >> 1) * population[i + 2]; + cost += (ulong)((j + 2) >> 1) * Unsafe.Add(ref countBase, j); } return cost; } } -internal sealed unsafe class OwnedVp8LHistogram : Vp8LHistogram, IDisposable +/// +/// A histogram that owns its backing memory. +/// +internal sealed class OwnedVp8LHistogram : Vp8LHistogram, IDisposable { + /// + /// The owner of the backing memory. + /// private readonly IMemoryOwner bufferOwner; - private MemoryHandle bufferHandle; + + /// + /// A value indicating whether the backing memory was released. + /// private bool isDisposed; - private OwnedVp8LHistogram( - IMemoryOwner bufferOwner, - ref MemoryHandle bufferHandle, - uint* basePointer, - int paletteCodeBits) - : base(basePointer, paletteCodeBits) - { - this.bufferOwner = bufferOwner; - this.bufferHandle = bufferHandle; - } + /// + /// Initializes a new instance of the class. + /// The histogram owns and disposes it. + /// + /// The owner of the backing memory of entries. + /// The palette code bits. + private OwnedVp8LHistogram(IMemoryOwner bufferOwner, int paletteCodeBits) + : base(bufferOwner.Memory, paletteCodeBits) + => this.bufferOwner = bufferOwner; /// /// Creates an that is not a member of a . /// /// The memory allocator. /// The palette code bits. + /// The new histogram with all counts set to zero. The caller owns the histogram and must dispose it. public static OwnedVp8LHistogram Create(MemoryAllocator memoryAllocator, int paletteCodeBits) { - IMemoryOwner bufferOwner = memoryAllocator.Allocate(BufferSize, AllocationOptions.Clean); - MemoryHandle bufferHandle = bufferOwner.Memory.Pin(); - return new OwnedVp8LHistogram(bufferOwner, ref bufferHandle, (uint*)bufferHandle.Pointer, paletteCodeBits); + IMemoryOwner bufferOwner = memoryAllocator.Allocate(GetBufferSize(paletteCodeBits), AllocationOptions.Clean); + return new OwnedVp8LHistogram(bufferOwner, paletteCodeBits); } /// @@ -581,18 +865,19 @@ public static OwnedVp8LHistogram Create(MemoryAllocator memoryAllocator, int pal /// The memory allocator. /// The backward references to initialize the histogram with. /// The palette code bits. - public static OwnedVp8LHistogram Create(MemoryAllocator memoryAllocator, Vp8LBackwardRefs refs, int paletteCodeBits) + /// The new histogram that holds the counts of . The caller owns the histogram and must dispose it. + public static OwnedVp8LHistogram Create(MemoryAllocator memoryAllocator, Vp8LBackwardReferences refs, int paletteCodeBits) { OwnedVp8LHistogram histogram = Create(memoryAllocator, paletteCodeBits); - histogram.StoreRefs(refs); + histogram.StoreRefs(refs, false, 0); return histogram; } + /// public void Dispose() { if (!this.isDisposed) { - this.bufferHandle.Dispose(); this.bufferOwner.Dispose(); this.isDisposed = true; } diff --git a/src/ImageSharp/Formats/Webp/Lossless/Vp8LHistogramSet.cs b/src/ImageSharp/Formats/Webp/Lossless/Vp8LHistogramSet.cs index 008ca9e60c..c15dc18275 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/Vp8LHistogramSet.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/Vp8LHistogramSet.cs @@ -10,63 +10,123 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; +/// +/// A list of histograms. The set keeps its histograms in one plane with one histogram in each row. The plane comes from the pool +/// in buffers of whole rows, so a set of many histograms causes no unpooled memory. +/// An entry can be null after a merge step removes its histogram. +/// internal sealed class Vp8LHistogramSet : IEnumerable, IDisposable { - private readonly IMemoryOwner buffer; - private MemoryHandle bufferHandle; + /// + /// The memory of all histograms. Row i holds the histogram that the set created at index i. + /// + private readonly Buffer2D buffer; + + /// + /// The histograms. + /// private readonly List items; + + /// + /// A value indicating whether the set was disposed. + /// private bool isDisposed; - public Vp8LHistogramSet(MemoryAllocator memoryAllocator, int capacity, int cacheBits) + /// + /// Initializes a new instance of the class. + /// Each histogram has the size for . + /// + /// The memory allocator. + /// The number of histograms. + /// The color cache bits of each histogram. + /// + /// The allocation options of the histogram memory. Use when the histograms + /// count into the memory. Use when each histogram is copied in before it is read. + /// + /// + /// Whether all histograms are in one buffer, so that is valid. Use it only for a small set. + /// + public Vp8LHistogramSet(MemoryAllocator memoryAllocator, int capacity, int cacheBits, AllocationOptions options, bool contiguous) { - this.buffer = memoryAllocator.Allocate(Vp8LHistogram.BufferSize * capacity, AllocationOptions.Clean); - this.bufferHandle = this.buffer.Memory.Pin(); + int histogramSize = Vp8LHistogram.GetBufferSize(cacheBits); + this.HistogramSize = histogramSize; + this.buffer = memoryAllocator.Allocate2D(histogramSize, capacity, contiguous, options); - unsafe + // Each histogram gets its own row of the plane. The set owns the plane, so the histograms are valid until the set is disposed. + this.items = new List(capacity); + for (int i = 0; i < capacity; i++) { - uint* basePointer = (uint*)this.bufferHandle.Pointer; - this.items = new List(capacity); - for (int i = 0; i < capacity; i++) - { - this.items.Add(new MemberVp8LHistogram(basePointer + (Vp8LHistogram.BufferSize * i), cacheBits)); - } + this.items.Add(new MemberVp8LHistogram(this.buffer.GetSafeRowMemory(i), cacheBits)); } } - public Vp8LHistogramSet(MemoryAllocator memoryAllocator, Vp8LBackwardRefs refs, int capacity, int cacheBits) + /// + /// Initializes a new instance of the class. + /// Each histogram has the size for and holds the counts of all backward references. + /// + /// The memory allocator. + /// The backward references to count into each histogram. + /// The number of histograms. + /// The color cache bits of each histogram. + public Vp8LHistogramSet(MemoryAllocator memoryAllocator, Vp8LBackwardReferences refs, int capacity, int cacheBits) { - this.buffer = memoryAllocator.Allocate(Vp8LHistogram.BufferSize * capacity, AllocationOptions.Clean); - this.bufferHandle = this.buffer.Memory.Pin(); + int histogramSize = Vp8LHistogram.GetBufferSize(cacheBits); + this.HistogramSize = histogramSize; + this.buffer = memoryAllocator.Allocate2D(histogramSize, capacity, AllocationOptions.Clean); - unsafe + // Each histogram gets its own row of the plane. The set owns the plane, so the histograms are valid until the set is disposed. + this.items = new List(capacity); + for (int i = 0; i < capacity; i++) { - uint* basePointer = (uint*)this.bufferHandle.Pointer; - this.items = new List(capacity); - for (int i = 0; i < capacity; i++) - { - this.items.Add(new MemberVp8LHistogram(basePointer + (Vp8LHistogram.BufferSize * i), refs, cacheBits)); - } + this.items.Add(new MemberVp8LHistogram(this.buffer.GetSafeRowMemory(i), refs, cacheBits)); } } - public Vp8LHistogramSet(int capacity) => this.items = new List(capacity); - - public Vp8LHistogramSet() => this.items = []; - + /// + /// Gets the number of entries in the set, null entries included. + /// public int Count => this.items.Count; + /// + /// Gets the number of entries of each histogram. + /// + public int HistogramSize { get; } + + /// + /// Gets the memory of all histograms of a contiguous set. Histogram i starts at i * . + /// The layout is valid until the first . + /// + public Span Buffer => this.buffer.DangerousGetSingleSpan(); + + /// + /// Gets or sets the histogram at an index. A null value marks a removed histogram. + /// + /// The index. + /// The histogram, or null. public Vp8LHistogram this[int index] { get => this.items[index]; set => this.items[index] = value; } + /// + /// Gets the memory of the histogram that the set created at an index. The layout is valid until the first . + /// + /// The index of the histogram when the set was created. + /// The entries of the histogram. + public Span GetHistogramMemory(int index) => this.buffer.DangerousGetRowSpan(index); + + /// + /// Removes the entry at an index. The entries after it move down by one. + /// + /// The index. public void RemoveAt(int index) { this.CheckDisposed(); this.items.RemoveAt(index); } + /// public void Dispose() { if (this.isDisposed) @@ -75,15 +135,19 @@ public void Dispose() } this.buffer.Dispose(); - this.bufferHandle.Dispose(); this.items.Clear(); this.isDisposed = true; } + /// public IEnumerator GetEnumerator() => ((IEnumerable)this.items).GetEnumerator(); + /// IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)this.items).GetEnumerator(); + /// + /// Throws when the set was disposed. The check runs only in debug builds. + /// [Conditional("DEBUG")] private void CheckDisposed() { @@ -93,17 +157,34 @@ private void CheckDisposed() } } + /// + /// Throws an for the set. + /// private static void ThrowDisposed() => throw new ObjectDisposedException(nameof(Vp8LHistogramSet)); - private sealed unsafe class MemberVp8LHistogram : Vp8LHistogram + /// + /// A histogram whose backing memory is a slice of the set memory. + /// + private sealed class MemberVp8LHistogram : Vp8LHistogram { - public MemberVp8LHistogram(uint* basePointer, int paletteCodeBits) - : base(basePointer, paletteCodeBits) + /// + /// Initializes a new instance of the class. + /// + /// The slice of the set memory for this histogram. The set owns the memory. + /// The palette code bits. + public MemberVp8LHistogram(Memory buffer, int paletteCodeBits) + : base(buffer, paletteCodeBits) { } - public MemberVp8LHistogram(uint* basePointer, Vp8LBackwardRefs refs, int paletteCodeBits) - : base(basePointer, refs, paletteCodeBits) + /// + /// Initializes a new instance of the class. + /// + /// The slice of the set memory for this histogram. The set owns the memory. + /// The backward references to initialize the histogram with. + /// The palette code bits. + public MemberVp8LHistogram(Memory buffer, Vp8LBackwardReferences refs, int paletteCodeBits) + : base(buffer, refs, paletteCodeBits) { } } diff --git a/src/ImageSharp/Formats/Webp/Lossless/Vp8LMetadata.cs b/src/ImageSharp/Formats/Webp/Lossless/Vp8LMetadata.cs index ca8e4a00b8..ad7858b9ee 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/Vp8LMetadata.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/Vp8LMetadata.cs @@ -7,23 +7,124 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; -internal class Vp8LMetadata +/// +/// Holds the entropy coding state of one lossless image: the color cache, the entropy image and the Huffman groups. +/// +/// +/// As in the JPEG decoder, the tables come from the memory allocator, so a decode does not allocate them on the managed heap. The metadata owns them. +/// +internal sealed class Vp8LMetadata : IDisposable { + /// + /// Gets or sets the number of color cache entries. The value is 0 when the image has no color cache. + /// public int ColorCacheSize { get; set; } - public ColorCache ColorCache { get; set; } + /// + /// Gets the color cache entries, or null when the image has no color cache. The metadata owns them. + /// + public IMemoryOwner ColorCacheColors { get; private set; } + /// + /// Gets the hash shift of the color cache: 32 minus the color cache bits. + /// + public int ColorCacheShift { get; private set; } + + /// + /// Gets or sets the mask that selects the column in a tile. A column with no masked bits starts a tile. + /// All bits are set when the image has no entropy image. + /// public int HuffmanMask { get; set; } + /// + /// Gets or sets the log2 of the entropy image tile size. The value is 0 when the image has no entropy image. + /// public int HuffmanSubSampleBits { get; set; } + /// + /// Gets or sets the number of entropy image tiles in a row. + /// public int HuffmanXSize { get; set; } + /// + /// Gets or sets the entropy image. Each entry holds the Huffman group index of one tile. + /// public IMemoryOwner HuffmanImage { get; set; } + /// + /// Gets or sets the number of Huffman groups. + /// public int NumHTreeGroups { get; set; } - public HTreeGroup[] HTreeGroups { get; set; } + /// + /// Gets the Huffman groups. + /// + public IMemoryOwner HTreeGroups { get; private set; } + + /// + /// Gets the Huffman tables of all groups. Each group keeps the offsets of its tables. + /// + public IMemoryOwner HuffmanTables { get; private set; } + + /// + /// Gets the packed tables of the groups that use one, or null when no group uses a packed table. + /// + public IMemoryOwner PackedTables { get; private set; } + + /// + /// Sets the color cache entries. The metadata disposes the entries that it had before. + /// + /// The entries, 1 << values, all zero. + /// The color cache bits. + public void SetColorCache(IMemoryOwner colors, int bits) + { + this.ColorCacheColors?.Dispose(); + this.ColorCacheColors = colors; + this.ColorCacheShift = 32 - bits; + } + + /// + /// Sets the Huffman groups. The metadata disposes the groups that it had before. + /// + /// The Huffman groups. + public void SetHTreeGroups(IMemoryOwner hTreeGroups) + { + this.HTreeGroups?.Dispose(); + this.HTreeGroups = hTreeGroups; + } + + /// + /// Sets the Huffman tables. The metadata disposes the tables that it had before. + /// + /// The Huffman tables of all groups. + public void SetHuffmanTables(IMemoryOwner huffmanTables) + { + this.HuffmanTables?.Dispose(); + this.HuffmanTables = huffmanTables; + } + + /// + /// Sets the packed tables. The metadata disposes the packed tables that it had before. + /// + /// The packed tables, or null when no group uses a packed table. + public void SetPackedTables(IMemoryOwner packedTables) + { + this.PackedTables?.Dispose(); + this.PackedTables = packedTables; + } - public HuffmanCode[] HuffmanTables { get; set; } + /// + public void Dispose() + { + this.HuffmanImage?.Dispose(); + this.ColorCacheColors?.Dispose(); + this.HTreeGroups?.Dispose(); + this.HuffmanTables?.Dispose(); + this.PackedTables?.Dispose(); + this.HuffmanImage = null; + this.ColorCacheColors = null; + this.HTreeGroups = null; + this.HuffmanTables = null; + this.PackedTables = null; + } } diff --git a/src/ImageSharp/Formats/Webp/Lossless/Vp8LStreaks.cs b/src/ImageSharp/Formats/Webp/Lossless/Vp8LStreaks.cs index 9a2021df06..bf79a7c848 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/Vp8LStreaks.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/Vp8LStreaks.cs @@ -3,39 +3,30 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless; -internal class Vp8LStreaks +/// +/// Holds the streak statistics of a histogram that estimate the cost of its Huffman code lengths. +/// +/// +/// The type is a value type, so a cost estimate keeps it on the stack. The default value has all counts set to zero. +/// +internal struct Vp8LStreaks { /// - /// Initializes a new instance of the class. + /// The number of streaks longer than 3. Index 0 is for streaks of zeros, index 1 for streaks of a nonzero value. /// - public Vp8LStreaks() - { - this.Counts = new int[2]; - this.Streaks = new int[2][]; - this.Streaks[0] = new int[2]; - this.Streaks[1] = new int[2]; - } + public InlineArray2 Counts; /// - /// Gets the streak count. - /// index: 0=zero streak, 1=non-zero streak. + /// The sum of the streak lengths. The index is (isNonZero * 2) + isLong: isNonZero is 1 for a streak of a nonzero + /// value, and isLong is 1 for a streak longer than 3. /// - public int[] Counts { get; } + public InlineArray4 Streaks; /// - /// Gets the streaks. - /// [zero/non-zero][streak < 3 / streak >= 3]. + /// Computes the estimated cost of the Huffman code lengths from the streak statistics. /// - public int[][] Streaks { get; } - - public void Clear() - { - this.Counts.AsSpan().Clear(); - this.Streaks[0].AsSpan().Clear(); - this.Streaks[1].AsSpan().Clear(); - } - - public double FinalHuffmanCost() + /// The estimated cost in bits. + public readonly double FinalHuffmanCost() { // The constants in this function are experimental and got rounded from // their original values in 1/8 when switched to 1/1024. @@ -43,22 +34,26 @@ public double FinalHuffmanCost() // Second coefficient: Many zeros in the histogram are covered efficiently // by a run-length encode. Originally 2/8. - retval += (this.Counts[0] * 1.5625) + (0.234375 * this.Streaks[0][1]); + retval += (this.Counts[0] * 1.5625) + (0.234375 * this.Streaks[1]); // Second coefficient: Constant values are encoded less efficiently, but still // RLE'ed. Originally 6/8. - retval += (this.Counts[1] * 2.578125) + (0.703125 * this.Streaks[1][1]); + retval += (this.Counts[1] * 2.578125) + (0.703125 * this.Streaks[3]); // 0s are usually encoded more efficiently than non-0s. // Originally 15/8. - retval += 1.796875 * this.Streaks[0][0]; + retval += 1.796875 * this.Streaks[0]; // Originally 26/8. - retval += 3.28125 * this.Streaks[1][0]; + retval += 3.28125 * this.Streaks[2]; return retval; } + /// + /// Gets the base cost of a Huffman code before the streak costs are added. + /// + /// The base cost in bits. private static double InitialHuffmanCost() { // Small bias because Huffman code length is typically not stored in full length. diff --git a/src/ImageSharp/Formats/Webp/Lossless/WebpLosslessDecoder.cs b/src/ImageSharp/Formats/Webp/Lossless/WebpLosslessDecoder.cs index 8a50025cf9..45d186fca6 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/WebpLosslessDecoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/WebpLosslessDecoder.cs @@ -5,6 +5,7 @@ using System.Buffers; using System.Diagnostics.CodeAnalysis; using System.Numerics; +using System.Numerics.Tensors; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using SixLabors.ImageSharp.ColorProfiles; @@ -40,17 +41,30 @@ internal sealed class WebpLosslessDecoder /// private readonly MemoryAllocator memoryAllocator; + /// + /// The marker that a packed table entry adds to its bit count when the entry holds a green code that is not a literal. + /// private const int BitsSpecialMarker = 0x100; - private const uint PackedNonLiteralCode = 0; + /// + /// The mask of the input bits that index a packed table. + /// + private const uint PackedTableMask = HuffmanUtils.HuffmanPackedTableSize - 1; - // Memory needed for lookup tables of one Huffman tree group. Red, blue, alpha and distance alphabets are constant (256 for red, blue and alpha, 40 for - // distance) and lookup table sizes for them in worst case are 630 and 410 respectively. Size of green alphabet depends on color cache size and is equal - // to 256 (green component values) + 24 (length prefix values) + color_cache_size (between 0 and 2048). - // All values computed for 8-bit first level lookup with Mark Adler's tool: - // http://www.hdfgroup.org/ftp/lib-external/zlib/zlib-1.2.5/examples/enough.c + /// + /// The worst case size of the lookup tables of the red, blue, alpha and distance codes of one Huffman tree group. + /// + /// + /// The red, blue, alpha and distance alphabets have fixed sizes: 256 symbols for red, blue and alpha, and 40 for distance. Their worst case table + /// sizes are 630 and 410. The green alphabet has 256 green values, 24 length prefix values and the color cache size, from 0 to 2048. + /// The sizes are for an 8-bit first level lookup, as Mark Adler's tool computes them: + /// http://www.hdfgroup.org/ftp/lib-external/zlib/zlib-1.2.5/examples/enough.c + /// private const int FixedTableSize = (630 * 3) + 410; + /// + /// The worst case size of the lookup tables of one Huffman tree group, for each number of color cache bits from 0 to 11. + /// private static readonly int[] TableSize = [ FixedTableSize + 654, @@ -67,8 +81,6 @@ internal sealed class WebpLosslessDecoder FixedTableSize + 2704 ]; - private static readonly int NumCodeLengthCodes = CodeLengthCodeOrder.Length; - /// /// The image data integrity mode of the current header read. sets it before it reads the headers. /// @@ -92,11 +104,21 @@ public WebpLosslessDecoder(Vp8LBitReader bitReader, MemoryAllocator memoryAlloca this.configuration = configuration; } - // This uses C#'s compiler optimization to refer to assembly's static data directly. - private static ReadOnlySpan CodeLengthCodeOrder => [17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 - ]; + /// + /// Gets the order in which the stream stores the code lengths of the code length code. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates no memory. + /// + private static ReadOnlySpan CodeLengthCodeOrder => [17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; - // This uses C#'s compiler optimization to refer to assembly's static data directly. + /// + /// Gets a flag for each code of a group: green, red, blue, alpha and distance. The flag is 1 for the red, blue and alpha codes. + /// A group has a trivial literal only when each flagged code has one symbol. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates no memory. + /// private static ReadOnlySpan LiteralMap => [0, 1, 1, 1, 0]; /// @@ -108,9 +130,10 @@ public WebpLosslessDecoder(Vp8LBitReader bitReader, MemoryAllocator memoryAlloca /// The width of the image. /// The selected source ICC converter, if available. /// The image data integrity mode. It controls damaged or truncated image data. - public void Decode( + /// The number of rows from the top that the method wrote. Damaged data in the ignore mode can stop the decode before the last row. + public int Decode( Vp8LDecoder decoder, - Buffer2D pixels, + Buffer2DRegion pixels, int width, ColorProfileConverter colorProfileConverter, SegmentIntegrityHandling segmentIntegrityHandling) @@ -118,9 +141,10 @@ public void Decode( { decoder.AllocatePixels(this.memoryAllocator); - // DecodePixelValues writes only the complete rows. The other rows keep their fill value. + // DecodePixelValues writes only the complete rows. int rows = this.DecodeImageRows(decoder, segmentIntegrityHandling, "The WebP lossless image data is damaged or ends before the last pixel."); this.DecodePixelValues(decoder, pixels, width, rows, colorProfileConverter); + return rows; } /// @@ -178,7 +202,7 @@ public bool TryReadHeaders(Vp8LDecoder decoder, SegmentIntegrityHandling segment /// public int DecodeImageRows(Vp8LDecoder decoder, SegmentIntegrityHandling segmentIntegrityHandling, string message) { - int decodedPixels = this.DecodeImageData(decoder, decoder.Pixels.Memory.Span); + int decodedPixels = this.DecodeImageData(decoder, decoder.Pixels); if (decodedPixels < decoder.Width * decoder.Height || this.bitReader.IsEndOfStream()) { segmentIntegrityHandling.ThrowOrIgnoreImageDataError(message); @@ -227,6 +251,8 @@ private bool TryReadImageStreamHeaders(Vp8LDecoder decoder, int xSize, int ySize } else { + // The metadata before belongs to the main image headers or to a sub-image that is complete, so nothing reads its tables again. + decoder.Metadata?.Dispose(); decoder.Metadata = new Vp8LMetadata(); } @@ -259,7 +285,7 @@ private bool TryReadImageStreamHeaders(Vp8LDecoder decoder, int xSize, int ySize // Finish setting up the color-cache. if (isColorCachePresent) { - decoder.Metadata.ColorCache = new ColorCache(colorCacheBits); + decoder.Metadata.SetColorCache(this.memoryAllocator.Allocate(1 << colorCacheBits, AllocationOptions.Clean), colorCacheBits); colorCacheSize = 1 << colorCacheBits; decoder.Metadata.ColorCacheSize = colorCacheSize; } @@ -294,7 +320,8 @@ private bool TryDecodeSubImage(Vp8LDecoder decoder, int xSize, int ySize, [NotNu // Use the Huffman trees to decode the LZ77 encoded data. IMemoryOwner data = this.memoryAllocator.Allocate(decoder.Width * decoder.Height, AllocationOptions.Clean); - if (this.DecodeImageData(decoder, data.GetSpan()) < decoder.Width * decoder.Height && !this.bitReader.IsEndOfStream()) + using Buffer2D view = Buffer2D.WrapMemory(data.Memory, decoder.Width, decoder.Height); + if (this.DecodeImageData(decoder, view) < decoder.Width * decoder.Height && !this.bitReader.IsEndOfStream()) { data.Dispose(); this.segmentIntegrityHandling.ThrowOrIgnoreImageDataError(this.imageExists, "The WebP lossless sub-image has a code that is not valid."); @@ -312,36 +339,47 @@ private bool TryDecodeSubImage(Vp8LDecoder decoder, int xSize, int ySize, [NotNu /// The decoder that holds the decoded pixels. /// The pixel buffer to write to. /// The width of the image. - /// The number of rows to write. Rows after them keep their fill value. + /// The number of rows to write. The method does not change the rows after them. /// The selected source ICC converter, if available. - private void DecodePixelValues(Vp8LDecoder decoder, Buffer2D pixels, int width, int height, ColorProfileConverter colorProfileConverter) + private void DecodePixelValues( + Vp8LDecoder decoder, + Buffer2DRegion pixels, + int width, + int height, + ColorProfileConverter colorProfileConverter) where TPixel : unmanaged, IPixel { - Span pixelData = decoder.Pixels.GetSpan(); - - // Apply reverse transformations, if any are present. - ApplyInverseTransforms(decoder, pixelData, this.memoryAllocator); - - Span pixelDataAsBytes = MemoryMarshal.Cast(pixelData); - int bytesPerRow = width * 4; + using IMemoryOwner cacheOwner = AllocateTransformCache(this.memoryAllocator, width); + Span cache = cacheOwner.GetSpan(); using IMemoryOwner vectorOwner = colorProfileConverter is null ? null : this.memoryAllocator.Allocate(width); - using IMemoryOwner rgbOwner = colorProfileConverter is null - ? null - : this.memoryAllocator.Allocate(width); - Span vectors = vectorOwner is null ? Span.Empty : vectorOwner.Memory.Span; - Span rgb = rgbOwner is null ? Span.Empty : rgbOwner.Memory.Span; + WebpColorConverterBase colorConverter = WebpColorConverterBase.GetConverter(WebpColorType.Rgba); + PixelOperations pixelOperations = PixelOperations.Instance; - for (int y = 0; y < height; y++) + for (int firstRow = 0; firstRow < height; firstRow += WebpConstants.NumArgbCacheRows) { - Span rowAsBytes = pixelDataAsBytes.Slice(y * bytesPerRow, bytesPerRow); - Span pixelRow = pixels.DangerousGetRowSpan(y); - ReadOnlySpan source = MemoryMarshal.Cast(rowAsBytes); - colorConverter.ConvertRgbRow(this.configuration, source, colorProfileConverter, vectors, rgb, pixelRow[..width]); + int rowCount = Math.Min(WebpConstants.NumArgbCacheRows, height - firstRow); + ReadOnlySpan batch = MemoryMarshal.Cast(ApplyInverseTransforms(decoder, firstRow, rowCount, cache, width)); + for (int y = 0; y < rowCount; y++) + { + ReadOnlySpan source = batch.Slice(y * width, width); + Span pixelRow = pixels.DangerousGetRowSpan(firstRow + y)[..width]; + if (colorProfileConverter is null) + { + pixelOperations.FromBgra32(this.configuration, source, pixelRow); + } + else + { + // ICC transforms straight vectors. The vectors are straight RGBA, so TPixel applies its own alpha representation. + Span row = vectors[..width]; + colorConverter.ConvertToRgb(source, colorProfileConverter, row); + pixelOperations.FromUnassociatedScaledVector4Destructive(this.configuration, row, pixelRow); + } + } } } @@ -353,179 +391,235 @@ private void DecodePixelValues(Vp8LDecoder decoder, Buffer2D pix /// The caller decides how to report the damage. The method keeps the pixels that it decodes before the damage. /// /// The decoder. - /// The pixel data to decode to. + /// + /// The pixel data to decode to. It has the size of the stream. As in the JPEG decoder, the rows can be in several pooled buffers, and each buffer holds + /// whole rows. + /// /// The number of decoded pixels. - public int DecodeImageData(Vp8LDecoder decoder, Span pixelData) + public int DecodeImageData(Vp8LDecoder decoder, Buffer2D pixelData) { - const int lastPixel = 0; - int width = decoder.Width; - int height = decoder.Height; - int row = lastPixel / width; - int col = lastPixel % width; const int lenCodeLimit = WebpConstants.NumLiteralCodes + WebpConstants.NumLengthCodes; - int colorCacheSize = decoder.Metadata.ColorCacheSize; - ColorCache colorCache = decoder.Metadata.ColorCache; - int colorCacheLimit = lenCodeLimit + colorCacheSize; - int mask = decoder.Metadata.HuffmanMask; - Span hTreeGroup = GetHTreeGroupForPos(decoder.Metadata, col, row); + int width = decoder.Width; + int totalPixels = width * decoder.Height; + DebugGuard.IsTrue(pixelData.Width == width && pixelData.Height == decoder.Height, "The pixel data has the size of the stream."); + + // The loop writes to one buffer of the group at a time. A buffer holds whole rows, so the decode moves to the next buffer only at the end of a row + // or after a copy. Each buffer except the last has bufferLength pixels. A single contiguous buffer is the common case, and then the loop never + // changes the buffer. + MemoryGroup pixelGroup = pixelData.FastMemoryGroup; + int bufferLength = pixelGroup.BufferLength; + int bufferIndex = 0; + Span buffer = pixelGroup[0].Span; + int bufferStart = 0; + int bufferEnd = buffer.Length; + + Vp8LMetadata metadata = decoder.Metadata; + int colorCacheLimit = lenCodeLimit + metadata.ColorCacheSize; + int mask = metadata.HuffmanMask; + GetEntropyImage(metadata, out ReadOnlySpan huffmanImage, out int huffmanXSize, out int huffmanBits); + Span groups = metadata.HTreeGroups.GetSpan(); + ref HuffmanCode tables = ref MemoryMarshal.GetReference(metadata.HuffmanTables.GetSpan()); + + // A group reads its packed table only when the group uses one, so the reference is not read when the image has no packed table. + Span packedTableSpan = metadata.PackedTables is null ? Span.Empty : metadata.PackedTables.GetSpan(); + ref HuffmanCode packedTables = ref MemoryMarshal.GetReference(packedTableSpan); + ref uint pixels = ref MemoryMarshal.GetReference(buffer); + + // The color cache is filled only when a cache code needs it. The pixels after the last fill go into the cache in their order, so the cache has the + // same content as a cache that gets each pixel at once. + Span cacheColors = metadata.ColorCacheColors is null ? default : metadata.ColorCacheColors.GetSpan(); + int cacheShift = metadata.ColorCacheShift; + + // The bit state stays in locals, so the JIT can keep it in registers. + ref byte data = ref MemoryMarshal.GetReference(this.bitReader.Data.Memory.Span); + int dataLength = this.bitReader.Length; + this.bitReader.LoadState(out ulong bits, out int bitCount, out int next); - int totalPixels = width * height; int decodedPixels = 0; - int lastCached = decodedPixels; + int col = 0; + int row = 0; + int lastCached = 0; + + // The end of the data gives zero bits, so the loop checks for it only at each row end and after each copy. The pixels before the last check that + // passed use only real data. + int checkedPixels = 0; + ref HuffmanTreeGroup group = ref groups[(int)huffmanImage[0]]; while (decodedPixels < totalPixels) { - int code; if ((col & mask) == 0) { - hTreeGroup = GetHTreeGroupForPos(decoder.Metadata, col, row); + group = ref groups[(int)huffmanImage[(huffmanXSize * (row >> huffmanBits)) + (col >> huffmanBits)]]; } - if (hTreeGroup[0].IsTrivialCode) + uint pixel; + if (group.IsTrivialCode) { - pixelData[decodedPixels] = hTreeGroup[0].LiteralArb; - AdvanceByOne(ref col, ref row, width, colorCache, ref decodedPixels, pixelData, ref lastCached); - continue; + pixel = group.LiteralArb; } - - this.bitReader.FillBitWindow(); - if (hTreeGroup[0].UsePackedTable) + else { - code = (int)this.ReadPackedSymbols(hTreeGroup, pixelData, decodedPixels); - if (this.bitReader.IsEndOfStream()) + Vp8LBitReader.Refill(ref data, dataLength, ref bits, ref bitCount, ref next); + int code; + if (group.UsePackedTable) { - break; + // A packed entry holds a whole literal pixel, or a green code that is not a literal. The marker on the bit count tells which. + ref HuffmanCode packed = ref Unsafe.Add(ref packedTables, (uint)group.PackedTable + ((uint)bits & PackedTableMask)); + if (packed.BitsUsed < BitsSpecialMarker) + { + Vp8LBitReader.Skip(packed.BitsUsed, ref bits, ref bitCount); + pixel = packed.Value; + code = -1; + } + else + { + Vp8LBitReader.Skip(packed.BitsUsed - BitsSpecialMarker, ref bits, ref bitCount); + pixel = 0; + code = (int)packed.Value; + } } - - if (code == PackedNonLiteralCode) + else { - AdvanceByOne(ref col, ref row, width, colorCache, ref decodedPixels, pixelData, ref lastCached); - continue; + pixel = 0; + code = ReadSymbol(ref Unsafe.Add(ref tables, (uint)group.Green), ref bits, ref bitCount); } - } - else - { - code = (int)this.ReadSymbol(hTreeGroup[0].HTrees[HuffIndex.Green]); - } - - if (this.bitReader.IsEndOfStream()) - { - break; - } - // Literal - if (code < WebpConstants.NumLiteralCodes) - { - if (hTreeGroup[0].IsTrivialLiteral) + if (code < WebpConstants.NumLiteralCodes) { - pixelData[decodedPixels] = hTreeGroup[0].LiteralArb | ((uint)code << 8); + // A negative code tells that the packed table gave the whole pixel. + if (code >= 0) + { + if (group.IsTrivialLiteral) + { + pixel = group.LiteralArb | ((uint)code << 8); + } + else + { + // Green and red use at most 30 of the 32 or more bits. The refill gives the bits for blue and alpha. + int red = ReadSymbol(ref Unsafe.Add(ref tables, (uint)group.Red), ref bits, ref bitCount); + Vp8LBitReader.Refill(ref data, dataLength, ref bits, ref bitCount, ref next); + int blue = ReadSymbol(ref Unsafe.Add(ref tables, (uint)group.Blue), ref bits, ref bitCount); + uint alpha = group.IsTrivialAlpha + ? group.TrivialAlpha + : (uint)(byte)ReadSymbol(ref Unsafe.Add(ref tables, (uint)group.Alpha), ref bits, ref bitCount) << 24; + + pixel = alpha | (uint)(((byte)red << 16) | ((byte)code << 8) | (byte)blue); + } + } } - else + else if (code < lenCodeLimit) { - uint red = this.ReadSymbol(hTreeGroup[0].HTrees[HuffIndex.Red]); - this.bitReader.FillBitWindow(); - uint blue = this.ReadSymbol(hTreeGroup[0].HTrees[HuffIndex.Blue]); - uint alpha = this.ReadSymbol(hTreeGroup[0].HTrees[HuffIndex.Alpha]); - if (this.bitReader.IsEndOfStream()) + // A backward reference. Green and the length extra bits use at most 25 of the 32 or more bits. A refill comes before the distance code and + // before its extra bits, which use at most 15 and 18 bits. + int length = ReadPrefixValue(code - WebpConstants.NumLiteralCodes, ref bits, ref bitCount); + Vp8LBitReader.Refill(ref data, dataLength, ref bits, ref bitCount, ref next); + int distSymbol = ReadSymbol(ref Unsafe.Add(ref tables, (uint)group.Dist), ref bits, ref bitCount); + Vp8LBitReader.Refill(ref data, dataLength, ref bits, ref bitCount, ref next); + int dist = PlaneCodeToDistance(width, ReadPrefixValue(distSymbol, ref bits, ref bitCount)); + + // libwebp rejects a reference that starts before the first pixel or that ends after the last pixel. + if (dist > decodedPixels || length > totalPixels - decodedPixels) { break; } - pixelData[decodedPixels] = (uint)(((byte)alpha << 24) | ((byte)red << 16) | ((byte)code << 8) | (byte)blue); - } + if (dist <= decodedPixels - bufferStart && length <= bufferEnd - decodedPixels) + { + // The source and the destination are in the current buffer. + CopyBlock(buffer, decodedPixels - bufferStart, dist, length); + } + else + { + CopyBlock(pixelGroup, bufferLength, decodedPixels, dist, length); + } - AdvanceByOne(ref col, ref row, width, colorCache, ref decodedPixels, pixelData, ref lastCached); - } - else if (code < lenCodeLimit) - { - // Backward reference is used. - int lengthSym = code - WebpConstants.NumLiteralCodes; - int length = this.GetCopyLength(lengthSym); - uint distSymbol = this.ReadSymbol(hTreeGroup[0].HTrees[HuffIndex.Dist]); - this.bitReader.FillBitWindow(); - int distCode = this.GetCopyDistance((int)distSymbol); - int dist = PlaneCodeToDistance(width, distCode); - if (this.bitReader.IsEndOfStream()) - { - break; - } + decodedPixels += length; + col += length; + while (col >= width) + { + col -= width; + row++; + } - // libwebp rejects a reference that starts before the first pixel or that ends after the last pixel. - if (dist > decodedPixels || length > totalPixels - decodedPixels) - { - break; - } + // A copy is at most 4096 pixels, and a pooled buffer holds many rows, so the copy can end in the next buffer. + while (decodedPixels >= bufferEnd && decodedPixels < totalPixels) + { + bufferIndex++; + bufferStart = bufferEnd; + buffer = pixelGroup[bufferIndex].Span; + bufferEnd += buffer.Length; + pixels = ref MemoryMarshal.GetReference(buffer); + } - CopyBlock(pixelData, decodedPixels, dist, length); - decodedPixels += length; - col += length; - while (col >= width) - { - col -= width; - row++; - } + if (Vp8LBitReader.IsEndOfStream(dataLength, bitCount, next)) + { + break; + } - if ((col & mask) != 0) - { - hTreeGroup = GetHTreeGroupForPos(decoder.Metadata, col, row); - } + checkedPixels = decodedPixels; - if (colorCache != null) + // The next pixel starts a new tile when its column is a multiple of the tile size. Then the loop selects the group. + if ((col & mask) != 0) + { + group = ref groups[(int)huffmanImage[(huffmanXSize * (row >> huffmanBits)) + (col >> huffmanBits)]]; + } + + continue; + } + else if (code < colorCacheLimit) { - while (lastCached < decodedPixels) + // A color cache code. The code is less than colorCacheLimit, so the cache exists and the key is in range. + ref uint cache = ref MemoryMarshal.GetReference(cacheColors); + if (lastCached < bufferStart) { - colorCache.Insert(pixelData[lastCached]); - lastCached++; + // The pixels after the last fill start in an earlier buffer. + FillColorCache(pixelGroup, bufferLength, lastCached, bufferStart, cacheColors, cacheShift); + lastCached = bufferStart; } + + for (; lastCached < decodedPixels; lastCached++) + { + uint cached = Unsafe.Add(ref pixels, (uint)(lastCached - bufferStart)); + Unsafe.Add(ref cache, (uint)ColorCache.HashPix(cached, cacheShift)) = cached; + } + + pixel = Unsafe.Add(ref cache, (uint)(code - lenCodeLimit)); } - } - else if (code < colorCacheLimit) - { - // Color cache should be used. - int key = code - lenCodeLimit; - while (lastCached < decodedPixels) + else { - colorCache.Insert(pixelData[lastCached]); - lastCached++; + // The code is not valid. + break; } - - pixelData[decodedPixels] = colorCache.Lookup(key); - AdvanceByOne(ref col, ref row, width, colorCache, ref decodedPixels, pixelData, ref lastCached); } - else + + Unsafe.Add(ref pixels, (uint)(decodedPixels - bufferStart)) = pixel; + decodedPixels++; + if (++col == width) { - // The code is not valid. - break; - } - } + col = 0; + row++; + if (Vp8LBitReader.IsEndOfStream(dataLength, bitCount, next)) + { + break; + } - return decodedPixels; - } + checkedPixels = decodedPixels; - private static void AdvanceByOne( - ref int col, - ref int row, - int width, - ColorCache colorCache, - ref int decodedPixels, - ReadOnlySpan pixelData, - ref int lastCached) - { - col++; - decodedPixels++; - if (col >= width) - { - col = 0; - row++; - - if (colorCache != null) - { - while (lastCached < decodedPixels) + // A buffer ends at the end of a row. + if (decodedPixels == bufferEnd && decodedPixels < totalPixels) { - colorCache.Insert(pixelData[lastCached]); - lastCached++; + bufferIndex++; + bufferStart = bufferEnd; + buffer = pixelGroup[bufferIndex].Span; + bufferEnd += buffer.Length; + pixels = ref MemoryMarshal.GetReference(buffer); } } } + + this.bitReader.StoreState(bits, bitCount, next); + + // Pixels that used bits after the end of the data are not valid. + return Vp8LBitReader.IsEndOfStream(dataLength, bitCount, next) ? checkedPixels : decodedPixels; } /// @@ -539,10 +633,6 @@ private static void AdvanceByOne( /// if the codes are valid. Otherwise . private bool TryReadHuffmanCodes(Vp8LDecoder decoder, int xSize, int ySize, int colorCacheBits, bool allowRecursion) { - int maxAlphabetSize = 0; - int numHTreeGroups = 1; - int numHTreeGroupsMax = 1; - // If the next bit is zero, there is only one meta Huffman code used everywhere in the image. No more data is stored. // If this bit is one, the image uses multiple meta Huffman codes. These meta Huffman codes are stored as an entropy image. if (allowRecursion && this.bitReader.ReadBit()) @@ -551,33 +641,76 @@ private bool TryReadHuffmanCodes(Vp8LDecoder decoder, int xSize, int ySize, int int huffmanPrecision = (int)(this.bitReader.ReadValue(3) + 2); int huffmanXSize = LosslessUtils.SubSampleSize(xSize, huffmanPrecision); int huffmanYSize = LosslessUtils.SubSampleSize(ySize, huffmanPrecision); - int huffmanPixels = huffmanXSize * huffmanYSize; if (!this.TryDecodeSubImage(decoder, huffmanXSize, huffmanYSize, out IMemoryOwner huffmanImage)) { return false; } + // TryDecodeSubImage allocates exactly one value for each tile. Span huffmanImageSpan = huffmanImage.GetSpan(); decoder.Metadata.HuffmanSubSampleBits = huffmanPrecision; - // TODO: Isn't huffmanPixels the length of the span? - for (int i = 0; i < huffmanPixels; i++) + // The group index of a tile is in the red and green bytes of its value. The group count is the largest index plus one. + TensorPrimitives.ShiftRightLogical(huffmanImageSpan, 8, huffmanImageSpan); + TensorPrimitives.BitwiseAnd(huffmanImageSpan, 0xffffu, huffmanImageSpan); + int numHTreeGroupsMax = (int)TensorPrimitives.Max(huffmanImageSpan) + 1; + decoder.Metadata.HuffmanImage = huffmanImage; + + // A stream can name up to 65536 groups with one tile. Thus, when the largest index is large, or larger than the tile count, the + // used indices map to a dense range in tile order, and only the used groups get tables. The codes of an unused group are read and + // checked, but not stored. The value 200 is above the group count of usual encoders. This is the rule of libwebp. + if (numHTreeGroupsMax <= 200 && numHTreeGroupsMax <= huffmanImageSpan.Length) { - // The huffman data is stored in red and green bytes. - uint group = (huffmanImageSpan[i] >> 8) & 0xffff; - huffmanImageSpan[i] = group; - if (group >= numHTreeGroupsMax) + return this.TryReadHuffmanGroups(decoder, colorCacheBits, numHTreeGroupsMax, numHTreeGroupsMax, default); + } + + // The map from the group index of the entropy image to the dense index of the stored group. -1 marks an unused index. + using IMemoryOwner mappingOwner = this.memoryAllocator.Allocate(numHTreeGroupsMax); + Span mapping = mappingOwner.GetSpan()[..numHTreeGroupsMax]; + mapping.Fill(-1); + int numHTreeGroups = 0; + for (int i = 0; i < huffmanImageSpan.Length; i++) + { + ref int mappedGroup = ref mapping[(int)huffmanImageSpan[i]]; + if (mappedGroup == -1) { - numHTreeGroupsMax = (int)group + 1; + mappedGroup = numHTreeGroups++; } + + huffmanImageSpan[i] = (uint)mappedGroup; } - numHTreeGroups = numHTreeGroupsMax; - decoder.Metadata.HuffmanImage = huffmanImage; + // With one used group, the entropy image selects nothing, so the decode does not read it. + if (numHTreeGroups == 1) + { + decoder.Metadata.HuffmanImage = null; + huffmanImage.Dispose(); + decoder.Metadata.HuffmanSubSampleBits = 0; + } + + return this.TryReadHuffmanGroups(decoder, colorCacheBits, numHTreeGroups, numHTreeGroupsMax, mapping); } + return this.TryReadHuffmanGroups(decoder, colorCacheBits, 1, 1, default); + } + + /// + /// Reads the Huffman codes of each group and builds the tables of the used groups. + /// + /// The decoder that gets the tables and the groups. + /// The color cache bits. + /// The number of stored groups. + /// The number of groups in the stream: the largest group index of the entropy image plus one. + /// + /// The map from each group index of the stream to the index of its stored group, with -1 for an unused group. It is empty when each group is + /// stored at its own index. + /// + /// if the codes are valid. Otherwise . + private bool TryReadHuffmanGroups(Vp8LDecoder decoder, int colorCacheBits, int numHTreeGroups, int numHTreeGroupsMax, ReadOnlySpan mapping) + { // Find maximum alphabet size for the hTree group. + int maxAlphabetSize = 0; for (int j = 0; j < WebpConstants.HuffmanCodesPerMetaCode; j++) { int alphabetSize = WebpConstants.AlphabetSize[j]; @@ -600,19 +733,58 @@ private bool TryReadHuffmanCodes(Vp8LDecoder decoder, int xSize, int ySize, int return false; } + // The table build writes each entry of the tables that it builds, and the decode reads only those entries. Thus the tables need no clear. + // The decoder accepts only complete codes, so the build writes each entry of the root table and of the second-level tables. + // The metadata owns the tables at once, so the decoder disposes them also when a code is not valid. With a map, one more group of tables + // after the stored groups is the scratch table for the codes of the unused groups. int tableSize = TableSize[colorCacheBits]; - HuffmanCode[] huffmanTables = new HuffmanCode[numHTreeGroups * tableSize]; - HTreeGroup[] hTreeGroups = new HTreeGroup[numHTreeGroups]; - Span huffmanTable = huffmanTables.AsSpan(); - int[] codeLengths = new int[maxAlphabetSize]; + int storedTableSize = numHTreeGroups * tableSize; + decoder.Metadata.SetHuffmanTables(this.memoryAllocator.Allocate(storedTableSize + (mapping.IsEmpty ? 0 : tableSize))); + Span huffmanTables = decoder.Metadata.HuffmanTables.GetSpan()[..storedTableSize]; + Span unusedGroupTable = mapping.IsEmpty ? default : decoder.Metadata.HuffmanTables.GetSpan().Slice(storedTableSize, tableSize); + + // The loop below sets the offsets and the flags of each group. It sets the literal and the packed table offset only for a group whose flags read + // them, so the groups need no clear. + decoder.Metadata.SetHTreeGroups(this.memoryAllocator.Allocate(numHTreeGroups)); + Span hTreeGroups = decoder.Metadata.HTreeGroups.GetSpan(); + Span huffmanTable = huffmanTables; + + // TryReadHuffmanCode clears the code lengths of each code before it reads them, and the table build writes the sorted symbols first. + using IMemoryOwner codeLengthsOwner = this.memoryAllocator.Allocate(maxAlphabetSize); + using IMemoryOwner sortedOwner = this.memoryAllocator.Allocate(maxAlphabetSize); + Span codeLengths = codeLengthsOwner.GetSpan(); + Span sorted = sortedOwner.GetSpan(); + + // HuffmanCodesPerMetaCode is 5. + InlineArray5 offsetStorage = default; + Span offsets = offsetStorage; + int packedGroups = 0; for (int i = 0; i < numHTreeGroupsMax; i++) { - hTreeGroups[i] = new HTreeGroup(HuffmanUtils.HuffmanPackedTableSize); - HTreeGroup hTreeGroup = hTreeGroups[i]; + if (!mapping.IsEmpty && mapping[i] == -1) + { + // The entropy image does not use this group. Its codes must be valid, but the decode never reads their tables. + for (int j = 0; j < WebpConstants.HuffmanCodesPerMetaCode; j++) + { + int alphabetSize = WebpConstants.AlphabetSize[j]; + if (j == 0 && colorCacheBits > 0) + { + alphabetSize += 1 << colorCacheBits; + } + + if (!this.TryReadHuffmanCode(alphabetSize, codeLengths, sorted, unusedGroupTable, out _)) + { + return false; + } + } + + continue; + } + + ref HuffmanTreeGroup hTreeGroup = ref hTreeGroups[mapping.IsEmpty ? i : mapping[i]]; int totalSize = 0; bool isTrivialLiteral = true; int maxBits = 0; - codeLengths.AsSpan().Clear(); for (int j = 0; j < WebpConstants.HuffmanCodesPerMetaCode; j++) { int alphabetSize = WebpConstants.AlphabetSize[j]; @@ -621,14 +793,12 @@ private bool TryReadHuffmanCodes(Vp8LDecoder decoder, int xSize, int ySize, int alphabetSize += 1 << colorCacheBits; } - if (!this.TryReadHuffmanCode(alphabetSize, codeLengths, huffmanTable, out int size)) + if (!this.TryReadHuffmanCode(alphabetSize, codeLengths, sorted, huffmanTable, out int size)) { return false; } - // TODO: Avoid allocation. - hTreeGroup.HTrees.Add([.. huffmanTable[..size]]); - + offsets[j] = huffmanTables.Length - huffmanTable.Length; HuffmanCode huffTableZero = huffmanTable[0]; if (isTrivialLiteral && LiteralMap[j] == 1) { @@ -638,31 +808,27 @@ private bool TryReadHuffmanCodes(Vp8LDecoder decoder, int xSize, int ySize, int totalSize += huffTableZero.BitsUsed; huffmanTable = huffmanTable[size..]; - if (j <= HuffIndex.Alpha) + if (j <= HuffmanIndex.Alpha) { - int localMaxBits = codeLengths[0]; - int k; - for (k = 1; k < alphabetSize; ++k) - { - int codeLengthK = codeLengths[k]; - if (codeLengthK > localMaxBits) - { - localMaxBits = codeLengthK; - } - } - - maxBits += localMaxBits; + maxBits += TensorPrimitives.Max(codeLengths[..alphabetSize]); } } + hTreeGroup.Green = offsets[HuffmanIndex.Green]; + hTreeGroup.Red = offsets[HuffmanIndex.Red]; + hTreeGroup.Blue = offsets[HuffmanIndex.Blue]; + hTreeGroup.Alpha = offsets[HuffmanIndex.Alpha]; + hTreeGroup.Dist = offsets[HuffmanIndex.Dist]; hTreeGroup.IsTrivialLiteral = isTrivialLiteral; + hTreeGroup.IsTrivialAlpha = huffmanTables[hTreeGroup.Alpha].BitsUsed == 0; + hTreeGroup.TrivialAlpha = huffmanTables[hTreeGroup.Alpha].Value << 24; hTreeGroup.IsTrivialCode = false; if (isTrivialLiteral) { - uint red = hTreeGroup.HTrees[HuffIndex.Red][0].Value; - uint blue = hTreeGroup.HTrees[HuffIndex.Blue][0].Value; - uint green = hTreeGroup.HTrees[HuffIndex.Green][0].Value; - uint alpha = hTreeGroup.HTrees[HuffIndex.Alpha][0].Value; + uint red = huffmanTables[hTreeGroup.Red].Value; + uint blue = huffmanTables[hTreeGroup.Blue].Value; + uint green = huffmanTables[hTreeGroup.Green].Value; + uint alpha = huffmanTables[hTreeGroup.Alpha].Value; hTreeGroup.LiteralArb = (alpha << 24) | (red << 16) | blue; if (totalSize == 0 && green < WebpConstants.NumLiteralCodes) { @@ -674,13 +840,26 @@ private bool TryReadHuffmanCodes(Vp8LDecoder decoder, int xSize, int ySize, int hTreeGroup.UsePackedTable = !hTreeGroup.IsTrivialCode && maxBits < HuffmanUtils.HuffmanPackedBits; if (hTreeGroup.UsePackedTable) { - BuildPackedTable(hTreeGroup); + hTreeGroup.PackedTable = packedGroups * (int)HuffmanUtils.HuffmanPackedTableSize; + packedGroups++; + } + } + + // The packed tables need the tables of their group, so they are built after all groups. BuildPackedTable writes each entry of the table of its + // group, so the tables need no clear. + int packedSize = packedGroups * (int)HuffmanUtils.HuffmanPackedTableSize; + decoder.Metadata.SetPackedTables(packedGroups == 0 ? null : this.memoryAllocator.Allocate(packedSize)); + for (int i = 0; i < numHTreeGroups; i++) + { + HuffmanTreeGroup hTreeGroup = hTreeGroups[i]; + if (hTreeGroup.UsePackedTable) + { + Span packedTable = decoder.Metadata.PackedTables.GetSpan().Slice(hTreeGroup.PackedTable, (int)HuffmanUtils.HuffmanPackedTableSize); + BuildPackedTable(huffmanTables, hTreeGroup, packedTable); } } decoder.Metadata.NumHTreeGroups = numHTreeGroups; - decoder.Metadata.HTreeGroups = hTreeGroups; - decoder.Metadata.HuffmanTables = huffmanTables; return true; } @@ -689,14 +868,15 @@ private bool TryReadHuffmanCodes(Vp8LDecoder decoder, int xSize, int ySize, int /// /// The alphabet size. /// The code lengths. + /// The scratch buffer of the table build, with at least one entry for each symbol. /// The table to build. /// The size of the built table. /// if the code is valid. Otherwise . - private bool TryReadHuffmanCode(int alphabetSize, int[] codeLengths, Span table, out int size) + private bool TryReadHuffmanCode(int alphabetSize, Span codeLengths, Span sorted, Span table, out int size) { size = 0; bool simpleCode = this.bitReader.ReadBit(); - codeLengths.AsSpan(0, alphabetSize).Clear(); + codeLengths[..alphabetSize].Clear(); if (simpleCode) { @@ -709,13 +889,13 @@ private bool TryReadHuffmanCode(int alphabetSize, int[] codeLengths, Span codeLengthCodeLengthStorage = default; + Span codeLengthCodeLengths = codeLengthCodeLengthStorage; uint numCodes = this.bitReader.ReadValue(4) + 4; for (int i = 0; i < numCodes; i++) { codeLengthCodeLengths[CodeLengthCodeOrder[i]] = (int)this.bitReader.ReadValue(3); } - if (!this.TryReadHuffmanCodeLengths(table, codeLengthCodeLengths, alphabetSize, codeLengths)) + if (!this.TryReadHuffmanCodeLengths(table, codeLengthCodeLengths, sorted, alphabetSize, codeLengths)) { return false; } } - // Code lengths that do not build a complete code give a table size of 0. libwebp rejects them. - size = HuffmanUtils.BuildHuffmanTable(table, HuffmanUtils.HuffmanTableBits, codeLengths, alphabetSize); + // An incomplete code leaves table entries that the build does not write, and an over-subscribed code gives a table size of 0. Both are + // not valid, as in libwebp. + if (!IsCompleteCode(codeLengths[..alphabetSize])) + { + this.segmentIntegrityHandling.ThrowOrIgnoreImageDataError(this.imageExists, "The Huffman code lengths do not give a complete code"); + return false; + } + + size = HuffmanTableBuilder.Build(table, HuffmanUtils.HuffmanTableBits, codeLengths[..alphabetSize], sorted); if (size == 0) { this.segmentIntegrityHandling.ThrowOrIgnoreImageDataError(this.imageExists, "Huffman table size is zero"); @@ -747,20 +936,58 @@ private bool TryReadHuffmanCode(int alphabetSize, int[] codeLengths, Span + /// Gets a value indicating whether code lengths give a complete prefix code: one used symbol, or a code tree with no free leaf. + /// + /// + /// A code is complete when the sum of 2^-length over the used symbols is 1. The sum is in units of 2^-15, the largest code length. A length + /// above 15 is not valid. See the WebP Lossless Bitstream Specification, section 6.2.2 "Decoding of Meta Prefix Codes": + /// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// + /// The code length of each symbol. Zero is an unused symbol. + /// if the code is complete; otherwise . + private static bool IsCompleteCode(ReadOnlySpan codeLengths) + { + const int maxLength = 15; + int used = 0; + int sum = 0; + foreach (int length in codeLengths) + { + if (length != 0) + { + if ((uint)length > maxLength) + { + return false; + } + + used++; + sum += 1 << (maxLength - length); + } + } + + return used == 1 || sum == 1 << maxLength; + } + /// /// Reads the code lengths of a Huffman code with the code length code. /// /// The scratch table for the code length code. /// The code lengths of the code length code. + /// The scratch buffer of the table build, with at least one entry for each symbol. /// The alphabet size. /// The code lengths to read. /// if the code lengths are valid. Otherwise . - private bool TryReadHuffmanCodeLengths(Span table, int[] codeLengthCodeLengths, int numSymbols, int[] codeLengths) + private bool TryReadHuffmanCodeLengths( + Span table, + ReadOnlySpan codeLengthCodeLengths, + Span sorted, + int numSymbols, + Span codeLengths) { int maxSymbol; int symbol = 0; int prevCodeLen = WebpConstants.DefaultCodeLength; - int size = HuffmanUtils.BuildHuffmanTable(table, WebpConstants.LengthTableBits, codeLengthCodeLengths, NumCodeLengthCodes); + int size = IsCompleteCode(codeLengthCodeLengths) ? HuffmanTableBuilder.Build(table, WebpConstants.LengthTableBits, codeLengthCodeLengths, sorted) : 0; if (size == 0) { this.segmentIntegrityHandling.ThrowOrIgnoreImageDataError(this.imageExists, "Error building huffman table"); @@ -787,6 +1014,10 @@ private bool TryReadHuffmanCodeLengths(Span table, int[] codeLength maxSymbol = numSymbols; } + // The bit state stays in locals for the loop. A refill gives at least 32 bits: 7 for the code length code and 7 for its extra bits. + ref byte data = ref MemoryMarshal.GetReference(this.bitReader.Data.Memory.Span); + int dataLength = this.bitReader.Length; + this.bitReader.LoadState(out ulong bits, out int bitCount, out int next); while (symbol < numSymbols) { if (maxSymbol-- == 0) @@ -794,11 +1025,9 @@ private bool TryReadHuffmanCodeLengths(Span table, int[] codeLength break; } - this.bitReader.FillBitWindow(); - ulong prefetchBits = this.bitReader.PrefetchBits(); - int idx = (int)(prefetchBits & 127); - HuffmanCode huffmanCode = table[idx]; - this.bitReader.AdvanceBitPosition(huffmanCode.BitsUsed); + Vp8LBitReader.Refill(ref data, dataLength, ref bits, ref bitCount, ref next); + HuffmanCode huffmanCode = table[(int)((uint)bits & ((1u << WebpConstants.LengthTableBits) - 1))]; + Vp8LBitReader.Skip(huffmanCode.BitsUsed, ref bits, ref bitCount); uint codeLen = huffmanCode.Value; if (codeLen < WebpConstants.CodeLengthLiterals) { @@ -814,22 +1043,23 @@ private bool TryReadHuffmanCodeLengths(Span table, int[] codeLength uint slot = codeLen - WebpConstants.CodeLengthLiterals; int extraBits = WebpConstants.CodeLengthExtraBits[slot]; int repeatOffset = WebpConstants.CodeLengthRepeatOffsets[slot]; - int repeat = (int)(this.bitReader.ReadValue(extraBits) + repeatOffset); + int repeat = (int)Vp8LBitReader.ReadBits(extraBits, ref bits, ref bitCount) + repeatOffset; if (symbol + repeat > numSymbols) { + this.bitReader.StoreState(bits, bitCount, next); + // A repeat past the alphabet leaves the code lengths incomplete. libwebp rejects the stream. this.segmentIntegrityHandling.ThrowOrIgnoreImageDataError(this.imageExists, "A repeated code length runs past the alphabet size"); return false; } int length = usePrev ? prevCodeLen : 0; - while (repeat-- > 0) - { - codeLengths[symbol++] = length; - } + codeLengths.Slice(symbol, repeat).Fill(length); + symbol += repeat; } } + this.bitReader.StoreState(bits, bitCount, next); return true; } @@ -846,10 +1076,13 @@ private bool TryReadTransformation(int xSize, int ySize, Vp8LDecoder decoder) Vp8LTransform transform = new(transformType, xSize, ySize); // Each transform is allowed to be used only once. - if (decoder.Transforms.Any(decoderTransform => decoderTransform.TransformType == transform.TransformType)) + foreach (Vp8LTransform decoderTransform in decoder.Transforms) { - this.segmentIntegrityHandling.ThrowOrIgnoreImageDataError(this.imageExists, "Each transform can only be present once"); - return false; + if (decoderTransform.TransformType == transform.TransformType) + { + this.segmentIntegrityHandling.ThrowOrIgnoreImageDataError(this.imageExists, "Each transform can only be present once"); + return false; + } } switch (transformType) @@ -913,131 +1146,238 @@ private bool TryReadTransformation(int xSize, int ySize, Vp8LDecoder decoder) return true; } + /// + /// Allocates the cache that uses: one row for the predictor, then rows, + /// then one row of palette index bytes for the color indexing transform. + /// + /// The memory allocator. + /// The width of the image. + /// The cache. Its content is not defined, because each batch writes the rows that it reads. + public static IMemoryOwner AllocateTransformCache(MemoryAllocator memoryAllocator, int width) + => memoryAllocator.Allocate((width * (1 + WebpConstants.NumArgbCacheRows)) + ((width + 3) / 4)); + /// /// A Webp lossless image can go through four different types of transformation before being entropy encoded. - /// This will reverse the transformations, if any are present. + /// This reverses the transformations, if any are present, for one batch of rows. /// - /// The decoder holding the transformation infos. - /// The pixel data to apply the transformation. - /// The memory allocator is needed to allocate memory during the predictor transform. - public static void ApplyInverseTransforms(Vp8LDecoder decoder, Span pixelData, MemoryAllocator memoryAllocator) + /// + /// As in libwebp, the transforms run on batches of at most rows. A batch of a wide image is about 123 KB, so + /// all transforms and the conversion that follows read the batch from the L2 cache. A pass over the whole image for each transform would read and write + /// the full pixel buffer from memory each time. The caller runs the batches in row order, because the predictor of a batch reads the last row of the + /// batch before it. + /// Without the color indexing transform, the transforms work in place on the decoded rows, so the batch needs no copy. A batch that + /// has no row above in its buffer, and each batch of an image with the color indexing transform, is copied to the cache first. + /// + /// The decoder that holds the transforms and the decoded pixels. + /// The first row of the batch. + /// The number of rows in the batch, from 1 to . + /// The cache from . + /// The width of the image. + /// + /// The final ARGB pixels of the batch rows, pixels for each row: in the cache, or in the decoded pixels after an in-place batch. + /// + public static ReadOnlySpan ApplyInverseTransforms(Vp8LDecoder decoder, int firstRow, int rowCount, Span cache, int width) { + // The decoded rows have the width of the stream. The color indexing transform packs several pixels in one value, so that width can be less than + // the image width. + int streamWidth = decoder.Width; + Buffer2D pixels = decoder.Pixels; List transforms = decoder.Transforms; + + int rowsEnd = width * (1 + WebpConstants.NumArgbCacheRows); + Span slot = cache[..width]; + + // Without the color indexing transform, each transform keeps the width, so the transforms can work in place on the decoded rows, with no copy. + // The entropy decode is complete, so no backward reference reads these rows again. The predictor reads the row above the batch at offset -width, + // so that row must be in the same buffer as the batch rows. A buffer of the group holds whole rows. The first batch has no row above, and it uses + // the cache. + bool hasColorIndexing = streamWidth != width; + MemoryGroup group = pixels.FastMemoryGroup; + int rowsPerBuffer = group.BufferLength / streamWidth; + int upperRow = firstRow - 1; + bool inPlace = upperRow >= 0 && !hasColorIndexing && upperRow / rowsPerBuffer == (firstRow + rowCount - 1) / rowsPerBuffer; + + // block is the row above the batch, then the batch rows. + Span block; + Span rows; + if (inPlace) + { + block = group[upperRow / rowsPerBuffer].Span.Slice((upperRow % rowsPerBuffer) * width, width * (1 + rowCount)); + rows = block[width..]; + if (transforms.Count == 0) + { + return rows; + } + } + else + { + // The batch rows follow the predictor row in the cache. A buffer of the pixel data holds whole rows, so each row is one copy. + block = cache[..rowsEnd]; + rows = cache[width..rowsEnd]; + for (int y = 0; y < rowCount; y++) + { + pixels.DangerousGetRowSpan(firstRow + y).CopyTo(rows.Slice(y * streamWidth, streamWidth)); + } + + if (transforms.Count == 0) + { + return rows[..(width * rowCount)]; + } + } + for (int i = transforms.Count - 1; i >= 0; i--) { - // TODO: Review these 1D allocations. They could conceivably exceed limits. Vp8LTransform transform = transforms[i]; switch (transform.TransformType) { case Vp8LTransformType.PredictorTransform: - using (IMemoryOwner output = memoryAllocator.Allocate(pixelData.Length, AllocationOptions.Clean)) + if (inPlace) { - LosslessUtils.PredictorInverseTransform(transform, pixelData, output.GetSpan()); + // The row above went through the transforms after the predictor in its batch, but the predictor reads its predictor output. The + // slot holds that output. The row above is already written to the destination, so it can change. + slot.CopyTo(block); + LosslessUtils.PredictorInverseTransform(transform, block, firstRow, rowCount); + + // The transform copies the predictor output of its last row to the first row of the block. Keep it for the next batch. + block[..width].CopyTo(slot); + } + else + { + // The predictor row of this transform ends where the batch rows start. + LosslessUtils.PredictorInverseTransform(transform, cache[(width - transform.XSize)..], firstRow, rowCount); } break; case Vp8LTransformType.SubtractGreen: - LosslessUtils.AddGreenToBlueAndRed(pixelData); + LosslessUtils.AddGreenToBlueAndRed(rows[..(transform.XSize * rowCount)]); break; case Vp8LTransformType.CrossColorTransform: - LosslessUtils.ColorSpaceInverseTransform(transform, pixelData); + LosslessUtils.ColorSpaceInverseTransform(transform, rows, firstRow, rowCount); break; case Vp8LTransformType.ColorIndexingTransform: - using (IMemoryOwner output = memoryAllocator.Allocate(transform.XSize * transform.YSize, AllocationOptions.Clean)) - { - LosslessUtils.ColorIndexInverseTransform(transform, pixelData, output.GetSpan()); - } - + LosslessUtils.ColorIndexInverseTransform(transform, rows, rowCount, MemoryMarshal.AsBytes(cache[rowsEnd..])); break; } } + + return rows[..(width * rowCount)]; } /// /// The alpha channel of a lossy webp image can be compressed using the lossless webp compression. /// This method will undo the compression. /// + /// + /// The decoder uses this method only for streams that need 1 byte for each value: green codes and copies only, with no color cache. + /// /// The alpha decoder. /// The image data integrity mode. It controls damaged or truncated alpha data. public void DecodeAlphaData(AlphaDecoder dec, SegmentIntegrityHandling segmentIntegrityHandling) { - Span pixelData = dec.Vp8LDec.Pixels.Memory.Span; - Span data = MemoryMarshal.Cast(pixelData); - int row = 0; - int col = 0; + const int lenCodeLimit = WebpConstants.NumLiteralCodes + WebpConstants.NumLengthCodes; Vp8LDecoder vp8LDec = dec.Vp8LDec; int width = vp8LDec.Width; - int height = vp8LDec.Height; + int end = width * vp8LDec.Height; + + // As in DecodeImageData, the loop writes to one buffer of the group at a time, and each buffer holds whole rows. + MemoryGroup valueGroup = vp8LDec.PaletteIndices.FastMemoryGroup; + int bufferLength = valueGroup.BufferLength; + int bufferIndex = 0; + Span buffer = valueGroup[0].Span; + int bufferStart = 0; + int bufferEnd = buffer.Length; Vp8LMetadata hdr = vp8LDec.Metadata; - int pos = 0; // Current position. - int end = width * height; // End of data. - int last = end; // Last pixel to decode. - int lastRow = height; - const int lenCodeLimit = WebpConstants.NumLiteralCodes + WebpConstants.NumLengthCodes; int mask = hdr.HuffmanMask; - Span htreeGroup = pos < last ? GetHTreeGroupForPos(hdr, col, row) : null; + GetEntropyImage(hdr, out ReadOnlySpan huffmanImage, out int huffmanXSize, out int huffmanBits); + Span groups = hdr.HTreeGroups.GetSpan(); + ref HuffmanCode tables = ref MemoryMarshal.GetReference(hdr.HuffmanTables.GetSpan()); + + // The bit state stays in locals, so the JIT can keep it in registers. + ref byte data = ref MemoryMarshal.GetReference(this.bitReader.Data.Memory.Span); + int dataLength = this.bitReader.Length; + this.bitReader.LoadState(out ulong bits, out int bitCount, out int next); + + int pos = 0; + int col = 0; + int row = 0; - // A code that is not valid leaves the loop with break before the last value. The loop uses if statements, not a switch statement, because break in a - // switch section cannot leave the loop. As in libwebp, the loop stops at the end of the data. - while (!this.bitReader.IsEndOfStream() && pos < last) + // The end of the data gives zero bits, so the loop checks for it only when a row ends. The rows before the last check that passed use only real + // data. A code that is not valid leaves the loop with break. + int checkedRows = 0; + ref HuffmanTreeGroup group = ref groups[(int)huffmanImage[0]]; + while (pos < end) { - // Only update when changing tile. if ((col & mask) == 0) { - htreeGroup = GetHTreeGroupForPos(hdr, col, row); + group = ref groups[(int)huffmanImage[(huffmanXSize * (row >> huffmanBits)) + (col >> huffmanBits)]]; } - this.bitReader.FillBitWindow(); - int code = (int)this.ReadSymbol(htreeGroup[0].HTrees[HuffIndex.Green]); + Vp8LBitReader.Refill(ref data, dataLength, ref bits, ref bitCount, ref next); + int code = ReadSymbol(ref Unsafe.Add(ref tables, (uint)group.Green), ref bits, ref bitCount); + int startRow = row; if (code < WebpConstants.NumLiteralCodes) { - // Literal - data[pos] = (byte)code; - ++pos; - ++col; - - if (col >= width) + buffer[pos - bufferStart] = (byte)code; + pos++; + if (++col == width) { col = 0; - ++row; - if (row <= lastRow && row % WebpConstants.NumArgbCacheRows == 0) + row++; + + // A buffer ends at the end of a row. + if (pos == bufferEnd && pos < end) { - dec.ExtractPalettedAlphaRows(row); + bufferIndex++; + bufferStart = bufferEnd; + buffer = valueGroup[bufferIndex].Span; + bufferEnd += buffer.Length; } } } else if (code < lenCodeLimit) { - // Backward reference - int lengthSym = code - WebpConstants.NumLiteralCodes; - int length = this.GetCopyLength(lengthSym); - int distSymbol = (int)this.ReadSymbol(htreeGroup[0].HTrees[HuffIndex.Dist]); - this.bitReader.FillBitWindow(); - int distCode = this.GetCopyDistance(distSymbol); - int dist = PlaneCodeToDistance(width, distCode); + // A backward reference. A refill comes before the distance code and before its extra bits. + int length = ReadPrefixValue(code - WebpConstants.NumLiteralCodes, ref bits, ref bitCount); + Vp8LBitReader.Refill(ref data, dataLength, ref bits, ref bitCount, ref next); + int distSymbol = ReadSymbol(ref Unsafe.Add(ref tables, (uint)group.Dist), ref bits, ref bitCount); + Vp8LBitReader.Refill(ref data, dataLength, ref bits, ref bitCount, ref next); + int dist = PlaneCodeToDistance(width, ReadPrefixValue(distSymbol, ref bits, ref bitCount)); if (pos < dist || end - pos < length) { // The reference starts before the first value or ends after the last value. break; } - CopyBlock8B(data, pos, dist, length); + if (dist <= pos - bufferStart && length <= bufferEnd - pos) + { + // The source and the destination are in the current buffer. + CopyBlock(buffer, pos - bufferStart, dist, length); + } + else + { + CopyBlock(valueGroup, bufferLength, pos, dist, length); + } pos += length; col += length; while (col >= width) { col -= width; - ++row; - if (row <= lastRow && row % WebpConstants.NumArgbCacheRows == 0) - { - dec.ExtractPalettedAlphaRows(row); - } + row++; + } + + // A copy is at most 4096 values, and a pooled buffer holds many rows, so the copy can end in the next buffer. + while (pos >= bufferEnd && pos < end) + { + bufferIndex++; + bufferStart = bufferEnd; + buffer = valueGroup[bufferIndex].Span; + bufferEnd += buffer.Length; } - if (pos < last && (col & mask) > 0) + if (pos < end && (col & mask) != 0) { - htreeGroup = GetHTreeGroupForPos(hdr, col, row); + group = ref groups[(int)huffmanImage[(huffmanXSize * (row >> huffmanBits)) + (col >> huffmanBits)]]; } } else @@ -1045,20 +1385,44 @@ public void DecodeAlphaData(AlphaDecoder dec, SegmentIntegrityHandling segmentIn // The code is not valid. break; } + + if (row != startRow) + { + if (Vp8LBitReader.IsEndOfStream(dataLength, bitCount, next)) + { + break; + } + + checkedRows = row; + + // The palette and the filters process the rows in blocks of NumArgbCacheRows rows. + if (row / WebpConstants.NumArgbCacheRows != startRow / WebpConstants.NumArgbCacheRows) + { + dec.ExtractPalettedAlphaRows(row - (row % WebpConstants.NumArgbCacheRows)); + } + } } + this.bitReader.StoreState(bits, bitCount, next); + // Process the remaining rows corresponding to last row-block. // The method keeps the complete rows that it decodes before any damage. The caller clears the other rows. - dec.ExtractPalettedAlphaRows(row > lastRow ? lastRow : row); + dec.ExtractPalettedAlphaRows(checkedRows); // Each stream uses one end-of-data rule, as in DecodeImageRows and libwebp. // Values that are not decoded, or a read past the end of the data, are damage. - if (pos < end || this.bitReader.IsEndOfStream()) + if (pos < end || Vp8LBitReader.IsEndOfStream(dataLength, bitCount, next)) { segmentIntegrityHandling.ThrowOrIgnoreImageDataError("The WebP alpha data is damaged or ends before the last value."); } } + /// + /// Sets the size of the image to decode and the entropy image tile values for that width. + /// + /// The decoder. + /// The width of the image to decode. + /// The height of the image to decode. private static void UpdateDecoder(Vp8LDecoder decoder, int width, int height) { int numBits = decoder.Metadata.HuffmanSubSampleBits; @@ -1068,29 +1432,19 @@ private static void UpdateDecoder(Vp8LDecoder decoder, int width, int height) decoder.Metadata.HuffmanMask = numBits == 0 ? ~0 : (1 << numBits) - 1; } - private uint ReadPackedSymbols(ReadOnlySpan group, Span pixelData, int decodedPixels) - { - uint val = (uint)(this.bitReader.PrefetchBits() & (HuffmanUtils.HuffmanPackedTableSize - 1)); - HuffmanCode code = group[0].PackedTable[val]; - if (code.BitsUsed < BitsSpecialMarker) - { - this.bitReader.AdvanceBitPosition(code.BitsUsed); - pixelData[decodedPixels] = code.Value; - return PackedNonLiteralCode; - } - - this.bitReader.AdvanceBitPosition(code.BitsUsed - BitsSpecialMarker); - - return code.Value; - } - - private static void BuildPackedTable(HTreeGroup hTreeGroup) + /// + /// Builds the packed table of a group. Each entry maps 6 input bits to a whole literal pixel, or to a green code that is not a literal. + /// + /// The Huffman tables of all groups. + /// The group. + /// The packed table of the group. + private static void BuildPackedTable(ReadOnlySpan tables, HuffmanTreeGroup group, Span packedTable) { for (uint code = 0; code < HuffmanUtils.HuffmanPackedTableSize; code++) { uint bits = code; - ref HuffmanCode huff = ref hTreeGroup.PackedTable[bits]; - HuffmanCode hCode = hTreeGroup.HTrees[HuffIndex.Green][bits]; + ref HuffmanCode huff = ref packedTable[(int)code]; + HuffmanCode hCode = tables[group.Green + (int)bits]; if (hCode.Value >= WebpConstants.NumLiteralCodes) { huff.BitsUsed = hCode.BitsUsed + BitsSpecialMarker; @@ -1101,72 +1455,93 @@ private static void BuildPackedTable(HTreeGroup hTreeGroup) huff.BitsUsed = 0; huff.Value = 0; bits >>= AccumulateHCode(hCode, 8, ref huff); - bits >>= AccumulateHCode(hTreeGroup.HTrees[HuffIndex.Red][bits], 16, ref huff); - bits >>= AccumulateHCode(hTreeGroup.HTrees[HuffIndex.Blue][bits], 0, ref huff); - bits >>= AccumulateHCode(hTreeGroup.HTrees[HuffIndex.Alpha][bits], 24, ref huff); + bits >>= AccumulateHCode(tables[group.Red + (int)bits], 16, ref huff); + bits >>= AccumulateHCode(tables[group.Blue + (int)bits], 0, ref huff); + bits >>= AccumulateHCode(tables[group.Alpha + (int)bits], 24, ref huff); } } } /// - /// Decodes the next Huffman code from the bit-stream. - /// FillBitWindow() needs to be called at minimum every second call to ReadSymbol, in order to pre-fetch enough bits. + /// Reads one Huffman symbol. At least 15 bits must be valid, the length of the longest code. /// - /// The Huffman table. - private uint ReadSymbol(Span table) + /// + /// The root entry for the low 8 bits holds the symbol and its code length, or the offset and the index width of a second-level table. The table build + /// rejects codes that are not complete, so each index stays in the table of the code. + /// + /// The first entry of the table of the code. + /// The bits that are not read. + /// The number of valid bits. + /// The symbol. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int ReadSymbol(ref HuffmanCode table, ref ulong bits, ref int count) { - uint val = (uint)this.bitReader.PrefetchBits(); - Span tableSpan = table[(int)(val & HuffmanUtils.HuffmanTableMask)..]; - int nBits = tableSpan[0].BitsUsed - HuffmanUtils.HuffmanTableBits; + ref HuffmanCode entry = ref Unsafe.Add(ref table, (uint)bits & HuffmanUtils.HuffmanTableMask); + int nBits = entry.BitsUsed - HuffmanUtils.HuffmanTableBits; if (nBits > 0) { - this.bitReader.AdvanceBitPosition(HuffmanUtils.HuffmanTableBits); - val = (uint)this.bitReader.PrefetchBits(); - tableSpan = tableSpan[(int)tableSpan[0].Value..]; - tableSpan = tableSpan[((int)val & ((1 << nBits) - 1))..]; + Vp8LBitReader.Skip(HuffmanUtils.HuffmanTableBits, ref bits, ref count); + entry = ref Unsafe.Add(ref entry, entry.Value + ((uint)bits & ((1u << nBits) - 1))); } - this.bitReader.AdvanceBitPosition(tableSpan[0].BitsUsed); - - return tableSpan[0].Value; + Vp8LBitReader.Skip(entry.BitsUsed, ref bits, ref count); + return (int)entry.Value; } - [MethodImpl(InliningOptions.ShortMethod)] - private int GetCopyLength(int lengthSymbol) => - this.GetCopyDistance(lengthSymbol); // Length and distance prefixes are encoded the same way. - - private int GetCopyDistance(int distanceSymbol) + /// + /// Reads the value of a length or distance prefix code and its extra bits. The extra bits of a prefix code are at most 18 bits, and at least that many + /// bits must be valid. + /// + /// The prefix code. + /// The bits that are not read. + /// The number of valid bits. + /// The length, or the distance code. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int ReadPrefixValue(int prefixCode, ref ulong bits, ref int count) { - if (distanceSymbol < 4) + if (prefixCode < 4) { - return distanceSymbol + 1; + return prefixCode + 1; } - int extraBits = (distanceSymbol - 2) >> 1; - int offset = (2 + (distanceSymbol & 1)) << extraBits; - - return (int)(offset + this.bitReader.ReadValue(extraBits) + 1); - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static Span GetHTreeGroupForPos(Vp8LMetadata metadata, int x, int y) - { - uint metaIndex = GetMetaIndex(metadata.HuffmanImage, metadata.HuffmanXSize, metadata.HuffmanSubSampleBits, x, y); - return metadata.HTreeGroups.AsSpan((int)metaIndex); + int extraBits = (prefixCode - 2) >> 1; + int offset = (2 + (prefixCode & 1)) << extraBits; + return offset + (int)Vp8LBitReader.ReadBits(extraBits, ref bits, ref count) + 1; } - [MethodImpl(InliningOptions.ShortMethod)] - private static uint GetMetaIndex(IMemoryOwner huffmanImage, int xSize, int bits, int x, int y) + /// + /// Gets the entropy image of a stream and the values that select a group from it. + /// + /// + /// A stream with no entropy image has one group. Then the image is one entry and the shift is 31, so each position, which is less than 2^31, maps to + /// that entry. Thus the decode loops select a group with the same expression for both cases. + /// + /// The metadata of the stream. + /// The group index of each tile. + /// The number of tiles in a row. + /// The shift that gives the tile of a position. + private static void GetEntropyImage(Vp8LMetadata metadata, out ReadOnlySpan huffmanImage, out int huffmanXSize, out int huffmanBits) { - if (bits is 0) + if (metadata.HuffmanSubSampleBits == 0) { - return 0; + huffmanImage = [0]; + huffmanXSize = 0; + huffmanBits = 31; + return; } - Span huffmanImageSpan = huffmanImage.GetSpan(); - return huffmanImageSpan[(xSize * (y >> bits)) + (x >> bits)]; + huffmanImage = metadata.HuffmanImage.GetSpan(); + huffmanXSize = metadata.HuffmanXSize; + huffmanBits = metadata.HuffmanSubSampleBits; } + /// + /// Converts a distance code to a pixel distance. The codes from 1 to 120 select one of the 120 nearest 2D neighbors. + /// A larger code is the distance plus 120. + /// + /// The image width. + /// The distance code. + /// The backward distance in pixels, with a minimum of 1 for a neighbor code. private static int PlaneCodeToDistance(int xSize, int planeCode) { if (planeCode > Lz77DistanceCodes.Count) @@ -1179,62 +1554,126 @@ private static int PlaneCodeToDistance(int xSize, int planeCode) } /// - /// Copies pixels when a backward reference is used. - /// Copy 'length' number of pixels (in scan-line order) from the sequence of pixels prior to them by 'dist' pixels. + /// Copies 'length' values (in scan-line order) from the values 'dist' positions before them. The caller makes sure that the source starts at or after the + /// first value and that the destination ends at or before the last value. /// - /// The pixel data. - /// The number of so far decoded pixels. - /// The backward reference distance prior to the current decoded pixel. - /// The number of pixels to copy. - private static void CopyBlock(Span pixelData, int decodedPixels, int dist, int length) + /// + /// + /// Most copies are short, so a copy of at most 16 values is a forward loop of single values, with no call. A forward copy of one value at a time + /// also repeats the last 'dist' values when the distance is less than the length, because each read gets a value that the loop wrote before. + /// + /// + /// For a longer copy with the distance less than the length, the copy repeats the last 'dist' values. A copy of distance 1 is a fill. For other + /// distances, the method copies chunks that double in size. Each chunk reads values that the copy wrote before, and the source and the destination of + /// a chunk do not overlap. + /// + /// + /// The value type: a pixel or an alpha value. + /// The values. + /// The position of the first value to write. + /// The backward reference distance. + /// The number of values to copy. + private static void CopyBlock(Span values, int position, int dist, int length) + where T : unmanaged { - // DecodeImageData checks that the reference starts at or after the first pixel and ends at or before the last pixel. - int start = decodedPixels - dist; + int start = position - dist; + if (length <= 16) + { + // The caller checked that the source starts at or after the first value and that the destination ends at or before the last value. + ref T source = ref Unsafe.Add(ref MemoryMarshal.GetReference(values), (uint)start); + ref T destination = ref Unsafe.Add(ref MemoryMarshal.GetReference(values), (uint)position); + for (nuint i = 0; i < (uint)length; i++) + { + Unsafe.Add(ref destination, i) = Unsafe.Add(ref source, i); + } + + return; + } + if (dist >= length) { - // no overlap. - Span src = pixelData.Slice(start, length); - Span dest = pixelData[decodedPixels..]; - src.CopyTo(dest); + values.Slice(start, length).CopyTo(values.Slice(position, length)); + return; } - else + + if (dist == 1) { - // There is overlap between the backward reference distance and the pixels to copy. - Span src = pixelData[start..]; - Span dest = pixelData[decodedPixels..]; - for (int i = 0; i < length; i++) - { - dest[i] = src[i]; - } + values.Slice(position, length).Fill(values[start]); + return; + } + + int copied = 0; + while (copied < length) + { + int chunk = Math.Min(length - copied, dist + copied); + values.Slice(start, chunk).CopyTo(values.Slice(position + copied, chunk)); + copied += chunk; } } /// - /// Copies alpha values when a backward reference is used. - /// Copy 'length' number of alpha values from the sequence of alpha values prior to them by 'dist'. + /// Copies 'length' values from the values 'dist' positions before them, when the source or the destination is not in one buffer of the group. /// - /// The alpha values. - /// The position of the so far decoded pixels. - /// The backward reference distance prior to the current decoded pixel. - /// The number of pixels to copy. - private static void CopyBlock8B(Span data, int pos, int dist, int length) + /// + /// Each chunk stays inside one source buffer and one destination buffer, and it is at most 'dist' values. Thus the source and the destination of a chunk + /// do not overlap, and the chunks in order give the same result as a copy of one value at a time. + /// + /// The value type: a pixel or a palette index. + /// The buffers of the values. Each buffer except the last has values. + /// The number of values in each buffer except the last. + /// The position of the first value to write. + /// The backward reference distance. + /// The number of values to copy. + private static void CopyBlock(MemoryGroup group, int bufferLength, int position, int dist, int length) + where T : struct { - if (dist >= length) + while (length > 0) { - // no overlap. - data.Slice(pos - dist, length).CopyTo(data[pos..]); + int source = position - dist; + Span sourceBuffer = group[source / bufferLength].Span; + Span destinationBuffer = group[position / bufferLength].Span; + int sourceOffset = source % bufferLength; + int destinationOffset = position % bufferLength; + int chunk = Math.Min(Math.Min(length, dist), Math.Min(sourceBuffer.Length - sourceOffset, destinationBuffer.Length - destinationOffset)); + sourceBuffer.Slice(sourceOffset, chunk).CopyTo(destinationBuffer.Slice(destinationOffset, chunk)); + position += chunk; + length -= chunk; } - else + } + + /// + /// Inserts the pixels from to into the color cache, in their order. + /// + /// The buffers of the pixels. Each buffer except the last has pixels. + /// The number of pixels in each buffer except the last. + /// The first pixel to insert. + /// The pixel after the last pixel to insert. + /// The color cache. + /// The hash shift of the color cache. + private static void FillColorCache(MemoryGroup group, int bufferLength, int start, int end, Span colors, int shift) + { + while (start < end) { - Span dst = data[pos..]; - Span src = data[(pos - dist)..]; - for (int i = 0; i < length; i++) + int index = start / bufferLength; + Span buffer = group[index].Span; + int offset = start - (index * bufferLength); + int count = Math.Min(end - start, buffer.Length - offset); + foreach (uint pixel in buffer.Slice(offset, count)) { - dst[i] = src[i]; + colors[ColorCache.HashPix(pixel, shift)] = pixel; } + + start += count; } } + /// + /// Adds one decoded component to a packed table entry. The bit count grows by the bits of the code, and the value is placed at the shift. + /// + /// The table entry of the component code. + /// The bit position of the component in the ARGB pixel. + /// The packed table entry. + /// The number of bits of the component code. [MethodImpl(InliningOptions.ShortMethod)] private static int AccumulateHCode(HuffmanCode hCode, int shift, ref HuffmanCode huff) { diff --git a/src/ImageSharp/Formats/Webp/Lossy/ChromaDownsampler.cs b/src/ImageSharp/Formats/Webp/Lossy/ChromaDownsampler.cs new file mode 100644 index 0000000000..05e6061984 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossy/ChromaDownsampler.cs @@ -0,0 +1,192 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using SixLabors.ImageSharp.PixelFormats; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossy; + +/// +/// Resamples two BGRA rows to one row of chroma-resolution RGB sums in linear light. +/// +internal static class ChromaDownsampler +{ + /// + /// Resamples each 2x2 group of two BGRA rows in linear light, with two fractional bits. + /// + /// The first BGRA row. + /// The second BGRA row, or the first row again for the final row of an odd height. + /// Whether each pixel is weighted by its alpha. It is false when both rows are opaque. + /// Four words for each chroma sample: red, green, blue, and the sum of the alpha values. + public static void Downsample(ReadOnlySpan row0, ReadOnlySpan row1, bool weightByAlpha, Span resampled) + { + // A 2x2 group gives one chroma sample. An odd width ends with a group of one column. + int width = row0.Length; + int groups = width >> 1; + AccumulateGroups(row0, row1, weightByAlpha, 0, groups, resampled); + if ((width & 1) != 0) + { + AccumulateEdge(row0[width - 1], row1[width - 1], weightByAlpha, resampled.Slice(groups * 4, 4)); + } + } + + /// + /// Resamples complete 2x2 groups in linear light and retains two fractional bits for chroma conversion. + /// + /// The first BGRA row. + /// The second BGRA row, or the first row again at the bottom edge. + /// Whether each pixel is weighted by its alpha. + /// The first chroma sample. Its group starts at pixel 2 * . + /// The number of complete groups. + /// Four words for each sample: red, green, blue, and the sum of the alpha values. + private static void AccumulateGroups( + ReadOnlySpan row0, + ReadOnlySpan row1, + bool weightByAlpha, + int firstSample, + int count, + Span resampled) + { + ref Bgra32 top = ref MemoryMarshal.GetReference(row0); + ref Bgra32 bottom = ref MemoryMarshal.GetReference(row1); + ref ushort destination = ref MemoryMarshal.GetReference(resampled); + + // A 2x2 group gives one chroma sample; gamma conversion happens before averaging the four source values. + for (int sample = firstSample; sample < firstSample + count; sample++) + { + nuint pixel = (uint)sample * 2; + Bgra32 topLeft = Unsafe.Add(ref top, pixel); + Bgra32 topRight = Unsafe.Add(ref top, pixel + 1); + Bgra32 bottomLeft = Unsafe.Add(ref bottom, pixel); + Bgra32 bottomRight = Unsafe.Add(ref bottom, pixel + 1); + ref ushort dst = ref Unsafe.Add(ref destination, (uint)sample * 4); + uint alphaSum = (uint)(topLeft.A + topRight.A + bottomLeft.A + bottomRight.A); + + // Opaque rows need no weighting. A fully opaque group gives the same unweighted sums, and a fully transparent + // group has no visible color and avoids division by zero. + if (!weightByAlpha || alphaSum is 4 * 0xff or 0) + { + dst = (ushort)LinearToGamma( + GammaToLinear(topLeft.R) + GammaToLinear(topRight.R) + GammaToLinear(bottomLeft.R) + GammaToLinear(bottomRight.R), 0); + + Unsafe.Add(ref dst, (nuint)1) = (ushort)LinearToGamma( + GammaToLinear(topLeft.G) + GammaToLinear(topRight.G) + GammaToLinear(bottomLeft.G) + GammaToLinear(bottomRight.G), 0); + + Unsafe.Add(ref dst, (nuint)2) = (ushort)LinearToGamma( + GammaToLinear(topLeft.B) + GammaToLinear(topRight.B) + GammaToLinear(bottomLeft.B) + GammaToLinear(bottomRight.B), 0); + } + else + { + dst = (ushort)LinearToGammaWeighted( + topLeft.R, topRight.R, bottomLeft.R, bottomRight.R, topLeft.A, topRight.A, bottomLeft.A, bottomRight.A, alphaSum); + + Unsafe.Add(ref dst, (nuint)1) = (ushort)LinearToGammaWeighted( + topLeft.G, topRight.G, bottomLeft.G, bottomRight.G, topLeft.A, topRight.A, bottomLeft.A, bottomRight.A, alphaSum); + + Unsafe.Add(ref dst, (nuint)2) = (ushort)LinearToGammaWeighted( + topLeft.B, topRight.B, bottomLeft.B, bottomRight.B, topLeft.A, topRight.A, bottomLeft.A, bottomRight.A, alphaSum); + } + + Unsafe.Add(ref dst, (nuint)3) = (ushort)alphaSum; + } + } + + /// + /// Resamples the one-column group at the right edge of an odd width. + /// + /// The pixel of the first row. + /// The pixel of the second row. + /// Whether each pixel is weighted by its alpha. + /// Four words: red, green, blue, and the sum of the alpha values. + private static void AccumulateEdge(Bgra32 top, Bgra32 bottom, bool weightByAlpha, Span destination) + { + // Each pixel counts twice, so the sums keep the four-sample scale of a complete group. + uint alphaSum = (uint)(2u * (top.A + bottom.A)); + if (!weightByAlpha || alphaSum is 4 * 0xff or 0) + { + destination[0] = (ushort)LinearToGamma(GammaToLinear(top.R) + GammaToLinear(bottom.R), 1); + destination[1] = (ushort)LinearToGamma(GammaToLinear(top.G) + GammaToLinear(bottom.G), 1); + destination[2] = (ushort)LinearToGamma(GammaToLinear(top.B) + GammaToLinear(bottom.B), 1); + } + else + { + destination[0] = (ushort)LinearToGammaWeighted(top.R, bottom.R, top.R, bottom.R, top.A, bottom.A, top.A, bottom.A, alphaSum); + destination[1] = (ushort)LinearToGammaWeighted(top.G, bottom.G, top.G, bottom.G, top.A, bottom.A, top.A, bottom.A, alphaSum); + destination[2] = (ushort)LinearToGammaWeighted(top.B, bottom.B, top.B, bottom.B, top.A, bottom.A, top.A, bottom.A, alphaSum); + } + + destination[3] = (ushort)alphaSum; + } + + /// + /// Averages four linear-light values by alpha and returns a gamma-encoded value with two fractional bits. + /// + /// The first channel value. + /// The second channel value. + /// The third channel value. + /// The fourth channel value. + /// The first alpha value. + /// The second alpha value. + /// The third alpha value. + /// The fourth alpha value. + /// The nonzero sum of the four alpha values. + /// The weighted channel value scaled by four. + [MethodImpl(InliningOptions.ShortMethod)] + private static int LinearToGammaWeighted(byte rgb0, byte rgb1, byte rgb2, byte rgb3, byte a0, byte a1, byte a2, byte a3, uint totalA) + { + uint sum = (a0 * GammaToLinear(rgb0)) + (a1 * GammaToLinear(rgb1)) + (a2 * GammaToLinear(rgb2)) + (a3 * GammaToLinear(rgb3)); + + // InvAlpha supplies the fixed-point reciprocal of the alpha sum; retain two extra bits for the chroma matrix. + // The alpha sum is at most 4 * 255 and InvAlpha has 4 * 255 + 1 entries, so the read needs no range check. + uint inverse = Unsafe.Add(ref MemoryMarshal.GetReference(WebpLookupTables.InvAlpha), (nuint)totalA); + return LinearToGamma((sum * inverse) >> (WebpConstants.AlphaFix - 2), 0); + } + + /// + /// Converts a linear-light sum to a gamma-encoded channel value with two fractional bits. + /// + /// The sum of the linear-light source values. + /// One when two samples replace the four-sample group; otherwise zero. + /// The gamma-encoded channel value scaled by four. + [MethodImpl(InliningOptions.ShortMethod)] + private static int LinearToGamma(uint baseValue, int shift) + { + // At an odd image edge, doubling a two-sample sum keeps the same scale as a complete 2x2 group. + int interpolated = Interpolate((int)(baseValue << shift)); + return (interpolated + WebpConstants.GammaTabRounder) >> WebpConstants.GammaTabFix; + } + + /// + /// Maps a gamma-encoded byte to the linear-light lookup-table scale. + /// + /// The gamma-encoded channel byte. + /// The linear-light value. + /// + /// The table has 256 entries, so a byte index is always inside it and the read needs no range check. + /// + [MethodImpl(InliningOptions.ShortMethod)] + private static uint GammaToLinear(byte v) => Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(WebpLookupTables.GammaToLinearTab), (nuint)v); + + /// + /// Interpolates neighboring entries in the linear-to-gamma table for a four-sample sum. + /// + /// The linear-light sum at the four-sample scale. + /// The interpolated gamma value at the table's fixed-point scale. + [MethodImpl(InliningOptions.ShortMethod)] + private static int Interpolate(int v) + { + // The low bits give the position between table entries. The extra two bits account for the four-sample sum. + // Every caller passes a sum of at most 4 * GammaScale, the largest four-sample sum or the equivalent weighted average, + // so tabPos is at most GammaTabSize - 1 and tabPos + 1 is the last of the GammaTabSize + 1 entries. + // The two reads therefore need no range check. + ref int table = ref MemoryMarshal.GetArrayDataReference(WebpLookupTables.LinearToGammaTab); + nuint tabPos = (uint)v >> (WebpConstants.GammaTabFix + 2); + int x = v & ((WebpConstants.GammaTabScale << 2) - 1); + int v0 = Unsafe.Add(ref table, tabPos); + int v1 = Unsafe.Add(ref table, tabPos + 1); + int y = (v1 * x) + (v0 * ((WebpConstants.GammaTabScale << 2) - x)); + + return y; + } +} diff --git a/src/ImageSharp/Formats/Webp/Lossy/ChromaUpsampler.cs b/src/ImageSharp/Formats/Webp/Lossy/ChromaUpsampler.cs new file mode 100644 index 0000000000..73b42275f2 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossy/ChromaUpsampler.cs @@ -0,0 +1,226 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossy; + +/// +/// Interpolates the full-resolution chroma of one output row from two half-resolution chroma rows. +/// +/// +/// +/// The near chroma row is the one nearer to the output row, and the far chroma row is the other one. Each output chroma +/// sample is the 9:3:3:1 blend of its four nearest chroma samples: weight 9 for the nearest sample, 3 for the near +/// sample on the other side and for the far sample on the same side, and 1 for the diagonal sample. +/// +/// +/// Output pixel 0 and, for an even width, the last output pixel have no chroma neighbor on one side. Repeating the +/// edge sample reduces the blend to the 3:1 vertical blend (3 * near + far + 2) >> 2. +/// +/// +/// Chroma pair x, the samples x and x + 1, gives output pixels 2x + 1 (odd) and 2x + 2 (even). The vector forms +/// compute the blend with one rounding, (sum + 8) >> 4, which is the same value as the two roundings of +/// the scalar form. +/// +/// +internal static class ChromaUpsampler +{ + /// + /// Interpolates one full-resolution chroma row. + /// + /// The chroma row nearer to the output row. + /// The other chroma row. + /// The full-resolution chroma row. Its length is the output width. + public static void Upsample(ReadOnlySpan near, ReadOnlySpan far, Span output) + { + ref byte nearBase = ref MemoryMarshal.GetReference(near); + ref byte farBase = ref MemoryMarshal.GetReference(far); + ref byte outputBase = ref MemoryMarshal.GetReference(output); + int length = output.Length; + nuint lastPair = (uint)(length - 1) >> 1; + nuint x = 0; + + outputBase = (byte)Edge(nearBase, farBase); + + // Each vector form reads the chroma at x and x + 1, so x + Count stays at or before the last chroma sample. + if (Vector512.IsHardwareAccelerated) + { + for (; x + (uint)Vector512.Count <= lastPair; x += (uint)Vector512.Count) + { + Interpolate512(ref Unsafe.Add(ref nearBase, x), ref Unsafe.Add(ref farBase, x)).StoreUnsafe(ref outputBase, (2 * x) + 1); + } + } + + if (Vector256.IsHardwareAccelerated) + { + for (; x + (uint)Vector256.Count <= lastPair; x += (uint)Vector256.Count) + { + Interpolate256(ref Unsafe.Add(ref nearBase, x), ref Unsafe.Add(ref farBase, x)).StoreUnsafe(ref outputBase, (2 * x) + 1); + } + } + + if (Vector128.IsHardwareAccelerated) + { + for (; x + (uint)Vector128.Count <= lastPair; x += (uint)Vector128.Count) + { + Interpolate128(ref Unsafe.Add(ref nearBase, x), ref Unsafe.Add(ref farBase, x)).StoreUnsafe(ref outputBase, (2 * x) + 1); + } + } + + for (; x < lastPair; x++) + { + Interpolate( + Unsafe.Add(ref nearBase, x), + Unsafe.Add(ref nearBase, x + 1), + Unsafe.Add(ref farBase, x), + Unsafe.Add(ref farBase, x + 1), + out int odd, + out int even); + + Unsafe.Add(ref outputBase, (2 * x) + 1) = (byte)odd; + Unsafe.Add(ref outputBase, (2 * x) + 2) = (byte)even; + } + + if ((length & 1) == 0) + { + Unsafe.Add(ref outputBase, (uint)length - 1) = (byte)Edge(Unsafe.Add(ref nearBase, lastPair), Unsafe.Add(ref farBase, lastPair)); + } + } + + /// + /// Gets the chroma of an output pixel at a row edge, which has a chroma neighbor on one side only. + /// + /// The edge sample of the near chroma row. + /// The edge sample of the far chroma row. + /// The 3:1 vertical blend of the two samples. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Edge(int near, int far) => ((3 * near) + far + 2) >> 2; + + /// + /// Gets the chroma of the two output pixels between two horizontally adjacent chroma samples. + /// + /// The left sample of the near chroma row. + /// The right sample of the near chroma row. + /// The left sample of the far chroma row. + /// The right sample of the far chroma row. + /// The chroma of the left output pixel. + /// The chroma of the right output pixel. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Interpolate(int nearLeft, int nearRight, int farLeft, int farRight, out int odd, out int even) + { + // The sum of the four samples plus eight is shared. Each diagonal adds twice its two samples, and the division + // by eight and the average with the nearest sample give the 9:3:3:1 blend divided by sixteen. + int roundedSum = nearLeft + nearRight + farLeft + farRight + 8; + odd = (((roundedSum + (2 * (nearRight + farLeft))) >> 3) + nearLeft) >> 1; + even = (((roundedSum + (2 * (nearLeft + farRight))) >> 3) + nearRight) >> 1; + } + + /// + /// Interpolates the chroma of 64 output pixels from 33 samples of each chroma row. + /// + /// The left sample of the first chroma pair in the near chroma row. + /// The left sample of the first chroma pair in the far chroma row. + /// The chroma of the output pixels in pixel order, the odd pixel of each pair first. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector512 Interpolate512(ref byte near, ref byte far) + { + (Vector512 odd, Vector512 even) = Blend( + Vector512.WidenLower(Vector512.Create(Vector256.LoadUnsafe(ref near), default)), + Vector512.WidenLower(Vector512.Create(Vector256.LoadUnsafe(ref near, 1), default)), + Vector512.WidenLower(Vector512.Create(Vector256.LoadUnsafe(ref far), default)), + Vector512.WidenLower(Vector512.Create(Vector256.LoadUnsafe(ref far, 1), default))); + + // Both values fit in one byte. The odd pixel goes to the low byte and the even pixel to the high byte, so the + // little-endian bytes are in pixel order. + return (odd | (even << 8)).AsByte(); + } + + /// + /// Interpolates the chroma of 32 output pixels from 17 samples of each chroma row. + /// + /// The left sample of the first chroma pair in the near chroma row. + /// The left sample of the first chroma pair in the far chroma row. + /// The chroma of the output pixels in pixel order, the odd pixel of each pair first. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 Interpolate256(ref byte near, ref byte far) + { + (Vector256 odd, Vector256 even) = Blend( + Vector256.WidenLower(Vector256.Create(Vector128.LoadUnsafe(ref near), default)), + Vector256.WidenLower(Vector256.Create(Vector128.LoadUnsafe(ref near, 1), default)), + Vector256.WidenLower(Vector256.Create(Vector128.LoadUnsafe(ref far), default)), + Vector256.WidenLower(Vector256.Create(Vector128.LoadUnsafe(ref far, 1), default))); + + // The same byte order as the 512-bit form. + return (odd | (even << 8)).AsByte(); + } + + /// + /// Interpolates the chroma of 16 output pixels from 9 samples of each chroma row. + /// + /// The left sample of the first chroma pair in the near chroma row. + /// The left sample of the first chroma pair in the far chroma row. + /// The chroma of the output pixels in pixel order, the odd pixel of each pair first. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 Interpolate128(ref byte near, ref byte far) + { + // An 8-byte load reads exactly the samples of the eight pairs, so it reads nothing past the second sample. + (Vector128 odd, Vector128 even) = Blend( + Vector128.WidenLower(Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref near)).AsByte()), + Vector128.WidenLower(Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref Unsafe.Add(ref near, (nuint)1))).AsByte()), + Vector128.WidenLower(Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref far)).AsByte()), + Vector128.WidenLower(Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref Unsafe.Add(ref far, (nuint)1))).AsByte())); + + // The same byte order as the 512-bit form. + return (odd | (even << 8)).AsByte(); + } + + /// + /// Applies the 9:3:3:1 blend to each lane, one chroma pair in each lane. + /// + /// The left samples of the near chroma row. + /// The right samples of the near chroma row. + /// The left samples of the far chroma row. + /// The right samples of the far chroma row. + /// The chroma of the odd and even output pixels. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static (Vector512 Odd, Vector512 Even) Blend( + Vector512 nearLeft, Vector512 nearRight, Vector512 farLeft, Vector512 farRight) + { + // The weights sum to sixteen. The largest sum is 16 * 255 + 8 = 4088, so the word lanes cannot overflow. + Vector512 three = Vector512.Create((ushort)3); + Vector512 nine = Vector512.Create((ushort)9); + Vector512 bias = Vector512.Create((ushort)8); + Vector512 odd = ((nearLeft * nine) + (nearRight * three) + (farLeft * three) + farRight + bias) >> 4; + Vector512 even = ((nearLeft * three) + (nearRight * nine) + farLeft + (farRight * three) + bias) >> 4; + return (odd, even); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static (Vector256 Odd, Vector256 Even) Blend( + Vector256 nearLeft, Vector256 nearRight, Vector256 farLeft, Vector256 farRight) + { + Vector256 three = Vector256.Create((ushort)3); + Vector256 nine = Vector256.Create((ushort)9); + Vector256 bias = Vector256.Create((ushort)8); + Vector256 odd = ((nearLeft * nine) + (nearRight * three) + (farLeft * three) + farRight + bias) >> 4; + Vector256 even = ((nearLeft * three) + (nearRight * nine) + farLeft + (farRight * three) + bias) >> 4; + return (odd, even); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static (Vector128 Odd, Vector128 Even) Blend( + Vector128 nearLeft, Vector128 nearRight, Vector128 farLeft, Vector128 farRight) + { + Vector128 three = Vector128.Create((ushort)3); + Vector128 nine = Vector128.Create((ushort)9); + Vector128 bias = Vector128.Create((ushort)8); + Vector128 odd = ((nearLeft * nine) + (nearRight * three) + (farLeft * three) + farRight + bias) >> 4; + Vector128 even = ((nearLeft * three) + (nearRight * nine) + farLeft + (farRight * three) + bias) >> 4; + return (odd, even); + } +} diff --git a/src/ImageSharp/Formats/Webp/Lossy/LossyUtils.cs b/src/ImageSharp/Formats/Webp/Lossy/LossyUtils.cs index bc7e474574..a28af6b8fe 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/LossyUtils.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/LossyUtils.cs @@ -10,115 +10,70 @@ // ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Formats.Webp.Lossy; +/// +/// Shared methods of the lossy (VP8) encoder and decoder: distortion measures, transforms, predictions and loop filters. +/// Unless a member states otherwise, the block rows have a stride of . +/// internal static class LossyUtils { + /// + /// Returns the sum of squared differences between two 16x16 blocks. + /// + /// The first sample of the first block. The rows have a stride of . + /// The first sample of the second block. The rows have a stride of . + /// The sum of squared differences. [MethodImpl(InliningOptions.ShortMethod)] - public static int Vp8_Sse16x16(Span a, Span b) - { - if (Vector256.IsHardwareAccelerated) - { - return Vp8_Sse16xN_Vector256(a, b, 4); - } - - if (Vector128.IsHardwareAccelerated) - { - return Vp8_16xN_Vector128(a, b, 8); - } - - return Vp8_SseNxN(a, b, 16, 16); - } + public static int Vp8_Sse16x16(Span a, Span b) => Vp8_Sse16xN(ref MemoryMarshal.GetReference(a), ref MemoryMarshal.GetReference(b), 16); + /// + /// Returns the sum of squared differences between two 16x8 blocks. + /// + /// The first sample of the first block. The rows have a stride of . + /// The first sample of the second block. The rows have a stride of . + /// The sum of squared differences. [MethodImpl(InliningOptions.ShortMethod)] - public static int Vp8_Sse16x8(Span a, Span b) - { - if (Vector256.IsHardwareAccelerated) - { - return Vp8_Sse16xN_Vector256(a, b, 2); - } - - if (Vector128.IsHardwareAccelerated) - { - return Vp8_16xN_Vector128(a, b, 4); - } - - return Vp8_SseNxN(a, b, 16, 8); - } + public static int Vp8_Sse16x8(Span a, Span b) => Vp8_Sse16xN(ref MemoryMarshal.GetReference(a), ref MemoryMarshal.GetReference(b), 8); + /// + /// Returns the sum of squared differences between two 4x4 blocks. + /// + /// The first sample of the first block. The rows have a stride of . + /// The first sample of the second block. The rows have a stride of . + /// The sum of squared differences. [MethodImpl(InliningOptions.ShortMethod)] public static int Vp8_Sse4x4(Span a, Span b) { - if (Vector256.IsHardwareAccelerated) - { - // Load values. - ref byte aRef = ref MemoryMarshal.GetReference(a); - ref byte bRef = ref MemoryMarshal.GetReference(b); - Vector256 a0 = Vector256.Create( - Unsafe.As>(ref aRef), - Unsafe.As>(ref Unsafe.Add(ref aRef, WebpConstants.Bps))); - Vector256 a1 = Vector256.Create( - Unsafe.As>(ref Unsafe.Add(ref aRef, WebpConstants.Bps * 2)), - Unsafe.As>(ref Unsafe.Add(ref aRef, WebpConstants.Bps * 3))); - Vector256 b0 = Vector256.Create( - Unsafe.As>(ref bRef), - Unsafe.As>(ref Unsafe.Add(ref bRef, WebpConstants.Bps))); - Vector256 b1 = Vector256.Create( - Unsafe.As>(ref Unsafe.Add(ref bRef, WebpConstants.Bps * 2)), - Unsafe.As>(ref Unsafe.Add(ref bRef, WebpConstants.Bps * 3))); - - // Combine pair of lines. - Vector256 a01 = Vector256_.UnpackLow(a0.AsInt32(), a1.AsInt32()); - Vector256 b01 = Vector256_.UnpackLow(b0.AsInt32(), b1.AsInt32()); - - // Convert to 16b. - Vector256 a01s = Vector256_.UnpackLow(a01.AsByte(), Vector256.Zero); - Vector256 b01s = Vector256_.UnpackLow(b01.AsByte(), Vector256.Zero); - - // subtract, square and accumulate. - Vector256 d0 = Vector256.SubtractSaturate(a01s.AsInt16(), b01s.AsInt16()); - Vector256 e0 = Vector256_.MultiplyAddAdjacent(d0, d0); - - return ReduceSumVector256(e0); - } - if (Vector128.IsHardwareAccelerated) { - // Load values. + // The four rows of 4 samples fill one vector, row y in 32-bit lane y. ref byte aRef = ref MemoryMarshal.GetReference(a); ref byte bRef = ref MemoryMarshal.GetReference(b); - Vector128 a0 = Unsafe.As>(ref aRef); - Vector128 a1 = Unsafe.As>(ref Unsafe.Add(ref aRef, WebpConstants.Bps)); - Vector128 a2 = Unsafe.As>(ref Unsafe.Add(ref aRef, WebpConstants.Bps * 2)); - Vector128 a3 = Unsafe.As>(ref Unsafe.Add(ref aRef, WebpConstants.Bps * 3)); - Vector128 b0 = Unsafe.As>(ref bRef); - Vector128 b1 = Unsafe.As>(ref Unsafe.Add(ref bRef, WebpConstants.Bps)); - Vector128 b2 = Unsafe.As>(ref Unsafe.Add(ref bRef, WebpConstants.Bps * 2)); - Vector128 b3 = Unsafe.As>(ref Unsafe.Add(ref bRef, WebpConstants.Bps * 3)); - - // Combine pair of lines. - Vector128 a01 = Vector128_.UnpackLow(a0.AsInt32(), a1.AsInt32()); - Vector128 a23 = Vector128_.UnpackLow(a2.AsInt32(), a3.AsInt32()); - Vector128 b01 = Vector128_.UnpackLow(b0.AsInt32(), b1.AsInt32()); - Vector128 b23 = Vector128_.UnpackLow(b2.AsInt32(), b3.AsInt32()); - - // Convert to 16b. - Vector128 a01s = Vector128_.UnpackLow(a01.AsByte(), Vector128.Zero); - Vector128 a23s = Vector128_.UnpackLow(a23.AsByte(), Vector128.Zero); - Vector128 b01s = Vector128_.UnpackLow(b01.AsByte(), Vector128.Zero); - Vector128 b23s = Vector128_.UnpackLow(b23.AsByte(), Vector128.Zero); - - // subtract, square and accumulate. - Vector128 d0 = Vector128.SubtractSaturate(a01s.AsInt16(), b01s.AsInt16()); - Vector128 d1 = Vector128.SubtractSaturate(a23s.AsInt16(), b23s.AsInt16()); - Vector128 e0 = Vector128_.MultiplyAddAdjacent(d0, d0); - Vector128 e1 = Vector128_.MultiplyAddAdjacent(d1, d1); - Vector128 sum = e0 + e1; - - return ReduceSumVector128(sum); + Vector128 a0 = Vector128.Create( + Unsafe.ReadUnaligned(ref aRef), + Unsafe.ReadUnaligned(ref Unsafe.Add(ref aRef, (nuint)WebpConstants.Bps)), + Unsafe.ReadUnaligned(ref Unsafe.Add(ref aRef, (nuint)(WebpConstants.Bps * 2))), + Unsafe.ReadUnaligned(ref Unsafe.Add(ref aRef, (nuint)(WebpConstants.Bps * 3)))).AsByte(); + + Vector128 b0 = Vector128.Create( + Unsafe.ReadUnaligned(ref bRef), + Unsafe.ReadUnaligned(ref Unsafe.Add(ref bRef, (nuint)WebpConstants.Bps)), + Unsafe.ReadUnaligned(ref Unsafe.Add(ref bRef, (nuint)(WebpConstants.Bps * 2))), + Unsafe.ReadUnaligned(ref Unsafe.Add(ref bRef, (nuint)(WebpConstants.Bps * 3)))).AsByte(); + + return Vector128.Sum(SubtractAndAccumulate(a0, b0)); } return Vp8_SseNxN(a, b, 4, 4); } + /// + /// Returns the sum of squared differences between two blocks of by samples. + /// + /// The first sample of the first block. The rows have a stride of . + /// The first sample of the second block. The rows have a stride of . + /// The block width. + /// The block height. + /// The sum of squared differences. [MethodImpl(InliningOptions.ShortMethod)] public static int Vp8_SseNxN(ReadOnlySpan a, ReadOnlySpan b, int w, int h) { @@ -138,574 +93,854 @@ public static int Vp8_SseNxN(ReadOnlySpan a, ReadOnlySpan b, int w, return count; } + /// + /// Returns the sum of squared differences between two blocks of 16 samples by rows. + /// + /// The first sample of the first block. The rows have a stride of . + /// The first sample of the second block. The rows have a stride of . + /// The number of rows: 8 or 16. + /// The sum of squared differences. [MethodImpl(InliningOptions.ShortMethod)] - private static int Vp8_16xN_Vector128(Span a, Span b, int numPairs) + private static int Vp8_Sse16xN(ref byte a, ref byte b, int rows) { - Vector128 sum = Vector128.Zero; - nuint offset = 0; - ref byte aRef = ref MemoryMarshal.GetReference(a); - ref byte bRef = ref MemoryMarshal.GetReference(b); - for (int i = 0; i < numPairs; i++) + // A 16-sample row is one 128-bit vector. A 256-bit vector holds two rows and a 512-bit vector holds four. The row + // count is a multiple of four, so the widest accelerated width takes all rows. + const nuint stride = WebpConstants.Bps; + nuint end = (uint)rows * stride; + if (Vector512.IsHardwareAccelerated) { - // Load values. - Vector128 a0 = Unsafe.As>(ref Unsafe.Add(ref aRef, offset)); - Vector128 b0 = Unsafe.As>(ref Unsafe.Add(ref bRef, offset)); - Vector128 a1 = Unsafe.As>(ref Unsafe.Add(ref aRef, offset + WebpConstants.Bps)); - Vector128 b1 = Unsafe.As>(ref Unsafe.Add(ref bRef, offset + WebpConstants.Bps)); + Vector512 sum = Vector512.Zero; + for (nuint offset = 0; offset < end; offset += 4 * stride) + { + ref byte a0 = ref Unsafe.Add(ref a, offset); + ref byte b0 = ref Unsafe.Add(ref b, offset); + Vector512 aRows = Vector512.Create( + Vector256.Create(Vector128.LoadUnsafe(ref a0), Vector128.LoadUnsafe(ref a0, stride)), + Vector256.Create(Vector128.LoadUnsafe(ref a0, 2 * stride), Vector128.LoadUnsafe(ref a0, 3 * stride))); - Vector128 sum1 = SubtractAndAccumulateVector128(a0, b0); - Vector128 sum2 = SubtractAndAccumulateVector128(a1, b1); - sum += sum1 + sum2; + Vector512 bRows = Vector512.Create( + Vector256.Create(Vector128.LoadUnsafe(ref b0), Vector128.LoadUnsafe(ref b0, stride)), + Vector256.Create(Vector128.LoadUnsafe(ref b0, 2 * stride), Vector128.LoadUnsafe(ref b0, 3 * stride))); - offset += 2 * WebpConstants.Bps; - } + sum += SubtractAndAccumulate(aRows, bRows); + } - return ReduceSumVector128(sum); - } + return Vector512.Sum(sum); + } - [MethodImpl(InliningOptions.ShortMethod)] - private static int Vp8_Sse16xN_Vector256(Span a, Span b, int numPairs) - { - Vector256 sum = Vector256.Zero; - nuint offset = 0; - ref byte aRef = ref MemoryMarshal.GetReference(a); - ref byte bRef = ref MemoryMarshal.GetReference(b); - for (int i = 0; i < numPairs; i++) + if (Vector256.IsHardwareAccelerated) { - // Load values. - Vector256 a0 = Vector256.Create( - Unsafe.As>(ref Unsafe.Add(ref aRef, offset)), - Unsafe.As>(ref Unsafe.Add(ref aRef, offset + WebpConstants.Bps))); - Vector256 b0 = Vector256.Create( - Unsafe.As>(ref Unsafe.Add(ref bRef, offset)), - Unsafe.As>(ref Unsafe.Add(ref bRef, offset + WebpConstants.Bps))); - Vector256 a1 = Vector256.Create( - Unsafe.As>(ref Unsafe.Add(ref aRef, offset + (2 * WebpConstants.Bps))), - Unsafe.As>(ref Unsafe.Add(ref aRef, offset + (3 * WebpConstants.Bps)))); - Vector256 b1 = Vector256.Create( - Unsafe.As>(ref Unsafe.Add(ref bRef, offset + (2 * WebpConstants.Bps))), - Unsafe.As>(ref Unsafe.Add(ref bRef, offset + (3 * WebpConstants.Bps)))); + Vector256 sum = Vector256.Zero; + for (nuint offset = 0; offset < end; offset += 2 * stride) + { + ref byte a0 = ref Unsafe.Add(ref a, offset); + ref byte b0 = ref Unsafe.Add(ref b, offset); + Vector256 aRows = Vector256.Create(Vector128.LoadUnsafe(ref a0), Vector128.LoadUnsafe(ref a0, stride)); + Vector256 bRows = Vector256.Create(Vector128.LoadUnsafe(ref b0), Vector128.LoadUnsafe(ref b0, stride)); + sum += SubtractAndAccumulate(aRows, bRows); + } - Vector256 sum1 = SubtractAndAccumulateVector256(a0, b0); - Vector256 sum2 = SubtractAndAccumulateVector256(a1, b1); - sum += sum1 + sum2; + return Vector256.Sum(sum); + } + + if (Vector128.IsHardwareAccelerated) + { + Vector128 sum = Vector128.Zero; + for (nuint offset = 0; offset < end; offset += stride) + { + sum += SubtractAndAccumulate(Vector128.LoadUnsafe(ref a, offset), Vector128.LoadUnsafe(ref b, offset)); + } - offset += 4 * WebpConstants.Bps; + return Vector128.Sum(sum); } - return ReduceSumVector256(sum); + return Vp8_SseNxN(MemoryMarshal.CreateReadOnlySpan(ref a, (int)end), MemoryMarshal.CreateReadOnlySpan(ref b, (int)end), 16, rows); } + /// + /// Returns the squared differences of two vectors of samples, added in groups of four. + /// + /// + /// The difference of two samples is |a - b| from 0 to 255, so each square is exact in a 16-bit multiply-add, and each + /// 32-bit lane holds the sum of four squares. The lane order does not matter, because the caller adds all lanes. + /// + /// The first samples. + /// The second samples. + /// The sums of squared differences. [MethodImpl(InliningOptions.ShortMethod)] - private static Vector128 SubtractAndAccumulateVector128(Vector128 a, Vector128 b) + private static Vector128 SubtractAndAccumulate(Vector128 a, Vector128 b) { - // Take abs(a-b) in 8b. - Vector128 ab = Vector128.SubtractSaturate(a, b); - Vector128 ba = Vector128.SubtractSaturate(b, a); - Vector128 absAb = ab | ba; - - // Zero-extend to 16b. - Vector128 c0 = Vector128_.UnpackLow(absAb, Vector128.Zero); - Vector128 c1 = Vector128_.UnpackHigh(absAb, Vector128.Zero); - - // Multiply with self. - Vector128 sum1 = Vector128_.MultiplyAddAdjacent(c0.AsInt16(), c0.AsInt16()); - Vector128 sum2 = Vector128_.MultiplyAddAdjacent(c1.AsInt16(), c1.AsInt16()); - - return sum1 + sum2; + // One of the two saturating differences is |a - b| and the other is 0, so their OR is |a - b|. + Vector128 difference = Vector128.SubtractSaturate(a, b) | Vector128.SubtractSaturate(b, a); + Vector128 low = Vector128_.UnpackLow(difference, Vector128.Zero).AsInt16(); + Vector128 high = Vector128_.UnpackHigh(difference, Vector128.Zero).AsInt16(); + return Vector128_.MultiplyAddAdjacent(low, low) + Vector128_.MultiplyAddAdjacent(high, high); } + /// [MethodImpl(InliningOptions.ShortMethod)] - private static Vector256 SubtractAndAccumulateVector256(Vector256 a, Vector256 b) + private static Vector256 SubtractAndAccumulate(Vector256 a, Vector256 b) { - // Take abs(a-b) in 8b. - Vector256 ab = Vector256.SubtractSaturate(a, b); - Vector256 ba = Vector256.SubtractSaturate(b, a); - Vector256 absAb = ab | ba; - - // Zero-extend to 16b. - Vector256 c0 = Vector256_.UnpackLow(absAb, Vector256.Zero); - Vector256 c1 = Vector256_.UnpackHigh(absAb, Vector256.Zero); - - // Multiply with self. - Vector256 sum1 = Vector256_.MultiplyAddAdjacent(c0.AsInt16(), c0.AsInt16()); - Vector256 sum2 = Vector256_.MultiplyAddAdjacent(c1.AsInt16(), c1.AsInt16()); - - return sum1 + sum2; + Vector256 difference = Vector256.SubtractSaturate(a, b) | Vector256.SubtractSaturate(b, a); + Vector256 low = Vector256_.UnpackLow(difference, Vector256.Zero).AsInt16(); + Vector256 high = Vector256_.UnpackHigh(difference, Vector256.Zero).AsInt16(); + return Vector256_.MultiplyAddAdjacent(low, low) + Vector256_.MultiplyAddAdjacent(high, high); } + /// [MethodImpl(InliningOptions.ShortMethod)] - public static void Vp8Copy4X4(Span src, Span dst) => Copy(src, dst, 4, 4); - - [MethodImpl(InliningOptions.ShortMethod)] - public static void Vp8Copy16X8(Span src, Span dst) => Copy(src, dst, 16, 8); - - [MethodImpl(InliningOptions.ShortMethod)] - public static void Copy(Span src, Span dst, int w, int h) + private static Vector512 SubtractAndAccumulate(Vector512 a, Vector512 b) { - int offset = 0; - for (int y = 0; y < h; y++) - { - src.Slice(offset, w).CopyTo(dst.Slice(offset, w)); - offset += WebpConstants.Bps; - } + Vector512 difference = Vector512.SubtractSaturate(a, b) | Vector512.SubtractSaturate(b, a); + Vector512 low = Vector512_.UnpackLow(difference, Vector512.Zero).AsInt16(); + Vector512 high = Vector512_.UnpackHigh(difference, Vector512.Zero).AsInt16(); + return Vector512_.MultiplyAddAdjacent(low, low) + Vector512_.MultiplyAddAdjacent(high, high); } + /// + /// Returns the sums of squared differences between one 4x4 source block and two horizontally adjacent 4x4 blocks. + /// + /// The first sample of the source block. The rows have a stride of . + /// + /// The first sample of the two blocks. Each row has the 4 samples of the first block, then the 4 samples of the second block. + /// The rows have a stride of . + /// + /// The sum of squared differences against the first block. + /// The sum of squared differences against the second block. [MethodImpl(InliningOptions.ShortMethod)] - public static int Vp8Disto16X16(Span a, Span b, Span w, Span scratch) + public static void Vp8_Sse4x4Pair(ref byte src, ref byte pair, out int sse0, out int sse1) { - int d = 0; - const int dataSize = (4 * WebpConstants.Bps) - 16; - for (int y = 0; y < 16 * WebpConstants.Bps; y += 4 * WebpConstants.Bps) + if (Vector128.IsHardwareAccelerated) { - for (int x = 0; x < 16; x += 4) + // Each row fills eight 16-bit lanes: the source row in lanes 0 to 3 and again in lanes 4 to 7, the first block row + // in lanes 0 to 3 and the second block row in lanes 4 to 7. Each difference is -255 to 255, so each square is + // exact, and the multiply-add gives 32-bit lane 0 and 1 the sums of the first block and lane 2 and 3 of the second. + Vector128 sum = Vector128.Zero; + for (nuint y = 0; y < 4 * WebpConstants.Bps; y += WebpConstants.Bps) { - d += Vp8Disto4X4(a.Slice(x + y, dataSize), b.Slice(x + y, dataSize), w, scratch); + Vector128 s = Vector128.WidenLower(Vp8Encoding.RepeatedSourceOperator.Load(ref Unsafe.Add(ref src, y))); + Vector128 p = Vector128.WidenLower(Vp8Encoding.AdjacentSourceOperator.Load(ref Unsafe.Add(ref pair, y))); + Vector128 d = (s - p).AsInt16(); + sum += Vector128_.MultiplyAddAdjacent(d, d); } - } - return d; - } + // Add each odd lane to its even lane. + sum += Vector128_.ShuffleNative(sum, 0b_10_11_00_01); + sse0 = sum.ToScalar(); + sse1 = sum.GetElement(2); + return; + } - [MethodImpl(InliningOptions.ShortMethod)] - public static int Vp8Disto4X4(Span a, Span b, Span w, Span scratch) - { - if (Vector128.IsHardwareAccelerated) + int sum0 = 0; + int sum1 = 0; + for (nuint y = 0; y < 4 * WebpConstants.Bps; y += WebpConstants.Bps) { - int diffSum = TTransformVector128(a, b, w); - return Math.Abs(diffSum) >> 5; + for (nuint x = 0; x < 4; x++) + { + int s = Unsafe.Add(ref src, y + x); + int d0 = s - Unsafe.Add(ref pair, y + x); + int d1 = s - Unsafe.Add(ref pair, y + x + 4); + sum0 += d0 * d0; + sum1 += d1 * d1; + } } - int sum1 = TTransform(a, w, scratch); - int sum2 = TTransform(b, w, scratch); - - return Math.Abs(sum2 - sum1) >> 5; + sse0 = sum0; + sse1 = sum1; } - public static void DC16(Span dst, ReadOnlySpan yuv, int offset) + /// + /// Copies a 4x4 block. + /// + /// The first source sample. The rows have a stride of . + /// The first destination sample, with the same layout as . + [MethodImpl(InliningOptions.ShortMethod)] + public static void Vp8Copy4X4(ref byte src, ref byte dst) { - int offsetMinus1 = offset - 1; - int offsetMinusBps = offset - WebpConstants.Bps; - int dc = 16; - for (int j = 0; j < 16; j++) + for (nuint y = 0; y < 4 * WebpConstants.Bps; y += WebpConstants.Bps) { - // DC += dst[-1 + j * BPS] + dst[j - BPS]; - dc += yuv[offsetMinus1 + (j * WebpConstants.Bps)] + yuv[offsetMinusBps + j]; + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, y), Unsafe.ReadUnaligned(ref Unsafe.Add(ref src, y))); } - - Put16(dc >> 5, dst); } + /// + /// Copies a block of 8 rows of 16 samples. + /// + /// The first source sample. The rows have a stride of . + /// The first destination sample, with the same layout as . [MethodImpl(InliningOptions.ShortMethod)] - public static void TM16(Span dst, Span yuv, int offset) => TrueMotion(dst, yuv, offset, 16); - - public static void VE16(Span dst, Span yuv, int offset) + public static void Vp8Copy16X8(ref byte src, ref byte dst) { - // vertical - Span src = yuv.Slice(offset - WebpConstants.Bps, 16); - for (int j = 0; j < 16; j++) + // The constant size lets the JIT copy each row with one 16-byte load and store. + for (nuint y = 0; y < 8 * WebpConstants.Bps; y += WebpConstants.Bps) { - // memcpy(dst + j * BPS, dst - BPS, 16); - src.CopyTo(dst[(j * WebpConstants.Bps)..]); + Unsafe.CopyBlockUnaligned(ref Unsafe.Add(ref dst, y), ref Unsafe.Add(ref src, y), 16); } } - public static void HE16(Span dst, ReadOnlySpan yuv, int offset) - { - // horizontal - offset--; - for (int j = 16; j > 0; j--) + /// + /// Returns the spectral distortion between a 16x16 source block and a 16x16 block: the sum over the 16 4x4 blocks of + /// the absolute difference of their weighted Hadamard sums, each divided by 32. + /// + /// + /// The first of the 16 weighted sums of the source blocks in raster order, from . + /// The source does not change between the modes of a macroblock, so its sums are computed once. + /// + /// The first sample of the block. The rows have a stride of . + /// The first of the 16 weights: a row-major symmetric 4x4 matrix. + /// The first of the 16 scratch integers of the scalar path. + /// The distortion. + public static int Vp8Disto16X16(ref int srcSums, ref byte b, ref ushort w, ref int scratch) + { + // Each 4x4 term is |S(a) - S(b)| >> 5 with the weighted sums S. The sums are exact integers, so the difference of + // the precomputed source sums and the block sums is the same as the difference in one transform of both blocks. + if (Vector128.IsHardwareAccelerated) { - // memset(dst, dst[-1], 16); - byte v = yuv[offset]; - Memset(dst, v, 0, 16); - offset += WebpConstants.Bps; - dst = dst[WebpConstants.Bps..]; + Vector128 d = Vector128.Zero; + for (nuint y = 0; y < 4; y++) + { + Vector128 sums = TTransformSums4(ref Unsafe.Add(ref b, y * 4 * WebpConstants.Bps), ref w); + d += Vector128.ShiftRightArithmetic(Vector128.Abs(Vector128.LoadUnsafe(ref srcSums, y * 4) - sums), 5); + } + + return Vector128.Sum(d); } - } - public static void DC16NoTop(Span dst, ReadOnlySpan yuv, int offset) - { - // DC with top samples not available. - int dc = 8; - for (int j = 0; j < 16; j++) + int disto = 0; + for (nuint y = 0; y < 4; y++) { - // DC += dst[-1 + j * BPS]; - dc += yuv[-1 + (j * WebpConstants.Bps) + offset]; + for (nuint x = 0; x < 4; x++) + { + int sum = TTransform(ref Unsafe.Add(ref b, (y * 4 * WebpConstants.Bps) + (x * 4)), ref w, ref scratch); + disto += Math.Abs(Unsafe.Add(ref srcSums, (y * 4) + x) - sum) >> 5; + } } - Put16(dc >> 4, dst); + return disto; } - public static void DC16NoLeft(Span dst, ReadOnlySpan yuv, int offset) + /// + /// Returns the spectral distortion between two 4x4 blocks: the absolute difference of their weighted Hadamard sums, + /// divided by 32. + /// + /// The first block. The rows have a stride of . + /// The second block, with the same layout as . + /// The 16 weights: a row-major symmetric 4x4 matrix. + /// The scratch buffer of the scalar path. It holds at least 16 integers. + /// The distortion. + public static int Vp8Disto4X4(Span a, Span b, Span w, Span scratch) { - // DC with left samples not available. - int dc = 8; - for (int i = 0; i < 16; i++) + ref byte aRef = ref MemoryMarshal.GetReference(a); + ref byte bRef = ref MemoryMarshal.GetReference(b); + ref ushort wRef = ref MemoryMarshal.GetReference(w); + if (Vector128.IsHardwareAccelerated) { - // DC += dst[i - BPS]; - dc += yuv[i - WebpConstants.Bps + offset]; + // Byte lanes 0 to 3 of each row hold the row of a, byte lanes 4 to 7 the row of b. + TTransform( + TTransformRows(ref aRef, ref bRef, 0), + TTransformRows(ref aRef, ref bRef, WebpConstants.Bps), + TTransformRows(ref aRef, ref bRef, WebpConstants.Bps * 2), + TTransformRows(ref aRef, ref bRef, WebpConstants.Bps * 3), + Vector128.LoadUnsafe(ref wRef).AsInt16(), + Vector128.LoadUnsafe(ref wRef, 8).AsInt16(), + out Vector128 sumA, + out Vector128 sumB); + + return Math.Abs(Vector128.Sum(sumA - sumB)) >> 5; } - Put16(dc >> 4, dst); + ref int scratchRef = ref MemoryMarshal.GetReference(scratch); + int sum1 = TTransform(ref aRef, ref wRef, ref scratchRef); + int sum2 = TTransform(ref bRef, ref wRef, ref scratchRef); + + return Math.Abs(sum2 - sum1) >> 5; } + /// + /// Loads one row of two 4x4 blocks in separate buffers for the 128-bit form of TTransform. + /// + /// The first sample of the first block. + /// The first sample of the second block. + /// The offset of the row. + /// The row samples: 16-bit lanes 0 to 3 for the first block, 4 to 7 for the second block. [MethodImpl(InliningOptions.ShortMethod)] - public static void DC16NoTopLeft(Span dst) => - Put16(0x80, dst); // DC with no top and left samples. - - public static void DC8uv(Span dst, ReadOnlySpan yuv, int offset) + private static Vector128 TTransformRows(ref byte a, ref byte b, nuint row) { - int dc0 = 8; - int offsetMinus1 = offset - 1; - int offsetMinusBps = offset - WebpConstants.Bps; - for (int i = 0; i < 8; i++) - { - // dc0 += dst[i - BPS] + dst[-1 + i * BPS]; - dc0 += yuv[offsetMinusBps + i] + yuv[offsetMinus1 + (i * WebpConstants.Bps)]; - } - - Put8x8uv((byte)(dc0 >> 4), dst); + uint rowA = Unsafe.ReadUnaligned(ref Unsafe.Add(ref a, row)); + uint rowB = Unsafe.ReadUnaligned(ref Unsafe.Add(ref b, row)); + return Vector128.WidenLower(Vector128.Create(rowA, rowB, 0, 0).AsByte()).AsInt16(); } - [MethodImpl(InliningOptions.ShortMethod)] - public static void TM8uv(Span dst, Span yuv, int offset) => - TrueMotion(dst, yuv, offset, 8); // TrueMotion + /// + /// Predicts a 16x16 luma block with the DC mode: the rounded mean of the 16 top and the 16 left samples. See RFC 6386, section 12.2. + /// + /// + /// Each intra predictor writes the block at in the work buffer, with bytes between rows. The top + /// samples are the row before the block, and the left samples the column before it. + /// + /// The first sample of the block. + public static void DC16(ref byte dst) => Fill16(ref dst, (byte)((16 + SumTop16(ref dst) + SumLeft(ref dst, 16)) >> 5)); - public static void VE8uv(Span dst, Span yuv, int offset) + /// + /// Predicts a 16x16 luma block with the TrueMotion mode. See RFC 6386, section 12.2. + /// + /// The first sample of the block. + public static void TM16(ref byte dst) => TrueMotion(ref dst, 16); + + /// + /// Predicts a 16x16 luma block with the vertical mode: each row is the top row. + /// + /// The first sample of the block. + public static void VE16(ref byte dst) { - // vertical - Span src = yuv.Slice(offset - WebpConstants.Bps, 8); + ref byte top = ref Unsafe.Subtract(ref dst, (nuint)WebpConstants.Bps); + if (Vector128.IsHardwareAccelerated) + { + Vector128 row = Vector128.LoadUnsafe(ref top); + for (nuint y = 0; y < 16; y++) + { + row.StoreUnsafe(ref dst, y * WebpConstants.Bps); + } + + return; + } - const int endIdx = 8 * WebpConstants.Bps; - for (int j = 0; j < endIdx; j += WebpConstants.Bps) + for (nuint y = 0; y < 16; y++) { - // memcpy(dst + j * BPS, dst - BPS, 8); - src.CopyTo(dst[j..]); + Unsafe.CopyBlockUnaligned(ref Unsafe.Add(ref dst, y * WebpConstants.Bps), ref top, 16); } } - public static void HE8uv(Span dst, ReadOnlySpan yuv, int offset) + /// + /// Predicts a 16x16 luma block with the horizontal mode: each row is its left sample. + /// + /// The first sample of the block. + public static void HE16(ref byte dst) { - // horizontal - offset--; - for (int j = 0; j < 8; j++) + for (nuint y = 0; y < 16; y++) { - // memset(dst, dst[-1], 8); - // dst += BPS; - byte v = yuv[offset]; - Memset(dst, v, 0, 8); - dst = dst[WebpConstants.Bps..]; - offset += WebpConstants.Bps; + ref byte row = ref Unsafe.Add(ref dst, y * WebpConstants.Bps); + FillRow16(ref row, Unsafe.Subtract(ref row, (nuint)1)); } } - public static void DC8uvNoTop(Span dst, ReadOnlySpan yuv, int offset) + /// + /// Predicts a 16x16 luma block with the DC mode when the top samples are not available. + /// + /// The first sample of the block. + public static void DC16NoTop(ref byte dst) => Fill16(ref dst, (byte)((8 + SumLeft(ref dst, 16)) >> 4)); + + /// + /// Predicts a 16x16 luma block with the DC mode when the left samples are not available. + /// + /// The first sample of the block. + public static void DC16NoLeft(ref byte dst) => Fill16(ref dst, (byte)((8 + SumTop16(ref dst)) >> 4)); + + /// + /// Predicts a 16x16 luma block with the DC mode when no samples are available: the value 128. + /// + /// The first sample of the block. + public static void DC16NoTopLeft(ref byte dst) => Fill16(ref dst, 0x80); + + /// + /// Predicts an 8x8 chroma block with the DC mode: the rounded mean of the 8 top and the 8 left samples. + /// + /// The first sample of the block. + public static void DC8uv(ref byte dst) => Fill8(ref dst, (byte)((8 + SumTop8(ref dst) + SumLeft(ref dst, 8)) >> 4)); + + /// + /// Predicts an 8x8 chroma block with the TrueMotion mode. + /// + /// The first sample of the block. + public static void TM8uv(ref byte dst) => TrueMotion(ref dst, 8); + + /// + /// Predicts an 8x8 chroma block with the vertical mode: each row is the top row. + /// + /// The first sample of the block. + public static void VE8uv(ref byte dst) { - // DC with no top samples. - int dc0 = 4; - int offsetMinusOne = offset - 1; - const int endIdx = 8 * WebpConstants.Bps; - for (int i = 0; i < endIdx; i += WebpConstants.Bps) + ulong top = Unsafe.ReadUnaligned(ref Unsafe.Subtract(ref dst, (nuint)WebpConstants.Bps)); + for (nuint y = 0; y < 8; y++) { - // dc0 += dst[-1 + i * BPS]; - dc0 += yuv[offsetMinusOne + i]; + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, y * WebpConstants.Bps), top); } - - Put8x8uv((byte)(dc0 >> 3), dst); } - public static void DC8uvNoLeft(Span dst, ReadOnlySpan yuv, int offset) + /// + /// Predicts an 8x8 chroma block with the horizontal mode: each row is its left sample. + /// + /// The first sample of the block. + public static void HE8uv(ref byte dst) { - // DC with no left samples. - int offsetMinusBps = offset - WebpConstants.Bps; - int dc0 = 4; - for (int i = 0; i < 8; i++) + for (nuint y = 0; y < 8; y++) { - // dc0 += dst[i - BPS]; - dc0 += yuv[offsetMinusBps + i]; + ref byte row = ref Unsafe.Add(ref dst, y * WebpConstants.Bps); + Unsafe.WriteUnaligned(ref row, 0x0101010101010101UL * Unsafe.Subtract(ref row, (nuint)1)); } + } + + /// + /// Predicts an 8x8 chroma block with the DC mode when the top samples are not available. + /// + /// The first sample of the block. + public static void DC8uvNoTop(ref byte dst) => Fill8(ref dst, (byte)((4 + SumLeft(ref dst, 8)) >> 3)); - Put8x8uv((byte)(dc0 >> 3), dst); + /// + /// Predicts an 8x8 chroma block with the DC mode when the left samples are not available. + /// + /// The first sample of the block. + public static void DC8uvNoLeft(ref byte dst) => Fill8(ref dst, (byte)((4 + SumTop8(ref dst)) >> 3)); + + /// + /// Predicts an 8x8 chroma block with the DC mode when no samples are available: the value 128. + /// + /// The first sample of the block. + public static void DC8uvNoTopLeft(ref byte dst) => Fill8(ref dst, 0x80); + + /// + /// Predicts a 4x4 luma block with the DC mode: the rounded mean of the 4 top and the 4 left samples. + /// + /// The first sample of the block. + public static void DC4(ref byte dst) + { + ref byte top = ref Unsafe.Subtract(ref dst, (nuint)WebpConstants.Bps); + int dc = 4 + top + Unsafe.Add(ref top, (nuint)1) + Unsafe.Add(ref top, (nuint)2) + Unsafe.Add(ref top, (nuint)3) + SumLeft(ref dst, 4); + Store4Rows(ref dst, 0x01010101U * (uint)(dc >> 3)); } - [MethodImpl(InliningOptions.ShortMethod)] - public static void DC8uvNoTopLeft(Span dst) => - Put8x8uv(0x80, dst); // DC with nothing. + /// + /// Predicts a 4x4 luma block with the TrueMotion mode. + /// + /// The first sample of the block. + public static void TM4(ref byte dst) => TrueMotion(ref dst, 4); - public static void DC4(Span dst, ReadOnlySpan yuv, int offset) + /// + /// Predicts a 4x4 luma block with the vertical mode: each row is the top row, smoothed with Avg3. + /// + /// The first sample of the block. + public static void VE4(ref byte dst) { - int dc = 4; - int offsetMinusBps = offset - WebpConstants.Bps; - int offsetMinusOne = offset - 1; - for (int i = 0; i < 4; i++) + ref byte top = ref Unsafe.Subtract(ref dst, (nuint)WebpConstants.Bps); + if (Vector128.IsHardwareAccelerated) { - dc += yuv[offsetMinusBps + i] + yuv[offsetMinusOne + (i * WebpConstants.Bps)]; + // Lanes 0 to 7 are the samples top[-1] to top[6]. Lane k of the result is Avg3(top[k - 1], top[k], top[k + 1]). + Vector128 xabcdefg = Load8(ref Unsafe.Subtract(ref top, (nuint)1)); + Vector128 abcdefg = Vector128_.ShiftRightBytesInVector(xabcdefg, 1); + Vector128 bcdefg = Vector128_.ShiftRightBytesInVector(xabcdefg, 2); + Store4Rows(ref dst, Average3(xabcdefg, abcdefg, bcdefg).AsUInt32().ToScalar()); + return; } - dc >>= 3; - const int endIndx = 4 * WebpConstants.Bps; - for (int i = 0; i < endIndx; i += WebpConstants.Bps) - { - Memset(dst, (byte)dc, i, 4); - } + uint row = Avg3(Unsafe.Subtract(ref top, (nuint)1), top, Unsafe.Add(ref top, (nuint)1)) + | ((uint)Avg3(top, Unsafe.Add(ref top, (nuint)1), Unsafe.Add(ref top, (nuint)2)) << 8) + | ((uint)Avg3(Unsafe.Add(ref top, (nuint)1), Unsafe.Add(ref top, (nuint)2), Unsafe.Add(ref top, (nuint)3)) << 16) + | ((uint)Avg3(Unsafe.Add(ref top, (nuint)2), Unsafe.Add(ref top, (nuint)3), Unsafe.Add(ref top, (nuint)4)) << 24); + Store4Rows(ref dst, BitConverter.IsLittleEndian ? row : BinaryPrimitives.ReverseEndianness(row)); } - [MethodImpl(InliningOptions.ShortMethod)] - public static void TM4(Span dst, Span yuv, int offset) => TrueMotion(dst, yuv, offset, 4); - - public static void VE4(Span dst, ReadOnlySpan yuv, int offset, Span vals) - { - // vertical - int topOffset = offset - WebpConstants.Bps; - vals[0] = Avg3(yuv[topOffset - 1], yuv[topOffset], yuv[topOffset + 1]); - vals[1] = Avg3(yuv[topOffset], yuv[topOffset + 1], yuv[topOffset + 2]); - vals[2] = Avg3(yuv[topOffset + 1], yuv[topOffset + 2], yuv[topOffset + 3]); - vals[3] = Avg3(yuv[topOffset + 2], yuv[topOffset + 3], yuv[topOffset + 4]); - const int endIdx = 4 * WebpConstants.Bps; - for (int i = 0; i < endIdx; i += WebpConstants.Bps) - { - vals.CopyTo(dst[i..]); - } - } - - public static void HE4(Span dst, ReadOnlySpan yuv, int offset) - { - // horizontal - int offsetMinusOne = offset - 1; - byte a = yuv[offsetMinusOne - WebpConstants.Bps]; - byte b = yuv[offsetMinusOne]; - byte c = yuv[offsetMinusOne + WebpConstants.Bps]; - byte d = yuv[offsetMinusOne + (2 * WebpConstants.Bps)]; - byte e = yuv[offsetMinusOne + (3 * WebpConstants.Bps)]; - uint val = 0x01010101U * Avg3(a, b, c); - BinaryPrimitives.WriteUInt32BigEndian(dst, val); - val = 0x01010101U * Avg3(b, c, d); - BinaryPrimitives.WriteUInt32BigEndian(dst[WebpConstants.Bps..], val); - val = 0x01010101U * Avg3(c, d, e); - BinaryPrimitives.WriteUInt32BigEndian(dst[(2 * WebpConstants.Bps)..], val); - val = 0x01010101U * Avg3(d, e, e); - BinaryPrimitives.WriteUInt32BigEndian(dst[(3 * WebpConstants.Bps)..], val); - } - - public static void RD4(Span dst, ReadOnlySpan yuv, int offset) - { - // Down-right - int offsetMinusOne = offset - 1; - byte i = yuv[offsetMinusOne]; - byte j = yuv[offsetMinusOne + (1 * WebpConstants.Bps)]; - byte k = yuv[offsetMinusOne + (2 * WebpConstants.Bps)]; - byte l = yuv[offsetMinusOne + (3 * WebpConstants.Bps)]; - byte x = yuv[offsetMinusOne - WebpConstants.Bps]; - byte a = yuv[offset - WebpConstants.Bps]; - byte b = yuv[offset + 1 - WebpConstants.Bps]; - byte c = yuv[offset + 2 - WebpConstants.Bps]; - byte d = yuv[offset + 3 - WebpConstants.Bps]; - - Dst(dst, 0, 3, Avg3(j, k, l)); + /// + /// Predicts a 4x4 luma block with the horizontal mode: each row is its left sample, smoothed with Avg3. + /// + /// The first sample of the block. + public static void HE4(ref byte dst) + { + byte a = Unsafe.Subtract(ref dst, (nuint)(WebpConstants.Bps + 1)); + byte b = Left(ref dst, 0); + byte c = Left(ref dst, 1); + byte d = Left(ref dst, 2); + byte e = Left(ref dst, 3); + Unsafe.WriteUnaligned(ref dst, 0x01010101U * Avg3(a, b, c)); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, (nuint)WebpConstants.Bps), 0x01010101U * Avg3(b, c, d)); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, (nuint)(2 * WebpConstants.Bps)), 0x01010101U * Avg3(c, d, e)); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, (nuint)(3 * WebpConstants.Bps)), 0x01010101U * Avg3(d, e, e)); + } + + /// + /// Predicts a 4x4 luma block with the down-right mode. + /// + /// The first sample of the block. + public static void RD4(ref byte dst) + { + byte i = Left(ref dst, 0); + byte j = Left(ref dst, 1); + byte k = Left(ref dst, 2); + byte l = Left(ref dst, 3); + ref byte top = ref Unsafe.Subtract(ref dst, (nuint)WebpConstants.Bps); + if (Vector128.IsHardwareAccelerated) + { + // Lanes 0 to 8 are the samples L, K, J, I, X, A, B, C, D: the left column from the bottom, then the top-left and the top row. Lane k of the + // result is Avg3 of lanes k, k + 1 and k + 2. The rows from the bottom up start at lanes 0, 1, 2 and 3. + Vector128 lkji = Vector128.CreateScalar((uint)(l | (k << 8) | (j << 16) | (i << 24))).AsByte(); + Vector128 lkjixabcd = lkji | Vector128_.ShiftLeftBytesInVector(Load8(ref Unsafe.Subtract(ref top, (nuint)1)), 4); + Vector128 kjixabcd = Vector128_.ShiftRightBytesInVector(lkjixabcd, 1); + Vector128 jixabcd = Vector128_.ShiftRightBytesInVector(lkjixabcd, 2); + Vector128 rows = Average3(jixabcd, kjixabcd, lkjixabcd); + StoreRow(ref dst, 3, rows); + StoreRow(ref dst, 2, Vector128_.ShiftRightBytesInVector(rows, 1)); + StoreRow(ref dst, 1, Vector128_.ShiftRightBytesInVector(rows, 2)); + StoreRow(ref dst, 0, Vector128_.ShiftRightBytesInVector(rows, 3)); + return; + } + + byte x = Unsafe.Subtract(ref top, (nuint)1); + byte a = top; + byte b = Unsafe.Add(ref top, (nuint)1); + byte c = Unsafe.Add(ref top, (nuint)2); + byte d = Unsafe.Add(ref top, (nuint)3); + Dst(ref dst, 0, 3, Avg3(j, k, l)); byte ijk = Avg3(i, j, k); - Dst(dst, 1, 3, ijk); - Dst(dst, 0, 2, ijk); + Dst(ref dst, 1, 3, ijk); + Dst(ref dst, 0, 2, ijk); byte xij = Avg3(x, i, j); - Dst(dst, 2, 3, xij); - Dst(dst, 1, 2, xij); - Dst(dst, 0, 1, xij); + Dst(ref dst, 2, 3, xij); + Dst(ref dst, 1, 2, xij); + Dst(ref dst, 0, 1, xij); byte axi = Avg3(a, x, i); - Dst(dst, 3, 3, axi); - Dst(dst, 2, 2, axi); - Dst(dst, 1, 1, axi); - Dst(dst, 0, 0, axi); + Dst(ref dst, 3, 3, axi); + Dst(ref dst, 2, 2, axi); + Dst(ref dst, 1, 1, axi); + Dst(ref dst, 0, 0, axi); byte bax = Avg3(b, a, x); - Dst(dst, 3, 2, bax); - Dst(dst, 2, 1, bax); - Dst(dst, 1, 0, bax); + Dst(ref dst, 3, 2, bax); + Dst(ref dst, 2, 1, bax); + Dst(ref dst, 1, 0, bax); byte cba = Avg3(c, b, a); - Dst(dst, 3, 1, cba); - Dst(dst, 2, 0, cba); - Dst(dst, 3, 0, Avg3(d, c, b)); + Dst(ref dst, 3, 1, cba); + Dst(ref dst, 2, 0, cba); + Dst(ref dst, 3, 0, Avg3(d, c, b)); } - public static void VR4(Span dst, ReadOnlySpan yuv, int offset) - { - // Vertical-Right - int offsetMinusOne = offset - 1; - byte i = yuv[offsetMinusOne]; - byte j = yuv[offsetMinusOne + (1 * WebpConstants.Bps)]; - byte k = yuv[offsetMinusOne + (2 * WebpConstants.Bps)]; - byte x = yuv[offsetMinusOne - WebpConstants.Bps]; - byte a = yuv[offset - WebpConstants.Bps]; - byte b = yuv[offset + 1 - WebpConstants.Bps]; - byte c = yuv[offset + 2 - WebpConstants.Bps]; - byte d = yuv[offset + 3 - WebpConstants.Bps]; - + /// + /// Predicts a 4x4 luma block with the vertical-right mode. + /// + /// The first sample of the block. + public static void VR4(ref byte dst) + { + byte i = Left(ref dst, 0); + byte j = Left(ref dst, 1); + byte k = Left(ref dst, 2); + ref byte top = ref Unsafe.Subtract(ref dst, (nuint)WebpConstants.Bps); + byte x = Unsafe.Subtract(ref top, (nuint)1); + if (Vector128.IsHardwareAccelerated) + { + // Lanes 0 to 7 are the samples X, A, B, C, D, E, F, G. Row 0 is Avg2 of the adjacent pairs, and row 1 is Avg3 of the triples that start at I. + // Rows 2 and 3 are rows 0 and 1, one sample to the right. Their first samples come from the left column. + Vector128 xabcd = Load8(ref Unsafe.Subtract(ref top, (nuint)1)); + Vector128 abcd = Vector128_.ShiftRightBytesInVector(xabcd, 1); + Vector128 ixabcd = Vector128_.ShiftLeftBytesInVector(xabcd, 1).AsUInt16().WithElement(0, (ushort)(i | (x << 8))).AsByte(); + Vector128 row0 = Vector128_.Average(xabcd, abcd); + Vector128 row1 = Average3(ixabcd, xabcd, abcd); + StoreRow(ref dst, 0, row0); + StoreRow(ref dst, 1, row1); + StoreRow(ref dst, 2, Vector128_.ShiftLeftBytesInVector(row0, 1)); + StoreRow(ref dst, 3, Vector128_.ShiftLeftBytesInVector(row1, 1)); + Dst(ref dst, 0, 2, Avg3(j, i, x)); + Dst(ref dst, 0, 3, Avg3(k, j, i)); + return; + } + + byte a = top; + byte b = Unsafe.Add(ref top, (nuint)1); + byte c = Unsafe.Add(ref top, (nuint)2); + byte d = Unsafe.Add(ref top, (nuint)3); byte xa = Avg2(x, a); - Dst(dst, 0, 0, xa); - Dst(dst, 1, 2, xa); + Dst(ref dst, 0, 0, xa); + Dst(ref dst, 1, 2, xa); byte ab = Avg2(a, b); - Dst(dst, 1, 0, ab); - Dst(dst, 2, 2, ab); + Dst(ref dst, 1, 0, ab); + Dst(ref dst, 2, 2, ab); byte bc = Avg2(b, c); - Dst(dst, 2, 0, bc); - Dst(dst, 3, 2, bc); - Dst(dst, 3, 0, Avg2(c, d)); - Dst(dst, 0, 3, Avg3(k, j, i)); - Dst(dst, 0, 2, Avg3(j, i, x)); + Dst(ref dst, 2, 0, bc); + Dst(ref dst, 3, 2, bc); + Dst(ref dst, 3, 0, Avg2(c, d)); + Dst(ref dst, 0, 3, Avg3(k, j, i)); + Dst(ref dst, 0, 2, Avg3(j, i, x)); byte ixa = Avg3(i, x, a); - Dst(dst, 0, 1, ixa); - Dst(dst, 1, 3, ixa); + Dst(ref dst, 0, 1, ixa); + Dst(ref dst, 1, 3, ixa); byte xab = Avg3(x, a, b); - Dst(dst, 1, 1, xab); - Dst(dst, 2, 3, xab); + Dst(ref dst, 1, 1, xab); + Dst(ref dst, 2, 3, xab); byte abc = Avg3(a, b, c); - Dst(dst, 2, 1, abc); - Dst(dst, 3, 3, abc); - Dst(dst, 3, 1, Avg3(b, c, d)); + Dst(ref dst, 2, 1, abc); + Dst(ref dst, 3, 3, abc); + Dst(ref dst, 3, 1, Avg3(b, c, d)); } - public static void LD4(Span dst, ReadOnlySpan yuv, int offset) + /// + /// Predicts a 4x4 luma block with the down-left mode. + /// + /// The first sample of the block. + public static void LD4(ref byte dst) { - // Down-Left - byte a = yuv[offset - WebpConstants.Bps]; - byte b = yuv[offset + 1 - WebpConstants.Bps]; - byte c = yuv[offset + 2 - WebpConstants.Bps]; - byte d = yuv[offset + 3 - WebpConstants.Bps]; - byte e = yuv[offset + 4 - WebpConstants.Bps]; - byte f = yuv[offset + 5 - WebpConstants.Bps]; - byte g = yuv[offset + 6 - WebpConstants.Bps]; - byte h = yuv[offset + 7 - WebpConstants.Bps]; - - Dst(dst, 0, 0, Avg3(a, b, c)); + ref byte top = ref Unsafe.Subtract(ref dst, (nuint)WebpConstants.Bps); + if (Vector128.IsHardwareAccelerated) + { + // Lanes 0 to 7 are the samples A to H. Lane k of the result is Avg3 of lanes k, k + 1 and k + 2, and the last triple repeats H. Row y starts + // at lane y. + Vector128 abcdefgh = Load8(ref top); + Vector128 bcdefgh = Vector128_.ShiftRightBytesInVector(abcdefgh, 1); + Vector128 cdefghh = Vector128_.ShiftRightBytesInVector(abcdefgh, 2).AsUInt16().WithElement(3, Unsafe.Add(ref top, (nuint)7)).AsByte(); + Vector128 rows = Average3(abcdefgh, bcdefgh, cdefghh); + StoreRow(ref dst, 0, rows); + StoreRow(ref dst, 1, Vector128_.ShiftRightBytesInVector(rows, 1)); + StoreRow(ref dst, 2, Vector128_.ShiftRightBytesInVector(rows, 2)); + StoreRow(ref dst, 3, Vector128_.ShiftRightBytesInVector(rows, 3)); + return; + } + + byte a = top; + byte b = Unsafe.Add(ref top, (nuint)1); + byte c = Unsafe.Add(ref top, (nuint)2); + byte d = Unsafe.Add(ref top, (nuint)3); + byte e = Unsafe.Add(ref top, (nuint)4); + byte f = Unsafe.Add(ref top, (nuint)5); + byte g = Unsafe.Add(ref top, (nuint)6); + byte h = Unsafe.Add(ref top, (nuint)7); + Dst(ref dst, 0, 0, Avg3(a, b, c)); byte bcd = Avg3(b, c, d); - Dst(dst, 1, 0, bcd); - Dst(dst, 0, 1, bcd); + Dst(ref dst, 1, 0, bcd); + Dst(ref dst, 0, 1, bcd); byte cde = Avg3(c, d, e); - Dst(dst, 2, 0, cde); - Dst(dst, 1, 1, cde); - Dst(dst, 0, 2, cde); + Dst(ref dst, 2, 0, cde); + Dst(ref dst, 1, 1, cde); + Dst(ref dst, 0, 2, cde); byte def = Avg3(d, e, f); - Dst(dst, 3, 0, def); - Dst(dst, 2, 1, def); - Dst(dst, 1, 2, def); - Dst(dst, 0, 3, def); + Dst(ref dst, 3, 0, def); + Dst(ref dst, 2, 1, def); + Dst(ref dst, 1, 2, def); + Dst(ref dst, 0, 3, def); byte efg = Avg3(e, f, g); - Dst(dst, 3, 1, efg); - Dst(dst, 2, 2, efg); - Dst(dst, 1, 3, efg); + Dst(ref dst, 3, 1, efg); + Dst(ref dst, 2, 2, efg); + Dst(ref dst, 1, 3, efg); byte fgh = Avg3(f, g, h); - Dst(dst, 3, 2, fgh); - Dst(dst, 2, 3, fgh); - Dst(dst, 3, 3, Avg3(g, h, h)); + Dst(ref dst, 3, 2, fgh); + Dst(ref dst, 2, 3, fgh); + Dst(ref dst, 3, 3, Avg3(g, h, h)); } - public static void VL4(Span dst, ReadOnlySpan yuv, int offset) + /// + /// Predicts a 4x4 luma block with the vertical-left mode. + /// + /// The first sample of the block. + public static void VL4(ref byte dst) { - // Vertical-Left - byte a = yuv[offset - WebpConstants.Bps]; - byte b = yuv[offset + 1 - WebpConstants.Bps]; - byte c = yuv[offset + 2 - WebpConstants.Bps]; - byte d = yuv[offset + 3 - WebpConstants.Bps]; - byte e = yuv[offset + 4 - WebpConstants.Bps]; - byte f = yuv[offset + 5 - WebpConstants.Bps]; - byte g = yuv[offset + 6 - WebpConstants.Bps]; - byte h = yuv[offset + 7 - WebpConstants.Bps]; - - Dst(dst, 0, 0, Avg2(a, b)); + ref byte top = ref Unsafe.Subtract(ref dst, (nuint)WebpConstants.Bps); + if (Vector128.IsHardwareAccelerated) + { + // Lanes 0 to 7 are the samples A to H. Rows 0 and 2 are Avg2 of the adjacent pairs, and rows 1 and 3 are Avg3 of the triples. Rows 2 and 3 + // start one sample later. Their last samples come from the triples that start at E and F. + Vector128 abcdefgh = Load8(ref top); + Vector128 bcdefgh = Vector128_.ShiftRightBytesInVector(abcdefgh, 1); + Vector128 cdefgh = Vector128_.ShiftRightBytesInVector(abcdefgh, 2); + Vector128 pairs = Vector128_.Average(abcdefgh, bcdefgh); + Vector128 triples = Average3(abcdefgh, bcdefgh, cdefgh); + StoreRow(ref dst, 0, pairs); + StoreRow(ref dst, 1, triples); + StoreRow(ref dst, 2, Vector128_.ShiftRightBytesInVector(pairs, 1)); + StoreRow(ref dst, 3, Vector128_.ShiftRightBytesInVector(triples, 1)); + Dst(ref dst, 3, 2, triples.GetElement(4)); + Dst(ref dst, 3, 3, triples.GetElement(5)); + return; + } + + byte a = top; + byte b = Unsafe.Add(ref top, (nuint)1); + byte c = Unsafe.Add(ref top, (nuint)2); + byte d = Unsafe.Add(ref top, (nuint)3); + byte e = Unsafe.Add(ref top, (nuint)4); + byte f = Unsafe.Add(ref top, (nuint)5); + byte g = Unsafe.Add(ref top, (nuint)6); + byte h = Unsafe.Add(ref top, (nuint)7); + Dst(ref dst, 0, 0, Avg2(a, b)); byte bc = Avg2(b, c); - Dst(dst, 1, 0, bc); - Dst(dst, 0, 2, bc); + Dst(ref dst, 1, 0, bc); + Dst(ref dst, 0, 2, bc); byte cd = Avg2(c, d); - Dst(dst, 2, 0, cd); - Dst(dst, 1, 2, cd); + Dst(ref dst, 2, 0, cd); + Dst(ref dst, 1, 2, cd); byte de = Avg2(d, e); - Dst(dst, 3, 0, de); - Dst(dst, 2, 2, de); - Dst(dst, 0, 1, Avg3(a, b, c)); + Dst(ref dst, 3, 0, de); + Dst(ref dst, 2, 2, de); + Dst(ref dst, 0, 1, Avg3(a, b, c)); byte bcd = Avg3(b, c, d); - Dst(dst, 1, 1, bcd); - Dst(dst, 0, 3, bcd); + Dst(ref dst, 1, 1, bcd); + Dst(ref dst, 0, 3, bcd); byte cde = Avg3(c, d, e); - Dst(dst, 2, 1, cde); - Dst(dst, 1, 3, cde); + Dst(ref dst, 2, 1, cde); + Dst(ref dst, 1, 3, cde); byte def = Avg3(d, e, f); - Dst(dst, 3, 1, def); - Dst(dst, 2, 3, def); - Dst(dst, 3, 2, Avg3(e, f, g)); - Dst(dst, 3, 3, Avg3(f, g, h)); + Dst(ref dst, 3, 1, def); + Dst(ref dst, 2, 3, def); + Dst(ref dst, 3, 2, Avg3(e, f, g)); + Dst(ref dst, 3, 3, Avg3(f, g, h)); } - public static void HD4(Span dst, ReadOnlySpan yuv, int offset) - { - // Horizontal-Down - byte i = yuv[offset - 1]; - byte j = yuv[offset - 1 + (1 * WebpConstants.Bps)]; - byte k = yuv[offset - 1 + (2 * WebpConstants.Bps)]; - byte l = yuv[offset - 1 + (3 * WebpConstants.Bps)]; - byte x = yuv[offset - 1 - WebpConstants.Bps]; - byte a = yuv[offset - WebpConstants.Bps]; - byte b = yuv[offset + 1 - WebpConstants.Bps]; - byte c = yuv[offset + 2 - WebpConstants.Bps]; + /// + /// Predicts a 4x4 luma block with the horizontal-down mode. + /// + /// The first sample of the block. + public static void HD4(ref byte dst) + { + ref byte top = ref Unsafe.Subtract(ref dst, (nuint)WebpConstants.Bps); + byte i = Left(ref dst, 0); + byte j = Left(ref dst, 1); + byte k = Left(ref dst, 2); + byte l = Left(ref dst, 3); + if (Vector128.IsHardwareAccelerated) + { + // Lanes 0 to 7 are the samples L, K, J, I, X, A, B, C: the left column from the bottom, then the top-left and the top row. Lane k of + // pairs is Avg2 of lanes k and k + 1, and lane k of triples is Avg3 of lanes k, k + 1 and k + 2. Avg2 and Avg3 do not change when the + // order of their outer samples changes, so row 3 is pairs[0], triples[0], pairs[1], triples[1]. Each row above starts one pair later. + // The interleave puts pair k in byte 2k and triple k in byte 2k + 1. Row 0 needs triples 4 and 5 in bytes 8 and 9, so the 16-bit lane 4 + // gets 16-bit lane 2 of triples. + Vector128 lkji = Vector128.CreateScalar((uint)(l | (k << 8) | (j << 16) | (i << 24))).AsByte(); + Vector128 lkjixabc = lkji | Vector128_.ShiftLeftBytesInVector(Load8(ref Unsafe.Subtract(ref top, (nuint)1)), 4); + Vector128 kjixabc = Vector128_.ShiftRightBytesInVector(lkjixabc, 1); + Vector128 jixabc = Vector128_.ShiftRightBytesInVector(lkjixabc, 2); + Vector128 pairs = Vector128_.Average(lkjixabc, kjixabc); + Vector128 triples = Average3(lkjixabc, kjixabc, jixabc); + Vector128 rows = Vector128_.UnpackLow(pairs, triples).AsUInt16().WithElement(4, triples.AsUInt16().GetElement(2)).AsByte(); + StoreRow(ref dst, 3, rows); + StoreRow(ref dst, 2, Vector128_.ShiftRightBytesInVector(rows, 2)); + StoreRow(ref dst, 1, Vector128_.ShiftRightBytesInVector(rows, 4)); + StoreRow(ref dst, 0, Vector128_.ShiftRightBytesInVector(rows, 6)); + return; + } + + byte x = Unsafe.Subtract(ref top, (nuint)1); + byte a = top; + byte b = Unsafe.Add(ref top, (nuint)1); + byte c = Unsafe.Add(ref top, (nuint)2); byte ix = Avg2(i, x); - Dst(dst, 0, 0, ix); - Dst(dst, 2, 1, ix); + Dst(ref dst, 0, 0, ix); + Dst(ref dst, 2, 1, ix); byte ji = Avg2(j, i); - Dst(dst, 0, 1, ji); - Dst(dst, 2, 2, ji); + Dst(ref dst, 0, 1, ji); + Dst(ref dst, 2, 2, ji); byte kj = Avg2(k, j); - Dst(dst, 0, 2, kj); - Dst(dst, 2, 3, kj); - Dst(dst, 0, 3, Avg2(l, k)); - Dst(dst, 3, 0, Avg3(a, b, c)); - Dst(dst, 2, 0, Avg3(x, a, b)); + Dst(ref dst, 0, 2, kj); + Dst(ref dst, 2, 3, kj); + Dst(ref dst, 0, 3, Avg2(l, k)); + Dst(ref dst, 3, 0, Avg3(a, b, c)); + Dst(ref dst, 2, 0, Avg3(x, a, b)); byte ixa = Avg3(i, x, a); - Dst(dst, 1, 0, ixa); - Dst(dst, 3, 1, ixa); + Dst(ref dst, 1, 0, ixa); + Dst(ref dst, 3, 1, ixa); byte jix = Avg3(j, i, x); - Dst(dst, 1, 1, jix); - Dst(dst, 3, 2, jix); + Dst(ref dst, 1, 1, jix); + Dst(ref dst, 3, 2, jix); byte kji = Avg3(k, j, i); - Dst(dst, 1, 2, kji); - Dst(dst, 3, 3, kji); - Dst(dst, 1, 3, Avg3(l, k, j)); + Dst(ref dst, 1, 2, kji); + Dst(ref dst, 3, 3, kji); + Dst(ref dst, 1, 3, Avg3(l, k, j)); } - public static void HU4(Span dst, ReadOnlySpan yuv, int offset) + /// + /// Predicts a 4x4 luma block with the horizontal-up mode. + /// + /// The first sample of the block. + public static void HU4(ref byte dst) { - // Horizontal-Up - byte i = yuv[offset - 1]; - byte j = yuv[offset - 1 + (1 * WebpConstants.Bps)]; - byte k = yuv[offset - 1 + (2 * WebpConstants.Bps)]; - byte l = yuv[offset - 1 + (3 * WebpConstants.Bps)]; - - Dst(dst, 0, 0, Avg2(i, j)); + byte i = Left(ref dst, 0); + byte j = Left(ref dst, 1); + byte k = Left(ref dst, 2); + byte l = Left(ref dst, 3); + if (Vector128.IsHardwareAccelerated) + { + // Lanes 0 to 7 are the samples I, J, K, L, L, L, L, L: the left column from the top, then L repeated. Lane k of pairs is Avg2 of lanes k + // and k + 1, and lane k of triples is Avg3 of lanes k, k + 1 and k + 2. Lanes 3 and 4 of both are L. The interleave puts pair k in byte 2k + // and triple k in byte 2k + 1, so row y is bytes 2y to 2y + 3. Row 3 is bytes 6 to 9, which are all L. + ulong ijkl = (uint)(i | (j << 8) | (k << 16) | (l << 24)) | ((0x01010101UL * l) << 32); + Vector128 ijklllll = Vector128.CreateScalar(ijkl).AsByte(); + Vector128 jklllll = Vector128_.ShiftRightBytesInVector(ijklllll, 1); + Vector128 klllll = Vector128_.ShiftRightBytesInVector(ijklllll, 2); + Vector128 pairs = Vector128_.Average(ijklllll, jklllll); + Vector128 triples = Average3(ijklllll, jklllll, klllll); + Vector128 rows = Vector128_.UnpackLow(pairs, triples); + StoreRow(ref dst, 0, rows); + StoreRow(ref dst, 1, Vector128_.ShiftRightBytesInVector(rows, 2)); + StoreRow(ref dst, 2, Vector128_.ShiftRightBytesInVector(rows, 4)); + StoreRow(ref dst, 3, Vector128_.ShiftRightBytesInVector(rows, 6)); + return; + } + + Dst(ref dst, 0, 0, Avg2(i, j)); byte jk = Avg2(j, k); - Dst(dst, 2, 0, jk); - Dst(dst, 0, 1, jk); + Dst(ref dst, 2, 0, jk); + Dst(ref dst, 0, 1, jk); byte kl = Avg2(k, l); - Dst(dst, 2, 1, kl); - Dst(dst, 0, 2, kl); - Dst(dst, 1, 0, Avg3(i, j, k)); + Dst(ref dst, 2, 1, kl); + Dst(ref dst, 0, 2, kl); + Dst(ref dst, 1, 0, Avg3(i, j, k)); byte jkl = Avg3(j, k, l); - Dst(dst, 3, 0, jkl); - Dst(dst, 1, 1, jkl); + Dst(ref dst, 3, 0, jkl); + Dst(ref dst, 1, 1, jkl); byte kll = Avg3(k, l, l); - Dst(dst, 3, 1, kll); - Dst(dst, 1, 2, kll); - Dst(dst, 3, 2, l); - Dst(dst, 2, 2, l); - Dst(dst, 0, 3, l); - Dst(dst, 1, 3, l); - Dst(dst, 2, 3, l); - Dst(dst, 3, 3, l); + Dst(ref dst, 3, 1, kll); + Dst(ref dst, 1, 2, kll); + Dst(ref dst, 3, 2, l); + Dst(ref dst, 2, 2, l); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, (nuint)(3 * WebpConstants.Bps)), 0x01010101U * l); } /// /// Paragraph 14.3: Implementation of the Walsh-Hadamard transform inversion. /// + /// The 16 Walsh-Hadamard coefficients of the luma DC values, in row-major order. + /// Receives the DC coefficient of each of the 16 luma blocks. Block n starts at index 16 * n. + /// The scratch buffer with at least 16 entries. public static void TransformWht(ReadOnlySpan input, Span output, Span scratch) { + if (Vector128.IsHardwareAccelerated) + { + // Lane layout: vector r holds input row r, coefficients 4r to 4r + 3, in 32-bit lanes. The first pass combines the rows lane by lane, so + // each lane is one column, as in the scalar loop. The transpose then gives vector j with element j of each first-pass row, so the second + // pass combines the vectors lane by lane too, with lane i for row i. The 32-bit lanes hold the same values as the scalar ints. + ref short inputRef = ref MemoryMarshal.GetReference(input); + Vector128 r0 = Vector128.WidenLower(Vector128.CreateScalarUnsafe(ReadCoefficientRow(ref inputRef, 0)).AsInt16()); + Vector128 r1 = Vector128.WidenLower(Vector128.CreateScalarUnsafe(ReadCoefficientRow(ref inputRef, 4)).AsInt16()); + Vector128 r2 = Vector128.WidenLower(Vector128.CreateScalarUnsafe(ReadCoefficientRow(ref inputRef, 8)).AsInt16()); + Vector128 r3 = Vector128.WidenLower(Vector128.CreateScalarUnsafe(ReadCoefficientRow(ref inputRef, 12)).AsInt16()); + + Vector128 a0 = r0 + r3; + Vector128 a1 = r1 + r2; + Vector128 a2 = r1 - r2; + Vector128 a3 = r0 - r3; + Vector128 t0 = a0 + a1; + Vector128 t1 = a3 + a2; + Vector128 t2 = a0 - a1; + Vector128 t3 = a3 - a2; + SimdUtils.Transpose(ref t0, ref t1, ref t2, ref t3); + + Vector128 dc = t0 + Vector128.Create(3); + a0 = dc + t3; + a1 = t1 + t2; + a2 = t1 - t2; + a3 = dc - t3; + Vector128 o0 = Vector128.ShiftRightArithmetic(a0 + a1, 3); + Vector128 o1 = Vector128.ShiftRightArithmetic(a3 + a2, 3); + Vector128 o2 = Vector128.ShiftRightArithmetic(a0 - a1, 3); + Vector128 o3 = Vector128.ShiftRightArithmetic(a3 - a2, 3); + + // Lane i gives the DC values of the blocks 4i to 4i + 3. Block n starts at index 16 * n, so the stores scatter. + for (int i = 0; i < 4; i++) + { + int offset = 64 * i; + output[offset] = (short)o0.GetElement(i); + output[offset + 16] = (short)o1.GetElement(i); + output[offset + 32] = (short)o2.GetElement(i); + output[offset + 48] = (short)o3.GetElement(i); + } + + return; + } + + // The first pass writes all 16 entries of tmp before the second pass reads them, so no clear is necessary. Span tmp = scratch[..16]; - tmp.Clear(); for (int i = 0; i < 4; i++) { int iPlus4 = 4 + i; @@ -739,92 +974,233 @@ public static void TransformWht(ReadOnlySpan input, Span output, S } /// - /// Hadamard transform - /// Returns the weighted sum of the absolute value of transformed coefficients. - /// w[] contains a row-major 4 by 4 symmetric matrix. + /// Returns the weighted sum of the absolute values of the Hadamard transform coefficients of one 4x4 block. /// - public static int TTransform(ReadOnlySpan input, Span w, Span scratch) + /// The first sample of the block. The rows have a stride of . + /// The first of the 16 weights: a row-major symmetric 4x4 matrix. + /// The first of the 16 scratch integers. + /// The weighted sum. + public static int TTransform(ref byte input, ref ushort w, ref int scratch) { int sum = 0; - Span tmp = scratch[..16]; - tmp.Clear(); + + // The horizontal pass writes all 16 entries of tmp before the vertical pass reads them, so no clear is necessary. + ref int tmp = ref scratch; // horizontal pass. - int inputOffset = 0; - for (int i = 0; i < 4; i++) - { - int inputOffsetPlusOne = inputOffset + 1; - int inputOffsetPlusTwo = inputOffset + 2; - int inputOffsetPlusThree = inputOffset + 3; - int a0 = input[inputOffset] + input[inputOffsetPlusTwo]; - int a1 = input[inputOffsetPlusOne] + input[inputOffsetPlusThree]; - int a2 = input[inputOffsetPlusOne] - input[inputOffsetPlusThree]; - int a3 = input[inputOffset] - input[inputOffsetPlusTwo]; - tmp[0 + (i * 4)] = a0 + a1; - tmp[1 + (i * 4)] = a3 + a2; - tmp[2 + (i * 4)] = a3 - a2; - tmp[3 + (i * 4)] = a0 - a1; + nuint inputOffset = 0; + for (nuint i = 0; i < 4; i++) + { + int i0 = Unsafe.Add(ref input, inputOffset); + int i1 = Unsafe.Add(ref input, inputOffset + 1); + int i2 = Unsafe.Add(ref input, inputOffset + 2); + int i3 = Unsafe.Add(ref input, inputOffset + 3); + int a0 = i0 + i2; + int a1 = i1 + i3; + int a2 = i1 - i3; + int a3 = i0 - i2; + Unsafe.Add(ref tmp, 0 + (i * 4)) = a0 + a1; + Unsafe.Add(ref tmp, 1 + (i * 4)) = a3 + a2; + Unsafe.Add(ref tmp, 2 + (i * 4)) = a3 - a2; + Unsafe.Add(ref tmp, 3 + (i * 4)) = a0 - a1; inputOffset += WebpConstants.Bps; } // vertical pass - for (int i = 0; i < 4; i++) - { - int a0 = tmp[0 + i] + tmp[8 + i]; - int a1 = tmp[4 + i] + tmp[12 + i]; - int a2 = tmp[4 + i] - tmp[12 + i]; - int a3 = tmp[0 + i] - tmp[8 + i]; + for (nuint i = 0; i < 4; i++) + { + int t0 = Unsafe.Add(ref tmp, i); + int t4 = Unsafe.Add(ref tmp, 4 + i); + int t8 = Unsafe.Add(ref tmp, 8 + i); + int t12 = Unsafe.Add(ref tmp, 12 + i); + int a0 = t0 + t8; + int a1 = t4 + t12; + int a2 = t4 - t12; + int a3 = t0 - t8; int b0 = a0 + a1; int b1 = a3 + a2; int b2 = a3 - a2; int b3 = a0 - a1; - sum += w[0] * Math.Abs(b0); - sum += w[4] * Math.Abs(b1); - sum += w[8] * Math.Abs(b2); - sum += w[12] * Math.Abs(b3); - - w = w[1..]; + sum += Unsafe.Add(ref w, i) * Math.Abs(b0); + sum += Unsafe.Add(ref w, 4 + i) * Math.Abs(b1); + sum += Unsafe.Add(ref w, 8 + i) * Math.Abs(b2); + sum += Unsafe.Add(ref w, 12 + i) * Math.Abs(b3); } return sum; } /// - /// Hadamard transform - /// Returns the weighted sum of the absolute value of transformed coefficients. - /// w[] contains a row-major 4 by 4 symmetric matrix. + /// Writes the weighted Hadamard sums of the 16 4x4 blocks of a 16x16 block, as returns them. /// - public static int TTransformVector128(Span inputA, Span inputB, Span w) + /// The first sample of the 16x16 block. The rows have a stride of . + /// The first of the 16 weights: a row-major symmetric 4x4 matrix. + /// The first of the 16 sums, in raster order of the 4x4 blocks. + /// The first of the 16 scratch integers of the scalar path. + public static void TTransformSums16X16(ref byte input, ref ushort w, ref int sums, ref int scratch) { - // Load and combine inputs. - Vector128 ina0 = Unsafe.As>(ref MemoryMarshal.GetReference(inputA)); - Vector128 ina1 = Unsafe.As>(ref MemoryMarshal.GetReference(inputA.Slice(WebpConstants.Bps, 16))); - Vector128 ina2 = Unsafe.As>(ref MemoryMarshal.GetReference(inputA.Slice(WebpConstants.Bps * 2, 16))); - Vector128 ina3 = Unsafe.As>(ref MemoryMarshal.GetReference(inputA.Slice(WebpConstants.Bps * 3, 16))).AsInt64(); - Vector128 inb0 = Unsafe.As>(ref MemoryMarshal.GetReference(inputB)); - Vector128 inb1 = Unsafe.As>(ref MemoryMarshal.GetReference(inputB.Slice(WebpConstants.Bps, 16))); - Vector128 inb2 = Unsafe.As>(ref MemoryMarshal.GetReference(inputB.Slice(WebpConstants.Bps * 2, 16))); - Vector128 inb3 = Unsafe.As>(ref MemoryMarshal.GetReference(inputB.Slice(WebpConstants.Bps * 3, 16))).AsInt64(); + if (Vector128.IsHardwareAccelerated) + { + for (nuint y = 0; y < 4; y++) + { + TTransformSums4(ref Unsafe.Add(ref input, y * 4 * WebpConstants.Bps), ref w).StoreUnsafe(ref sums, y * 4); + } - // Combine inA and inB (we'll do two transforms in parallel). - Vector128 inab0 = Vector128_.UnpackLow(ina0.AsInt32(), inb0.AsInt32()); - Vector128 inab1 = Vector128_.UnpackLow(ina1.AsInt32(), inb1.AsInt32()); - Vector128 inab2 = Vector128_.UnpackLow(ina2.AsInt32(), inb2.AsInt32()); - Vector128 inab3 = Vector128_.UnpackLow(ina3.AsInt32(), inb3.AsInt32()); - Vector128 tmp0 = Vector128.WidenLower(inab0.AsByte()).AsInt16(); - Vector128 tmp1 = Vector128.WidenLower(inab1.AsByte()).AsInt16(); - Vector128 tmp2 = Vector128.WidenLower(inab2.AsByte()).AsInt16(); - Vector128 tmp3 = Vector128.WidenLower(inab3.AsByte()).AsInt16(); + return; + } + + for (nuint y = 0; y < 4; y++) + { + for (nuint x = 0; x < 4; x++) + { + Unsafe.Add(ref sums, (y * 4) + x) = TTransform(ref Unsafe.Add(ref input, (y * 4 * WebpConstants.Bps) + (x * 4)), ref w, ref scratch); + } + } + } + + /// + /// Returns the weighted Hadamard sums of two horizontally adjacent 4x4 blocks, as returns them. + /// + /// + /// The first sample of the two blocks. Each row has the 4 samples of the first block, then the 4 samples of the second block. + /// The rows have a stride of . + /// + /// The first of the 16 weights: a row-major symmetric 4x4 matrix. + /// The first of the 16 scratch integers of the scalar path. + /// The sum of the first block. + /// The sum of the second block. + [MethodImpl(InliningOptions.ShortMethod)] + public static void TTransformSums2(ref byte input, ref ushort w, ref int scratch, out int sum0, out int sum1) + { + if (Vector128.IsHardwareAccelerated) + { + // Each row fills eight 16-bit lanes: the first block in lanes 0 to 3, the second block in lanes 4 to 7. + TTransform( + Vector128.WidenLower(Vp8Encoding.AdjacentSourceOperator.Load(ref input)).AsInt16(), + Vector128.WidenLower(Vp8Encoding.AdjacentSourceOperator.Load(ref Unsafe.Add(ref input, (nuint)WebpConstants.Bps))).AsInt16(), + Vector128.WidenLower(Vp8Encoding.AdjacentSourceOperator.Load(ref Unsafe.Add(ref input, (nuint)(WebpConstants.Bps * 2)))).AsInt16(), + Vector128.WidenLower(Vp8Encoding.AdjacentSourceOperator.Load(ref Unsafe.Add(ref input, (nuint)(WebpConstants.Bps * 3)))).AsInt16(), + Vector128.LoadUnsafe(ref w).AsInt16(), + Vector128.LoadUnsafe(ref w, 8).AsInt16(), + out Vector128 sumA, + out Vector128 sumB); + + // t = [a0 + a2, b0 + b2, a1 + a3, b1 + b3]. Adding the swapped 64-bit halves gives the two sums in lanes 0 and 1. + Vector128 t = Vector128_.UnpackLow(sumA, sumB) + Vector128_.UnpackHigh(sumA, sumB); + t += Vector128_.ShuffleNative(t, SimdUtils.Shuffle.MMShuffle1032); + sum0 = t.ToScalar(); + sum1 = t.GetElement(1); + return; + } + + sum0 = TTransform(ref input, ref w, ref scratch); + sum1 = TTransform(ref Unsafe.Add(ref input, (nuint)4), ref w, ref scratch); + } + + /// + /// Returns the weighted Hadamard sums of four horizontally adjacent 4x4 blocks, as returns them. + /// The caller checks . + /// + /// The first sample of the 4 blocks: 4 rows of 16 samples with a stride of . + /// The first of the 16 weights: a row-major symmetric 4x4 matrix. + /// The sum of block k in lane k. + [MethodImpl(InliningOptions.ShortMethod)] + private static Vector128 TTransformSums4(ref byte input, ref ushort w) + { + Vector128 w0 = Vector128.LoadUnsafe(ref w).AsInt16(); + Vector128 w8 = Vector128.LoadUnsafe(ref w, 8).AsInt16(); + Vector128 t01; + Vector128 t23; + if (Vector256.IsHardwareAccelerated) + { + // Each row of 16 samples fills sixteen 16-bit lanes: the 128-bit lane 0 holds blocks 0 and 1, + // the 128-bit lane 1 holds blocks 2 and 3. + TTransform( + Vector256.WidenLower(Vector128.LoadUnsafe(ref input).ToVector256Unsafe()).AsInt16(), + Vector256.WidenLower(Vector128.LoadUnsafe(ref input, WebpConstants.Bps).ToVector256Unsafe()).AsInt16(), + Vector256.WidenLower(Vector128.LoadUnsafe(ref input, WebpConstants.Bps * 2).ToVector256Unsafe()).AsInt16(), + Vector256.WidenLower(Vector128.LoadUnsafe(ref input, WebpConstants.Bps * 3).ToVector256Unsafe()).AsInt16(), + Vector256.Create(w0, w0), + Vector256.Create(w8, w8), + out Vector256 sumEven, + out Vector256 sumOdd); + + // Each 128-bit lane of t is [p0 + p2, q0 + q2, p1 + p3, q1 + q3] for the partial sums p of the even block + // and q of the odd block of that lane. + Vector256 t = Vector256_.UnpackLow(sumEven, sumOdd) + Vector256_.UnpackHigh(sumEven, sumOdd); + t01 = t.GetLower().AsInt64(); + t23 = t.GetUpper().AsInt64(); + } + else + { + // Each row of 16 samples is widened to two vectors: blocks 0 and 1, then blocks 2 and 3. + Vector128 row0 = Vector128.LoadUnsafe(ref input); + Vector128 row1 = Vector128.LoadUnsafe(ref input, WebpConstants.Bps); + Vector128 row2 = Vector128.LoadUnsafe(ref input, WebpConstants.Bps * 2); + Vector128 row3 = Vector128.LoadUnsafe(ref input, WebpConstants.Bps * 3); + TTransform( + Vector128.WidenLower(row0).AsInt16(), + Vector128.WidenLower(row1).AsInt16(), + Vector128.WidenLower(row2).AsInt16(), + Vector128.WidenLower(row3).AsInt16(), + w0, + w8, + out Vector128 sum0, + out Vector128 sum1); + + TTransform( + Vector128.WidenUpper(row0).AsInt16(), + Vector128.WidenUpper(row1).AsInt16(), + Vector128.WidenUpper(row2).AsInt16(), + Vector128.WidenUpper(row3).AsInt16(), + w0, + w8, + out Vector128 sum2, + out Vector128 sum3); + + // [p0 + p2, q0 + q2, p1 + p3, q1 + q3] for the partial sums p of the even block and q of the odd block. + t01 = (Vector128_.UnpackLow(sum0, sum1) + Vector128_.UnpackHigh(sum0, sum1)).AsInt64(); + t23 = (Vector128_.UnpackLow(sum2, sum3) + Vector128_.UnpackHigh(sum2, sum3)).AsInt64(); + } + + // The low 64 bits of both hold the first half sums of the four blocks in order, the high 64 bits the second half sums. + return Vector128_.UnpackLow(t01, t23).AsInt32() + Vector128_.UnpackHigh(t01, t23).AsInt32(); + } + /// + /// Computes the weighted Hadamard transform sums of two 4x4 blocks at once. + /// + /// + /// The vertical pass comes first, then the horizontal pass. This avoids a transpose. The order of the passes does not + /// change the result, because the weight matrix is symmetric. All values fit 16-bit lanes: a sum of 16 samples is at + /// most 4080. + /// + /// Row 0: 16-bit lanes 0 to 3 hold block a, lanes 4 to 7 block b. + /// Row 1. + /// Row 2. + /// Row 3. + /// The weights 0 to 7. + /// The weights 8 to 15. + /// Four partial sums of block a. Their total is the weighted sum of block a. + /// Four partial sums of block b. Their total is the weighted sum of block b. + [MethodImpl(InliningOptions.ShortMethod)] + private static void TTransform( + Vector128 tmp0, + Vector128 tmp1, + Vector128 tmp2, + Vector128 tmp3, + Vector128 w0, + Vector128 w8, + out Vector128 sumA, + out Vector128 sumB) + { // a00 a01 a02 a03 b00 b01 b02 b03 // a10 a11 a12 a13 b10 b11 b12 b13 // a20 a21 a22 a23 b20 b21 b22 b23 // a30 a31 a32 a33 b30 b31 b32 b33 - // Vertical pass first to avoid a transpose (vertical and horizontal passes - // are commutative because w/kWeightY is symmetric) and subsequent transpose. - // Calculate a and b (two 4x4 at once). + // Vertical pass (two 4x4 at once). Vector128 a0 = tmp0 + tmp2; Vector128 a1 = tmp1 + tmp3; Vector128 a2 = tmp1 - tmp3; @@ -834,12 +1210,8 @@ public static int TTransformVector128(Span inputA, Span inputB, Span Vector128 b2 = a3 - a2; Vector128 b3 = a0 - a1; - // a00 a01 a02 a03 b00 b01 b02 b03 - // a10 a11 a12 a13 b10 b11 b12 b13 - // a20 a21 a22 a23 b20 b21 b22 b23 - // a30 a31 a32 a33 b30 b31 b32 b33 // Transpose the two 4x4. - Vp8Transpose_2_4x4_16bVector128( + Vp8Transpose_2_4x4_16b( b0, b1, b2, @@ -853,11 +1225,7 @@ public static int TTransformVector128(Span inputA, Span inputB, Span // a01 a11 a21 a31 b01 b11 b21 b31 // a02 a12 a22 a32 b02 b12 b22 b32 // a03 a13 a23 a33 b03 b13 b23 b33 - // Horizontal pass and difference of weighted sums. - Vector128 w0 = Unsafe.As>(ref MemoryMarshal.GetReference(w)); - Vector128 w8 = Unsafe.As>(ref MemoryMarshal.GetReference(w.Slice(8, 8))); - - // Calculate a and b (two 4x4 at once). + // Horizontal pass (two 4x4 at once). a0 = output0.AsInt16() + output2.AsInt16(); a1 = output1.AsInt16() + output3.AsInt16(); a2 = output1.AsInt16() - output3.AsInt16(); @@ -867,34 +1235,101 @@ public static int TTransformVector128(Span inputA, Span inputB, Span b2 = a3 - a2; b3 = a0 - a1; - // Separate the transforms of inA and inB. + // Separate the transforms of a and b. Vector128 ab0 = Vector128_.UnpackLow(b0.AsInt64(), b1.AsInt64()); Vector128 ab2 = Vector128_.UnpackLow(b2.AsInt64(), b3.AsInt64()); Vector128 bb0 = Vector128_.UnpackHigh(b0.AsInt64(), b1.AsInt64()); Vector128 bb2 = Vector128_.UnpackHigh(b2.AsInt64(), b3.AsInt64()); - Vector128 ab0Abs = Vector128.Abs(ab0.AsInt16()); - Vector128 ab2Abs = Vector128.Abs(ab2.AsInt16()); - Vector128 b0Abs = Vector128.Abs(bb0.AsInt16()); - Vector128 bb2Abs = Vector128.Abs(bb2.AsInt16()); + // Weighted sums of the absolute values. + sumA = Vector128_.MultiplyAddAdjacent(Vector128.Abs(ab0.AsInt16()), w0) + Vector128_.MultiplyAddAdjacent(Vector128.Abs(ab2.AsInt16()), w8); + sumB = Vector128_.MultiplyAddAdjacent(Vector128.Abs(bb0.AsInt16()), w0) + Vector128_.MultiplyAddAdjacent(Vector128.Abs(bb2.AsInt16()), w8); + } - // weighted sums. - Vector128 ab0mulw0 = Vector128_.MultiplyAddAdjacent(ab0Abs, w0.AsInt16()); - Vector128 ab2mulw8 = Vector128_.MultiplyAddAdjacent(ab2Abs, w8.AsInt16()); - Vector128 b0mulw0 = Vector128_.MultiplyAddAdjacent(b0Abs, w0.AsInt16()); - Vector128 bb2mulw8 = Vector128_.MultiplyAddAdjacent(bb2Abs, w8.AsInt16()); - Vector128 ab0ab2Sum = ab0mulw0 + ab2mulw8; - Vector128 b0w0bb2w8Sum = b0mulw0 + bb2mulw8; + /// + /// Computes the weighted Hadamard transform sums of four 4x4 blocks at once. + /// + /// + /// Each 128-bit lane holds two blocks in the layout of the 128-bit form of TTransform. Each operation keeps the values + /// in their 128-bit lane, so each lane gives the same results as one run of the 128-bit form. + /// + /// Row 0: blocks 0 and 1 in the 128-bit lane 0, blocks 2 and 3 in lane 1. + /// Row 1. + /// Row 2. + /// Row 3. + /// The weights 0 to 7 in each 128-bit lane. + /// The weights 8 to 15 in each 128-bit lane. + /// The partial sums of block 0 in the 128-bit lane 0 and of block 2 in lane 1. + /// The partial sums of block 1 in the 128-bit lane 0 and of block 3 in lane 1. + [MethodImpl(InliningOptions.ShortMethod)] + private static void TTransform( + Vector256 tmp0, + Vector256 tmp1, + Vector256 tmp2, + Vector256 tmp3, + Vector256 w0, + Vector256 w8, + out Vector256 sumEven, + out Vector256 sumOdd) + { + // Vertical pass (four 4x4 at once). + Vector256 a0 = tmp0 + tmp2; + Vector256 a1 = tmp1 + tmp3; + Vector256 a2 = tmp1 - tmp3; + Vector256 a3 = tmp0 - tmp2; + Vector256 b0 = a0 + a1; + Vector256 b1 = a3 + a2; + Vector256 b2 = a3 - a2; + Vector256 b3 = a0 - a1; + + // Transpose the two 4x4 in each 128-bit lane, with the steps of Vp8Transpose_2_4x4_16bVector128. + Vector256 transpose00 = Vector256_.UnpackLow(b0, b1); + Vector256 transpose01 = Vector256_.UnpackLow(b2, b3); + Vector256 transpose02 = Vector256_.UnpackHigh(b0, b1); + Vector256 transpose03 = Vector256_.UnpackHigh(b2, b3); + Vector256 transpose10 = Vector256_.UnpackLow(transpose00.AsInt32(), transpose01.AsInt32()); + Vector256 transpose11 = Vector256_.UnpackLow(transpose02.AsInt32(), transpose03.AsInt32()); + Vector256 transpose12 = Vector256_.UnpackHigh(transpose00.AsInt32(), transpose01.AsInt32()); + Vector256 transpose13 = Vector256_.UnpackHigh(transpose02.AsInt32(), transpose03.AsInt32()); + Vector256 output0 = Vector256_.UnpackLow(transpose10.AsInt64(), transpose11.AsInt64()).AsInt16(); + Vector256 output1 = Vector256_.UnpackHigh(transpose10.AsInt64(), transpose11.AsInt64()).AsInt16(); + Vector256 output2 = Vector256_.UnpackLow(transpose12.AsInt64(), transpose13.AsInt64()).AsInt16(); + Vector256 output3 = Vector256_.UnpackHigh(transpose12.AsInt64(), transpose13.AsInt64()).AsInt16(); + + // Horizontal pass (four 4x4 at once). + a0 = output0 + output2; + a1 = output1 + output3; + a2 = output1 - output3; + a3 = output0 - output2; + b0 = a0 + a1; + b1 = a3 + a2; + b2 = a3 - a2; + b3 = a0 - a1; - // difference of weighted sums. - Vector128 result = ab0ab2Sum - b0w0bb2w8Sum; + // Separate the even and the odd block of each 128-bit lane. + Vector256 even0 = Vector256_.UnpackLow(b0.AsInt64(), b1.AsInt64()); + Vector256 even2 = Vector256_.UnpackLow(b2.AsInt64(), b3.AsInt64()); + Vector256 odd0 = Vector256_.UnpackHigh(b0.AsInt64(), b1.AsInt64()); + Vector256 odd2 = Vector256_.UnpackHigh(b2.AsInt64(), b3.AsInt64()); - return ReduceSumVector128(result); + // Weighted sums of the absolute values. + sumEven = Vector256_.MultiplyAddAdjacent(Vector256.Abs(even0.AsInt16()), w0) + Vector256_.MultiplyAddAdjacent(Vector256.Abs(even2.AsInt16()), w8); + sumOdd = Vector256_.MultiplyAddAdjacent(Vector256.Abs(odd0.AsInt16()), w0) + Vector256_.MultiplyAddAdjacent(Vector256.Abs(odd2.AsInt16()), w8); } - // Transpose two 4x4 16b matrices horizontally stored in registers. + /// + /// Transposes two 4x4 matrices of 16-bit values. Lanes 0 to 3 of each vector hold the first matrix and lanes 4 to 7 the second matrix. + /// + /// Row 0 of both matrices. + /// Row 1 of both matrices. + /// Row 2 of both matrices. + /// Row 3 of both matrices. + /// Column 0 of both matrices, in the same lane layout. + /// Column 1 of both matrices, in the same lane layout. + /// Column 2 of both matrices, in the same lane layout. + /// Column 3 of both matrices, in the same lane layout. [MethodImpl(InliningOptions.ShortMethod)] - public static void Vp8Transpose_2_4x4_16bVector128( + public static void Vp8Transpose_2_4x4_16b( Vector128 b0, Vector128 b1, Vector128 b2, @@ -938,162 +1373,77 @@ public static void Vp8Transpose_2_4x4_16bVector128( // a03 a13 a23 a33 b03 b13 b23 b33 } - // Transforms (Paragraph 14.4). - // Does two transforms. + /// + /// Transposes two 4x4 matrices of 16-bit values in each 128-bit lane. In each lane, 16-bit lanes 0 to 3 of each vector hold the first matrix and + /// 16-bit lanes 4 to 7 the second matrix. + /// + /// + /// Each unpack stays inside its 128-bit lane, so each lane gets the transpose of the overload. The two lanes do not mix. + /// + /// Row 0 of the matrices. + /// Row 1 of the matrices. + /// Row 2 of the matrices. + /// Row 3 of the matrices. + /// Column 0 of the matrices, in the same lane layout. + /// Column 1 of the matrices, in the same lane layout. + /// Column 2 of the matrices, in the same lane layout. + /// Column 3 of the matrices, in the same lane layout. + [MethodImpl(InliningOptions.ShortMethod)] + private static void Vp8Transpose_2_4x4_16b( + Vector256 b0, + Vector256 b1, + Vector256 b2, + Vector256 b3, + out Vector256 output0, + out Vector256 output1, + out Vector256 output2, + out Vector256 output3) + { + Vector256 transpose00 = Vector256_.UnpackLow(b0, b1); + Vector256 transpose01 = Vector256_.UnpackLow(b2, b3); + Vector256 transpose02 = Vector256_.UnpackHigh(b0, b1); + Vector256 transpose03 = Vector256_.UnpackHigh(b2, b3); + + Vector256 transpose10 = Vector256_.UnpackLow(transpose00.AsInt32(), transpose01.AsInt32()); + Vector256 transpose11 = Vector256_.UnpackLow(transpose02.AsInt32(), transpose03.AsInt32()); + Vector256 transpose12 = Vector256_.UnpackHigh(transpose00.AsInt32(), transpose01.AsInt32()); + Vector256 transpose13 = Vector256_.UnpackHigh(transpose02.AsInt32(), transpose03.AsInt32()); + + output0 = Vector256_.UnpackLow(transpose10.AsInt64(), transpose11.AsInt64()); + output1 = Vector256_.UnpackHigh(transpose10.AsInt64(), transpose11.AsInt64()); + output2 = Vector256_.UnpackLow(transpose12.AsInt64(), transpose13.AsInt64()); + output3 = Vector256_.UnpackHigh(transpose12.AsInt64(), transpose13.AsInt64()); + } + + /// + /// Adds the inverse transforms of two horizontally adjacent 4x4 blocks to the samples of the blocks, with the clamp to [0, 255]. + /// + /// + /// See RFC 6386, section 14.4. + /// + /// The 32 coefficients: 16 of the left block, then 16 of the right block. + /// The first sample of the left block. The right block starts 4 samples after it. + /// The scratch buffer of the scalar path. It holds at least 16 integers. public static void TransformTwo(Span src, Span dst, Span scratch) { if (Vector128.IsHardwareAccelerated) { - // This implementation makes use of 16-bit fixed point versions of two - // multiply constants: - // K1 = sqrt(2) * cos (pi/8) ~= 85627 / 2^16 - // K2 = sqrt(2) * sin (pi/8) ~= 35468 / 2^16 - // - // To be able to use signed 16-bit integers, we use the following trick to - // have constants within range: - // - Associated constants are obtained by subtracting the 16-bit fixed point - // version of one: - // k = K - (1 << 16) => K = k + (1 << 16) - // K1 = 85267 => k1 = 20091 - // K2 = 35468 => k2 = -30068 - // - The multiplication of a variable by a constant become the sum of the - // variable and the multiplication of that variable by the associated - // constant: - // (x * K) >> 16 = (x * (k + (1 << 16))) >> 16 = ((x * k ) >> 16) + x - - // Load and concatenate the transform coefficients (we'll do two transforms - // in parallel). - ref short srcRef = ref MemoryMarshal.GetReference(src); - Vector128 in0 = Vector128.Create(Unsafe.As(ref srcRef), 0); - Vector128 in1 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, 4)), 0); - Vector128 in2 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, 8)), 0); - Vector128 in3 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, 12)), 0); - - // a00 a10 a20 a30 x x x x - // a01 a11 a21 a31 x x x x - // a02 a12 a22 a32 x x x x - // a03 a13 a23 a33 x x x x - Vector128 inb0 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, 16)), 0); - Vector128 inb1 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, 20)), 0); - Vector128 inb2 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, 24)), 0); - Vector128 inb3 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, 28)), 0); - - in0 = Vector128_.UnpackLow(in0, inb0); - in1 = Vector128_.UnpackLow(in1, inb1); - in2 = Vector128_.UnpackLow(in2, inb2); - in3 = Vector128_.UnpackLow(in3, inb3); - - // a00 a10 a20 a30 b00 b10 b20 b30 - // a01 a11 a21 a31 b01 b11 b21 b31 - // a02 a12 a22 a32 b02 b12 b22 b32 - // a03 a13 a23 a33 b03 b13 b23 b33 - - // Vertical pass and subsequent transpose. - // First pass, c and d calculations are longer because of the "trick" multiplications. - Vector128 a = in0.AsInt16() + in2.AsInt16(); - Vector128 b = in0.AsInt16() - in2.AsInt16(); - - Vector128 k1 = Vector128.Create((short)20091); - Vector128 k2 = Vector128.Create((short)-30068); - - // c = MUL(in1, K2) - MUL(in3, K1) = MUL(in1, k2) - MUL(in3, k1) + in1 - in3 - Vector128 c1 = Vector128_.MultiplyHigh(in1.AsInt16(), k2); - Vector128 c2 = Vector128_.MultiplyHigh(in3.AsInt16(), k1); - Vector128 c3 = in1.AsInt16() - in3.AsInt16(); - Vector128 c4 = c1 - c2; - Vector128 c = c3.AsInt16() + c4; - - // d = MUL(in1, K1) + MUL(in3, K2) = MUL(in1, k1) + MUL(in3, k2) + in1 + in3 - Vector128 d1 = Vector128_.MultiplyHigh(in1.AsInt16(), k1); - Vector128 d2 = Vector128_.MultiplyHigh(in3.AsInt16(), k2); - Vector128 d3 = in1.AsInt16() + in3.AsInt16(); - Vector128 d4 = d1 + d2; - Vector128 d = d3 + d4; - - // Second pass. - Vector128 tmp0 = a.AsInt16() + d; - Vector128 tmp1 = b.AsInt16() + c; - Vector128 tmp2 = b.AsInt16() - c; - Vector128 tmp3 = a.AsInt16() - d; - - // Transpose the two 4x4. - Vp8Transpose_2_4x4_16bVector128( - tmp0, - tmp1, - tmp2, - tmp3, - out Vector128 t0, - out Vector128 t1, - out Vector128 t2, - out Vector128 t3); - - // Horizontal pass and subsequent transpose. - // First pass, c and d calculations are longer because of the "trick" multiplications. - Vector128 dc = t0.AsInt16() + Vector128.Create((short)4); - a = dc + t2.AsInt16(); - b = dc - t2.AsInt16(); - - // c = MUL(T1, K2) - MUL(T3, K1) = MUL(T1, k2) - MUL(T3, k1) + T1 - T3 - c1 = Vector128_.MultiplyHigh(t1.AsInt16(), k2); - c2 = Vector128_.MultiplyHigh(t3.AsInt16(), k1); - c3 = t1.AsInt16() - t3.AsInt16(); - c4 = c1 - c2; - c = c3 + c4; - - // d = MUL(T1, K1) + MUL(T3, K2) = MUL(T1, k1) + MUL(T3, k2) + T1 + T3 - d1 = Vector128_.MultiplyHigh(t1.AsInt16(), k1); - d2 = Vector128_.MultiplyHigh(t3.AsInt16(), k2); - d3 = t1.AsInt16() + t3.AsInt16(); - d4 = d1 + d2; - d = d3 + d4; - - // Second pass. - tmp0 = a + d; - tmp1 = b + c; - tmp2 = b - c; - tmp3 = a - d; - Vector128 shifted0 = Vector128.ShiftRightArithmetic(tmp0, 3); - Vector128 shifted1 = Vector128.ShiftRightArithmetic(tmp1, 3); - Vector128 shifted2 = Vector128.ShiftRightArithmetic(tmp2, 3); - Vector128 shifted3 = Vector128.ShiftRightArithmetic(tmp3, 3); - - // Transpose the two 4x4. - Vp8Transpose_2_4x4_16bVector128(shifted0, shifted1, shifted2, shifted3, out t0, out t1, out t2, out t3); - - // Add inverse transform to 'dst' and store. - // Load the reference(s). - // Load eight bytes/pixels per line. - ref byte dstRef = ref MemoryMarshal.GetReference(dst); - Vector128 dst0 = Vector128.Create(Unsafe.As(ref dstRef), 0).AsByte(); - Vector128 dst1 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref dstRef, WebpConstants.Bps)), 0).AsByte(); - Vector128 dst2 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref dstRef, WebpConstants.Bps * 2)), 0).AsByte(); - Vector128 dst3 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref dstRef, WebpConstants.Bps * 3)), 0).AsByte(); - - // Convert to 16b. - dst0 = Vector128_.UnpackLow(dst0, Vector128.Zero); - dst1 = Vector128_.UnpackLow(dst1, Vector128.Zero); - dst2 = Vector128_.UnpackLow(dst2, Vector128.Zero); - dst3 = Vector128_.UnpackLow(dst3, Vector128.Zero); - - // Add the inverse transform(s). - dst0 = (dst0.AsInt16() + t0.AsInt16()).AsByte(); - dst1 = (dst1.AsInt16() + t1.AsInt16()).AsByte(); - dst2 = (dst2.AsInt16() + t2.AsInt16()).AsByte(); - dst3 = (dst3.AsInt16() + t3.AsInt16()).AsByte(); - - // Unsigned saturate to 8b. - dst0 = Vector128_.PackUnsignedSaturate(dst0.AsInt16(), dst0.AsInt16()); - dst1 = Vector128_.PackUnsignedSaturate(dst1.AsInt16(), dst1.AsInt16()); - dst2 = Vector128_.PackUnsignedSaturate(dst2.AsInt16(), dst2.AsInt16()); - dst3 = Vector128_.PackUnsignedSaturate(dst3.AsInt16(), dst3.AsInt16()); - - // Store the results. - // Store eight bytes/pixels per line. - ref byte outputRef = ref MemoryMarshal.GetReference(dst); - Unsafe.As>(ref outputRef) = dst0.GetLower(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, WebpConstants.Bps)) = dst1.GetLower(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, WebpConstants.Bps * 2)) = dst2.GetLower(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, WebpConstants.Bps * 3)) = dst3.GetLower(); + // Coefficient row r of the left block goes to lanes 0 to 3, and row r of the right block to lanes 4 to 7. + ref short coefficients = ref MemoryMarshal.GetReference(src); + InverseTransform( + Vector128.Create(ReadCoefficientRow(ref coefficients, 0), ReadCoefficientRow(ref coefficients, 16)).AsInt16(), + Vector128.Create(ReadCoefficientRow(ref coefficients, 4), ReadCoefficientRow(ref coefficients, 20)).AsInt16(), + Vector128.Create(ReadCoefficientRow(ref coefficients, 8), ReadCoefficientRow(ref coefficients, 24)).AsInt16(), + Vector128.Create(ReadCoefficientRow(ref coefficients, 12), ReadCoefficientRow(ref coefficients, 28)).AsInt16(), + out Vector128 row0, + out Vector128 row1, + out Vector128 row2, + out Vector128 row3); + + // Residual row r holds the 8 values of sample row r, because the two blocks are adjacent in the row. + ref byte samples = ref MemoryMarshal.GetReference(dst); + AddToRows8(ref samples, ref Unsafe.Add(ref samples, (nuint)WebpConstants.Bps), row0, row1); + AddToRows8(ref Unsafe.Add(ref samples, (nuint)(2 * WebpConstants.Bps)), ref Unsafe.Add(ref samples, (nuint)(3 * WebpConstants.Bps)), row2, row3); } else { @@ -1102,132 +1452,34 @@ public static void TransformTwo(Span src, Span dst, Span scrat } } + /// + /// Adds the inverse transform of one 4x4 block to the samples of the block, with the clamp to [0, 255]. + /// + /// The 16 coefficients of the block. + /// The first sample of the block. + /// The scratch buffer of the scalar path. It holds at least 16 integers. public static void TransformOne(Span src, Span dst, Span scratch) { if (Vector128.IsHardwareAccelerated) { - // Load and concatenate the transform coefficients. - ref short srcRef = ref MemoryMarshal.GetReference(src); - Vector128 in0 = Vector128.Create(Unsafe.As(ref srcRef), 0); - Vector128 in1 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, 4)), 0); - Vector128 in2 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, 8)), 0); - Vector128 in3 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, 12)), 0); - - // a00 a10 a20 a30 x x x x - // a01 a11 a21 a31 x x x x - // a02 a12 a22 a32 x x x x - // a03 a13 a23 a33 x x x x - - // Vertical pass and subsequent transpose. - // First pass, c and d calculations are longer because of the "trick" multiplications. - Vector128 a = in0.AsInt16() + in2.AsInt16(); - Vector128 b = in0.AsInt16() - in2.AsInt16(); - - Vector128 k1 = Vector128.Create((short)20091); - Vector128 k2 = Vector128.Create((short)-30068); - - // c = MUL(in1, K2) - MUL(in3, K1) = MUL(in1, k2) - MUL(in3, k1) + in1 - in3 - Vector128 c1 = Vector128_.MultiplyHigh(in1.AsInt16(), k2); - Vector128 c2 = Vector128_.MultiplyHigh(in3.AsInt16(), k1); - Vector128 c3 = in1.AsInt16() - in3.AsInt16(); - Vector128 c4 = c1 - c2; - Vector128 c = c3.AsInt16() + c4; - - // d = MUL(in1, K1) + MUL(in3, K2) = MUL(in1, k1) + MUL(in3, k2) + in1 + in3 - Vector128 d1 = Vector128_.MultiplyHigh(in1.AsInt16(), k1); - Vector128 d2 = Vector128_.MultiplyHigh(in3.AsInt16(), k2); - Vector128 d3 = in1.AsInt16() + in3.AsInt16(); - Vector128 d4 = d1 + d2; - Vector128 d = d3 + d4; - - // Second pass. - Vector128 tmp0 = a.AsInt16() + d; - Vector128 tmp1 = b.AsInt16() + c; - Vector128 tmp2 = b.AsInt16() - c; - Vector128 tmp3 = a.AsInt16() - d; - - // Transpose the two 4x4. - Vp8Transpose_2_4x4_16bVector128( - tmp0, - tmp1, - tmp2, - tmp3, - out Vector128 t0, - out Vector128 t1, - out Vector128 t2, - out Vector128 t3); - - // Horizontal pass and subsequent transpose. - // First pass, c and d calculations are longer because of the "trick" multiplications. - Vector128 dc = t0.AsInt16() + Vector128.Create((short)4); - a = dc + t2.AsInt16(); - b = dc - t2.AsInt16(); - - // c = MUL(T1, K2) - MUL(T3, K1) = MUL(T1, k2) - MUL(T3, k1) + T1 - T3 - c1 = Vector128_.MultiplyHigh(t1.AsInt16(), k2); - c2 = Vector128_.MultiplyHigh(t3.AsInt16(), k1); - c3 = t1.AsInt16() - t3.AsInt16(); - c4 = c1 - c2; - c = c3 + c4; - - // d = MUL(T1, K1) + MUL(T3, K2) = MUL(T1, k1) + MUL(T3, k2) + T1 + T3 - d1 = Vector128_.MultiplyHigh(t1.AsInt16(), k1); - d2 = Vector128_.MultiplyHigh(t3.AsInt16(), k2); - d3 = t1.AsInt16() + t3.AsInt16(); - d4 = d1 + d2; - d = d3 + d4; - - // Second pass. - tmp0 = a + d; - tmp1 = b + c; - tmp2 = b - c; - tmp3 = a - d; - Vector128 shifted0 = Vector128.ShiftRightArithmetic(tmp0, 3); - Vector128 shifted1 = Vector128.ShiftRightArithmetic(tmp1, 3); - Vector128 shifted2 = Vector128.ShiftRightArithmetic(tmp2, 3); - Vector128 shifted3 = Vector128.ShiftRightArithmetic(tmp3, 3); - - // Transpose the two 4x4. - Vp8Transpose_2_4x4_16bVector128(shifted0, shifted1, shifted2, shifted3, out t0, out t1, out t2, out t3); - - // Add inverse transform to 'dst' and store. - // Load the reference(s). - // Load four bytes/pixels per line. - ref byte dstRef = ref MemoryMarshal.GetReference(dst); - Vector128 dst0 = Vector128.CreateScalar(Unsafe.As(ref dstRef)).AsByte(); - Vector128 dst1 = Vector128.CreateScalar(Unsafe.As(ref Unsafe.Add(ref dstRef, WebpConstants.Bps))).AsByte(); - Vector128 dst2 = Vector128.CreateScalar(Unsafe.As(ref Unsafe.Add(ref dstRef, WebpConstants.Bps * 2))).AsByte(); - Vector128 dst3 = Vector128.CreateScalar(Unsafe.As(ref Unsafe.Add(ref dstRef, WebpConstants.Bps * 3))).AsByte(); - - // Convert to 16b. - dst0 = Vector128_.UnpackLow(dst0, Vector128.Zero); - dst1 = Vector128_.UnpackLow(dst1, Vector128.Zero); - dst2 = Vector128_.UnpackLow(dst2, Vector128.Zero); - dst3 = Vector128_.UnpackLow(dst3, Vector128.Zero); - - // Add the inverse transform(s). - dst0 = (dst0.AsInt16() + t0.AsInt16()).AsByte(); - dst1 = (dst1.AsInt16() + t1.AsInt16()).AsByte(); - dst2 = (dst2.AsInt16() + t2.AsInt16()).AsByte(); - dst3 = (dst3.AsInt16() + t3.AsInt16()).AsByte(); - - // Unsigned saturate to 8b. - dst0 = Vector128_.PackUnsignedSaturate(dst0.AsInt16(), dst0.AsInt16()); - dst1 = Vector128_.PackUnsignedSaturate(dst1.AsInt16(), dst1.AsInt16()); - dst2 = Vector128_.PackUnsignedSaturate(dst2.AsInt16(), dst2.AsInt16()); - dst3 = Vector128_.PackUnsignedSaturate(dst3.AsInt16(), dst3.AsInt16()); - - // Store the results. - // Store four bytes/pixels per line. - ref byte outputRef = ref MemoryMarshal.GetReference(dst); - int output0 = dst0.AsInt32().ToScalar(); - int output1 = dst1.AsInt32().ToScalar(); - int output2 = dst2.AsInt32().ToScalar(); - int output3 = dst3.AsInt32().ToScalar(); - Unsafe.As(ref outputRef) = output0; - Unsafe.As(ref Unsafe.Add(ref outputRef, WebpConstants.Bps)) = output1; - Unsafe.As(ref Unsafe.Add(ref outputRef, WebpConstants.Bps * 2)) = output2; - Unsafe.As(ref Unsafe.Add(ref outputRef, WebpConstants.Bps * 3)) = output3; + // Coefficient row r goes to lanes 0 to 3. Lanes 4 to 7 are not defined. The transform does not mix them into lanes 0 to 3, and the add + // below uses only lanes 0 to 3 of each residual row. + ref short coefficients = ref MemoryMarshal.GetReference(src); + InverseTransform( + Vector128.CreateScalarUnsafe(ReadCoefficientRow(ref coefficients, 0)).AsInt16(), + Vector128.CreateScalarUnsafe(ReadCoefficientRow(ref coefficients, 4)).AsInt16(), + Vector128.CreateScalarUnsafe(ReadCoefficientRow(ref coefficients, 8)).AsInt16(), + Vector128.CreateScalarUnsafe(ReadCoefficientRow(ref coefficients, 12)).AsInt16(), + out Vector128 row0, + out Vector128 row1, + out Vector128 row2, + out Vector128 row3); + + // The 64-bit unpacks join lanes 0 to 3 of two residual rows, which is the layout of the two row pairs of the block add. + AddToBlock4x4( + ref MemoryMarshal.GetReference(dst), + Vector128_.UnpackLow(row0.AsInt64(), row1.AsInt64()).AsInt16(), + Vector128_.UnpackLow(row2.AsInt64(), row3.AsInt64()).AsInt16()); } else { @@ -1253,7 +1505,7 @@ public static void TransformOne(Span src, Span dst, Span scrat // The exact value is (2. + (20091 + 35468) / 65536). // After the second pass, maximum interval is [-3794, 3794], assuming // an input in [-2048, 2047] interval. We then need to add a dst value in the [0, 255] range. - // In the worst case scenario, the input to Clip8B can be as large as [-60713, 60968]. + // In the worst case scenario, the input to the clamp can be as large as [-60713, 60968]. tmpOffset = 0; int dstOffset = 0; for (int i = 0; i < 4; i++) @@ -1278,9 +1530,153 @@ public static void TransformOne(Span src, Span dst, Span scrat } } + /// + /// Computes the inverse transforms of two 4x4 blocks. See RFC 6386, section 14.3. + /// + /// + /// + /// Each input holds one coefficient row of each block: lanes 0 to 3 for the first block and lanes 4 to 7 for the second block. Each output holds + /// one residual row of each block in the same lanes. The residuals include the rounding term 4 and the shift right by 3, so the caller adds them + /// to the samples. The blocks do not mix, so lanes 0 to 3 of the outputs depend only on lanes 0 to 3 of the inputs. + /// + /// + /// The format multiplies by K1 = sqrt(2) * cos(pi / 8) and K2 = sqrt(2) * sin(pi / 8) in 16.16 fixed point: K1 = 20091 + (1 << 16) and + /// K2 = 35468. A signed 16-bit lane cannot hold K1 or K2, so the code uses k = K - (1 << 16): k1 = 20091 and k2 = -30068. Then + /// (x * K) >> 16 = ((x * k) >> 16) + x, because x * (1 << 16) has no bits below bit 16. MultiplyHigh gives (x * k) >> 16. + /// + /// + /// Coefficient row 0. + /// Coefficient row 1. + /// Coefficient row 2. + /// Coefficient row 3. + /// Residual row 0. + /// Residual row 1. + /// Residual row 2. + /// Residual row 3. + [MethodImpl(InliningOptions.ShortMethod)] + public static void InverseTransform( + Vector128 in0, + Vector128 in1, + Vector128 in2, + Vector128 in3, + out Vector128 out0, + out Vector128 out1, + out Vector128 out2, + out Vector128 out3) + { + Vector128 k1 = Vector128.Create((short)20091); + Vector128 k2 = Vector128.Create((short)-30068); + + // Vertical pass: c = MUL(in1, K2) - MUL(in3, K1) and d = MUL(in1, K1) + MUL(in3, K2). + Vector128 a = in0 + in2; + Vector128 b = in0 - in2; + Vector128 c = (in1 - in3) + (Vector128_.MultiplyHigh(in1, k2) - Vector128_.MultiplyHigh(in3, k1)); + Vector128 d = (in1 + in3) + (Vector128_.MultiplyHigh(in1, k1) + Vector128_.MultiplyHigh(in3, k2)); + + // The transpose turns the columns of the vertical pass into the rows of the horizontal pass. + Vp8Transpose_2_4x4_16b(a + d, b + c, b - c, a - d, out Vector128 t0, out Vector128 t1, out Vector128 t2, out Vector128 t3); + + // Horizontal pass. The DC term gets the rounding term 4 before the shift right by 3. + Vector128 dc = t0.AsInt16() + Vector128.Create((short)4); + a = dc + t2.AsInt16(); + b = dc - t2.AsInt16(); + c = (t1.AsInt16() - t3.AsInt16()) + (Vector128_.MultiplyHigh(t1.AsInt16(), k2) - Vector128_.MultiplyHigh(t3.AsInt16(), k1)); + d = (t1.AsInt16() + t3.AsInt16()) + (Vector128_.MultiplyHigh(t1.AsInt16(), k1) + Vector128_.MultiplyHigh(t3.AsInt16(), k2)); + + // The second transpose puts the residuals back in sample row order. + Vp8Transpose_2_4x4_16b( + Vector128.ShiftRightArithmetic(a + d, 3), + Vector128.ShiftRightArithmetic(b + c, 3), + Vector128.ShiftRightArithmetic(b - c, 3), + Vector128.ShiftRightArithmetic(a - d, 3), + out t0, + out t1, + out t2, + out t3); + + out0 = t0.AsInt16(); + out1 = t1.AsInt16(); + out2 = t2.AsInt16(); + out3 = t3.AsInt16(); + } + + /// + /// Computes the inverse transforms of four 4x4 blocks: two blocks in each 128-bit lane. See RFC 6386, section 14.3. + /// + /// + /// Each 128-bit lane has the layout and the result of the overload. The adds, subtracts, high multiplies and shifts + /// work on each 16-bit lane, and the unpacks of the transposes stay inside each 128-bit lane, so the two lanes do not mix. + /// + /// Coefficient row 0. + /// Coefficient row 1. + /// Coefficient row 2. + /// Coefficient row 3. + /// Residual row 0. + /// Residual row 1. + /// Residual row 2. + /// Residual row 3. + [MethodImpl(InliningOptions.ShortMethod)] + private static void InverseTransform( + Vector256 in0, + Vector256 in1, + Vector256 in2, + Vector256 in3, + out Vector256 out0, + out Vector256 out1, + out Vector256 out2, + out Vector256 out3) + { + Vector256 k1 = Vector256.Create((short)20091); + Vector256 k2 = Vector256.Create((short)-30068); + + // Vertical pass: c = MUL(in1, K2) - MUL(in3, K1) and d = MUL(in1, K1) + MUL(in3, K2). + Vector256 a = in0 + in2; + Vector256 b = in0 - in2; + Vector256 c = (in1 - in3) + (Vector256_.MultiplyHigh(in1, k2) - Vector256_.MultiplyHigh(in3, k1)); + Vector256 d = (in1 + in3) + (Vector256_.MultiplyHigh(in1, k1) + Vector256_.MultiplyHigh(in3, k2)); + + // The transpose turns the columns of the vertical pass into the rows of the horizontal pass. + Vp8Transpose_2_4x4_16b(a + d, b + c, b - c, a - d, out Vector256 t0, out Vector256 t1, out Vector256 t2, out Vector256 t3); + + // Horizontal pass. The DC term gets the rounding term 4 before the shift right by 3. + Vector256 dc = t0.AsInt16() + Vector256.Create((short)4); + a = dc + t2.AsInt16(); + b = dc - t2.AsInt16(); + c = (t1.AsInt16() - t3.AsInt16()) + (Vector256_.MultiplyHigh(t1.AsInt16(), k2) - Vector256_.MultiplyHigh(t3.AsInt16(), k1)); + d = (t1.AsInt16() + t3.AsInt16()) + (Vector256_.MultiplyHigh(t1.AsInt16(), k1) + Vector256_.MultiplyHigh(t3.AsInt16(), k2)); + + // The second transpose puts the residuals back in sample row order. + Vp8Transpose_2_4x4_16b( + Vector256.ShiftRightArithmetic(a + d, 3), + Vector256.ShiftRightArithmetic(b + c, 3), + Vector256.ShiftRightArithmetic(b - c, 3), + Vector256.ShiftRightArithmetic(a - d, 3), + out t0, + out t1, + out t2, + out t3); + + out0 = t0.AsInt16(); + out1 = t1.AsInt16(); + out2 = t2.AsInt16(); + out3 = t3.AsInt16(); + } + + /// + /// Adds the inverse transform of a block with only a DC coefficient: each sample gets (dc + 4) >> 3, with the clamp to [0, 255]. + /// + /// The coefficients of the block. + /// The first sample of the 4x4 block, with bytes between rows. public static void TransformDc(ReadOnlySpan src, Span dst) { int dc = src[0] + 4; + if (Vector128.IsHardwareAccelerated) + { + Vector128 value = Vector128.Create((short)(dc >> 3)); + AddToBlock4x4(ref MemoryMarshal.GetReference(dst), value, value); + return; + } + for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) @@ -1290,7 +1686,15 @@ public static void TransformDc(ReadOnlySpan src, Span dst) } } - // Simplified transform when only src[0], src[1] and src[4] are non-zero + /// + /// Adds the inverse transform of a block with only the coefficients 0, 1 and 4, with the clamp to [0, 255]. + /// + /// + /// The value of row y and column x is the sum of a row term and a column term, shifted right by 3. The row terms come from coefficients 0 and 4, and the + /// column terms from coefficient 1. + /// + /// The coefficients of the block. + /// The first sample of the 4x4 block, with bytes between rows. public static void TransformAc3(ReadOnlySpan src, Span dst) { int a = src[0] + 4; @@ -1298,18 +1702,93 @@ public static void TransformAc3(ReadOnlySpan src, Span dst) int d4 = Mul1(src[4]); int c1 = Mul2(src[1]); int d1 = Mul1(src[1]); + if (Vector128.IsHardwareAccelerated) + { + // Lanes 0 to 3 are row 0 or row 2, and lanes 4 to 7 are row 1 or row 3, as in the widened samples. + Vector128 columns = Vector128.Create(d1, c1, -c1, -d1); + Vector128 rows01 = Vector128.Narrow( + Vector128.ShiftRightArithmetic(Vector128.Create(a + d4) + columns, 3), + Vector128.ShiftRightArithmetic(Vector128.Create(a + c4) + columns, 3)); + + Vector128 rows23 = Vector128.Narrow( + Vector128.ShiftRightArithmetic(Vector128.Create(a - c4) + columns, 3), + Vector128.ShiftRightArithmetic(Vector128.Create(a - d4) + columns, 3)); + + AddToBlock4x4(ref MemoryMarshal.GetReference(dst), rows01, rows23); + return; + } + Store2(dst, 0, a + d4, d1, c1); Store2(dst, 1, a + c4, d1, c1); Store2(dst, 2, a - c4, d1, c1); Store2(dst, 3, a - d4, d1, c1); } + /// + /// Adds the inverse transforms of the four 4x4 blocks of an 8x8 chroma block to its samples, with the clamp to [0, 255]. + /// + /// The 64 coefficients: 16 for each block, in the order top-left, top-right, bottom-left, bottom-right. + /// The first sample of the 8x8 block. + /// The scratch buffer of the scalar path. It holds at least 16 integers. public static void TransformUv(Span src, Span dst, Span scratch) { + if (Vector256.IsHardwareAccelerated) + { + // The low 128-bit lane holds the top-left block in lanes 0 to 3 and the top-right block in lanes 4 to 7, as in TransformTwo. The high + // 128-bit lane holds the bottom-left and the bottom-right blocks in the same way. Each lane gets the result of TransformTwo. + ref short coefficients = ref MemoryMarshal.GetReference(src); + InverseTransform( + Vector256.Create( + ReadCoefficientRow(ref coefficients, 0), + ReadCoefficientRow(ref coefficients, 16), + ReadCoefficientRow(ref coefficients, 32), + ReadCoefficientRow(ref coefficients, 48)).AsInt16(), + Vector256.Create( + ReadCoefficientRow(ref coefficients, 4), + ReadCoefficientRow(ref coefficients, 20), + ReadCoefficientRow(ref coefficients, 36), + ReadCoefficientRow(ref coefficients, 52)).AsInt16(), + Vector256.Create( + ReadCoefficientRow(ref coefficients, 8), + ReadCoefficientRow(ref coefficients, 24), + ReadCoefficientRow(ref coefficients, 40), + ReadCoefficientRow(ref coefficients, 56)).AsInt16(), + Vector256.Create( + ReadCoefficientRow(ref coefficients, 12), + ReadCoefficientRow(ref coefficients, 28), + ReadCoefficientRow(ref coefficients, 44), + ReadCoefficientRow(ref coefficients, 60)).AsInt16(), + out Vector256 row0, + out Vector256 row1, + out Vector256 row2, + out Vector256 row3); + + // Residual row r of the low lane goes to sample row r, and residual row r of the high lane to sample row r + 4. + ref byte top = ref MemoryMarshal.GetReference(dst); + ref byte bottom = ref Unsafe.Add(ref top, (nuint)(4 * WebpConstants.Bps)); + AddToRows8(ref top, ref bottom, row0.GetLower(), row0.GetUpper()); + top = ref Unsafe.Add(ref top, (nuint)WebpConstants.Bps); + bottom = ref Unsafe.Add(ref bottom, (nuint)WebpConstants.Bps); + AddToRows8(ref top, ref bottom, row1.GetLower(), row1.GetUpper()); + top = ref Unsafe.Add(ref top, (nuint)WebpConstants.Bps); + bottom = ref Unsafe.Add(ref bottom, (nuint)WebpConstants.Bps); + AddToRows8(ref top, ref bottom, row2.GetLower(), row2.GetUpper()); + top = ref Unsafe.Add(ref top, (nuint)WebpConstants.Bps); + bottom = ref Unsafe.Add(ref bottom, (nuint)WebpConstants.Bps); + AddToRows8(ref top, ref bottom, row3.GetLower(), row3.GetUpper()); + return; + } + TransformTwo(src[..], dst, scratch); TransformTwo(src[(2 * 16)..], dst[(4 * WebpConstants.Bps)..], scratch); } + /// + /// Adds the inverse transforms of the DC coefficients of the four 4x4 blocks of an 8x8 chroma block, with the clamp to [0, 255]. + /// The method ignores the AC coefficients. A block with a zero DC coefficient does not change. + /// + /// The 64 coefficients: 16 for each block, in the order top-left, top-right, bottom-left, bottom-right. + /// The first sample of the 8x8 block. public static void TransformDcuv(Span src, Span dst) { if (src[0 * 16] != 0) @@ -1333,243 +1812,255 @@ public static void TransformDcuv(Span src, Span dst) } } - // Simple In-loop filtering (Paragraph 15.2) - public static void SimpleVFilter16(Span p, int offset, int stride, int thresh) + /// + /// Applies the simple loop filter to the 16 positions of a horizontal edge. The filter changes the sample above and the sample below the edge. + /// + /// + /// See RFC 6386, section 15.2. + /// + /// The first sample below the edge. + /// The distance between two rows. + /// The edge limit. A position gets the filter when 2 * |p0 - q0| + |p1 - q1| / 2 is at most this value. + public static void SimpleVFilter16(ref byte p, nuint stride, int thresh) { if (Vector128.IsHardwareAccelerated) { - // Load. - ref byte pRef = ref Unsafe.Add(ref MemoryMarshal.GetReference(p), (uint)offset); - - Vector128 p1 = Unsafe.As>(ref Unsafe.Subtract(ref pRef, 2 * stride)); - Vector128 p0 = Unsafe.As>(ref Unsafe.Subtract(ref pRef, stride)); - Vector128 q0 = Unsafe.As>(ref pRef); - Vector128 q1 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)stride)); + // Each vector is one row of 16 positions. The rows p1 and p0 are above the edge, q0 and q1 below it. + ref byte p0Ref = ref Unsafe.Subtract(ref p, stride); + Vector128 p1 = Vector128.LoadUnsafe(ref Unsafe.Subtract(ref p0Ref, stride)); + Vector128 p0 = Vector128.LoadUnsafe(ref p0Ref); + Vector128 q0 = Vector128.LoadUnsafe(ref p); + Vector128 q1 = Vector128.LoadUnsafe(ref p, stride); - DoFilter2Vector128(ref p1, ref p0, ref q0, ref q1, thresh); + DoFilter2(ref p1, ref p0, ref q0, ref q1, thresh); - // Store. - ref byte outputRef = ref Unsafe.Add(ref MemoryMarshal.GetReference(p), (uint)offset); - Unsafe.As>(ref Unsafe.Subtract(ref outputRef, stride)) = p0.AsSByte(); - Unsafe.As>(ref outputRef) = q0.AsSByte(); + p0.StoreUnsafe(ref p0Ref); + q0.StoreUnsafe(ref p); } else { int thresh2 = (2 * thresh) + 1; - int end = 16 + offset; - for (int i = offset; i < end; i++) + for (nuint i = 0; i < 16; i++) { - if (NeedsFilter(p, i, stride, thresh2)) + ref byte q0 = ref Unsafe.Add(ref p, i); + if (NeedsFilter(ref q0, stride, thresh2)) { - DoFilter2(p, i, stride); + DoFilter2(ref q0, stride); } } } } - public static void SimpleHFilter16(Span p, int offset, int stride, int thresh) + /// + /// Applies the simple loop filter to the 16 positions of a vertical edge. The filter changes the sample left and the sample right of the edge. + /// + /// The first sample right of the edge, in the top row. + /// The distance between two rows. + /// The edge limit. A position gets the filter when 2 * |p0 - q0| + |p1 - q1| / 2 is at most this value. + public static void SimpleHFilter16(ref byte p, nuint stride, int thresh) { if (Vector128.IsHardwareAccelerated) { - // Beginning of p1 - ref byte pRef = ref Unsafe.Add(ref MemoryMarshal.GetReference(p), (uint)(offset - 2)); + // The transpose reads the 4 columns p1, p0, q0 and q1, which start 2 samples left of the edge. + ref byte r0 = ref Unsafe.Subtract(ref p, (nuint)2); + ref byte r8 = ref Unsafe.Add(ref r0, 8 * stride); + Load16x4(ref r0, ref r8, stride, out Vector128 p1, out Vector128 p0, out Vector128 q0, out Vector128 q1); - Load16x4Vector128( - ref pRef, - ref Unsafe.Add(ref pRef, 8 * (uint)stride), - stride, - out Vector128 p1, - out Vector128 p0, - out Vector128 q0, - out Vector128 q1); - - DoFilter2Vector128(ref p1, ref p0, ref q0, ref q1, thresh); - Store16x4Vector128(p1, p0, q0, q1, ref pRef, ref Unsafe.Add(ref pRef, 8 * (uint)stride), stride); + DoFilter2(ref p1, ref p0, ref q0, ref q1, thresh); + Store16x4(p1, p0, q0, q1, ref r0, ref r8, stride); } else { int thresh2 = (2 * thresh) + 1; - int end = offset + (16 * stride); - for (int i = offset; i < end; i += stride) + ref byte q0 = ref p; + for (int i = 0; i < 16; i++) { - if (NeedsFilter(p, i, 1, thresh2)) + if (NeedsFilter(ref q0, 1, thresh2)) { - DoFilter2(p, i, 1); + DoFilter2(ref q0, 1); } - } - } - } - public static void SimpleVFilter16i(Span p, int offset, int stride, int thresh) - { - if (Vector128.IsHardwareAccelerated) - { - for (int k = 3; k > 0; k--) - { - offset += 4 * stride; - SimpleVFilter16(p, offset, stride, thresh); - } - } - else - { - for (int k = 3; k > 0; k--) - { - offset += 4 * stride; - SimpleVFilter16(p, offset, stride, thresh); + q0 = ref Unsafe.Add(ref q0, stride); } } } - public static void SimpleHFilter16i(Span p, int offset, int stride, int thresh) + /// + /// Applies the simple loop filter to the three inner horizontal edges of a 16x16 macroblock, at rows 4, 8 and 12. + /// + /// The first sample of the macroblock. + /// The distance between two rows. + /// The edge limit. A position gets the filter when 2 * |p0 - q0| + |p1 - q1| / 2 is at most this value. + public static void SimpleVFilter16i(ref byte p, nuint stride, int thresh) { - if (Vector128.IsHardwareAccelerated) + for (int k = 3; k > 0; k--) { - for (int k = 3; k > 0; k--) - { - offset += 4; - SimpleHFilter16(p, offset, stride, thresh); - } + p = ref Unsafe.Add(ref p, 4 * stride); + SimpleVFilter16(ref p, stride, thresh); } - else + } + + /// + /// Applies the simple loop filter to the three inner vertical edges of a 16x16 macroblock, at columns 4, 8 and 12. + /// + /// The first sample of the macroblock. + /// The distance between two rows. + /// The edge limit. A position gets the filter when 2 * |p0 - q0| + |p1 - q1| / 2 is at most this value. + public static void SimpleHFilter16i(ref byte p, nuint stride, int thresh) + { + for (int k = 3; k > 0; k--) { - for (int k = 3; k > 0; k--) - { - offset += 4; - SimpleHFilter16(p, offset, stride, thresh); - } + p = ref Unsafe.Add(ref p, (nuint)4); + SimpleHFilter16(ref p, stride, thresh); } } - // On macroblock edges. + /// + /// Applies the normal loop filter to the 16 positions of a horizontal macroblock edge. The filter reads 4 samples and changes up to 3 samples + /// on each side of the edge. + /// + /// The first sample below the edge. + /// The distance between two rows. + /// The edge limit. A position gets the filter when 2 * |p0 - q0| + |p1 - q1| / 2 is at most this value. + /// The interior limit. A position gets the filter when no difference between adjacent samples on one side is larger. + /// + /// The high edge variance threshold. When |p1 - p0| or |q1 - q0| is larger, the filter changes only the sample on each side next to the edge. + /// [MethodImpl(InliningOptions.ShortMethod)] - public static void VFilter16(Span p, int offset, int stride, int thresh, int ithresh, int hevThresh) + public static void VFilter16(ref byte p, nuint stride, int thresh, int ithresh, int hevThresh) { if (Vector128.IsHardwareAccelerated) { - ref byte pRef = ref MemoryMarshal.GetReference(p); - Vector128 t1 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)(offset - (4 * stride)))); - Vector128 p2 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)(offset - (3 * stride)))); - Vector128 p1 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)(offset - (2 * stride)))); - Vector128 p0 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)(offset - stride))); - - Vector128 mask = AbsVector128(p1, p0); - mask = Vector128.Max(mask, AbsVector128(t1, p2)); - mask = Vector128.Max(mask, AbsVector128(p2, p1)); - - Vector128 q0 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)offset)); - Vector128 q1 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)(offset + stride))); - Vector128 q2 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)(offset + (2 * stride)))); - t1 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)(offset + (3 * stride)))); - - mask = Vector128.Max(mask, AbsVector128(q1, q0)); - mask = Vector128.Max(mask, AbsVector128(t1, q2)); - mask = Vector128.Max(mask, AbsVector128(q2, q1)); - - ComplexMaskVector128(p1, p0, q0, q1, thresh, ithresh, ref mask); - DoFilter6Vector128(ref p2, ref p1, ref p0, ref q0, ref q1, ref q2, mask, hevThresh); - - // Store. - ref byte outputRef = ref MemoryMarshal.GetReference(p); - Unsafe.As>(ref Unsafe.Add(ref outputRef, (uint)(offset - (3 * stride)))) = p2.AsInt32(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, (uint)(offset - (2 * stride)))) = p1.AsInt32(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, (uint)(offset - stride))) = p0.AsInt32(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, (uint)offset)) = q0.AsInt32(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, (uint)(offset + stride))) = q1.AsInt32(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, (uint)(offset + (2 * stride)))) = q2.AsInt32(); + // Each vector is one row of 16 positions. The rows p3 to p0 start 4 rows above the edge, and the rows q0 to q3 start at the edge. + ref byte p3Ref = ref Unsafe.Subtract(ref p, 4 * stride); + Vector128 t1 = Vector128.LoadUnsafe(ref p3Ref); + Vector128 p2 = Vector128.LoadUnsafe(ref p3Ref, stride); + Vector128 p1 = Vector128.LoadUnsafe(ref p3Ref, 2 * stride); + Vector128 p0 = Vector128.LoadUnsafe(ref p3Ref, 3 * stride); + + Vector128 mask = AbsoluteDifference(p1, p0); + mask = Vector128.Max(mask, AbsoluteDifference(t1, p2)); + mask = Vector128.Max(mask, AbsoluteDifference(p2, p1)); + + Vector128 q0 = Vector128.LoadUnsafe(ref p); + Vector128 q1 = Vector128.LoadUnsafe(ref p, stride); + Vector128 q2 = Vector128.LoadUnsafe(ref p, 2 * stride); + t1 = Vector128.LoadUnsafe(ref p, 3 * stride); + + mask = Vector128.Max(mask, AbsoluteDifference(q1, q0)); + mask = Vector128.Max(mask, AbsoluteDifference(t1, q2)); + mask = Vector128.Max(mask, AbsoluteDifference(q2, q1)); + + ComplexMask(p1, p0, q0, q1, thresh, ithresh, ref mask); + DoFilter6(ref p2, ref p1, ref p0, ref q0, ref q1, ref q2, mask, hevThresh); + + // The filter does not change p3 and q3. + p2.StoreUnsafe(ref p3Ref, stride); + p1.StoreUnsafe(ref p3Ref, 2 * stride); + p0.StoreUnsafe(ref p3Ref, 3 * stride); + q0.StoreUnsafe(ref p); + q1.StoreUnsafe(ref p, stride); + q2.StoreUnsafe(ref p, 2 * stride); } else { - FilterLoop26(p, offset, stride, 1, 16, thresh, ithresh, hevThresh); + FilterLoop26(ref p, stride, 1, 16, thresh, ithresh, hevThresh); } } + /// + /// Applies the normal loop filter to the 16 positions of a vertical macroblock edge. The filter reads 4 samples and changes up to 3 samples + /// on each side of the edge. + /// + /// The first sample right of the edge, in the top row. + /// The distance between two rows. + /// The edge limit. A position gets the filter when 2 * |p0 - q0| + |p1 - q1| / 2 is at most this value. + /// The interior limit. A position gets the filter when no difference between adjacent samples on one side is larger. + /// + /// The high edge variance threshold. When |p1 - p0| or |q1 - q0| is larger, the filter changes only the sample on each side next to the edge. + /// [MethodImpl(InliningOptions.ShortMethod)] - public static void HFilter16(Span p, int offset, int stride, int thresh, int ithresh, int hevThresh) + public static void HFilter16(ref byte p, nuint stride, int thresh, int ithresh, int hevThresh) { if (Vector128.IsHardwareAccelerated) { - ref byte pRef = ref MemoryMarshal.GetReference(p); - ref byte bRef = ref Unsafe.Add(ref pRef, (uint)offset - 4); - Load16x4Vector128( - ref bRef, - ref Unsafe.Add(ref bRef, 8 * (uint)stride), - stride, - out Vector128 p3, - out Vector128 p2, - out Vector128 p1, - out Vector128 p0); + // The transposes read the columns p3 to p0, which start 4 samples left of the edge, and the columns q0 to q3, which start at the edge. + ref byte p3Ref = ref Unsafe.Subtract(ref p, (nuint)4); + ref byte p3Row8 = ref Unsafe.Add(ref p3Ref, 8 * stride); + Load16x4(ref p3Ref, ref p3Row8, stride, out Vector128 p3, out Vector128 p2, out Vector128 p1, out Vector128 p0); - Vector128 mask = AbsVector128(p1, p0); - mask = Vector128.Max(mask, AbsVector128(p3, p2)); - mask = Vector128.Max(mask, AbsVector128(p2, p1)); + Vector128 mask = AbsoluteDifference(p1, p0); + mask = Vector128.Max(mask, AbsoluteDifference(p3, p2)); + mask = Vector128.Max(mask, AbsoluteDifference(p2, p1)); - Load16x4Vector128( - ref Unsafe.Add(ref pRef, (uint)offset), - ref Unsafe.Add(ref pRef, (uint)(offset + (8 * stride))), - stride, - out Vector128 q0, - out Vector128 q1, - out Vector128 q2, - out Vector128 q3); + ref byte q0Row8 = ref Unsafe.Add(ref p, 8 * stride); + Load16x4(ref p, ref q0Row8, stride, out Vector128 q0, out Vector128 q1, out Vector128 q2, out Vector128 q3); - mask = Vector128.Max(mask, AbsVector128(q1, q0)); - mask = Vector128.Max(mask, AbsVector128(q3, q2)); - mask = Vector128.Max(mask, AbsVector128(q2, q1)); + mask = Vector128.Max(mask, AbsoluteDifference(q1, q0)); + mask = Vector128.Max(mask, AbsoluteDifference(q3, q2)); + mask = Vector128.Max(mask, AbsoluteDifference(q2, q1)); - ComplexMaskVector128(p1, p0, q0, q1, thresh, ithresh, ref mask); - DoFilter6Vector128(ref p2, ref p1, ref p0, ref q0, ref q1, ref q2, mask, hevThresh); + ComplexMask(p1, p0, q0, q1, thresh, ithresh, ref mask); + DoFilter6(ref p2, ref p1, ref p0, ref q0, ref q1, ref q2, mask, hevThresh); - Store16x4Vector128(p3, p2, p1, p0, ref bRef, ref Unsafe.Add(ref bRef, 8 * (uint)stride), stride); - Store16x4Vector128(q0, q1, q2, q3, ref Unsafe.Add(ref pRef, (uint)offset), ref Unsafe.Add(ref pRef, (uint)(offset + (8 * stride))), stride); + Store16x4(p3, p2, p1, p0, ref p3Ref, ref p3Row8, stride); + Store16x4(q0, q1, q2, q3, ref p, ref q0Row8, stride); } else { - FilterLoop26(p, offset, 1, stride, 16, thresh, ithresh, hevThresh); + FilterLoop26(ref p, 1, stride, 16, thresh, ithresh, hevThresh); } } - public static void VFilter16i(Span p, int offset, int stride, int thresh, int ithresh, int hevThresh) + /// + /// Applies the normal loop filter to the three inner horizontal edges of a 16x16 macroblock, at rows 4, 8 and 12. + /// The filter reads 4 samples and changes up to 2 samples on each side of an edge. + /// + /// The first sample of the macroblock. + /// The distance between two rows. + /// The edge limit. A position gets the filter when 2 * |p0 - q0| + |p1 - q1| / 2 is at most this value. + /// The interior limit. A position gets the filter when no difference between adjacent samples on one side is larger. + /// + /// The high edge variance threshold. When |p1 - p0| or |q1 - q0| is larger, the filter changes only the sample on each side next to the edge. + /// + public static void VFilter16i(ref byte p, nuint stride, int thresh, int ithresh, int hevThresh) { if (Vector128.IsHardwareAccelerated) { - ref byte pRef = ref MemoryMarshal.GetReference(p); - Vector128 p3 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)offset)); - Vector128 p2 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)(offset + stride))); - Vector128 p1 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)(offset + (2 * stride)))); - Vector128 p0 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)(offset + (3 * stride)))); + // Rows 0 to 3 are p3 to p0 of the first inner edge. + Vector128 p3 = Vector128.LoadUnsafe(ref p); + Vector128 p2 = Vector128.LoadUnsafe(ref p, stride); + Vector128 p1 = Vector128.LoadUnsafe(ref p, 2 * stride); + Vector128 p0 = Vector128.LoadUnsafe(ref p, 3 * stride); for (int k = 3; k > 0; k--) { - // Beginning of p1. - Span b = p[(offset + (2 * stride))..]; - offset += 4 * stride; - - Vector128 mask = AbsVector128(p0, p1); - mask = Vector128.Max(mask, AbsVector128(p3, p2)); - mask = Vector128.Max(mask, AbsVector128(p2, p1)); - - p3 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)offset)); - p2 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)(offset + stride))); - Vector128 tmp1 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)(offset + (2 * stride)))); - Vector128 tmp2 = Unsafe.As>(ref Unsafe.Add(ref pRef, (uint)(offset + (3 * stride)))); - - mask = Vector128.Max(mask, AbsVector128(tmp1, tmp2)); - mask = Vector128.Max(mask, AbsVector128(p3, p2)); - mask = Vector128.Max(mask, AbsVector128(p2, tmp1)); - - // p3 and p2 are not just temporary variables here: they will be - // re-used for next span. And q2/q3 will become p1/p0 accordingly. - ComplexMaskVector128(p1, p0, p3, p2, thresh, ithresh, ref mask); - DoFilter4Vector128(ref p1, ref p0, ref p3, ref p2, mask, hevThresh); - - // Store. - ref byte outputRef = ref MemoryMarshal.GetReference(b); - Unsafe.As>(ref outputRef) = p1.AsInt32(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, (uint)stride)) = p0.AsInt32(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, (uint)(stride * 2))) = p3.AsInt32(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, (uint)(stride * 3))) = p2.AsInt32(); - - // Rotate samples. + // b is the row of p1. p moves to the next edge, the row of q0. + ref byte b = ref Unsafe.Add(ref p, 2 * stride); + p = ref Unsafe.Add(ref p, 4 * stride); + + Vector128 mask = AbsoluteDifference(p0, p1); + mask = Vector128.Max(mask, AbsoluteDifference(p3, p2)); + mask = Vector128.Max(mask, AbsoluteDifference(p2, p1)); + + p3 = Vector128.LoadUnsafe(ref p); + p2 = Vector128.LoadUnsafe(ref p, stride); + Vector128 tmp1 = Vector128.LoadUnsafe(ref p, 2 * stride); + Vector128 tmp2 = Vector128.LoadUnsafe(ref p, 3 * stride); + + mask = Vector128.Max(mask, AbsoluteDifference(tmp1, tmp2)); + mask = Vector128.Max(mask, AbsoluteDifference(p3, p2)); + mask = Vector128.Max(mask, AbsoluteDifference(p2, tmp1)); + + // p3 and p2 hold q0 and q1 of this edge. After the filter, the rows q2 and q3 become p1 and p0 of the next edge. + ComplexMask(p1, p0, p3, p2, thresh, ithresh, ref mask); + DoFilter4(ref p1, ref p0, ref p3, ref p2, mask, hevThresh); + + p1.StoreUnsafe(ref b); + p0.StoreUnsafe(ref b, stride); + p3.StoreUnsafe(ref b, 2 * stride); + p2.StoreUnsafe(ref b, 3 * stride); + p1 = tmp1; p0 = tmp2; } @@ -1578,59 +2069,59 @@ public static void VFilter16i(Span p, int offset, int stride, int thresh, { for (int k = 3; k > 0; k--) { - offset += 4 * stride; - FilterLoop24(p, offset, stride, 1, 16, thresh, ithresh, hevThresh); + p = ref Unsafe.Add(ref p, 4 * stride); + FilterLoop24(ref p, stride, 1, 16, thresh, ithresh, hevThresh); } } } - public static void HFilter16i(Span p, int offset, int stride, int thresh, int ithresh, int hevThresh) + /// + /// Applies the normal loop filter to the three inner vertical edges of a 16x16 macroblock, at columns 4, 8 and 12. + /// The filter reads 4 samples and changes up to 2 samples on each side of an edge. + /// + /// The first sample of the macroblock. + /// The distance between two rows. + /// The edge limit. A position gets the filter when 2 * |p0 - q0| + |p1 - q1| / 2 is at most this value. + /// The interior limit. A position gets the filter when no difference between adjacent samples on one side is larger. + /// + /// The high edge variance threshold. When |p1 - p0| or |q1 - q0| is larger, the filter changes only the sample on each side next to the edge. + /// + public static void HFilter16i(ref byte p, nuint stride, int thresh, int ithresh, int hevThresh) { if (Vector128.IsHardwareAccelerated) { - ref byte pRef = ref MemoryMarshal.GetReference(p); - Load16x4Vector128( - ref Unsafe.Add(ref pRef, (uint)offset), - ref Unsafe.Add(ref pRef, (uint)(offset + (8 * stride))), + // Columns 0 to 3 are p3 to p0 of the first inner edge. + Load16x4( + ref p, + ref Unsafe.Add(ref p, 8 * stride), stride, out Vector128 p3, out Vector128 p2, out Vector128 p1, out Vector128 p0); - Vector128 mask; for (int k = 3; k > 0; k--) { - // Beginning of p1. - ref byte bRef = ref Unsafe.Add(ref pRef, (uint)offset + 2); - - // Beginning of q0 (and next span). - offset += 4; + // b is the column of p1. p moves to the next edge, the column of q0. + ref byte b = ref Unsafe.Add(ref p, (nuint)2); + p = ref Unsafe.Add(ref p, (nuint)4); - // Compute partial mask. - mask = AbsVector128(p1, p0); - mask = Vector128.Max(mask, AbsVector128(p3, p2)); - mask = Vector128.Max(mask, AbsVector128(p2, p1)); + Vector128 mask = AbsoluteDifference(p1, p0); + mask = Vector128.Max(mask, AbsoluteDifference(p3, p2)); + mask = Vector128.Max(mask, AbsoluteDifference(p2, p1)); - Load16x4Vector128( - ref Unsafe.Add(ref pRef, (uint)offset), - ref Unsafe.Add(ref pRef, (uint)(offset + (8 * stride))), - stride, - out p3, - out p2, - out Vector128 tmp1, - out Vector128 tmp2); + Load16x4(ref p, ref Unsafe.Add(ref p, 8 * stride), stride, out p3, out p2, out Vector128 tmp1, out Vector128 tmp2); - mask = Vector128.Max(mask, AbsVector128(tmp1, tmp2)); - mask = Vector128.Max(mask, AbsVector128(p3, p2)); - mask = Vector128.Max(mask, AbsVector128(p2, tmp1)); + mask = Vector128.Max(mask, AbsoluteDifference(tmp1, tmp2)); + mask = Vector128.Max(mask, AbsoluteDifference(p3, p2)); + mask = Vector128.Max(mask, AbsoluteDifference(p2, tmp1)); - ComplexMaskVector128(p1, p0, p3, p2, thresh, ithresh, ref mask); - DoFilter4Vector128(ref p1, ref p0, ref p3, ref p2, mask, hevThresh); + // p3 and p2 hold q0 and q1 of this edge. After the filter, the columns q2 and q3 become p1 and p0 of the next edge. + ComplexMask(p1, p0, p3, p2, thresh, ithresh, ref mask); + DoFilter4(ref p1, ref p0, ref p3, ref p2, mask, hevThresh); - Store16x4Vector128(p1, p0, p3, p2, ref bRef, ref Unsafe.Add(ref bRef, 8 * (uint)stride), stride); + Store16x4(p1, p0, p3, p2, ref b, ref Unsafe.Add(ref b, 8 * stride), stride); - // Rotate samples. p1 = tmp1; p0 = tmp2; } @@ -1639,209 +2130,231 @@ ref Unsafe.Add(ref pRef, (uint)(offset + (8 * stride))), { for (int k = 3; k > 0; k--) { - offset += 4; - FilterLoop24(p, offset, 1, stride, 16, thresh, ithresh, hevThresh); + p = ref Unsafe.Add(ref p, (nuint)4); + FilterLoop24(ref p, 1, stride, 16, thresh, ithresh, hevThresh); } } } - // 8-pixels wide variant, for chroma filtering. + /// + /// Applies the normal loop filter to the 8 positions of a horizontal macroblock edge in the U block and in the V block. + /// The filter reads 4 samples and changes up to 3 samples on each side of the edge. + /// + /// The first U sample below the edge. + /// The first V sample below the edge. + /// The distance between two rows, in both planes. + /// The edge limit. A position gets the filter when 2 * |p0 - q0| + |p1 - q1| / 2 is at most this value. + /// The interior limit. A position gets the filter when no difference between adjacent samples on one side is larger. + /// + /// The high edge variance threshold. When |p1 - p0| or |q1 - q0| is larger, the filter changes only the sample on each side next to the edge. + /// [MethodImpl(InliningOptions.ShortMethod)] - public static void VFilter8(Span u, Span v, int offset, int stride, int thresh, int ithresh, int hevThresh) + public static void VFilter8(ref byte u, ref byte v, nuint stride, int thresh, int ithresh, int hevThresh) { if (Vector128.IsHardwareAccelerated) { - // Load uv h-edges. - ref byte uRef = ref MemoryMarshal.GetReference(u); - ref byte vRef = ref MemoryMarshal.GetReference(v); - Vector128 t1 = LoadUvEdgeVector128(ref uRef, ref vRef, offset - (4 * stride)); - Vector128 p2 = LoadUvEdgeVector128(ref uRef, ref vRef, offset - (3 * stride)); - Vector128 p1 = LoadUvEdgeVector128(ref uRef, ref vRef, offset - (2 * stride)); - Vector128 p0 = LoadUvEdgeVector128(ref uRef, ref vRef, offset - stride); - - Vector128 mask = AbsVector128(p1, p0); - mask = Vector128.Max(mask, AbsVector128(t1, p2)); - mask = Vector128.Max(mask, AbsVector128(p2, p1)); - - Vector128 q0 = LoadUvEdgeVector128(ref uRef, ref vRef, offset); - Vector128 q1 = LoadUvEdgeVector128(ref uRef, ref vRef, offset + stride); - Vector128 q2 = LoadUvEdgeVector128(ref uRef, ref vRef, offset + (2 * stride)); - t1 = LoadUvEdgeVector128(ref uRef, ref vRef, offset + (3 * stride)); - - mask = Vector128.Max(mask, AbsVector128(q1, q0)); - mask = Vector128.Max(mask, AbsVector128(t1, q2)); - mask = Vector128.Max(mask, AbsVector128(q2, q1)); - - ComplexMaskVector128(p1, p0, q0, q1, thresh, ithresh, ref mask); - DoFilter6Vector128(ref p2, ref p1, ref p0, ref q0, ref q1, ref q2, mask, hevThresh); - - // Store. - StoreUvVector128(p2, ref uRef, ref vRef, offset - (3 * stride)); - StoreUvVector128(p1, ref uRef, ref vRef, offset - (2 * stride)); - StoreUvVector128(p0, ref uRef, ref vRef, offset - stride); - StoreUvVector128(q0, ref uRef, ref vRef, offset); - StoreUvVector128(q1, ref uRef, ref vRef, offset + (1 * stride)); - StoreUvVector128(q2, ref uRef, ref vRef, offset + (2 * stride)); + // Each vector holds one U row in bytes 0 to 7 and the V row in bytes 8 to 15. The rows p3 to p0 start 4 rows above the edge. + ref byte uTop = ref Unsafe.Subtract(ref u, 4 * stride); + ref byte vTop = ref Unsafe.Subtract(ref v, 4 * stride); + Vector128 t1 = LoadUvEdge(ref uTop, ref vTop, 0); + Vector128 p2 = LoadUvEdge(ref uTop, ref vTop, stride); + Vector128 p1 = LoadUvEdge(ref uTop, ref vTop, 2 * stride); + Vector128 p0 = LoadUvEdge(ref uTop, ref vTop, 3 * stride); + + Vector128 mask = AbsoluteDifference(p1, p0); + mask = Vector128.Max(mask, AbsoluteDifference(t1, p2)); + mask = Vector128.Max(mask, AbsoluteDifference(p2, p1)); + + Vector128 q0 = LoadUvEdge(ref u, ref v, 0); + Vector128 q1 = LoadUvEdge(ref u, ref v, stride); + Vector128 q2 = LoadUvEdge(ref u, ref v, 2 * stride); + t1 = LoadUvEdge(ref u, ref v, 3 * stride); + + mask = Vector128.Max(mask, AbsoluteDifference(q1, q0)); + mask = Vector128.Max(mask, AbsoluteDifference(t1, q2)); + mask = Vector128.Max(mask, AbsoluteDifference(q2, q1)); + + ComplexMask(p1, p0, q0, q1, thresh, ithresh, ref mask); + DoFilter6(ref p2, ref p1, ref p0, ref q0, ref q1, ref q2, mask, hevThresh); + + // The filter does not change p3 and q3. + StoreUv(p2, ref uTop, ref vTop, stride); + StoreUv(p1, ref uTop, ref vTop, 2 * stride); + StoreUv(p0, ref uTop, ref vTop, 3 * stride); + StoreUv(q0, ref u, ref v, 0); + StoreUv(q1, ref u, ref v, stride); + StoreUv(q2, ref u, ref v, 2 * stride); } else { - FilterLoop26(u, offset, stride, 1, 8, thresh, ithresh, hevThresh); - FilterLoop26(v, offset, stride, 1, 8, thresh, ithresh, hevThresh); + FilterLoop26(ref u, stride, 1, 8, thresh, ithresh, hevThresh); + FilterLoop26(ref v, stride, 1, 8, thresh, ithresh, hevThresh); } } + /// + /// Applies the normal loop filter to the 8 positions of a vertical macroblock edge in the U block and in the V block. + /// The filter reads 4 samples and changes up to 3 samples on each side of the edge. + /// + /// The first U sample right of the edge, in the top row. + /// The first V sample right of the edge, in the top row. + /// The distance between two rows, in both planes. + /// The edge limit. A position gets the filter when 2 * |p0 - q0| + |p1 - q1| / 2 is at most this value. + /// The interior limit. A position gets the filter when no difference between adjacent samples on one side is larger. + /// + /// The high edge variance threshold. When |p1 - p0| or |q1 - q0| is larger, the filter changes only the sample on each side next to the edge. + /// [MethodImpl(InliningOptions.ShortMethod)] - public static void HFilter8(Span u, Span v, int offset, int stride, int thresh, int ithresh, int hevThresh) + public static void HFilter8(ref byte u, ref byte v, nuint stride, int thresh, int ithresh, int hevThresh) { if (Vector128.IsHardwareAccelerated) { - ref byte uRef = ref MemoryMarshal.GetReference(u); - ref byte vRef = ref MemoryMarshal.GetReference(v); - Load16x4Vector128( - ref Unsafe.Add(ref uRef, (uint)offset - 4), - ref Unsafe.Add(ref vRef, (uint)offset - 4), - stride, - out Vector128 p3, - out Vector128 p2, - out Vector128 p1, - out Vector128 p0); + // The transposes read the 8 U rows to byte lanes 0 to 7 and the 8 V rows to byte lanes 8 to 15. The columns p3 to p0 start 4 samples + // left of the edge. + ref byte uLeft = ref Unsafe.Subtract(ref u, (nuint)4); + ref byte vLeft = ref Unsafe.Subtract(ref v, (nuint)4); + Load16x4(ref uLeft, ref vLeft, stride, out Vector128 p3, out Vector128 p2, out Vector128 p1, out Vector128 p0); - Vector128 mask = AbsVector128(p1, p0); - mask = Vector128.Max(mask, AbsVector128(p3, p2)); - mask = Vector128.Max(mask, AbsVector128(p2, p1)); + Vector128 mask = AbsoluteDifference(p1, p0); + mask = Vector128.Max(mask, AbsoluteDifference(p3, p2)); + mask = Vector128.Max(mask, AbsoluteDifference(p2, p1)); - Load16x4Vector128( - ref Unsafe.Add(ref uRef, (uint)offset), - ref Unsafe.Add(ref vRef, (uint)offset), - stride, - out Vector128 q0, - out Vector128 q1, - out Vector128 q2, - out Vector128 q3); + Load16x4(ref u, ref v, stride, out Vector128 q0, out Vector128 q1, out Vector128 q2, out Vector128 q3); - mask = Vector128.Max(mask, AbsVector128(q1, q0)); - mask = Vector128.Max(mask, AbsVector128(q3, q2)); - mask = Vector128.Max(mask, AbsVector128(q2, q1)); + mask = Vector128.Max(mask, AbsoluteDifference(q1, q0)); + mask = Vector128.Max(mask, AbsoluteDifference(q3, q2)); + mask = Vector128.Max(mask, AbsoluteDifference(q2, q1)); - ComplexMaskVector128(p1, p0, q0, q1, thresh, ithresh, ref mask); - DoFilter6Vector128(ref p2, ref p1, ref p0, ref q0, ref q1, ref q2, mask, hevThresh); + ComplexMask(p1, p0, q0, q1, thresh, ithresh, ref mask); + DoFilter6(ref p2, ref p1, ref p0, ref q0, ref q1, ref q2, mask, hevThresh); - Store16x4Vector128(p3, p2, p1, p0, ref Unsafe.Add(ref uRef, (uint)offset - 4), ref Unsafe.Add(ref vRef, (uint)offset - 4), stride); - Store16x4Vector128(q0, q1, q2, q3, ref Unsafe.Add(ref uRef, (uint)offset), ref Unsafe.Add(ref vRef, (uint)offset), stride); + Store16x4(p3, p2, p1, p0, ref uLeft, ref vLeft, stride); + Store16x4(q0, q1, q2, q3, ref u, ref v, stride); } else { - FilterLoop26(u, offset, 1, stride, 8, thresh, ithresh, hevThresh); - FilterLoop26(v, offset, 1, stride, 8, thresh, ithresh, hevThresh); + FilterLoop26(ref u, 1, stride, 8, thresh, ithresh, hevThresh); + FilterLoop26(ref v, 1, stride, 8, thresh, ithresh, hevThresh); } } + /// + /// Applies the normal loop filter to the inner horizontal edge, at row 4, of the 8x8 U block and the 8x8 V block. + /// The filter reads 4 samples and changes up to 2 samples on each side of the edge. + /// + /// The first U sample of the block. + /// The first V sample of the block. + /// The distance between two rows, in both planes. + /// The edge limit. A position gets the filter when 2 * |p0 - q0| + |p1 - q1| / 2 is at most this value. + /// The interior limit. A position gets the filter when no difference between adjacent samples on one side is larger. + /// + /// The high edge variance threshold. When |p1 - p0| or |q1 - q0| is larger, the filter changes only the sample on each side next to the edge. + /// [MethodImpl(InliningOptions.ShortMethod)] - public static void VFilter8i(Span u, Span v, int offset, int stride, int thresh, int ithresh, int hevThresh) + public static void VFilter8i(ref byte u, ref byte v, nuint stride, int thresh, int ithresh, int hevThresh) { + // The inner edge is 4 rows below the first row. + ref byte uEdge = ref Unsafe.Add(ref u, 4 * stride); + ref byte vEdge = ref Unsafe.Add(ref v, 4 * stride); if (Vector128.IsHardwareAccelerated) { - // Load uv h-edges. - ref byte uRef = ref MemoryMarshal.GetReference(u); - ref byte vRef = ref MemoryMarshal.GetReference(v); - Vector128 t2 = LoadUvEdgeVector128(ref uRef, ref vRef, offset); - Vector128 t1 = LoadUvEdgeVector128(ref uRef, ref vRef, offset + stride); - Vector128 p1 = LoadUvEdgeVector128(ref uRef, ref vRef, offset + (stride * 2)); - Vector128 p0 = LoadUvEdgeVector128(ref uRef, ref vRef, offset + (stride * 3)); + // Each vector holds one U row in bytes 0 to 7 and the V row in bytes 8 to 15. Rows 0 to 3 are p3 to p0. + Vector128 t2 = LoadUvEdge(ref u, ref v, 0); + Vector128 t1 = LoadUvEdge(ref u, ref v, stride); + Vector128 p1 = LoadUvEdge(ref u, ref v, 2 * stride); + Vector128 p0 = LoadUvEdge(ref u, ref v, 3 * stride); - Vector128 mask = AbsVector128(p1, p0); - mask = Vector128.Max(mask, AbsVector128(t2, t1)); - mask = Vector128.Max(mask, AbsVector128(t1, p1)); + Vector128 mask = AbsoluteDifference(p1, p0); + mask = Vector128.Max(mask, AbsoluteDifference(t2, t1)); + mask = Vector128.Max(mask, AbsoluteDifference(t1, p1)); - offset += 4 * stride; + Vector128 q0 = LoadUvEdge(ref uEdge, ref vEdge, 0); + Vector128 q1 = LoadUvEdge(ref uEdge, ref vEdge, stride); + t1 = LoadUvEdge(ref uEdge, ref vEdge, 2 * stride); + t2 = LoadUvEdge(ref uEdge, ref vEdge, 3 * stride); - Vector128 q0 = LoadUvEdgeVector128(ref uRef, ref vRef, offset); - Vector128 q1 = LoadUvEdgeVector128(ref uRef, ref vRef, offset + stride); - t1 = LoadUvEdgeVector128(ref uRef, ref vRef, offset + (stride * 2)); - t2 = LoadUvEdgeVector128(ref uRef, ref vRef, offset + (stride * 3)); + mask = Vector128.Max(mask, AbsoluteDifference(q1, q0)); + mask = Vector128.Max(mask, AbsoluteDifference(t2, t1)); + mask = Vector128.Max(mask, AbsoluteDifference(t1, q1)); - mask = Vector128.Max(mask, AbsVector128(q1, q0)); - mask = Vector128.Max(mask, AbsVector128(t2, t1)); - mask = Vector128.Max(mask, AbsVector128(t1, q1)); + ComplexMask(p1, p0, q0, q1, thresh, ithresh, ref mask); + DoFilter4(ref p1, ref p0, ref q0, ref q1, mask, hevThresh); - ComplexMaskVector128(p1, p0, q0, q1, thresh, ithresh, ref mask); - DoFilter4Vector128(ref p1, ref p0, ref q0, ref q1, mask, hevThresh); - - // Store. - StoreUvVector128(p1, ref uRef, ref vRef, offset + (-2 * stride)); - StoreUvVector128(p0, ref uRef, ref vRef, offset + (-1 * stride)); - StoreUvVector128(q0, ref uRef, ref vRef, offset); - StoreUvVector128(q1, ref uRef, ref vRef, offset + stride); + StoreUv(p1, ref u, ref v, 2 * stride); + StoreUv(p0, ref u, ref v, 3 * stride); + StoreUv(q0, ref uEdge, ref vEdge, 0); + StoreUv(q1, ref uEdge, ref vEdge, stride); } else { - int offset4mulstride = offset + (4 * stride); - FilterLoop24(u, offset4mulstride, stride, 1, 8, thresh, ithresh, hevThresh); - FilterLoop24(v, offset4mulstride, stride, 1, 8, thresh, ithresh, hevThresh); + FilterLoop24(ref uEdge, stride, 1, 8, thresh, ithresh, hevThresh); + FilterLoop24(ref vEdge, stride, 1, 8, thresh, ithresh, hevThresh); } } + /// + /// Applies the normal loop filter to the inner vertical edge, at column 4, of the 8x8 U block and the 8x8 V block. + /// The filter reads 4 samples and changes up to 2 samples on each side of the edge. + /// + /// The first U sample of the block. + /// The first V sample of the block. + /// The distance between two rows, in both planes. + /// The edge limit. A position gets the filter when 2 * |p0 - q0| + |p1 - q1| / 2 is at most this value. + /// The interior limit. A position gets the filter when no difference between adjacent samples on one side is larger. + /// + /// The high edge variance threshold. When |p1 - p0| or |q1 - q0| is larger, the filter changes only the sample on each side next to the edge. + /// [MethodImpl(InliningOptions.ShortMethod)] - public static void HFilter8i(Span u, Span v, int offset, int stride, int thresh, int ithresh, int hevThresh) + public static void HFilter8i(ref byte u, ref byte v, nuint stride, int thresh, int ithresh, int hevThresh) { + // The inner edge is 4 columns right of the first column. + ref byte uEdge = ref Unsafe.Add(ref u, (nuint)4); + ref byte vEdge = ref Unsafe.Add(ref v, (nuint)4); if (Vector128.IsHardwareAccelerated) { - ref byte uRef = ref MemoryMarshal.GetReference(u); - ref byte vRef = ref MemoryMarshal.GetReference(v); - Load16x4Vector128( - ref Unsafe.Add(ref uRef, (uint)offset), - ref Unsafe.Add(ref vRef, (uint)offset), - stride, - out Vector128 t2, - out Vector128 t1, - out Vector128 p1, - out Vector128 p0); + // The transposes read the 8 U rows to byte lanes 0 to 7 and the 8 V rows to byte lanes 8 to 15. Columns 0 to 3 are p3 to p0. + Load16x4(ref u, ref v, stride, out Vector128 t2, out Vector128 t1, out Vector128 p1, out Vector128 p0); - Vector128 mask = AbsVector128(p1, p0); - mask = Vector128.Max(mask, AbsVector128(t2, t1)); - mask = Vector128.Max(mask, AbsVector128(t1, p1)); + Vector128 mask = AbsoluteDifference(p1, p0); + mask = Vector128.Max(mask, AbsoluteDifference(t2, t1)); + mask = Vector128.Max(mask, AbsoluteDifference(t1, p1)); - // Beginning of q0. - offset += 4; - - Load16x4Vector128( - ref Unsafe.Add(ref uRef, (uint)offset), - ref Unsafe.Add(ref vRef, (uint)offset), - stride, - out Vector128 q0, - out Vector128 q1, - out t1, - out t2); + Load16x4(ref uEdge, ref vEdge, stride, out Vector128 q0, out Vector128 q1, out t1, out t2); - mask = Vector128.Max(mask, AbsVector128(q1, q0)); - mask = Vector128.Max(mask, AbsVector128(t2, t1)); - mask = Vector128.Max(mask, AbsVector128(t1, q1)); + mask = Vector128.Max(mask, AbsoluteDifference(q1, q0)); + mask = Vector128.Max(mask, AbsoluteDifference(t2, t1)); + mask = Vector128.Max(mask, AbsoluteDifference(t1, q1)); - ComplexMaskVector128(p1, p0, q0, q1, thresh, ithresh, ref mask); - DoFilter4Vector128(ref p1, ref p0, ref q0, ref q1, mask, hevThresh); + ComplexMask(p1, p0, q0, q1, thresh, ithresh, ref mask); + DoFilter4(ref p1, ref p0, ref q0, ref q1, mask, hevThresh); - // Beginning of p1. - offset -= 2; - Store16x4Vector128(p1, p0, q0, q1, ref Unsafe.Add(ref uRef, (uint)offset), ref Unsafe.Add(ref vRef, (uint)offset), stride); + // The changed columns p1, p0, q0 and q1 start 2 columns right of the first column. + Store16x4(p1, p0, q0, q1, ref Unsafe.Add(ref u, (nuint)2), ref Unsafe.Add(ref v, (nuint)2), stride); } else { - int offsetPlus4 = offset + 4; - FilterLoop24(u, offsetPlus4, 1, stride, 8, thresh, ithresh, hevThresh); - FilterLoop24(v, offsetPlus4, 1, stride, 8, thresh, ithresh, hevThresh); + FilterLoop24(ref uEdge, 1, stride, 8, thresh, ithresh, hevThresh); + FilterLoop24(ref vEdge, 1, stride, 8, thresh, ithresh, hevThresh); } } + /// + /// Computes the sum of the 16 samples of each of the four 4x4 blocks in a 16x4 area. + /// + /// The first sample of the area. + /// The four sums, from the left block to the right block. public static void Mean16x4(Span input, Span dc) { if (Vector128.IsHardwareAccelerated) { Vector128 mean16x4Mask = Vector128.Create((short)0x00ff).AsByte(); - Vector128 a0 = Unsafe.As>(ref MemoryMarshal.GetReference(input)); - Vector128 a1 = Unsafe.As>(ref MemoryMarshal.GetReference(input.Slice(WebpConstants.Bps, 16))); - Vector128 a2 = Unsafe.As>(ref MemoryMarshal.GetReference(input.Slice(WebpConstants.Bps * 2, 16))); - Vector128 a3 = Unsafe.As>(ref MemoryMarshal.GetReference(input.Slice(WebpConstants.Bps * 3, 16))); + // Each 16-byte row of the area is one load. The rows are WebpConstants.Bps bytes apart, so wider vectors cannot load more of the area. + ref byte inputRef = ref MemoryMarshal.GetReference(input); + Vector128 a0 = Vector128.LoadUnsafe(ref inputRef); + Vector128 a1 = Vector128.LoadUnsafe(ref inputRef, (nuint)WebpConstants.Bps); + Vector128 a2 = Vector128.LoadUnsafe(ref inputRef, (nuint)(WebpConstants.Bps * 2)); + Vector128 a3 = Vector128.LoadUnsafe(ref inputRef, (nuint)(WebpConstants.Bps * 3)); Vector128 b0 = Vector128.ShiftRightLogical(a0.AsInt16(), 8); // hi byte Vector128 b1 = Vector128.ShiftRightLogical(a1.AsInt16(), 8); Vector128 b2 = Vector128.ShiftRightLogical(a2.AsInt16(), 8); @@ -1860,8 +2373,7 @@ public static void Mean16x4(Span input, Span dc) Vector128 hadd = Vector128_.HorizontalAdd(f0.AsInt16(), f0.AsInt16()); Vector128 wide = Vector128_.UnpackLow(hadd, Vector128.Zero).AsUInt32(); - ref uint outputRef = ref MemoryMarshal.GetReference(dc); - Unsafe.As>(ref outputRef) = wide; + wide.StoreUnsafe(ref MemoryMarshal.GetReference(dc)); } else { @@ -1882,94 +2394,301 @@ public static void Mean16x4(Span input, Span dc) } } + /// + /// Computes the rounded mean of two samples: (a + b + 1) / 2, rounded down. + /// + /// The first sample. + /// The second sample. + /// The mean. [MethodImpl(InliningOptions.ShortMethod)] public static byte Avg2(byte a, byte b) => (byte)((a + b + 1) >> 1); + /// + /// Computes the smoothed value of three adjacent samples: (a + 2b + c + 2) / 4, rounded down. + /// + /// The first sample. + /// The center sample. + /// The last sample. + /// The smoothed sample. [MethodImpl(InliningOptions.ShortMethod)] public static byte Avg3(byte a, byte b, byte c) => (byte)((a + (2 * b) + c + 2) >> 2); + /// + /// Writes one sample of a block. + /// + /// The first sample of the block. + /// The column. + /// The row. + /// The sample. [MethodImpl(InliningOptions.ShortMethod)] public static void Dst(Span dst, int x, int y, byte v) => dst[x + (y * WebpConstants.Bps)] = v; - [MethodImpl(InliningOptions.ShortMethod)] - public static byte Clip8B(int v) => (byte)((v & ~0xff) == 0 ? v : v < 0 ? 0 : 255); - - // Cost of coding one event with probability 'proba'. + /// + /// Gets the cost of coding one bit with the boolean entropy coder. + /// + /// The bit: 0 or not 0. + /// The probability of a zero bit, in units of 1 / 256. + /// The cost in units of 1 / 256 bit. public static int Vp8BitCost(int bit, byte proba) => bit == 0 ? WebpLookupTables.Vp8EntropyCost[proba] : WebpLookupTables.Vp8EntropyCost[255 - proba]; /// - /// Reduces elements of the vector into one sum. + /// Writes one sample of a 4x4 block. + /// + /// The first sample of the block. + /// The column. + /// The row. + /// The sample. + [MethodImpl(InliningOptions.ShortMethod)] + private static void Dst(ref byte dst, int x, int y, byte v) => Unsafe.Add(ref dst, (uint)(x + (y * WebpConstants.Bps))) = v; + + /// + /// Reads the left sample of a row of a block. /// - /// The accumulator to reduce. - /// The sum of all elements. + /// The first sample of the block. + /// The row. + /// The sample before the row. [MethodImpl(InliningOptions.ShortMethod)] - public static int ReduceSumVector256(Vector256 accumulator) + private static byte Left(ref byte dst, int y) => Unsafe.Add(ref Unsafe.Subtract(ref dst, (nuint)1), (uint)(y * WebpConstants.Bps)); + + /// + /// Sums the left samples of the first rows of a block. + /// + /// + /// The left samples are one column with bytes between them. A vector load cannot read a column, so the sum + /// stays scalar. + /// + /// The first sample of the block. + /// The number of rows. + /// The sum. + private static int SumLeft(ref byte dst, int count) { - // Add upper lane to lower lane. - Vector128 vsum = accumulator.GetLower() + accumulator.GetUpper(); + int sum = 0; + for (int y = 0; y < count; y++) + { + sum += Left(ref dst, y); + } + + return sum; + } - // Add odd to even. - vsum += Vector128_.ShuffleNative(vsum, 0b_11_11_01_01); + /// + /// Sums the 16 top samples of a block. + /// + /// The first sample of the block. + /// The sum. + private static int SumTop16(ref byte dst) + { + ref byte top = ref Unsafe.Subtract(ref dst, (nuint)WebpConstants.Bps); + if (Vector128.IsHardwareAccelerated) + { + // The sum of the absolute differences from zero is the sum of the samples. Only the total over the lanes is defined. + return (int)Vector128.Sum(Vector128_.SumAbsoluteDifferences(Vector128.LoadUnsafe(ref top), Vector128.Zero, Vector128.Zero)); + } - // Add high to low. - vsum += Vector128_.ShuffleNative(vsum, 0b_11_10_11_10); + int sum = 0; + for (nuint x = 0; x < 16; x++) + { + sum += Unsafe.Add(ref top, x); + } - return vsum.ToScalar(); + return sum; } /// - /// Reduces elements of the vector into one sum. + /// Sums the 8 top samples of a block. /// - /// The accumulator to reduce. - /// The sum of all elements. - [MethodImpl(InliningOptions.ShortMethod)] - private static int ReduceSumVector128(Vector128 accumulator) + /// The first sample of the block. + /// The sum. + private static int SumTop8(ref byte dst) { - // Add odd to even. - Vector128 vsum = accumulator + Vector128_.ShuffleNative(accumulator, 0b_11_11_01_01); + ref byte top = ref Unsafe.Subtract(ref dst, (nuint)WebpConstants.Bps); + if (Vector128.IsHardwareAccelerated) + { + // The sum of the absolute differences of bytes 0 to 7 from zero is the sum of the 8 samples. + return (int)Vector128_.SumAbsoluteDifferencesLow(Load8(ref top), Vector128.Zero).ToScalar(); + } + + int sum = 0; + for (nuint x = 0; x < 8; x++) + { + sum += Unsafe.Add(ref top, x); + } + + return sum; + } - // Add high to low. - vsum += Vector128_.ShuffleNative(vsum, 0b_11_10_11_10); + /// + /// Fills the 16 rows of a 16x16 block with one value. + /// + /// The first sample of the block. + /// The value. + private static void Fill16(ref byte dst, byte value) + { + for (nuint y = 0; y < 16; y++) + { + FillRow16(ref Unsafe.Add(ref dst, y * WebpConstants.Bps), value); + } + } - return vsum.ToScalar(); + /// + /// Fills the 8 rows of an 8x8 block with one value. + /// + /// The first sample of the block. + /// The value. + private static void Fill8(ref byte dst, byte value) + { + ulong row = 0x0101010101010101UL * value; + for (nuint y = 0; y < 8; y++) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, y * WebpConstants.Bps), row); + } } + /// + /// Fills the first 16 samples of a row with one value. + /// + /// The first sample of the row. + /// The value. [MethodImpl(InliningOptions.ShortMethod)] - private static void Put16(int v, Span dst) + private static void FillRow16(ref byte row, byte value) { - for (int j = 0; j < 16; j++) + if (Vector128.IsHardwareAccelerated) { - Memset(dst[(j * WebpConstants.Bps)..], (byte)v, 0, 16); + Vector128.Create(value).StoreUnsafe(ref row); + return; } + + ulong values = 0x0101010101010101UL * value; + Unsafe.WriteUnaligned(ref row, values); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref row, (nuint)8), values); + } + + /// + /// Writes one 4-sample row value to each row of a 4x4 block. + /// + /// The first sample of the block. + /// The 4 samples, in memory order. + [MethodImpl(InliningOptions.ShortMethod)] + private static void Store4Rows(ref byte dst, uint row) + { + Unsafe.WriteUnaligned(ref dst, row); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, (nuint)WebpConstants.Bps), row); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, (nuint)(2 * WebpConstants.Bps)), row); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, (nuint)(3 * WebpConstants.Bps)), row); } - private static void TrueMotion(Span dst, Span yuv, int offset, int size) + /// + /// Writes byte lanes 0 to 3 to a row of a 4x4 block. + /// + /// The first sample of the block. + /// The row. + /// The samples in lanes 0 to 3. + [MethodImpl(InliningOptions.ShortMethod)] + private static void StoreRow(ref byte dst, int y, Vector128 samples) + => Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, (uint)(y * WebpConstants.Bps)), samples.AsUInt32().ToScalar()); + + /// + /// Loads 8 samples to byte lanes 0 to 7. The other lanes are 0. + /// + /// The first sample. + /// The samples. + [MethodImpl(InliningOptions.ShortMethod)] + private static Vector128 Load8(ref byte source) => Vector128.CreateScalar(Unsafe.ReadUnaligned(ref source)).AsByte(); + + /// + /// Computes Avg3 in each byte lane: (a + 2b + c + 2) / 4, rounded down. + /// + /// + /// gives (a + c + 1) / 2. The low bit of a ^ c is 1 when a + c is odd, so the + /// subtraction gives (a + c) / 2, rounded down. The second average gives ((a + c) / 2 + b + 1) / 2, which is (a + 2b + c + 2) / 4 for each a, b, c. + /// + /// The first samples. + /// The center samples. + /// The last samples. + /// The smoothed samples. + [MethodImpl(InliningOptions.ShortMethod)] + private static Vector128 Average3(Vector128 a, Vector128 b, Vector128 c) { - // For information about how true motion works, see rfc6386, page 52. ff and section 20.14. - int topOffset = offset - WebpConstants.Bps; - Span top = yuv[topOffset..]; - byte p = yuv[topOffset - 1]; - int leftOffset = offset - 1; - byte left = yuv[leftOffset]; - for (int y = 0; y < size; y++) + Vector128 ac = Vector128_.Average(a, c) - ((a ^ c) & Vector128.One); + return Vector128_.Average(ac, b); + } + + /// + /// Predicts a block with the TrueMotion mode: each sample is clamp(left + top - topLeft). See RFC 6386, section 12.2. + /// + /// + /// The top row widens to 16-bit lanes. Each row adds left - topLeft to it, and the unsigned saturating pack gives the clamp to [0, 255]. + /// + /// The first sample of the block. + /// The block size: 4, 8 or 16. + private static void TrueMotion(ref byte dst, int size) + { + ref byte top = ref Unsafe.Subtract(ref dst, (nuint)WebpConstants.Bps); + int topLeft = Unsafe.Subtract(ref top, (nuint)1); + if (Vector128.IsHardwareAccelerated) { - for (int x = 0; x < size; x++) + if (size == 16) + { + (Vector128 low, Vector128 high) = Vector128.Widen(Vector128.LoadUnsafe(ref top)); + for (nuint y = 0; y < 16; y++) + { + ref byte row = ref Unsafe.Add(ref dst, y * WebpConstants.Bps); + Vector128 delta = Vector128.Create((short)(Unsafe.Subtract(ref row, (nuint)1) - topLeft)); + Vector128_.PackUnsignedSaturate(low.AsInt16() + delta, high.AsInt16() + delta).StoreUnsafe(ref row); + } + + return; + } + + // Sizes 4 and 8 use the low 8 lanes. The store writes the first size samples of each row. + Vector128 topRow = Vector128.WidenLower(Load8(ref top)).AsInt16(); + for (nuint y = 0; y < (uint)size; y++) { - dst[x] = (byte)Clamp255(left + top[x] - p); + ref byte row = ref Unsafe.Add(ref dst, y * WebpConstants.Bps); + Vector128 delta = Vector128.Create((short)(Unsafe.Subtract(ref row, (nuint)1) - topLeft)); + Vector128 samples = Vector128_.PackUnsignedSaturate(topRow + delta, topRow + delta); + if (size == 8) + { + Unsafe.WriteUnaligned(ref row, samples.AsUInt64().ToScalar()); + } + else + { + Unsafe.WriteUnaligned(ref row, samples.AsUInt32().ToScalar()); + } } - leftOffset += WebpConstants.Bps; - left = yuv[leftOffset]; - dst = dst[WebpConstants.Bps..]; + return; + } + + for (nuint y = 0; y < (uint)size; y++) + { + ref byte row = ref Unsafe.Add(ref dst, y * WebpConstants.Bps); + int delta = Unsafe.Subtract(ref row, (nuint)1) - topLeft; + for (nuint x = 0; x < (uint)size; x++) + { + Unsafe.Add(ref row, x) = Numerics.ClampToByte(Unsafe.Add(ref top, x) + delta); + } } } - // Complex In-loop filtering (Paragraph 15.3) + /// + /// Applies the normal loop filter of an inner edge to positions along the edge. This is the scalar form. + /// A position with high edge variance gets the simple filter. Other positions get the filter that changes 2 samples on each side. + /// + /// + /// See RFC 6386, section 15.3. + /// + /// The first sample after the edge, at the first position. + /// The distance between two samples across the edge. + /// The distance between two positions along the edge. + /// The number of positions. + /// The edge limit. A position gets the filter when 2 * |p0 - q0| + |p1 - q1| / 2 is at most this value. + /// The interior limit. A position gets the filter when no difference between adjacent samples on one side is larger. + /// The high edge variance threshold for . private static void FilterLoop24( - Span p, - int offset, - int hStride, - int vStride, + ref byte p, + nuint hStride, + nuint vStride, int size, int thresh, int ithresh, @@ -1978,27 +2697,37 @@ private static void FilterLoop24( int thresh2 = (2 * thresh) + 1; while (size-- > 0) { - if (NeedsFilter2(p, offset, hStride, thresh2, ithresh)) + if (NeedsFilter2(ref p, hStride, thresh2, ithresh)) { - if (Hev(p, offset, hStride, hevThresh)) + if (Hev(ref p, hStride, hevThresh)) { - DoFilter2(p, offset, hStride); + DoFilter2(ref p, hStride); } else { - DoFilter4(p, offset, hStride); + DoFilter4(ref p, hStride); } } - offset += vStride; + p = ref Unsafe.Add(ref p, vStride); } } + /// + /// Applies the normal loop filter of a macroblock edge to positions along the edge. This is the scalar form. + /// A position with high edge variance gets the simple filter. Other positions get the filter that changes 3 samples on each side. + /// + /// The first sample after the edge, at the first position. + /// The distance between two samples across the edge. + /// The distance between two positions along the edge. + /// The number of positions. + /// The edge limit. A position gets the filter when 2 * |p0 - q0| + |p1 - q1| / 2 is at most this value. + /// The interior limit. A position gets the filter when no difference between adjacent samples on one side is larger. + /// The high edge variance threshold for . private static void FilterLoop26( - Span p, - int offset, - int hStride, - int vStride, + ref byte p, + nuint hStride, + nuint vStride, int size, int thresh, int ithresh, @@ -2007,65 +2736,89 @@ private static void FilterLoop26( int thresh2 = (2 * thresh) + 1; while (size-- > 0) { - if (NeedsFilter2(p, offset, hStride, thresh2, ithresh)) + if (NeedsFilter2(ref p, hStride, thresh2, ithresh)) { - if (Hev(p, offset, hStride, hevThresh)) + if (Hev(ref p, hStride, hevThresh)) { - DoFilter2(p, offset, hStride); + DoFilter2(ref p, hStride); } else { - DoFilter6(p, offset, hStride); + DoFilter6(ref p, hStride); } } - offset += vStride; + p = ref Unsafe.Add(ref p, vStride); } } - // Applies filter on 2 pixels (p0 and q0) - private static void DoFilter2(Span p, int offset, int step) + /// + /// Applies the simple filter to one position: a = 3 * (q0 - p0) + clamp(p1 - q1). p0 gets (a + 3) >> 3 added + /// and q0 gets (a + 4) >> 3 subtracted, with the clamps of the format. + /// + /// The sample q0, the first sample after the edge. + /// The distance between two samples across the edge. + private static void DoFilter2(ref byte p, nuint step) { // 4 pixels in, 2 pixels out. - int p1 = p[offset - (2 * step)]; - int p0 = p[offset - step]; - int q0 = p[offset]; - int q1 = p[offset + step]; + ref byte p0Ref = ref Unsafe.Subtract(ref p, step); + int p1 = Unsafe.Subtract(ref p0Ref, step); + int p0 = p0Ref; + int q0 = p; + int q1 = Unsafe.Add(ref p, step); int a = (3 * (q0 - p0)) + WebpLookupTables.Sclip1(p1 - q1); int a1 = WebpLookupTables.Sclip2((a + 4) >> 3); int a2 = WebpLookupTables.Sclip2((a + 3) >> 3); - p[offset - step] = WebpLookupTables.Clip1(p0 + a2); - p[offset] = WebpLookupTables.Clip1(q0 - a1); + p0Ref = WebpLookupTables.Clip1(p0 + a2); + p = WebpLookupTables.Clip1(q0 - a1); } - // Applies filter on 2 pixels (p0 and q0) - private static void DoFilter2Vector128(ref Vector128 p1, ref Vector128 p0, ref Vector128 q0, ref Vector128 q1, int thresh) + /// + /// Applies the simple filter to the 16 positions in the byte lanes. Only the lanes that pass the edge limit change. + /// + /// The second samples before the edge. + /// The samples before the edge. On return, the filtered samples. + /// The samples after the edge. On return, the filtered samples. + /// The second samples after the edge. + /// The edge limit. A lane gets the filter when 2 * |p0 - q0| + |p1 - q1| / 2 is at most this value. + [MethodImpl(InliningOptions.ShortMethod)] + private static void DoFilter2(ref Vector128 p1, ref Vector128 p0, ref Vector128 q0, ref Vector128 q1, int thresh) { Vector128 signBit = Vector128.Create((byte)0x80); // Convert p1/q1 to byte (for GetBaseDelta). Vector128 p1s = p1 ^ signBit; Vector128 q1s = q1 ^ signBit; - Vector128 mask = NeedsFilterVector128(p1, p0, q0, q1, thresh); + Vector128 mask = NeedsFilter(p1, p0, q0, q1, thresh); // Flip sign. p0 ^= signBit; q0 ^= signBit; - Vector128 a = GetBaseDeltaVector128(p1s.AsSByte(), p0.AsSByte(), q0.AsSByte(), q1s.AsSByte()).AsByte(); + Vector128 a = GetBaseDelta(p1s.AsSByte(), p0.AsSByte(), q0.AsSByte(), q1s.AsSByte()).AsByte(); // Mask filter values we don't care about. a &= mask; - DoSimpleFilterVector128(ref p0, ref q0, a); + DoSimpleFilter(ref p0, ref q0, a); // Flip sign. p0 ^= signBit; q0 ^= signBit; } - // Applies filter on 4 pixels (p1, p0, q0 and q1) - private static void DoFilter4Vector128( + /// + /// Applies the inner edge filter to the 16 positions in the byte lanes. Only the lanes set in change. + /// A lane with high edge variance changes p0 and q0, with the p1 - q1 term. Other lanes change p1, p0, q0 and q1, without that term. + /// + /// The second samples before the edge. On return, the filtered samples. + /// The samples before the edge. On return, the filtered samples. + /// The samples after the edge. On return, the filtered samples. + /// The second samples after the edge. On return, the filtered samples. + /// The lanes to filter: 0xFF to filter, 0 to keep. + /// The high edge variance threshold. + [MethodImpl(InliningOptions.ShortMethod)] + private static void DoFilter4( ref Vector128 p1, ref Vector128 p0, ref Vector128 q0, @@ -2074,7 +2827,7 @@ private static void DoFilter4Vector128( int tresh) { // Compute hev mask. - Vector128 notHev = GetNotHevVector128(ref p1, ref p0, ref q0, ref q1, tresh); + Vector128 notHev = GetNotHev(ref p1, ref p0, ref q0, ref q1, tresh); Vector128 signBit = Vector128.Create((byte)0x80); @@ -2094,8 +2847,8 @@ private static void DoFilter4Vector128( t2 = Vector128.AddSaturate(t1, Vector128.Create((byte)3).AsSByte()); // 3 * (q0 - p0) + hev(p1 - q1) + 3 Vector128 t3 = Vector128.AddSaturate(t1, Vector128.Create((byte)4).AsSByte()); // 3 * (q0 - p0) + hev(p1 - q1) + 4 - t2 = SignedShift8bVector128(t2.AsByte()); // (3 * (q0 - p0) + hev(p1 - q1) + 3) >> 3 - t3 = SignedShift8bVector128(t3.AsByte()); // (3 * (q0 - p0) + hev(p1 - q1) + 4) >> 3 + t2 = SignedShift8b(t2.AsByte()); // (3 * (q0 - p0) + hev(p1 - q1) + 3) >> 3 + t3 = SignedShift8b(t3.AsByte()); // (3 * (q0 - p0) + hev(p1 - q1) + 4) >> 3 p0 = Vector128.AddSaturate(p0.AsSByte(), t2).AsByte(); // p0 += t2 q0 = Vector128.SubtractSaturate(q0.AsSByte(), t3).AsByte(); // q0 -= t3 p0 ^= signBit; @@ -2113,8 +2866,20 @@ private static void DoFilter4Vector128( q1 = q1.AsByte() ^ signBit; } - // Applies filter on 6 pixels (p2, p1, p0, q0, q1 and q2) - private static void DoFilter6Vector128( + /// + /// Applies the macroblock edge filter to the 16 positions in the byte lanes. Only the lanes set in change. + /// A lane with high edge variance gets the simple filter on p0 and q0. Other lanes change p2 to q2 with the weights 27, 18 and 9. + /// + /// The third samples before the edge. On return, the filtered samples. + /// The second samples before the edge. On return, the filtered samples. + /// The samples before the edge. On return, the filtered samples. + /// The samples after the edge. On return, the filtered samples. + /// The second samples after the edge. On return, the filtered samples. + /// The third samples after the edge. On return, the filtered samples. + /// The lanes to filter: 0xFF to filter, 0 to keep. + /// The high edge variance threshold. + [MethodImpl(InliningOptions.ShortMethod)] + private static void DoFilter6( ref Vector128 p2, ref Vector128 p1, ref Vector128 p0, @@ -2125,7 +2890,7 @@ private static void DoFilter6Vector128( int tresh) { // Compute hev mask. - Vector128 notHev = GetNotHevVector128(ref p1, ref p0, ref q0, ref q1, tresh); + Vector128 notHev = GetNotHev(ref p1, ref p0, ref q0, ref q1, tresh); // Convert to signed values. Vector128 signBit = Vector128.Create((byte)0x80); @@ -2136,12 +2901,12 @@ private static void DoFilter6Vector128( p2 ^= signBit; q2 ^= signBit; - Vector128 a = GetBaseDeltaVector128(p1.AsSByte(), p0.AsSByte(), q0.AsSByte(), q1.AsSByte()); + Vector128 a = GetBaseDelta(p1.AsSByte(), p0.AsSByte(), q0.AsSByte(), q1.AsSByte()); // Do simple filter on pixels with hev. Vector128 m = ~notHev & mask; Vector128 f = a.AsByte() & m; - DoSimpleFilterVector128(ref p0, ref q0, f); + DoSimpleFilter(ref p0, ref q0, f); // Do strong filter on pixels with not hev. m = notHev & mask; @@ -2163,31 +2928,48 @@ private static void DoFilter6Vector128( Vector128 a0Low = a1Low + f9Low; // Filter * 27 + 63 Vector128 a0High = a1High + f9High; // Filter * 27 + 63 - Update2PixelsVector128(ref p2, ref q2, a2Low, a2High); - Update2PixelsVector128(ref p1, ref q1, a1Low, a1High); - Update2PixelsVector128(ref p0, ref q0, a0Low, a0High); + Update2Pixels(ref p2, ref q2, a2Low, a2High); + Update2Pixels(ref p1, ref q1, a1Low, a1High); + Update2Pixels(ref p0, ref q0, a0Low, a0High); } - private static void DoSimpleFilterVector128(ref Vector128 p0, ref Vector128 q0, Vector128 fl) + /// + /// Adds (fl + 3) >> 3 to p0 and subtracts (fl + 4) >> 3 from q0, in each byte lane with signed saturation. + /// + /// The samples before the edge, as signed values (sample ^ 0x80). On return, the filtered samples. + /// The samples after the edge, as signed values (sample ^ 0x80). On return, the filtered samples. + /// The signed filter values. A zero lane does not change the samples. + [MethodImpl(InliningOptions.ShortMethod)] + private static void DoSimpleFilter(ref Vector128 p0, ref Vector128 q0, Vector128 fl) { Vector128 v3 = Vector128.AddSaturate(fl.AsSByte(), Vector128.Create((byte)3).AsSByte()); Vector128 v4 = Vector128.AddSaturate(fl.AsSByte(), Vector128.Create((byte)4).AsSByte()); - v4 = SignedShift8bVector128(v4.AsByte()).AsSByte(); // v4 >> 3 - v3 = SignedShift8bVector128(v3.AsByte()).AsSByte(); // v3 >> 3 + v4 = SignedShift8b(v4.AsByte()).AsSByte(); // v4 >> 3 + v3 = SignedShift8b(v3.AsByte()).AsSByte(); // v3 >> 3 q0 = Vector128.SubtractSaturate(q0.AsSByte(), v4).AsByte(); // q0 -= v4 p0 = Vector128.AddSaturate(p0.AsSByte(), v3).AsByte(); // p0 += v3 } - private static Vector128 GetNotHevVector128( + /// + /// Gets the lanes without high edge variance: the lanes where |p1 - p0| and |q1 - q0| are at most . + /// + /// The second samples before the edge. + /// The samples before the edge. + /// The samples after the edge. + /// The second samples after the edge. + /// The high edge variance threshold. + /// A mask with 0xFF in the lanes without high edge variance and 0 in the other lanes. + [MethodImpl(InliningOptions.ShortMethod)] + private static Vector128 GetNotHev( ref Vector128 p1, ref Vector128 p0, ref Vector128 q0, ref Vector128 q1, int hevThresh) { - Vector128 t1 = AbsVector128(p1, p0); - Vector128 t2 = AbsVector128(q1, q0); + Vector128 t1 = AbsoluteDifference(p1, p0); + Vector128 t2 = AbsoluteDifference(q1, q0); Vector128 h = Vector128.Create((byte)hevThresh); Vector128 tMax = Vector128.Max(t1, t2); @@ -2198,74 +2980,99 @@ private static Vector128 GetNotHevVector128( return Vector128.Equals(tMaxH, Vector128.Zero); } - // Applies filter on 4 pixels (p1, p0, q0 and q1) - private static void DoFilter4(Span p, int offset, int step) + /// + /// Applies the inner edge filter to one position without high edge variance. The filter changes p1, p0, q0 and q1. + /// + /// The sample q0, the first sample after the edge. + /// The distance between two samples across the edge. + private static void DoFilter4(ref byte p, nuint step) { // 4 pixels in, 4 pixels out. - int offsetMinus2Step = offset - (2 * step); - int p1 = p[offsetMinus2Step]; - int p0 = p[offset - step]; - int q0 = p[offset]; - int q1 = p[offset + step]; + ref byte p0Ref = ref Unsafe.Subtract(ref p, step); + ref byte p1Ref = ref Unsafe.Subtract(ref p0Ref, step); + ref byte q1Ref = ref Unsafe.Add(ref p, step); + int p1 = p1Ref; + int p0 = p0Ref; + int q0 = p; + int q1 = q1Ref; int a = 3 * (q0 - p0); int a1 = WebpLookupTables.Sclip2((a + 4) >> 3); int a2 = WebpLookupTables.Sclip2((a + 3) >> 3); int a3 = (a1 + 1) >> 1; - p[offsetMinus2Step] = WebpLookupTables.Clip1(p1 + a3); - p[offset - step] = WebpLookupTables.Clip1(p0 + a2); - p[offset] = WebpLookupTables.Clip1(q0 - a1); - p[offset + step] = WebpLookupTables.Clip1(q1 - a3); + p1Ref = WebpLookupTables.Clip1(p1 + a3); + p0Ref = WebpLookupTables.Clip1(p0 + a2); + p = WebpLookupTables.Clip1(q0 - a1); + q1Ref = WebpLookupTables.Clip1(q1 - a3); } - // Applies filter on 6 pixels (p2, p1, p0, q0, q1 and q2) - private static void DoFilter6(Span p, int offset, int step) + /// + /// Applies the macroblock edge filter to one position without high edge variance. The filter changes p2, p1, p0, q0, q1 and q2. + /// + /// The sample q0, the first sample after the edge. + /// The distance between two samples across the edge. + private static void DoFilter6(ref byte p, nuint step) { // 6 pixels in, 6 pixels out. - int step2 = 2 * step; - int step3 = 3 * step; - int offsetMinusStep = offset - step; - int p2 = p[offset - step3]; - int p1 = p[offset - step2]; - int p0 = p[offsetMinusStep]; - int q0 = p[offset]; - int q1 = p[offset + step]; - int q2 = p[offset + step2]; + ref byte p0Ref = ref Unsafe.Subtract(ref p, step); + ref byte p1Ref = ref Unsafe.Subtract(ref p0Ref, step); + ref byte p2Ref = ref Unsafe.Subtract(ref p1Ref, step); + ref byte q1Ref = ref Unsafe.Add(ref p, step); + ref byte q2Ref = ref Unsafe.Add(ref q1Ref, step); + int p2 = p2Ref; + int p1 = p1Ref; + int p0 = p0Ref; + int q0 = p; + int q1 = q1Ref; + int q2 = q2Ref; int a = WebpLookupTables.Sclip1((3 * (q0 - p0)) + WebpLookupTables.Sclip1(p1 - q1)); // a is in [-128,127], a1 in [-27,27], a2 in [-18,18] and a3 in [-9,9] int a1 = ((27 * a) + 63) >> 7; // eq. to ((3 * a + 7) * 9) >> 7 int a2 = ((18 * a) + 63) >> 7; // eq. to ((2 * a + 7) * 9) >> 7 int a3 = ((9 * a) + 63) >> 7; // eq. to ((1 * a + 7) * 9) >> 7 - p[offset - step3] = WebpLookupTables.Clip1(p2 + a3); - p[offset - step2] = WebpLookupTables.Clip1(p1 + a2); - p[offsetMinusStep] = WebpLookupTables.Clip1(p0 + a1); - p[offset] = WebpLookupTables.Clip1(q0 - a1); - p[offset + step] = WebpLookupTables.Clip1(q1 - a2); - p[offset + step2] = WebpLookupTables.Clip1(q2 - a3); + p2Ref = WebpLookupTables.Clip1(p2 + a3); + p1Ref = WebpLookupTables.Clip1(p1 + a2); + p0Ref = WebpLookupTables.Clip1(p0 + a1); + p = WebpLookupTables.Clip1(q0 - a1); + q1Ref = WebpLookupTables.Clip1(q1 - a2); + q2Ref = WebpLookupTables.Clip1(q2 - a3); } + /// + /// Returns a value indicating whether one position passes the edge limit: 4 * |p0 - q0| + |p1 - q1| is at most . + /// + /// The sample q0, the first sample after the edge. + /// The distance between two samples across the edge. + /// The limit: 2 * edge limit + 1. + /// if the position gets the filter; otherwise, . [MethodImpl(InliningOptions.ShortMethod)] - private static bool NeedsFilter(ReadOnlySpan p, int offset, int step, int t) + private static bool NeedsFilter(ref byte p, nuint step, int t) { - int p1 = p[offset + (-2 * step)]; - int p0 = p[offset - step]; - int q0 = p[offset]; - int q1 = p[offset + step]; + int p1 = Unsafe.Subtract(ref p, 2 * step); + int p0 = Unsafe.Subtract(ref p, step); + int q0 = p; + int q1 = Unsafe.Add(ref p, step); return (4 * WebpLookupTables.Abs0(p0 - q0)) + WebpLookupTables.Abs0(p1 - q1) <= t; } - private static bool NeedsFilter2(ReadOnlySpan p, int offset, int step, int t, int it) - { - int step2 = 2 * step; - int step3 = 3 * step; - int p3 = p[offset - (4 * step)]; - int p2 = p[offset - step3]; - int p1 = p[offset - step2]; - int p0 = p[offset - step]; - int q0 = p[offset]; - int q1 = p[offset + step]; - int q2 = p[offset + step2]; - int q3 = p[offset + step3]; + /// + /// Returns a value indicating whether one position passes the edge limit and the interior limit of the normal filter. + /// + /// The sample q0, the first sample after the edge. + /// The distance between two samples across the edge. + /// The limit of 4 * |p0 - q0| + |p1 - q1|: 2 * edge limit + 1. + /// The interior limit: the largest difference between adjacent samples among p3 to p0 and among q0 to q3. + /// if the position gets the filter; otherwise, . + private static bool NeedsFilter2(ref byte p, nuint step, int t, int it) + { + int p3 = Unsafe.Subtract(ref p, 4 * step); + int p2 = Unsafe.Subtract(ref p, 3 * step); + int p1 = Unsafe.Subtract(ref p, 2 * step); + int p0 = Unsafe.Subtract(ref p, step); + int q0 = p; + int q1 = Unsafe.Add(ref p, step); + int q2 = Unsafe.Add(ref p, 2 * step); + int q3 = Unsafe.Add(ref p, 3 * step); if ((4 * WebpLookupTables.Abs0(p0 - q0)) + WebpLookupTables.Abs0(p1 - q1) > t) { return false; @@ -2276,15 +3083,29 @@ private static bool NeedsFilter2(ReadOnlySpan p, int offset, int step, int WebpLookupTables.Abs0(q2 - q1) <= it && WebpLookupTables.Abs0(q1 - q0) <= it; } - private static Vector128 NeedsFilterVector128(Vector128 p1, Vector128 p0, Vector128 q0, Vector128 q1, int thresh) + /// + /// Gets the lanes that pass the edge limit: 2 * |p0 - q0| + |p1 - q1| / 2 is at most . + /// + /// + /// The division is an integer division, and the adds saturate at 255. For a threshold below 255, the test is the same as the + /// scalar test 4 * |p0 - q0| + |p1 - q1| <= 2 * thresh + 1. + /// + /// The second samples before the edge. + /// The samples before the edge. + /// The samples after the edge. + /// The second samples after the edge. + /// The edge limit. + /// A mask with 0xFF in the lanes that get the filter and 0 in the other lanes. + [MethodImpl(InliningOptions.ShortMethod)] + private static Vector128 NeedsFilter(Vector128 p1, Vector128 p0, Vector128 q0, Vector128 q1, int thresh) { Vector128 mthresh = Vector128.Create((byte)thresh); - Vector128 t1 = AbsVector128(p1, q1); // abs(p1 - q1) + Vector128 t1 = AbsoluteDifference(p1, q1); // abs(p1 - q1) Vector128 fe = Vector128.Create((byte)0xFE); Vector128 t2 = t1 & fe; // set lsb of each byte to zero. Vector128 t3 = Vector128.ShiftRightLogical(t2.AsInt16(), 1); // abs(p1 - q1) / 2 - Vector128 t4 = AbsVector128(p0, q0); // abs(p0 - q0) + Vector128 t4 = AbsoluteDifference(p0, q0); // abs(p0 - q0) Vector128 t5 = Vector128.AddSaturate(t4, t4); // abs(p0 - q0) * 2 Vector128 t6 = Vector128.AddSaturate(t5.AsByte(), t3.AsByte()); // abs(p0-q0)*2 + abs(p1-q1)/2 @@ -2293,10 +3114,21 @@ private static Vector128 NeedsFilterVector128(Vector128 p1, Vector12 return Vector128.Equals(t7, Vector128.Zero); } - private static void Load16x4Vector128( + /// + /// Reads 4 adjacent columns of 16 rows and transposes them: each output holds one column, with row n in byte lane n. + /// + /// The first sample of row 0. + /// The first sample of row 8. + /// The distance between two rows. + /// Column 0. + /// Column 1. + /// Column 2. + /// Column 3. + [MethodImpl(InliningOptions.ShortMethod)] + private static void Load16x4( ref byte r0, ref byte r8, - int stride, + nuint stride, out Vector128 p1, out Vector128 p0, out Vector128 q0, @@ -2317,8 +3149,8 @@ private static void Load16x4Vector128( // q0 = 73 63 53 43 33 23 13 03 72 62 52 42 32 22 12 02 // p0 = f1 e1 d1 c1 b1 a1 91 81 f0 e0 d0 c0 b0 a0 90 80 // q1 = f3 e3 d3 c3 b3 a3 93 83 f2 e2 d2 c2 b2 a2 92 82 - Load8x4Vector128(ref r0, (uint)stride, out Vector128 t1, out Vector128 t2); - Load8x4Vector128(ref r8, (uint)stride, out p0, out q1); + Load8x4(ref r0, stride, out Vector128 t1, out Vector128 t2); + Load8x4(ref r8, stride, out p0, out q1); // p1 = f0 e0 d0 c0 b0 a0 90 80 70 60 50 40 30 20 10 00 // p0 = f1 e1 d1 c1 b1 a1 91 81 71 61 51 41 31 21 11 01 @@ -2330,20 +3162,27 @@ private static void Load16x4Vector128( q1 = Vector128_.UnpackHigh(t2.AsInt64(), q1.AsInt64()).AsByte(); } - // Reads 8 rows across a vertical edge. - private static void Load8x4Vector128(ref byte bRef, nuint stride, out Vector128 p, out Vector128 q) + /// + /// Reads 4 adjacent columns of 8 rows and transposes them into two vectors of two columns each. + /// + /// The first sample of row 0. + /// The distance between two rows. + /// Column 0 in byte lanes 0 to 7 and column 1 in byte lanes 8 to 15. Lane n of each half is row n. + /// Column 2 in byte lanes 0 to 7 and column 3 in byte lanes 8 to 15, in the same row order. + [MethodImpl(InliningOptions.ShortMethod)] + private static void Load8x4(ref byte bRef, nuint stride, out Vector128 p, out Vector128 q) { // A0 = 63 62 61 60 23 22 21 20 43 42 41 40 03 02 01 00 // A1 = 73 72 71 70 33 32 31 30 53 52 51 50 13 12 11 10 - uint a00 = Unsafe.As(ref Unsafe.Add(ref bRef, 6 * stride)); - uint a01 = Unsafe.As(ref Unsafe.Add(ref bRef, 2 * stride)); - uint a02 = Unsafe.As(ref Unsafe.Add(ref bRef, 4 * stride)); - uint a03 = Unsafe.As(ref Unsafe.Add(ref bRef, 0 * stride)); + uint a00 = Unsafe.ReadUnaligned(ref Unsafe.Add(ref bRef, 6 * stride)); + uint a01 = Unsafe.ReadUnaligned(ref Unsafe.Add(ref bRef, 2 * stride)); + uint a02 = Unsafe.ReadUnaligned(ref Unsafe.Add(ref bRef, 4 * stride)); + uint a03 = Unsafe.ReadUnaligned(ref Unsafe.Add(ref bRef, 0 * stride)); Vector128 a0 = Vector128.Create(a03, a02, a01, a00).AsByte(); - uint a10 = Unsafe.As(ref Unsafe.Add(ref bRef, 7 * stride)); - uint a11 = Unsafe.As(ref Unsafe.Add(ref bRef, 3 * stride)); - uint a12 = Unsafe.As(ref Unsafe.Add(ref bRef, 5 * stride)); - uint a13 = Unsafe.As(ref Unsafe.Add(ref bRef, 1 * stride)); + uint a10 = Unsafe.ReadUnaligned(ref Unsafe.Add(ref bRef, 7 * stride)); + uint a11 = Unsafe.ReadUnaligned(ref Unsafe.Add(ref bRef, 3 * stride)); + uint a12 = Unsafe.ReadUnaligned(ref Unsafe.Add(ref bRef, 5 * stride)); + uint a13 = Unsafe.ReadUnaligned(ref Unsafe.Add(ref bRef, 1 * stride)); Vector128 a1 = Vector128.Create(a13, a12, a11, a10).AsByte(); // B0 = 53 43 52 42 51 41 50 40 13 03 12 02 11 01 10 00 @@ -2362,15 +3201,25 @@ private static void Load8x4Vector128(ref byte bRef, nuint stride, out Vector128< q = Vector128_.UnpackHigh(c0.AsInt32(), c1.AsInt32()).AsByte(); } - // Transpose back and store - private static void Store16x4Vector128( + /// + /// Transposes 4 columns of 16 rows and writes them back. This is the inverse of . + /// + /// Column 0, with row n in byte lane n. + /// Column 1, with row n in byte lane n. + /// Column 2, with row n in byte lane n. + /// Column 3, with row n in byte lane n. + /// The first sample of row 0. + /// The first sample of row 8. + /// The distance between two rows. + [MethodImpl(InliningOptions.ShortMethod)] + private static void Store16x4( Vector128 p1, Vector128 p0, Vector128 q0, Vector128 q1, ref byte r0Ref, ref byte r8Ref, - int stride) + nuint stride) { // p0 = 71 70 61 60 51 50 41 40 31 30 21 20 11 10 01 00 // p1 = f1 f0 e1 e0 d1 d0 c1 c0 b1 b0 a1 a0 91 90 81 80 @@ -2394,26 +3243,41 @@ private static void Store16x4Vector128( p1s = Vector128_.UnpackLow(t1.AsInt16(), q1s.AsInt16()).AsByte(); q1s = Vector128_.UnpackHigh(t1.AsInt16(), q1s.AsInt16()).AsByte(); - Store4x4Vector128(p0s, ref r0Ref, stride); - Store4x4Vector128(q0s, ref Unsafe.Add(ref r0Ref, 4 * (uint)stride), stride); + Store4x4(p0s, ref r0Ref, stride); + Store4x4(q0s, ref Unsafe.Add(ref r0Ref, 4 * stride), stride); - Store4x4Vector128(p1s, ref r8Ref, stride); - Store4x4Vector128(q1s, ref Unsafe.Add(ref r8Ref, 4 * (uint)stride), stride); + Store4x4(p1s, ref r8Ref, stride); + Store4x4(q1s, ref Unsafe.Add(ref r8Ref, 4 * stride), stride); } - private static void Store4x4Vector128(Vector128 x, ref byte dstRef, int stride) + /// + /// Writes the four 32-bit lanes of a vector to 4 rows: lane n goes to row n. + /// + /// The 4 rows of 4 samples. + /// The first sample of row 0. + /// The distance between two rows. + [MethodImpl(InliningOptions.ShortMethod)] + private static void Store4x4(Vector128 x, ref byte dstRef, nuint stride) { - int offset = 0; - for (int i = 0; i < 4; i++) - { - Unsafe.As(ref Unsafe.Add(ref dstRef, (uint)offset)) = x.AsInt32().ToScalar(); - x = Vector128_.ShiftRightBytesInVector(x, 4); - offset += stride; - } + // Each 32-bit lane holds one row of 4 samples. A lane extract is one instruction on SSE4.1 and Arm64, + // so the rows are stored without the byte shifts of a loop. + Vector128 rows = x.AsInt32(); + Unsafe.WriteUnaligned(ref dstRef, rows.ToScalar()); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dstRef, stride), rows.GetElement(1)); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dstRef, stride * 2), rows.GetElement(2)); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dstRef, stride * 3), rows.GetElement(3)); } + /// + /// Computes the base filter value p1 - q1 + 3 * (q0 - p0) in each byte lane, with signed saturation after each step. + /// + /// The second samples before the edge, as signed values. + /// The samples before the edge, as signed values. + /// The samples after the edge, as signed values. + /// The second samples after the edge, as signed values. + /// The base filter values. [MethodImpl(InliningOptions.ShortMethod)] - private static Vector128 GetBaseDeltaVector128(Vector128 p1, Vector128 p0, Vector128 q0, Vector128 q1) + private static Vector128 GetBaseDelta(Vector128 p1, Vector128 p0, Vector128 q0, Vector128 q1) { // Beware of addition order, for saturation! Vector128 p1q1 = Vector128.SubtractSaturate(p1, q1); // p1 - q1 @@ -2423,9 +3287,13 @@ private static Vector128 GetBaseDeltaVector128(Vector128 p1, Vecto return Vector128.AddSaturate(q0p0, s2); // p1 - q1 + 3 * (q0 - p0) } - // Shift each byte of "x" by 3 bits while preserving by the sign bit. + /// + /// Shifts each signed byte lane right by 3 bits, with sign extension. + /// + /// The signed values. + /// The shifted values. [MethodImpl(InliningOptions.ShortMethod)] - private static Vector128 SignedShift8bVector128(Vector128 x) + private static Vector128 SignedShift8b(Vector128 x) { Vector128 low0 = Vector128_.UnpackLow(Vector128.Zero, x); Vector128 high0 = Vector128_.UnpackHigh(Vector128.Zero, x); @@ -2435,8 +3303,21 @@ private static Vector128 SignedShift8bVector128(Vector128 x) return Vector128.NarrowWithSaturation(low1, high1); } + /// + /// Gets the lanes that pass the interior limit and the edge limit of the normal filter. + /// + /// The second samples before the edge. + /// The samples before the edge. + /// The samples after the edge. + /// The second samples after the edge. + /// The edge limit. + /// The interior limit. + /// + /// On input, the largest difference between adjacent samples on each side of the edge, for each lane. + /// On return, 0xFF in the lanes that get the filter and 0 in the other lanes. + /// [MethodImpl(InliningOptions.ShortMethod)] - private static void ComplexMaskVector128( + private static void ComplexMask( Vector128 p1, Vector128 p0, Vector128 q0, @@ -2448,16 +3329,25 @@ private static void ComplexMaskVector128( Vector128 it = Vector128.Create((byte)ithresh); Vector128 diff = Vector128.SubtractSaturate(mask, it); Vector128 threshMask = Vector128.Equals(diff, Vector128.Zero); - Vector128 filterMask = NeedsFilterVector128(p1, p0, q0, q1, thresh); + Vector128 filterMask = NeedsFilter(p1, p0, q0, q1, thresh); mask = threshMask & filterMask; } - // Updates values of 2 pixels at MB edge during complex filtering. - // Update operations: - // q = q - delta and p = p + delta; where delta = [(a_hi >> 7), (a_lo >> 7)] - // Pixels 'pi' and 'qi' are int8_t on input, uint8_t on output (sign flip). - private static void Update2PixelsVector128(ref Vector128 pi, ref Vector128 qi, Vector128 a0Low, Vector128 a0High) + /// + /// Adds a filter delta to the samples before the edge and subtracts it from the samples after the edge. + /// The delta of each lane is its 16-bit value shifted right by 7 bits, with signed saturation. + /// + /// + /// The complex filter uses this step at a macroblock edge: q = q - delta and p = p + delta, with delta = [(a_hi >> 7), (a_lo >> 7)]. + /// The samples are signed on input and unsigned on output, so the step also flips the sign bit. + /// + /// The samples before the edge, as signed values. On return, the filtered samples as unsigned values. + /// The samples after the edge, as signed values. On return, the filtered samples as unsigned values. + /// The 16-bit filter values of byte lanes 0 to 7. + /// The 16-bit filter values of byte lanes 8 to 15. + [MethodImpl(InliningOptions.ShortMethod)] + private static void Update2Pixels(ref Vector128 pi, ref Vector128 qi, Vector128 a0Low, Vector128 a0High) { Vector128 signBit = Vector128.Create((byte)0x80); Vector128 a1Low = Vector128.ShiftRightArithmetic(a0Low, 7); @@ -2469,43 +3359,146 @@ private static void Update2PixelsVector128(ref Vector128 pi, ref Vector128 qi ^= signBit.AsByte(); } + /// + /// Loads 8 U samples to byte lanes 0 to 7 and 8 V samples to byte lanes 8 to 15. + /// + /// The base U sample. + /// The base V sample. + /// The distance of the first sample to load from the base sample, in both planes. + /// The U and V samples. [MethodImpl(InliningOptions.ShortMethod)] - private static Vector128 LoadUvEdgeVector128(ref byte uRef, ref byte vRef, int offset) + private static Vector128 LoadUvEdge(ref byte uRef, ref byte vRef, nuint offset) { - Vector128 uVec = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref uRef, (uint)offset)), 0); - Vector128 vVec = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref vRef, (uint)offset)), 0); - return Vector128_.UnpackLow(uVec, vVec).AsByte(); + ulong u = Unsafe.ReadUnaligned(ref Unsafe.Add(ref uRef, offset)); + ulong v = Unsafe.ReadUnaligned(ref Unsafe.Add(ref vRef, offset)); + return Vector128.Create(u, v).AsByte(); } + /// + /// Stores byte lanes 0 to 7 as 8 U samples and byte lanes 8 to 15 as 8 V samples. This is the inverse of . + /// + /// The U and V samples. + /// The base U sample. + /// The base V sample. + /// The distance of the first sample to store from the base sample, in both planes. [MethodImpl(InliningOptions.ShortMethod)] - private static void StoreUvVector128(Vector128 x, ref byte uRef, ref byte vRef, int offset) + private static void StoreUv(Vector128 x, ref byte uRef, ref byte vRef, nuint offset) { - Unsafe.As>(ref Unsafe.Add(ref uRef, (uint)offset)) = x.GetLower(); - Unsafe.As>(ref Unsafe.Add(ref vRef, (uint)offset)) = x.GetUpper(); + Vector128 rows = x.AsUInt64(); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref uRef, offset), rows.ToScalar()); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref vRef, offset), rows.GetElement(1)); } - // Compute abs(p - q) = subs(p - q) OR subs(q - p) + /// + /// Computes |p - q| in each unsigned byte lane. + /// + /// The first samples. + /// The second samples. + /// The absolute differences. [MethodImpl(InliningOptions.ShortMethod)] - private static Vector128 AbsVector128(Vector128 p, Vector128 q) + private static Vector128 AbsoluteDifference(Vector128 p, Vector128 q) => Vector128.SubtractSaturate(q, p) | Vector128.SubtractSaturate(p, q); + /// + /// Returns a value indicating whether one position has high edge variance: |p1 - p0| or |q1 - q0| is larger than . + /// + /// The sample q0, the first sample after the edge. + /// The distance between two samples across the edge. + /// The high edge variance threshold. + /// if the position has high edge variance; otherwise, . [MethodImpl(InliningOptions.ShortMethod)] - private static bool Hev(ReadOnlySpan p, int offset, int step, int thresh) + private static bool Hev(ref byte p, nuint step, int thresh) { - int p1 = p[offset - (2 * step)]; - int p0 = p[offset - step]; - int q0 = p[offset]; - int q1 = p[offset + step]; + int p1 = Unsafe.Subtract(ref p, 2 * step); + int p0 = Unsafe.Subtract(ref p, step); + int q0 = p; + int q1 = Unsafe.Add(ref p, step); return WebpLookupTables.Abs0(p1 - p0) > thresh || WebpLookupTables.Abs0(q1 - q0) > thresh; } + /// + /// Adds values to the samples of a 4x4 block, with the clamp to [0, 255]. + /// + /// + /// The four rows load as one vector, row y in 32-bit lane y. The widen gives rows 0 and 1 in the low half and rows 2 and 3 in the high half. The + /// unsigned saturating pack gives the clamp of . + /// + /// The first sample of the block. + /// The values of rows 0 and 1. + /// The values of rows 2 and 3. + [MethodImpl(InliningOptions.ShortMethod)] + private static void AddToBlock4x4(ref byte dst, Vector128 rows01, Vector128 rows23) + { + ref byte row1 = ref Unsafe.Add(ref dst, (nuint)WebpConstants.Bps); + ref byte row2 = ref Unsafe.Add(ref dst, (nuint)(2 * WebpConstants.Bps)); + ref byte row3 = ref Unsafe.Add(ref dst, (nuint)(3 * WebpConstants.Bps)); + Vector128 samples = Vector128.Create( + Unsafe.ReadUnaligned(ref dst), + Unsafe.ReadUnaligned(ref row1), + Unsafe.ReadUnaligned(ref row2), + Unsafe.ReadUnaligned(ref row3)).AsByte(); + + (Vector128 low, Vector128 high) = Vector128.Widen(samples); + Vector128 result = Vector128_.PackUnsignedSaturate(low.AsInt16() + rows01, high.AsInt16() + rows23).AsUInt32(); + Unsafe.WriteUnaligned(ref dst, result.GetElement(0)); + Unsafe.WriteUnaligned(ref row1, result.GetElement(1)); + Unsafe.WriteUnaligned(ref row2, result.GetElement(2)); + Unsafe.WriteUnaligned(ref row3, result.GetElement(3)); + } + + /// + /// Adds values to 8 samples of each of two rows, with the clamp to [0, 255]. + /// + /// + /// The two rows load as one vector, the first row in bytes 0 to 7 and the second row in bytes 8 to 15. The widen gives the first row in the low + /// half and the second row in the high half. The unsigned saturating pack gives the clamp of . + /// + /// The first sample of the first row. + /// The first sample of the second row. + /// The 8 values of the first row. + /// The 8 values of the second row. + [MethodImpl(InliningOptions.ShortMethod)] + private static void AddToRows8(ref byte row0, ref byte row1, Vector128 values0, Vector128 values1) + { + Vector128 samples = Vector128.Create(Unsafe.ReadUnaligned(ref row0), Unsafe.ReadUnaligned(ref row1)).AsByte(); + (Vector128 low, Vector128 high) = Vector128.Widen(samples); + Vector128 result = Vector128_.PackUnsignedSaturate(low.AsInt16() + values0, high.AsInt16() + values1).AsUInt64(); + Unsafe.WriteUnaligned(ref row0, result.ToScalar()); + Unsafe.WriteUnaligned(ref row1, result.GetElement(1)); + } + + /// + /// Reads one row of 4 coefficients as one 64-bit value. + /// + /// The first coefficient. + /// The index of the first coefficient of the row. + /// The row: coefficient k is in bits 16k to 16k + 15. + [MethodImpl(InliningOptions.ShortMethod)] + public static long ReadCoefficientRow(ref short coefficients, nuint offset) + => Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.Add(ref coefficients, offset))); + + /// + /// Adds v >> 3 to one sample of a block, with the clamp to [0, 255]. + /// + /// The first sample of the block. + /// The column. + /// The row. + /// The inverse transform value before the descale by 8. [MethodImpl(InliningOptions.ShortMethod)] private static void Store(Span dst, int x, int y, int v) { int index = x + (y * WebpConstants.Bps); - dst[index] = Clip8B(dst[index] + (v >> 3)); + dst[index] = Numerics.ClampToByte(dst[index] + (v >> 3)); } + /// + /// Adds the values dc + d, dc + c, dc - c and dc - d, each shifted right by 3, to the 4 samples of one row of a 4x4 block. + /// + /// The first sample of the block. + /// The row. + /// The row term. + /// The column term of columns 0 and 3. + /// The column term of columns 1 and 2. [MethodImpl(InliningOptions.ShortMethod)] private static void Store2(Span dst, int y, int dc, int d, int c) { @@ -2515,26 +3508,19 @@ private static void Store2(Span dst, int y, int dc, int d, int c) Store(dst, 3, y, dc - d); } + /// + /// Multiplies a value by sqrt(2) * cos(pi / 8), with the 16.16 fixed-point multiplier 20091 + (1 << 16). + /// + /// The value. + /// ((a * 20091) >> 16) + a. [MethodImpl(InliningOptions.ShortMethod)] private static int Mul1(int a) => ((a * 20091) >> 16) + a; + /// + /// Multiplies a value by sqrt(2) * sin(pi / 8), with the 16.16 fixed-point multiplier 35468. + /// + /// The value. + /// (a * 35468) >> 16. [MethodImpl(InliningOptions.ShortMethod)] private static int Mul2(int a) => (a * 35468) >> 16; - - [MethodImpl(InliningOptions.ShortMethod)] - private static void Put8x8uv(byte value, Span dst) - { - const int end = 8 * WebpConstants.Bps; - for (int j = 0; j < end; j += WebpConstants.Bps) - { - // memset(dst + j * BPS, value, 8); - Memset(dst, value, j, 8); - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static void Memset(Span dst, byte value, int startIdx, int count) => dst.Slice(startIdx, count).Fill(value); - - [MethodImpl(InliningOptions.ShortMethod)] - private static int Clamp255(int x) => Math.Clamp(x, 0, 255); } diff --git a/src/ImageSharp/Formats/Webp/Lossy/PassStatistics.cs b/src/ImageSharp/Formats/Webp/Lossy/PassStatistics.cs new file mode 100644 index 0000000000..19a3a785bb --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossy/PassStatistics.cs @@ -0,0 +1,127 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.ImageSharp.Formats.Webp.Lossy; + +/// +/// Class for organizing convergence in either size or PSNR. +/// +internal class PassStatistics +{ + /// + /// Initializes a new instance of the class. + /// + /// + /// A non-zero selects the size search. Otherwise the search targets , + /// or 40 dB when is not positive. + /// + /// The target encoded size in bytes, or 0 to search for a PSNR. + /// The target PSNR in dB. The size search ignores this value. + /// The minimum quality that the search can select. + /// The maximum quality that the search can select. + /// The initial quality. The constructor clamps it to [, ]. + public PassStatistics(long targetSize, float targetPsnr, int qMin, int qMax, uint quality) + { + bool doSizeSearch = targetSize != 0; + + this.IsFirst = true; + this.Dq = 10.0f; + this.Qmin = qMin; + this.Qmax = qMax; + this.Q = ColorNumerics.ClampToFinite(quality, qMin, qMax); + this.LastQ = this.Q; + this.Target = doSizeSearch ? targetSize + : targetPsnr > 0.0f ? targetPsnr + : 40.0f; // default, just in case + + this.Value = 0.0f; + this.LastValue = 0.0f; + this.DoSizeSearch = doSizeSearch; + } + + /// + /// Gets or sets a value indicating whether the next call to is the first step of the search. + /// + public bool IsFirst { get; set; } + + /// + /// Gets or sets the last quality step. The first step uses this value with the sign that moves toward . + /// + public float Dq { get; set; } + + /// + /// Gets or sets the current quality. + /// + public float Q { get; set; } + + /// + /// Gets or sets the quality of the previous pass. + /// + public float LastQ { get; set; } + + /// + /// Gets the minimum quality that the search can select. + /// + public float Qmin { get; } + + /// + /// Gets the maximum quality that the search can select. + /// + public float Qmax { get; } + + /// + /// Gets or sets the measured result of the current pass: the encoded size in bytes or the PSNR in dB. + /// + public double Value { get; set; } // PSNR or size + + /// + /// Gets or sets the measured result of the previous pass. + /// + public double LastValue { get; set; } + + /// + /// Gets the target result: the encoded size in bytes for a size search, otherwise the PSNR in dB. + /// + public double Target { get; } + + /// + /// Gets a value indicating whether the search targets the encoded size. Otherwise it targets the PSNR. + /// + public bool DoSizeSearch { get; } + + /// + /// Computes the quality for the next pass from and the result of the previous pass. + /// + /// + /// The first step moves by toward . The next steps use the secant through the last two + /// results. The step is clamped to [-30, 30] and the quality to [, ]. + /// The method also moves the current quality and result into and . + /// + /// The quality for the next pass. + public float ComputeNextQ() + { + float dq; + if (this.IsFirst) + { + dq = this.Value > this.Target ? -this.Dq : this.Dq; + this.IsFirst = false; + } + else if (this.Value != this.LastValue) + { + double slope = (this.Target - this.Value) / (this.LastValue - this.Value); + dq = (float)(slope * (this.LastQ - this.Q)); + } + else + { + dq = 0.0f; // we're done?! + } + + // Limit variable to avoid large swings. + this.Dq = ColorNumerics.ClampToFinite(dq, -30.0f, 30.0f); + this.LastQ = this.Q; + this.LastValue = this.Value; + this.Q = ColorNumerics.ClampToFinite(this.Q + this.Dq, this.Qmin, this.Qmax); + + return this.Q; + } +} diff --git a/src/ImageSharp/Formats/Webp/Lossy/PassStats.cs b/src/ImageSharp/Formats/Webp/Lossy/PassStats.cs deleted file mode 100644 index 6d409489f3..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossy/PassStats.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossy; - -/// -/// Class for organizing convergence in either size or PSNR. -/// -internal class PassStats -{ - public PassStats(long targetSize, float targetPsnr, int qMin, int qMax, uint quality) - { - bool doSizeSearch = targetSize != 0; - - this.IsFirst = true; - this.Dq = 10.0f; - this.Qmin = qMin; - this.Qmax = qMax; - this.Q = ColorNumerics.ClampToFinite(quality, qMin, qMax); - this.LastQ = this.Q; - this.Target = doSizeSearch ? targetSize - : targetPsnr > 0.0f ? targetPsnr - : 40.0f; // default, just in case - this.Value = 0.0f; - this.LastValue = 0.0f; - this.DoSizeSearch = doSizeSearch; - } - - public bool IsFirst { get; set; } - - public float Dq { get; set; } - - public float Q { get; set; } - - public float LastQ { get; set; } - - public float Qmin { get; } - - public float Qmax { get; } - - public double Value { get; set; } // PSNR or size - - public double LastValue { get; set; } - - public double Target { get; } - - public bool DoSizeSearch { get; } - - public float ComputeNextQ() - { - float dq; - if (this.IsFirst) - { - dq = this.Value > this.Target ? -this.Dq : this.Dq; - this.IsFirst = false; - } - else if (this.Value != this.LastValue) - { - double slope = (this.Target - this.Value) / (this.LastValue - this.Value); - dq = (float)(slope * (this.LastQ - this.Q)); - } - else - { - dq = 0.0f; // we're done?! - } - - // Limit variable to avoid large swings. - this.Dq = ColorNumerics.ClampToFinite(dq, -30.0f, 30.0f); - this.LastQ = this.Q; - this.LastValue = this.Value; - this.Q = ColorNumerics.ClampToFinite(this.Q + this.Dq, this.Qmin, this.Qmax); - - return this.Q; - } -} diff --git a/src/ImageSharp/Formats/Webp/Lossy/QuantEnc.cs b/src/ImageSharp/Formats/Webp/Lossy/QuantEnc.cs deleted file mode 100644 index 3105df4bbc..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossy/QuantEnc.cs +++ /dev/null @@ -1,886 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Runtime.Intrinsics; -using System.Runtime.Intrinsics.X86; -using SixLabors.ImageSharp.Common.Helpers; - -namespace SixLabors.ImageSharp.Formats.Webp.Lossy; - -/// -/// Quantization methods. -/// -internal static unsafe class QuantEnc -{ - private static readonly ushort[] WeightY = [38, 32, 20, 9, 32, 28, 17, 7, 20, 17, 10, 4, 9, 7, 4, 2]; - - private const int MaxLevel = 2047; - - // Diffusion weights. We under-correct a bit (15/16th of the error is actually - // diffused) to avoid 'rainbow' chessboard pattern of blocks at q~=0. - private const int C1 = 7; // fraction of error sent to the 4x4 block below - private const int C2 = 8; // fraction of error sent to the 4x4 block on the right - private const int DSHIFT = 4; - private const int DSCALE = 1; // storage descaling, needed to make the error fit byte - - // This uses C#'s optimization to refer to the static data segment of the assembly, no allocation occurs. - private static ReadOnlySpan Zigzag => [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; - - public static void PickBestIntra16(Vp8EncIterator it, ref Vp8ModeScore rd, Vp8SegmentInfo[] segmentInfos, Vp8EncProba proba) - { - const int numBlocks = 16; - Vp8SegmentInfo dqm = segmentInfos[it.CurrentMacroBlockInfo.Segment]; - int lambda = dqm.LambdaI16; - int tlambda = dqm.TLambda; - Span src = it.YuvIn.AsSpan(Vp8EncIterator.YOffEnc); - Span scratch = it.Scratch3.AsSpan(); - - // Reuse the iterator scratch accumulator instead of allocating one per macroblock. - // Clear it so that it starts from the same zeroed state as a fresh instance. - Vp8ModeScore rdTmp = it.RdScratch; - rdTmp.Clear(); - Vp8Residual res = it.ResidualScratch; - Vp8ModeScore rdCur = rdTmp; - Vp8ModeScore rdBest = rd; - int mode; - bool isFlat = IsFlatSource16(src); - rd.ModeI16 = -1; - for (mode = 0; mode < WebpConstants.NumPredModes; ++mode) - { - // Scratch buffer. - Span tmpDst = it.YuvOut2.AsSpan(Vp8EncIterator.YOffEnc); - rdCur.ModeI16 = mode; - - // Reconstruct. - rdCur.Nz = (uint)ReconstructIntra16(it, dqm, rdCur, tmpDst, mode); - - // Measure RD-score. - rdCur.D = LossyUtils.Vp8_Sse16x16(src, tmpDst); - rdCur.SD = tlambda != 0 ? Mult8B(tlambda, LossyUtils.Vp8Disto16X16(src, tmpDst, WeightY, scratch)) : 0; - rdCur.H = WebpConstants.Vp8FixedCostsI16[mode]; - rdCur.R = it.GetCostLuma16(rdCur, proba, res); - - if (isFlat) - { - // Refine the first impression (which was in pixel space). - isFlat = IsFlat(rdCur.YAcLevels, numBlocks, WebpConstants.FlatnessLimitI16); - if (isFlat) - { - // Block is very flat. We put emphasis on the distortion being very low! - rdCur.D *= 2; - rdCur.SD *= 2; - } - } - - // The search always checks Intra16 first, so it can overwrite *rd directly. - rdCur.SetRdScore(lambda); - - if (mode == 0 || rdCur.Score < rdBest.Score) - { - RuntimeUtility.Swap(ref rdBest, ref rdCur); - it.SwapOut(); - } - } - - // The rejected accumulator becomes the scratch instance for the next macroblock. When the - // best result lives in the scratch instance, the caller's reference is exchanged for it so - // that no levels need to be copied. - it.RdScratch = rdCur; - if (rdBest != rd) - { - rd = rdBest; - } - - // Finalize score for mode decision. - rd.SetRdScore(dqm.LambdaMode); - it.SetIntra16Mode(rd.ModeI16); - - // We have a blocky macroblock (only DCs are non-zero) with fairly high - // distortion, record max delta so we can later adjust the minimal filtering - // strength needed to smooth these blocks out. - if ((rd.Nz & 0x100ffff) == 0x1000000 && rd.D > dqm.MinDisto) - { - dqm.StoreMaxDelta(rd.YDcLevels); - } - } - - public static bool PickBestIntra4(Vp8EncIterator it, ref Vp8ModeScore rd, Vp8SegmentInfo[] segmentInfos, Vp8EncProba proba, int maxI4HeaderBits) - { - Vp8SegmentInfo dqm = segmentInfos[it.CurrentMacroBlockInfo.Segment]; - int lambda = dqm.LambdaI4; - int tlambda = dqm.TLambda; - Span src0 = it.YuvIn.AsSpan(Vp8EncIterator.YOffEnc); - Span bestBlocks = it.YuvOut2.AsSpan(Vp8EncIterator.YOffEnc); - Span scratch = it.Scratch3.AsSpan(); - int totalHeaderBits = 0; - - // Reuse the iterator scratch accumulators instead of allocating per macroblock. rdBest - // collects the winning levels of every 4x4 block, so it must start zeroed like a fresh instance. - Vp8ModeScore rdBest = it.RdScratch2; - rdBest.Clear(); - - if (maxI4HeaderBits == 0) - { - return false; - } - - rdBest.InitScore(); - rdBest.H = 211; // '211' is the value of LossyUtils.Vp8BitCost(0, 145) - rdBest.SetRdScore(dqm.LambdaMode); - it.StartI4(); - - // Both accumulators are cleared inside the loops before they are read. - Vp8ModeScore rdi4 = it.RdScratch3; - Vp8ModeScore rdTmp = it.RdScratch; - Vp8Residual res = it.ResidualScratch; - Span tmpLevels = stackalloc short[16]; - do - { - const int numBlocks = 1; - rdi4.Clear(); - int mode; - int bestMode = -1; - Span src = src0[WebpLookupTables.Vp8Scan[it.I4]..]; - short[] modeCosts = it.GetCostModeI4(rd.ModesI4); - Span bestBlock = bestBlocks[WebpLookupTables.Vp8Scan[it.I4]..]; - Span tmpDst = it.Scratch.AsSpan(); - tmpDst.Clear(); - - rdi4.InitScore(); - it.MakeIntra4Preds(); - for (mode = 0; mode < WebpConstants.NumBModes; ++mode) - { - rdTmp.Clear(); - tmpLevels.Clear(); - - // Reconstruct. - rdTmp.Nz = (uint)ReconstructIntra4(it, dqm, tmpLevels, src, tmpDst, mode); - - // Compute RD-score. - rdTmp.D = LossyUtils.Vp8_Sse4x4(src, tmpDst); - rdTmp.SD = tlambda != 0 ? Mult8B(tlambda, LossyUtils.Vp8Disto4X4(src, tmpDst, WeightY, scratch)) : 0; - rdTmp.H = modeCosts[mode]; - - // Add flatness penalty, to avoid flat area to be mispredicted by a complex mode. - if (mode > 0 && IsFlat(tmpLevels, numBlocks, WebpConstants.FlatnessLimitI4)) - { - rdTmp.R = WebpConstants.FlatnessPenality * numBlocks; - } - else - { - rdTmp.R = 0; - } - - // Early-out check. - rdTmp.SetRdScore(lambda); - if (bestMode >= 0 && rdTmp.Score >= rdi4.Score) - { - continue; - } - - // Finish computing score. - rdTmp.R += it.GetCostLuma4(tmpLevels, proba, res); - rdTmp.SetRdScore(lambda); - - if (bestMode < 0 || rdTmp.Score < rdi4.Score) - { - rdi4.CopyScore(rdTmp); - bestMode = mode; - - RuntimeUtility.Swap(ref tmpDst, ref bestBlock); - tmpLevels.CopyTo(rdBest.YAcLevels.AsSpan(it.I4 * 16, 16)); - } - } - - rdi4.SetRdScore(dqm.LambdaMode); - rdBest.AddScore(rdi4); - if (rdBest.Score >= rd.Score) - { - return false; - } - - totalHeaderBits += (int)rdi4.H; // <- equal to modeCosts[bestMode]; - if (totalHeaderBits > maxI4HeaderBits) - { - return false; - } - - // Copy selected samples to the right place. - LossyUtils.Vp8Copy4X4(bestBlock, bestBlocks[WebpLookupTables.Vp8Scan[it.I4]..]); - - rd.ModesI4[it.I4] = (byte)bestMode; - it.TopNz[it.I4 & 3] = it.LeftNz[it.I4 >> 2] = rdi4.Nz != 0 ? 1 : 0; - } - while (it.RotateI4(bestBlocks)); - - // Finalize state. - rd.CopyScore(rdBest); - it.SetIntra4Mode(rd.ModesI4); - it.SwapOut(); - rdBest.YAcLevels.AsSpan().CopyTo(rd.YAcLevels); - - // Select intra4x4 over intra16x16. - return true; - } - - public static void PickBestUv(Vp8EncIterator it, ref Vp8ModeScore rd, Vp8SegmentInfo[] segmentInfos, Vp8EncProba proba) - { - const int numBlocks = 8; - Vp8SegmentInfo dqm = segmentInfos[it.CurrentMacroBlockInfo.Segment]; - int lambda = dqm.LambdaUv; - Span src = it.YuvIn.AsSpan(Vp8EncIterator.UOffEnc); - Span tmpDst = it.YuvOut2.AsSpan(Vp8EncIterator.UOffEnc); - Span dst0 = it.YuvOut.AsSpan(Vp8EncIterator.UOffEnc); - Span dst = dst0; - - // Reuse the iterator scratch accumulators instead of allocating per macroblock. Only the - // scores of rdBest are read, and rdUv is cleared before every mode, so neither needs clearing here. - Vp8ModeScore rdBest = it.RdScratch2; - Vp8ModeScore rdUv = it.RdScratch3; - Vp8Residual res = it.ResidualScratch; - int mode; - - rd.ModeUv = -1; - rdBest.InitScore(); - for (mode = 0; mode < WebpConstants.NumPredModes; ++mode) - { - rdUv.Clear(); - - // Reconstruct - rdUv.Nz = (uint)ReconstructUv(it, dqm, rdUv, tmpDst, mode); - - // Compute RD-score - rdUv.D = LossyUtils.Vp8_Sse16x8(src, tmpDst); - rdUv.SD = 0; // not calling TDisto here: it tends to flatten areas. - rdUv.H = WebpConstants.Vp8FixedCostsUv[mode]; - rdUv.R = it.GetCostUv(rdUv, proba, res); - if (mode > 0 && IsFlat(rdUv.UvLevels, numBlocks, WebpConstants.FlatnessLimitIUv)) - { - rdUv.R += WebpConstants.FlatnessPenality * numBlocks; - } - - rdUv.SetRdScore(lambda); - if (mode == 0 || rdUv.Score < rdBest.Score) - { - rdBest.CopyScore(rdUv); - rd.ModeUv = mode; - rdUv.UvLevels.CopyTo(rd.UvLevels.AsSpan()); - for (int i = 0; i < 2; i++) - { - rd.Derr[i, 0] = rdUv.Derr[i, 0]; - rd.Derr[i, 1] = rdUv.Derr[i, 1]; - rd.Derr[i, 2] = rdUv.Derr[i, 2]; - } - - RuntimeUtility.Swap(ref tmpDst, ref dst); - } - } - - it.SetIntraUvMode(rd.ModeUv); - rd.AddScore(rdBest); - if (dst != dst0) - { - // copy 16x8 block if needed. - LossyUtils.Vp8Copy16X8(dst, dst0); - } - - // Store diffusion errors for next block. - it.StoreDiffusionErrors(rd); - } - - public static int ReconstructIntra16(Vp8EncIterator it, Vp8SegmentInfo dqm, Vp8ModeScore rd, Span yuvOut, int mode) - { - Span reference = it.YuvP.AsSpan(Vp8Encoding.Vp8I16ModeOffsets[mode]); - Span src = it.YuvIn.AsSpan(Vp8EncIterator.YOffEnc); - int nz = 0; - int n; - Span shortScratchSpan = it.Scratch2.AsSpan(); - Span scratch = it.Scratch3.AsSpan(); - shortScratchSpan.Clear(); - scratch.Clear(); - Span dcTmp = shortScratchSpan[..16]; - Span tmp = shortScratchSpan.Slice(16, 16 * 16); - - for (n = 0; n < 16; n += 2) - { - Vp8Encoding.FTransform2( - src[WebpLookupTables.Vp8Scan[n]..], - reference[WebpLookupTables.Vp8Scan[n]..], - tmp.Slice(n * 16, 16), - tmp.Slice((n + 1) * 16, 16), - scratch); - } - - Vp8Encoding.FTransformWht(tmp, dcTmp, scratch); - nz |= QuantizeBlock(dcTmp, rd.YDcLevels, ref dqm.Y2) << 24; - - for (n = 0; n < 16; n += 2) - { - // Zero-out the first coeff, so that: a) nz is correct below, and - // b) finding 'last' non-zero coeffs in SetResidualCoeffs() is simplified. - tmp[n * 16] = tmp[(n + 1) * 16] = 0; - nz |= Quantize2Blocks(tmp.Slice(n * 16, 32), rd.YAcLevels.AsSpan(n * 16, 32), ref dqm.Y1) << n; - } - - // Transform back. - LossyUtils.TransformWht(dcTmp, tmp, scratch); - for (n = 0; n < 16; n += 2) - { - Vp8Encoding.ITransformTwo(reference[WebpLookupTables.Vp8Scan[n]..], tmp.Slice(n * 16, 32), yuvOut[WebpLookupTables.Vp8Scan[n]..], scratch); - } - - return nz; - } - - public static int ReconstructIntra4(Vp8EncIterator it, Vp8SegmentInfo dqm, Span levels, Span src, Span yuvOut, int mode) - { - Span reference = it.YuvP.AsSpan(Vp8Encoding.Vp8I4ModeOffsets[mode]); - Span tmp = it.Scratch2.AsSpan(0, 16); - Span scratch = it.Scratch3.AsSpan(); - Vp8Encoding.FTransform(src, reference, tmp, scratch); - int nz = QuantizeBlock(tmp, levels, ref dqm.Y1); - Vp8Encoding.ITransformOne(reference, tmp, yuvOut, scratch); - - return nz; - } - - public static int ReconstructUv(Vp8EncIterator it, Vp8SegmentInfo dqm, Vp8ModeScore rd, Span yuvOut, int mode) - { - Span reference = it.YuvP.AsSpan(Vp8Encoding.Vp8UvModeOffsets[mode]); - Span src = it.YuvIn.AsSpan(Vp8EncIterator.UOffEnc); - int nz = 0; - int n; - Span tmp = it.Scratch2.AsSpan(0, 8 * 16); - Span scratch = it.Scratch3.AsSpan(); - - for (n = 0; n < 8; n += 2) - { - Vp8Encoding.FTransform2( - src[WebpLookupTables.Vp8ScanUv[n]..], - reference[WebpLookupTables.Vp8ScanUv[n]..], - tmp.Slice(n * 16, 16), - tmp.Slice((n + 1) * 16, 16), - scratch); - } - - CorrectDcValues(it, ref dqm.Uv, tmp, rd); - - for (n = 0; n < 8; n += 2) - { - nz |= Quantize2Blocks(tmp.Slice(n * 16, 32), rd.UvLevels.AsSpan(n * 16, 32), ref dqm.Uv) << n; - } - - for (n = 0; n < 8; n += 2) - { - Vp8Encoding.ITransformTwo(reference[WebpLookupTables.Vp8ScanUv[n]..], tmp.Slice(n * 16, 32), yuvOut[WebpLookupTables.Vp8ScanUv[n]..], scratch); - } - - return nz << 16; - } - - // Refine intra16/intra4 sub-modes based on distortion only (not rate). - public static void RefineUsingDistortion( - Vp8EncIterator it, - Vp8SegmentInfo[] segmentInfos, - Vp8ModeScore rd, - bool tryBothModes, - bool refineUvMode, - int mbHeaderLimit) - { - long bestScore = Vp8ModeScore.MaxCost; - int nz = 0; - int mode; - bool isI16 = tryBothModes || it.CurrentMacroBlockInfo.MacroBlockType == Vp8MacroBlockType.I16X16; - Vp8SegmentInfo dqm = segmentInfos[it.CurrentMacroBlockInfo.Segment]; - - // Some empiric constants, of approximate order of magnitude. - const int lambdaDi16 = 106; - const int lambdaDi4 = 11; - const int lambdaDuv = 120; - long scoreI4 = dqm.I4Penalty; - long i4BitSum = 0; - long bitLimit = tryBothModes - ? mbHeaderLimit - : Vp8ModeScore.MaxCost; // no early-out allowed. - - if (isI16) - { - int bestMode = -1; - Span src = it.YuvIn.AsSpan(Vp8EncIterator.YOffEnc); - for (mode = 0; mode < WebpConstants.NumPredModes; ++mode) - { - Span reference = it.YuvP.AsSpan(Vp8Encoding.Vp8I16ModeOffsets[mode]); - long score = (LossyUtils.Vp8_Sse16x16(src, reference) * WebpConstants.RdDistoMult) + (WebpConstants.Vp8FixedCostsI16[mode] * lambdaDi16); - - if (mode > 0 && WebpConstants.Vp8FixedCostsI16[mode] > bitLimit) - { - continue; - } - - if (score < bestScore) - { - bestMode = mode; - bestScore = score; - } - } - - if (it.X == 0 || it.Y == 0) - { - // Avoid starting a checkerboard resonance from the border. See bug #432 of libwebp. - if (IsFlatSource16(src)) - { - bestMode = it.X == 0 ? 0 : 2; - tryBothModes = false; // Stick to i16. - } - } - - it.SetIntra16Mode(bestMode); - - // We'll reconstruct later, if i16 mode actually gets selected. - } - - // Next, evaluate Intra4. - if (tryBothModes || !isI16) - { - // We don't evaluate the rate here, but just account for it through a - // constant penalty (i4 mode usually needs more bits compared to i16). - isI16 = false; - it.StartI4(); - do - { - int bestI4Mode = -1; - long bestI4Score = Vp8ModeScore.MaxCost; - Span src = it.YuvIn.AsSpan(Vp8EncIterator.YOffEnc + WebpLookupTables.Vp8Scan[it.I4]); - short[] modeCosts = it.GetCostModeI4(rd.ModesI4); - - it.MakeIntra4Preds(); - for (mode = 0; mode < WebpConstants.NumBModes; ++mode) - { - Span reference = it.YuvP.AsSpan(Vp8Encoding.Vp8I4ModeOffsets[mode]); - long score = (LossyUtils.Vp8_Sse4x4(src, reference) * WebpConstants.RdDistoMult) + (modeCosts[mode] * lambdaDi4); - if (score < bestI4Score) - { - bestI4Mode = mode; - bestI4Score = score; - } - } - - i4BitSum += modeCosts[bestI4Mode]; - rd.ModesI4[it.I4] = (byte)bestI4Mode; - scoreI4 += bestI4Score; - if (scoreI4 >= bestScore || i4BitSum > bitLimit) - { - // Intra4 won't be better than Intra16. Bail out and pick Intra16. - isI16 = true; - break; - } - else - { - // Reconstruct partial block inside YuvOut2 buffer - Span tmpDst = it.YuvOut2.AsSpan(Vp8EncIterator.YOffEnc + WebpLookupTables.Vp8Scan[it.I4]); - nz |= ReconstructIntra4(it, dqm, rd.YAcLevels.AsSpan(it.I4 * 16, 16), src, tmpDst, bestI4Mode) << it.I4; - } - } - while (it.RotateI4(it.YuvOut2.AsSpan(Vp8EncIterator.YOffEnc))); - } - - // Final reconstruction, depending on which mode is selected. - if (!isI16) - { - it.SetIntra4Mode(rd.ModesI4); - it.SwapOut(); - bestScore = scoreI4; - } - else - { - int intra16Mode = it.Preds[it.PredIdx]; - nz = ReconstructIntra16(it, dqm, rd, it.YuvOut.AsSpan(Vp8EncIterator.YOffEnc), intra16Mode); - } - - // ... and UV! - if (refineUvMode) - { - int bestMode = -1; - long bestUvScore = Vp8ModeScore.MaxCost; - Span src = it.YuvIn.AsSpan(Vp8EncIterator.UOffEnc); - for (mode = 0; mode < WebpConstants.NumPredModes; ++mode) - { - Span reference = it.YuvP.AsSpan(Vp8Encoding.Vp8UvModeOffsets[mode]); - long score = (LossyUtils.Vp8_Sse16x8(src, reference) * WebpConstants.RdDistoMult) + (WebpConstants.Vp8FixedCostsUv[mode] * lambdaDuv); - if (score < bestUvScore) - { - bestMode = mode; - bestUvScore = score; - } - } - - it.SetIntraUvMode(bestMode); - } - - nz |= ReconstructUv(it, dqm, rd, it.YuvOut.AsSpan(Vp8EncIterator.UOffEnc), it.CurrentMacroBlockInfo.UvMode); - - rd.Nz = (uint)nz; - rd.Score = bestScore; - } - - [MethodImpl(InliningOptions.ShortMethod)] - public static int Quantize2Blocks(Span input, Span output, ref Vp8Matrix mtx) - { - int nz = QuantizeBlock(input[..16], output[..16], ref mtx) << 0; - nz |= QuantizeBlock(input.Slice(1 * 16, 16), output.Slice(1 * 16, 16), ref mtx) << 1; - return nz; - } - - public static int QuantizeBlock(Span input, Span output, ref Vp8Matrix mtx) - { - if (Avx2.IsSupported) - { - // Load all inputs. - Vector256 input0 = Unsafe.As>(ref MemoryMarshal.GetReference(input)); - Vector256 iq0 = Unsafe.As>(ref mtx.IQ[0]); - Vector256 q0 = Unsafe.As>(ref mtx.Q[0]); - - // coeff = abs(in) - Vector256 coeff0 = Avx2.Abs(input0); - - // Each lane stores the magnitude of one input coefficient. - // Add its sharpening bias before quantization, as the scalar path does. - // A magnitude is at most 32768. Vp8Matrix.Expand limits each bias to 12. - // The sum fits in an unsigned 16-bit lane. - Vector256 sharpen0 = Unsafe.As>(ref mtx.Sharpen[0]); - coeff0 = Avx2.Add(coeff0.AsInt16(), sharpen0).AsUInt16(); - - // out = (coeff * iQ + B) >> QFIX - // doing calculations with 32b precision (QFIX=17) - // out = (coeff * iQ) - Vector256 coeffiQ0H = Avx2.MultiplyHigh(coeff0, iq0); - Vector256 coeffiQ0L = Avx2.MultiplyLow(coeff0, iq0); - Vector256 out00 = Avx2.UnpackLow(coeffiQ0L, coeffiQ0H); - Vector256 out08 = Avx2.UnpackHigh(coeffiQ0L, coeffiQ0H); - - // out = (coeff * iQ + B) - Vector256 bias00 = Unsafe.As>(ref mtx.Bias[0]); - Vector256 bias08 = Unsafe.As>(ref mtx.Bias[8]); - out00 = Avx2.Add(out00.AsInt32(), bias00.AsInt32()).AsUInt16(); - out08 = Avx2.Add(out08.AsInt32(), bias08.AsInt32()).AsUInt16(); - - // out = QUANTDIV(coeff, iQ, B, QFIX) - out00 = Avx2.ShiftRightArithmetic(out00.AsInt32(), WebpConstants.QFix).AsUInt16(); - out08 = Avx2.ShiftRightArithmetic(out08.AsInt32(), WebpConstants.QFix).AsUInt16(); - - // Pack result as 16b. - Vector256 out0 = Avx2.PackSignedSaturate(out00.AsInt32(), out08.AsInt32()); - - // if (coeff > 2047) coeff = 2047 - out0 = Avx2.Min(out0, Vector256.Create((short)MaxLevel)); - - // Put the sign back. - out0 = Avx2.Sign(out0, input0); - - // in = out * Q - input0 = Avx2.MultiplyLow(out0, q0.AsInt16()); - ref short inputRef = ref MemoryMarshal.GetReference(input); - Unsafe.As>(ref inputRef) = input0; - - // zigzag the output before storing it. - Vector256 tmp256 = Avx2.Shuffle( - out0.AsByte(), - Vector256.Create(0, 1, 2, 3, 8, 9, 254, 255, 10, 11, 4, 5, 6, 7, 12, 13, 2, 3, 8, 9, 10, 11, 4, 5, 254, 255, 6, 7, 12, 13, 14, 15)); // Cst256 - Vector256 tmp78 = Avx2.Shuffle( - out0.AsByte(), - Vector256.Create( - 254, - 255, - 254, - 255, - 254, - 255, - 254, - 255, - 14, - 15, - 254, - 255, - 254, - 255, - 254, - 255, - 254, - 255, - 254, - 255, - 254, - 255, - 0, - 1, - 254, - 255, - 254, - 255, - 254, - 255, - 254, - 255)); // Cst78 - - // Reverse the order of the 16-byte lanes. - Vector256 tmp87 = Avx2.Permute2x128(tmp78, tmp78, 1); - Vector256 outZ = Avx2.Or(tmp256, tmp87).AsInt16(); - - ref short outputRef = ref MemoryMarshal.GetReference(output); - Unsafe.As>(ref outputRef) = outZ; - - Vector256 packedOutput = Avx2.PackSignedSaturate(outZ, outZ); - - // Detect if all 'out' values are zeros or not. - Vector256 cmpeq = Avx2.CompareEqual(packedOutput, Vector256.Zero); - return Avx2.MoveMask(cmpeq) != -1 ? 1 : 0; - } - else if (Sse41.IsSupported) - { - // Load all inputs. - Vector128 input0 = Unsafe.As>(ref MemoryMarshal.GetReference(input)); - Vector128 input8 = Unsafe.As>(ref MemoryMarshal.GetReference(input.Slice(8, 8))); - Vector128 iq0 = Unsafe.As>(ref mtx.IQ[0]); - Vector128 iq8 = Unsafe.As>(ref mtx.IQ[8]); - Vector128 q0 = Unsafe.As>(ref mtx.Q[0]); - Vector128 q8 = Unsafe.As>(ref mtx.Q[8]); - - // coeff = abs(in) - Vector128 coeff0 = Ssse3.Abs(input0); - Vector128 coeff8 = Ssse3.Abs(input8); - - // coeff0 holds magnitudes for coefficients 0 through 7. - // coeff8 holds magnitudes for coefficients 8 through 15. - // Add each coefficient's sharpening bias before quantization. - // As in AVX2, each sum fits in an unsigned 16-bit lane. - Vector128 sharpen0 = Unsafe.As>(ref mtx.Sharpen[0]); - Vector128 sharpen8 = Unsafe.As>(ref mtx.Sharpen[8]); - coeff0 = Sse2.Add(coeff0.AsInt16(), sharpen0).AsUInt16(); - coeff8 = Sse2.Add(coeff8.AsInt16(), sharpen8).AsUInt16(); - - // out = (coeff * iQ + B) >> QFIX - // doing calculations with 32b precision (QFIX=17) - // out = (coeff * iQ) - Vector128 coeffiQ0H = Sse2.MultiplyHigh(coeff0, iq0); - Vector128 coeffiQ0L = Sse2.MultiplyLow(coeff0, iq0); - Vector128 coeffiQ8H = Sse2.MultiplyHigh(coeff8, iq8); - Vector128 coeffiQ8L = Sse2.MultiplyLow(coeff8, iq8); - Vector128 out00 = Sse2.UnpackLow(coeffiQ0L, coeffiQ0H); - Vector128 out04 = Sse2.UnpackHigh(coeffiQ0L, coeffiQ0H); - Vector128 out08 = Sse2.UnpackLow(coeffiQ8L, coeffiQ8H); - Vector128 out12 = Sse2.UnpackHigh(coeffiQ8L, coeffiQ8H); - - // out = (coeff * iQ + B) - Vector128 bias00 = Unsafe.As>(ref mtx.Bias[0]); - Vector128 bias04 = Unsafe.As>(ref mtx.Bias[4]); - Vector128 bias08 = Unsafe.As>(ref mtx.Bias[8]); - Vector128 bias12 = Unsafe.As>(ref mtx.Bias[12]); - out00 = Sse2.Add(out00.AsInt32(), bias00.AsInt32()).AsUInt16(); - out04 = Sse2.Add(out04.AsInt32(), bias04.AsInt32()).AsUInt16(); - out08 = Sse2.Add(out08.AsInt32(), bias08.AsInt32()).AsUInt16(); - out12 = Sse2.Add(out12.AsInt32(), bias12.AsInt32()).AsUInt16(); - - // out = QUANTDIV(coeff, iQ, B, QFIX) - out00 = Sse2.ShiftRightArithmetic(out00.AsInt32(), WebpConstants.QFix).AsUInt16(); - out04 = Sse2.ShiftRightArithmetic(out04.AsInt32(), WebpConstants.QFix).AsUInt16(); - out08 = Sse2.ShiftRightArithmetic(out08.AsInt32(), WebpConstants.QFix).AsUInt16(); - out12 = Sse2.ShiftRightArithmetic(out12.AsInt32(), WebpConstants.QFix).AsUInt16(); - - // Pack result as 16b. - Vector128 out0 = Sse2.PackSignedSaturate(out00.AsInt32(), out04.AsInt32()); - Vector128 out8 = Sse2.PackSignedSaturate(out08.AsInt32(), out12.AsInt32()); - - // if (coeff > 2047) coeff = 2047 - Vector128 maxCoeff2047 = Vector128.Create((short)MaxLevel); - out0 = Sse2.Min(out0, maxCoeff2047); - out8 = Sse2.Min(out8, maxCoeff2047); - - // Put the sign back. - out0 = Ssse3.Sign(out0, input0); - out8 = Ssse3.Sign(out8, input8); - - // in = out * Q - input0 = Sse2.MultiplyLow(out0, q0.AsInt16()); - input8 = Sse2.MultiplyLow(out8, q8.AsInt16()); - - // in = out * Q - ref short inputRef = ref MemoryMarshal.GetReference(input); - Unsafe.As>(ref inputRef) = input0; - Unsafe.As>(ref Unsafe.Add(ref inputRef, 8)) = input8; - - // zigzag the output before storing it. The re-ordering is: - // 0 1 2 3 4 5 6 7 | 8 9 10 11 12 13 14 15 - // -> 0 1 4[8]5 2 3 6 | 9 12 13 10 [7]11 14 15 - // There's only two misplaced entries ([8] and [7]) that are crossing the - // reg's boundaries. - // We use pshufb instead of pshuflo/pshufhi. - Vector128 tmpLo = Ssse3.Shuffle(out0.AsByte(), Vector128.Create(0, 1, 2, 3, 8, 9, 254, 255, 10, 11, 4, 5, 6, 7, 12, 13)); - Vector128 tmp7 = Ssse3.Shuffle( - out0.AsByte(), - Vector128.Create(254, 255, 254, 255, 254, 255, 254, 255, 14, 15, 254, 255, 254, 255, 254, 255)); // extract #7 - Vector128 tmpHi = Ssse3.Shuffle(out8.AsByte(), Vector128.Create(2, 3, 8, 9, 10, 11, 4, 5, 254, 255, 6, 7, 12, 13, 14, 15)); - - Vector128 tmp8 = Ssse3.Shuffle( - out8.AsByte(), - Vector128.Create(254, 255, 254, 255, 254, 255, 0, 1, 254, 255, 254, 255, 254, 255, 254, 255)); // extract #8 - Vector128 outZ0 = Sse2.Or(tmpLo, tmp8); - Vector128 outZ8 = Sse2.Or(tmpHi, tmp7); - - ref short outputRef = ref MemoryMarshal.GetReference(output); - Unsafe.As>(ref outputRef) = outZ0.AsInt16(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, 8)) = outZ8.AsInt16(); - - Vector128 packedOutput = Sse2.PackSignedSaturate(outZ0.AsInt16(), outZ8.AsInt16()); - - // Detect if all 'out' values are zeros or not. - Vector128 cmpeq = Sse2.CompareEqual(packedOutput, Vector128.Zero); - return Sse2.MoveMask(cmpeq) != 0xffff ? 1 : 0; - } - else - { - int last = -1; - int n; - for (n = 0; n < 16; ++n) - { - int j = Zigzag[n]; - bool sign = input[j] < 0; - uint coeff = (uint)((sign ? -input[j] : input[j]) + mtx.Sharpen[j]); - if (coeff > mtx.ZThresh[j]) - { - uint q = mtx.Q[j]; - uint iQ = mtx.IQ[j]; - uint b = mtx.Bias[j]; - int level = QuantDiv(coeff, iQ, b); - if (level > MaxLevel) - { - level = MaxLevel; - } - - if (sign) - { - level = -level; - } - - input[j] = (short)(level * (int)q); - output[n] = (short)level; - if (level != 0) - { - last = n; - } - } - else - { - output[n] = 0; - input[j] = 0; - } - } - - return last >= 0 ? 1 : 0; - } - } - - // Quantize as usual, but also compute and return the quantization error. - // Error is already divided by DSHIFT. - public static int QuantizeSingle(Span v, ref Vp8Matrix mtx) - { - int v0 = v[0]; - bool sign = v0 < 0; - if (sign) - { - v0 = -v0; - } - - if (v0 > (int)mtx.ZThresh[0]) - { - int qV = QuantDiv((uint)v0, mtx.IQ[0], mtx.Bias[0]) * mtx.Q[0]; - int err = v0 - qV; - v[0] = (short)(sign ? -qV : qV); - return (sign ? -err : err) >> DSCALE; - } - - v[0] = 0; - return (sign ? -v0 : v0) >> DSCALE; - } - - public static void CorrectDcValues(Vp8EncIterator it, ref Vp8Matrix mtx, Span tmp, Vp8ModeScore rd) - { -#pragma warning disable SA1005 // Single line comments should begin with single space - // | top[0] | top[1] - // --------+--------+--------- - // left[0] | tmp[0] tmp[1] <-> err0 err1 - // left[1] | tmp[2] tmp[3] err2 err3 - // - // Final errors {err1,err2,err3} are preserved and later restored - // as top[]/left[] on the next block. -#pragma warning restore SA1005 // Single line comments should begin with single space - for (int ch = 0; ch <= 1; ++ch) - { - Span top = it.TopDerr.AsSpan((it.X * 4) + ch, 2); - Span left = it.LeftDerr.AsSpan(ch, 2); - Span c = tmp.Slice(ch * 4 * 16, 4 * 16); - c[0] += (short)(((C1 * top[0]) + (C2 * left[0])) >> (DSHIFT - DSCALE)); - int err0 = QuantizeSingle(c, ref mtx); - c[1 * 16] += (short)(((C1 * top[1]) + (C2 * err0)) >> (DSHIFT - DSCALE)); - int err1 = QuantizeSingle(c[(1 * 16)..], ref mtx); - c[2 * 16] += (short)(((C1 * err0) + (C2 * left[1])) >> (DSHIFT - DSCALE)); - int err2 = QuantizeSingle(c[(2 * 16)..], ref mtx); - c[3 * 16] += (short)(((C1 * err1) + (C2 * err2)) >> (DSHIFT - DSCALE)); - int err3 = QuantizeSingle(c[(3 * 16)..], ref mtx); - - rd.Derr[ch, 0] = err1; - rd.Derr[ch, 1] = err2; - rd.Derr[ch, 2] = err3; - } - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static bool IsFlatSource16(Span src) - { - uint v = src[0] * 0x01010101u; - Span vSpan = BitConverter.GetBytes(v).AsSpan(); - for (nuint i = 0; i < 16; i++) - { - if (!src[..4].SequenceEqual(vSpan) || !src.Slice(4, 4).SequenceEqual(vSpan) || - !src.Slice(8, 4).SequenceEqual(vSpan) || !src.Slice(12, 4).SequenceEqual(vSpan)) - { - return false; - } - - src = src[WebpConstants.Bps..]; - } - - return true; - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static bool IsFlat(Span levels, int numBlocks, int thresh) - { - int score = 0; - ref short levelsRef = ref MemoryMarshal.GetReference(levels); - nuint offset = 0; - while (numBlocks-- > 0) - { - for (nuint i = 1; i < 16; i++) - { - // omit DC, we're only interested in AC - score += Unsafe.Add(ref levelsRef, offset + i) != 0 ? 1 : 0; - if (score > thresh) - { - return false; - } - } - - offset += 16; - } - - return true; - } - - [MethodImpl(InliningOptions.ShortMethod)] - private static int Mult8B(int a, int b) => ((a * b) + 128) >> 8; - - [MethodImpl(InliningOptions.ShortMethod)] - private static int QuantDiv(uint n, uint iQ, uint b) => (int)(((n * iQ) + b) >> WebpConstants.QFix); -} diff --git a/src/ImageSharp/Formats/Webp/Lossy/RgbToYuvConverter{TPixel}.cs b/src/ImageSharp/Formats/Webp/Lossy/RgbToYuvConverter{TPixel}.cs new file mode 100644 index 0000000000..634b797f88 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossy/RgbToYuvConverter{TPixel}.cs @@ -0,0 +1,178 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Buffers; +using System.Numerics; +using SixLabors.ImageSharp.ColorProfiles; +using SixLabors.ImageSharp.Formats.Webp.ColorConverters; +using SixLabors.ImageSharp.Memory; +using SixLabors.ImageSharp.PixelFormats; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossy; + +/// +/// Converts the pixels of an image region to the Y, U, V planes and the alpha plane that the lossy encoder reads. +/// +/// The source pixel format. +internal sealed class RgbToYuvConverter + where TPixel : unmanaged, IPixel +{ + /// + /// The pixel conversion configuration. + /// + private readonly Configuration configuration; + + /// + /// The allocator for temporary row storage and the alpha plane. + /// + private readonly MemoryAllocator memoryAllocator; + + /// + /// The return transform from sRGB to the encoded RGB profile, or null when no transform is required. + /// + private readonly ColorProfileConverter? converter; + + /// + /// A value indicating whether pixels with zero alpha are encoded with all components set to zero. + /// + private readonly bool clearTransparentPixels; + + /// + /// The converter that turns BGRA rows into the Y, U and V planes. + /// + private readonly WebpColorConverterBase colorConverter = WebpColorConverterBase.GetConverter(WebpColorType.Yuv); + + /// + /// Initializes a new instance of the class. + /// + /// The pixel conversion configuration. + /// The allocator for temporary row storage and the alpha plane. + /// The return transform from sRGB to the encoded RGB profile, or null. + /// Whether pixels with zero alpha are encoded with all components set to zero. + public RgbToYuvConverter(Configuration configuration, MemoryAllocator memoryAllocator, ColorProfileConverter? converter, bool clearTransparentPixels) + { + this.configuration = configuration; + this.memoryAllocator = memoryAllocator; + this.converter = converter; + this.clearTransparentPixels = clearTransparentPixels; + } + + /// + /// Converts an image region to full-resolution luma and half-resolution chroma planes. + /// The same pass extracts the full-resolution alpha plane when the region is non-opaque. + /// + /// The source image region. + /// Reusable straight RGBA row scratch, empty when no transform and no clear is required. + /// The full-resolution luma plane. A row of the region is the start of a plane row. + /// The half-resolution U plane. + /// The half-resolution V plane. + /// + /// The alpha plane with the size of the region when any source pixel is non-opaque; otherwise, null. + /// The caller owns and disposes the alpha plane. + /// + public Buffer2D? Convert(Buffer2DRegion frame, Span vectors, Buffer2D y, Buffer2D u, Buffer2D v) + { + MemoryAllocator memoryAllocator = this.memoryAllocator; + WebpColorConverterBase colorConverter = this.colorConverter; + Configuration configuration = this.configuration; + ColorProfileConverter? converter = this.converter; + bool clear = this.clearTransparentPixels; + int width = frame.Width; + int height = frame.Height; + int uvWidth = (width + 1) >> 1; + + // Reuse two BGRA source rows. As in the JPEG encoder, one converter call for each row pair does all color math. + using IMemoryOwner bgraRow0Buffer = memoryAllocator.Allocate(width); + using IMemoryOwner bgraRow1Buffer = memoryAllocator.Allocate(width); + Span bgraRow0 = bgraRow0Buffer.GetSpan()[..width]; + Span bgraRow1 = bgraRow1Buffer.GetSpan()[..width]; + int uvRowIndex = 0; + int rowIndex; + + // The alpha plane is allocated at the first non-opaque row, so an opaque image needs no plane. Until then, the alpha + // values of the current rows go to this scratch, because the extraction also gives the opaque result. + using IMemoryOwner alphaRowsBuffer = memoryAllocator.Allocate(2 * width); + Span alphaRows = alphaRowsBuffer.GetSpan(); + Buffer2D? alphaBuffer = null; + + try + { + for (rowIndex = 0; rowIndex < height - 1; rowIndex += 2) + { + WebpColorConverterBase.ConvertSourceToBgra(configuration, frame.DangerousGetRowSpan(rowIndex), converter, clear, vectors, bgraRow0); + WebpColorConverterBase.ConvertSourceToBgra(configuration, frame.DangerousGetRowSpan(rowIndex + 1), converter, clear, vectors, bgraRow1); + + // Both rows contribute to each chroma sample; transparency in either row requires alpha-weighted resampling. + Span alphaRow0 = alphaBuffer is null ? alphaRows[..width] : alphaBuffer.DangerousGetRowSpan(rowIndex); + Span alphaRow1 = alphaBuffer is null ? alphaRows[width..] : alphaBuffer.DangerousGetRowSpan(rowIndex + 1); + bool row0Opaque = AlphaEncoder.ExtractAlpha(bgraRow0, alphaRow0); + bool row1Opaque = AlphaEncoder.ExtractAlpha(bgraRow1, alphaRow1); + bool rowsHaveAlpha = !(row0Opaque && row1Opaque); + if (rowsHaveAlpha && alphaBuffer is null) + { + alphaBuffer = memoryAllocator.Allocate2D(width, height); + + // All earlier rows are opaque, so each of their alpha values is 255. + for (int r = 0; r < rowIndex; r++) + { + alphaBuffer.DangerousGetRowSpan(r).Fill(byte.MaxValue); + } + + alphaRow0.CopyTo(alphaBuffer.DangerousGetRowSpan(rowIndex)); + alphaRow1.CopyTo(alphaBuffer.DangerousGetRowSpan(rowIndex + 1)); + } + + colorConverter.ConvertFromRgb( + bgraRow0, + bgraRow1, + rowsHaveAlpha, + y.DangerousGetRowSpan(rowIndex)[..width], + y.DangerousGetRowSpan(rowIndex + 1)[..width], + u.DangerousGetRowSpan(uvRowIndex)[..uvWidth], + v.DangerousGetRowSpan(uvRowIndex)[..uvWidth]); + + uvRowIndex++; + } + + // Repeat the final row when height is odd so chroma still receives a complete 2x2 sample group. + if ((height & 1) != 0) + { + WebpColorConverterBase.ConvertSourceToBgra(configuration, frame.DangerousGetRowSpan(rowIndex), converter, clear, vectors, bgraRow0); + + Span rowAlpha = alphaBuffer is null ? alphaRows[..width] : alphaBuffer.DangerousGetRowSpan(rowIndex); + bool rowOpaque = AlphaEncoder.ExtractAlpha(bgraRow0, rowAlpha); + if (!rowOpaque && alphaBuffer is null) + { + alphaBuffer = memoryAllocator.Allocate2D(width, height); + + // All earlier rows are opaque, so each of their alpha values is 255. + for (int r = 0; r < rowIndex; r++) + { + alphaBuffer.DangerousGetRowSpan(r).Fill(byte.MaxValue); + } + + rowAlpha.CopyTo(alphaBuffer.DangerousGetRowSpan(rowIndex)); + } + + // The final row is both rows of its chroma groups, and only its first luma row is output. + colorConverter.ConvertFromRgb( + bgraRow0, + bgraRow0, + !rowOpaque, + y.DangerousGetRowSpan(rowIndex)[..width], + default, + u.DangerousGetRowSpan(uvRowIndex)[..uvWidth], + v.DangerousGetRowSpan(uvRowIndex)[..uvWidth]); + } + } + catch + { + // The caller owns the alpha plane only after this method returns. A row conversion can throw after + // the allocation, for example in the ICC transform, so dispose the plane here. + alphaBuffer?.Dispose(); + throw; + } + + return alphaBuffer; + } +} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8BandProbas.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8BandProbas.cs deleted file mode 100644 index 90506efb81..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8BandProbas.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossy; - -/// -/// All the probabilities associated to one band. -/// -internal class Vp8BandProbas -{ - /// - /// Initializes a new instance of the class. - /// - public Vp8BandProbas() - { - this.Probabilities = new Vp8ProbaArray[WebpConstants.NumCtx]; - for (int i = 0; i < WebpConstants.NumCtx; i++) - { - this.Probabilities[i] = new Vp8ProbaArray(); - } - } - - /// - /// Gets the Probabilities. - /// - public Vp8ProbaArray[] Probabilities { get; } -} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8CostArray.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8CostArray.cs deleted file mode 100644 index 2c8d723d74..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8CostArray.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossy; - -internal class Vp8CostArray -{ - /// - /// Initializes a new instance of the class. - /// - public Vp8CostArray() => this.Costs = new ushort[67 + 1]; - - public ushort[] Costs { get; } -} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Costs.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Costs.cs deleted file mode 100644 index eee22159e1..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Costs.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossy; - -internal class Vp8Costs -{ - /// - /// Initializes a new instance of the class. - /// - public Vp8Costs() - { - this.Costs = new Vp8CostArray[WebpConstants.NumCtx]; - for (int i = 0; i < WebpConstants.NumCtx; i++) - { - this.Costs[i] = new Vp8CostArray(); - } - } - - /// - /// Gets the Costs. - /// - public Vp8CostArray[] Costs { get; } -} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Decoder.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Decoder.cs index 2882911807..55aea10023 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Decoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Decoder.cs @@ -13,13 +13,35 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy; /// internal class Vp8Decoder : IDisposable { - // The widest upsampling block produces 64 pixels. Keep U and V for each of its two output rows in separate planes. - private const int UpsamplingBufferSize = 4 * 64; + /// + /// The number of coefficients of one macroblock: 24 blocks of 16 values. + /// + public const int CoefficientsPerMacroBlock = 384; + + /// + /// The number of top samples of one macroblock column in : 16 Y samples, then 8 U samples and 8 V samples. + /// + public const int TopSamplesPerMacroBlock = 32; + + /// + /// The offset of the 8 U samples in the top samples of one macroblock column. + /// + public const int TopSamplesUOffset = 16; + + /// + /// The offset of the 8 V samples in the top samples of one macroblock column. + /// + public const int TopSamplesVOffset = 24; + /// + /// The non-zero coefficient context of the macroblock to the left of the current one. + /// private Vp8MacroBlock leftMacroBlock; - // Reuse the four 64-byte chroma planes for each upsampling block. - private IMemoryOwner upsamplingBuffer; + /// + /// The left intra modes: one 4x4 mode for each block row of the current macroblock. + /// + private InlineArray4 intraL; /// /// Initializes a new instance of the class. @@ -32,41 +54,23 @@ public Vp8Decoder( Vp8FrameHeader frameHeader, Vp8PictureHeader pictureHeader, Vp8SegmentHeader segmentHeader, - Vp8Proba probabilities) + Vp8Probabilities probabilities) { this.FilterHeader = new Vp8FilterHeader(); this.FrameHeader = frameHeader; this.PictureHeader = pictureHeader; this.SegmentHeader = segmentHeader; this.Probabilities = probabilities; - this.IntraL = new byte[4]; this.MbWidth = (int)((this.PictureHeader.Width + 15) >> 4); this.MbHeight = (int)((this.PictureHeader.Height + 15) >> 4); this.CacheYStride = 16 * this.MbWidth; this.CacheUvStride = 8 * this.MbWidth; - this.MacroBlockInfo = new Vp8MacroBlock[this.MbWidth + 1]; - this.MacroBlockData = new Vp8MacroBlockData[this.MbWidth]; - this.YuvTopSamples = new Vp8TopSamples[this.MbWidth]; - this.FilterInfo = new Vp8FilterInfo[this.MbWidth]; - for (int i = 0; i < this.MbWidth; i++) - { - this.MacroBlockInfo[i] = new Vp8MacroBlock(); - this.MacroBlockData[i] = new Vp8MacroBlockData(); - this.YuvTopSamples[i] = new Vp8TopSamples(); - this.FilterInfo[i] = new Vp8FilterInfo(); - } - - this.MacroBlockInfo[this.MbWidth] = new Vp8MacroBlock(); - this.DeQuantMatrices = new Vp8QuantMatrix[WebpConstants.NumMbSegments]; + this.DeQuantMatrices = new Vp8QuantizationMatrix[WebpConstants.NumMbSegments]; this.FilterStrength = new Vp8FilterInfo[WebpConstants.NumMbSegments, 2]; for (int i = 0; i < WebpConstants.NumMbSegments; i++) { - this.DeQuantMatrices[i] = new Vp8QuantMatrix(); - for (int j = 0; j < 2; j++) - { - this.FilterStrength[i, j] = new Vp8FilterInfo(); - } + this.DeQuantMatrices[i] = new Vp8QuantizationMatrix(); } this.Vp8BitReaders = new Vp8BitReader[WebpConstants.MaxNumPartitions]; @@ -105,7 +109,7 @@ public Vp8Decoder( /// /// Gets the dequantization matrices (one set of DC/AC dequant factor per segment). /// - public Vp8QuantMatrix[] DeQuantMatrices { get; } + public Vp8QuantizationMatrix[] DeQuantMatrices { get; } /// /// Gets or sets a value indicating whether to use the skip probabilities. @@ -120,17 +124,17 @@ public Vp8Decoder( /// /// Gets or sets the Probabilities. /// - public Vp8Proba Probabilities { get; set; } + public Vp8Probabilities Probabilities { get; set; } /// - /// Gets or sets the top intra modes values: 4 * MbWidth. + /// Gets the top intra modes: 4 modes for each macroblock column. creates it with all modes 0. /// - public byte[] IntraT { get; set; } + public IMemoryOwner IntraT { get; private set; } /// - /// Gets the left intra modes values. + /// Gets the left intra modes: one 4x4 mode for each block row of the current macroblock. /// - public byte[] IntraL { get; } + public Span IntraL => this.intraL; /// /// Gets the width in macroblock units. @@ -173,14 +177,15 @@ public Vp8Decoder( public int MbY { get; set; } /// - /// Gets the parsed reconstruction data. + /// Gets the parsed reconstruction data: one value for each macroblock column of the current macroblock row. creates it. /// - public Vp8MacroBlockData[] MacroBlockData { get; } + public IMemoryOwner MacroBlockData { get; private set; } /// - /// Gets the contextual macroblock info. + /// Gets the non-zero coefficient context of each macroblock column. Before the residual parse of a column, it holds the flags of the macroblock + /// above. After the parse, it holds the flags of the current macroblock. creates it with all flags 0. /// - public Vp8MacroBlock[] MacroBlockInfo { get; } + public IMemoryOwner MacroBlockInfo { get; private set; } /// /// Gets or sets the loop filter used. The purpose of the loop filter is to eliminate (or at least reduce) @@ -193,51 +198,92 @@ public Vp8Decoder( /// public Vp8FilterInfo[,] FilterStrength { get; } + /// + /// Gets the dequantized coefficients of each macroblock of the current macroblock row: values for each + /// macroblock column, 16 luma blocks, then 4 U and 4 V blocks of 16 values. creates it. + /// + public IMemoryOwner Coefficients { get; private set; } + + /// + /// Gets the work buffer in which the decoder reconstructs one macroblock. It holds the Y, U and V samples with the top and left border samples + /// that the prediction reads. The row stride is . creates it. + /// public IMemoryOwner YuvBuffer { get; private set; } - public Vp8TopSamples[] YuvTopSamples { get; } + /// + /// Gets the bottom Y, U and V samples of each macroblock in the previous macroblock row. The prediction of the current row uses them as the top samples. + /// Each macroblock column has bytes at the offsets and + /// . creates it. + /// + public IMemoryOwner YuvTopSamples { get; private set; } + /// + /// Gets the luma cache. It holds the reconstructed luma rows of the current macroblock row, after the extra rows of the previous macroblock row + /// that the loop filter still changes. The row stride is . creates it. + /// public IMemoryOwner CacheY { get; private set; } + /// + /// Gets the U cache. It has the same layout as at half resolution. The row stride is . + /// public IMemoryOwner CacheU { get; private set; } + /// + /// Gets the V cache. It has the same layout as at half resolution. The row stride is . + /// public IMemoryOwner CacheV { get; private set; } + /// + /// Gets or sets the offset in of the first row of the current macroblock row. The bytes before it hold the extra rows + /// that the loop filter needs. + /// public int CacheYOffset { get; set; } + /// + /// Gets or sets the offset in and of the first row of the current macroblock row. + /// public int CacheUvOffset { get; set; } + /// + /// Gets the row stride of in bytes. It is 16 times . + /// public int CacheYStride { get; } + /// + /// Gets the row stride of and in bytes. It is 8 times . + /// public int CacheUvStride { get; } + /// + /// Gets the buffer for the last luma row of an emitted range. The chroma upsampler needs the next chroma row to finish that row, + /// so the next call writes it. + /// public IMemoryOwner TmpYBuffer { get; private set; } + /// + /// Gets the buffer for the last U row of an emitted range. The next call uses it as the top U row of the upsampler. + /// public IMemoryOwner TmpUBuffer { get; private set; } + /// + /// Gets the buffer for the last V row of an emitted range. The next call uses it as the top V row of the upsampler. + /// public IMemoryOwner TmpVBuffer { get; private set; } /// - /// Gets the pixel buffer where the decoded pixel data will be stored. + /// Gets the loop filter strength of each macroblock column of the current macroblock row. creates it. /// - public IMemoryOwner Pixels { get; private set; } + public IMemoryOwner FilterInfo { get; private set; } /// - /// Gets the reusable workspace used while upsampling YUV rows. + /// Gets the non-zero coefficient context of the macroblock to the left of the current one. The decoder clears it at the start of each macroblock row. /// - public Span UpsamplingBuffer => this.upsamplingBuffer.Memory.Span[..UpsamplingBufferSize]; + public ref Vp8MacroBlock LeftMacroBlock => ref this.leftMacroBlock; /// - /// Gets or sets filter info. + /// Calculates the loop filter strengths for each segment, for macroblocks with and without 4x4 prediction. The result goes to + /// . The method does nothing when the loop filter is off. /// - public Vp8FilterInfo[] FilterInfo { get; set; } - - public Vp8MacroBlock CurrentMacroBlock => this.MacroBlockInfo[this.MbX]; - - public Vp8MacroBlock LeftMacroBlock => this.leftMacroBlock ??= new Vp8MacroBlock(); - - public Vp8MacroBlockData CurrentBlockData => this.MacroBlockData[this.MbX]; - public void PrecomputeFilterStrengths() { if (this.Filter == LoopFilter.None) @@ -266,7 +312,7 @@ public void PrecomputeFilterStrengths() for (int i4x4 = 0; i4x4 <= 1; i4x4++) { - Vp8FilterInfo info = this.FilterStrength[s, i4x4]; + ref Vp8FilterInfo info = ref this.FilterStrength[s, i4x4]; int level = baseLevel; if (hdr.UseLfDelta) { @@ -319,8 +365,8 @@ public void PrecomputeFilterStrengths() } /// - /// Allocates the buffers that the macroblock decode uses: the YUV work buffer, the row caches, the temporary rows, the upsampling workspace - /// and the output pixels. + /// Allocates the buffers that the macroblock decode uses: the state of each macroblock column, the YUV work buffer, the row caches, the temporary + /// rows, the upsampling workspace and the output pixels. /// /// /// The header parse needs none of these buffers, and it runs before the decoder creates the image. The decoder calls this method after it @@ -330,21 +376,35 @@ public void PrecomputeFilterStrengths() public void AllocateBuffers(MemoryAllocator memoryAllocator) { uint width = this.PictureHeader.Width; - uint height = this.PictureHeader.Height; int extraRows = WebpConstants.FilterExtraRows[(int)LoopFilter.Complex]; // assuming worst case: complex filter int extraY = extraRows * this.CacheYStride; int extraUv = extraRows / 2 * this.CacheUvStride; - this.YuvBuffer = memoryAllocator.Allocate((WebpConstants.Bps * 17) + (WebpConstants.Bps * 9) + extraY); - this.CacheY = memoryAllocator.Allocate((16 * this.CacheYStride) + extraY, AllocationOptions.Clean); - int cacheUvSize = (16 * this.CacheUvStride) + extraUv; + + // The work buffer holds 17 luma rows (the top row and 16 rows) and 9 chroma rows (the top row and 8 rows), each with a stride of Bps. + this.YuvBuffer = memoryAllocator.Allocate((WebpConstants.Bps * 17) + (WebpConstants.Bps * 9)); + + // The residual parse clears the coefficients of each macroblock before it reads them, so the buffer needs no clear. + this.Coefficients = memoryAllocator.Allocate(this.MbWidth * CoefficientsPerMacroBlock); + + // A cache holds the extra rows above the current macroblock row, then the rows of that macroblock row: 16 luma rows or 8 chroma rows. + // The row output reads the extra rows only after the rotation of the previous row writes them, so the caches need no clear. + this.CacheY = memoryAllocator.Allocate((16 * this.CacheYStride) + extraY); + int cacheUvSize = (8 * this.CacheUvStride) + extraUv; this.CacheU = memoryAllocator.Allocate(cacheUvSize); this.CacheV = memoryAllocator.Allocate(cacheUvSize); this.TmpYBuffer = memoryAllocator.Allocate((int)width); this.TmpUBuffer = memoryAllocator.Allocate((int)width); this.TmpVBuffer = memoryAllocator.Allocate((int)width); - this.upsamplingBuffer = memoryAllocator.Allocate(UpsamplingBufferSize); - this.Pixels = memoryAllocator.Allocate((int)(width * height * 4), AllocationOptions.Clean); + + // The first macroblock row has no row above it. It reads 0 for the top non-zero contexts and the top intra modes, so these buffers start + // at 0. Each row writes the block data, the filter strength and the top samples of a column before the row or the next row reads them, so + // these buffers need no clear. + this.MacroBlockInfo = memoryAllocator.Allocate(this.MbWidth, AllocationOptions.Clean); + this.IntraT = memoryAllocator.Allocate(4 * this.MbWidth, AllocationOptions.Clean); + this.MacroBlockData = memoryAllocator.Allocate(this.MbWidth); + this.FilterInfo = memoryAllocator.Allocate(this.MbWidth); + this.YuvTopSamples = memoryAllocator.Allocate(this.MbWidth * TopSamplesPerMacroBlock); #if DEBUG // Filling those buffers with 205, is only useful for debugging, @@ -361,13 +421,17 @@ public void Dispose() { // A damaged frame can stop after the header parse, before AllocateBuffers runs. Then the buffers do not exist. this.YuvBuffer?.Dispose(); + this.Coefficients?.Dispose(); this.CacheY?.Dispose(); this.CacheU?.Dispose(); this.CacheV?.Dispose(); this.TmpYBuffer?.Dispose(); this.TmpUBuffer?.Dispose(); this.TmpVBuffer?.Dispose(); - this.upsamplingBuffer?.Dispose(); - this.Pixels?.Dispose(); + this.MacroBlockInfo?.Dispose(); + this.IntraT?.Dispose(); + this.MacroBlockData?.Dispose(); + this.FilterInfo?.Dispose(); + this.YuvTopSamples?.Dispose(); } } diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8DiffusionErrors.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8DiffusionErrors.cs new file mode 100644 index 0000000000..c01b593880 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8DiffusionErrors.cs @@ -0,0 +1,27 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Diagnostics.CodeAnalysis; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossy; + +/// +/// Holds the chroma DC diffusion errors of one macroblock: three errors for each of the two chroma channels. +/// The six values are kept in one flat inline buffer, channel by channel. +/// +internal struct Vp8DiffusionErrors +{ + /// + /// The errors. The error at index of channel channel is at (channel * 3) + index. + /// + private InlineArray6 values; + + /// + /// Gets a reference to one diffusion error. + /// + /// The chroma channel: 0 for U, 1 for V. + /// The error index in the channel, from 0 to 2. + /// The reference to the error. + [UnscopedRef] + public ref int this[int channel, int index] => ref this.values[(channel * 3) + index]; +} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncIterator.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncIterator.cs deleted file mode 100644 index 641e48feff..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncIterator.cs +++ /dev/null @@ -1,973 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossy; - -/// -/// Iterator structure to iterate through macroblocks, pointing to the -/// right neighbouring data (samples, predictions, contexts, ...) -/// -internal class Vp8EncIterator -{ - public const int YOffEnc = 0; - - public const int UOffEnc = 16; - - public const int VOffEnc = 16 + 8; - - private const int MaxIntra16Mode = 2; - - private const int MaxIntra4Mode = 2; - - private const int MaxUvMode = 2; - - private const int DefaultAlpha = -1; - - private readonly int mbw; - - private readonly int mbh; - - /// - /// Stride of the prediction plane(=4*mbw + 1). - /// - private readonly int predsWidth; - - /// - /// Array to record the position of the top sample to pass to the prediction functions. - /// - private readonly byte[] vp8TopLeftI4 = - [ - 17, 21, 25, 29, - 13, 17, 21, 25, - 9, 13, 17, 21, - 5, 9, 13, 17 - ]; - - private int currentMbIdx; - - private int nzIdx; - private int yTopIdx; - - private int uvTopIdx; - - public Vp8EncIterator(Vp8Encoder enc) - : this(enc.YTop, enc.UvTop, enc.Nz, enc.MbInfo, enc.Preds, enc.TopDerr, enc.Mbw, enc.Mbh) - { - } - - public Vp8EncIterator(byte[] yTop, byte[] uvTop, uint[] nz, Vp8MacroBlockInfo[] mb, byte[] preds, sbyte[] topDerr, int mbw, int mbh) - { - this.YTop = yTop; - this.UvTop = uvTop; - this.Nz = nz; - this.Mb = mb; - this.Preds = preds; - this.TopDerr = topDerr; - this.LeftDerr = new sbyte[2 * 2]; - this.mbw = mbw; - this.mbh = mbh; - this.currentMbIdx = 0; - this.nzIdx = 1; - this.yTopIdx = 0; - this.uvTopIdx = 0; - this.predsWidth = (4 * mbw) + 1; - this.PredIdx = this.predsWidth; - this.YuvIn = new byte[WebpConstants.Bps * 16]; - this.YuvOut = new byte[WebpConstants.Bps * 16]; - this.YuvOut2 = new byte[WebpConstants.Bps * 16]; - this.YuvP = new byte[(32 * WebpConstants.Bps) + (16 * WebpConstants.Bps) + (8 * WebpConstants.Bps)]; // I16+Chroma+I4 preds - this.YLeft = new byte[32]; - this.UvLeft = new byte[32]; - this.TopNz = new int[9]; - this.LeftNz = new int[9]; - this.I4Boundary = new byte[37]; - this.BitCount = new long[4, 3]; - this.Scratch = new byte[WebpConstants.Bps * 16]; - this.Scratch2 = new short[17 * 16]; - this.Scratch3 = new int[16]; - this.RdScratch = new Vp8ModeScore(); - this.RdScratch2 = new Vp8ModeScore(); - this.RdScratch3 = new Vp8ModeScore(); - this.ResidualScratch = new Vp8Residual(); - - // To match the C initial values of the reference implementation, initialize all with 204. - const byte defaultInitVal = 204; - this.YuvIn.AsSpan().Fill(defaultInitVal); - this.YuvOut.AsSpan().Fill(defaultInitVal); - this.YuvOut2.AsSpan().Fill(defaultInitVal); - this.YuvP.AsSpan().Fill(defaultInitVal); - this.YLeft.AsSpan().Fill(defaultInitVal); - this.UvLeft.AsSpan().Fill(defaultInitVal); - this.Scratch.AsSpan().Fill(defaultInitVal); - - this.Reset(); - } - - /// - /// Gets or sets the current macroblock X value. - /// - public int X { get; set; } - - /// - /// Gets or sets the current macroblock Y. - /// - public int Y { get; set; } - - /// - /// Gets the input samples. - /// - public byte[] YuvIn { get; } - - /// - /// Gets or sets the output samples. - /// - public byte[] YuvOut { get; set; } - - /// - /// Gets or sets the secondary buffer swapped with YuvOut. - /// - public byte[] YuvOut2 { get; set; } - - /// - /// Gets the scratch buffer for prediction. - /// - public byte[] YuvP { get; } - - /// - /// Gets the left luma samples. - /// - public byte[] YLeft { get; } - - /// - /// Gets the left uv samples. - /// - public byte[] UvLeft { get; } - - /// - /// Gets the left error diffusion (u/v). - /// - public sbyte[] LeftDerr { get; } - - /// - /// Gets the top luma samples at position 'X'. - /// - public byte[] YTop { get; } - - /// - /// Gets the top u/v samples at position 'X', packed as 16 bytes. - /// - public byte[] UvTop { get; } - - /// - /// Gets the intra mode predictors (4x4 blocks). - /// - public byte[] Preds { get; } - - /// - /// Gets the current start index of the intra mode predictors. - /// - public int PredIdx { get; private set; } - - /// - /// Gets the non-zero pattern. - /// - public uint[] Nz { get; } - - /// - /// Gets the top diffusion error. - /// - public sbyte[] TopDerr { get; } - - /// - /// Gets 32+5 boundary samples needed by intra4x4. - /// - public byte[] I4Boundary { get; } - - /// - /// Gets or sets the index to the current top boundary sample. - /// - public int I4BoundaryIdx { get; set; } - - /// - /// Gets or sets the current intra4x4 mode being tested. - /// - public int I4 { get; set; } - - /// - /// Gets the top-non-zero context. - /// - public int[] TopNz { get; } - - /// - /// Gets the left-non-zero. leftNz[8] is independent. - /// - public int[] LeftNz { get; } - - /// - /// Gets or sets the macroblock bit-cost for luma. - /// - public long LumaBits { get; set; } - - /// - /// Gets the bit counters for coded levels. - /// - public long[,] BitCount { get; } - - /// - /// Gets or sets the macroblock bit-cost for chroma. - /// - public long UvBits { get; set; } - - /// - /// Gets or sets the number of mb still to be processed. - /// - public int CountDown { get; set; } - - /// - /// Gets the byte scratch buffer. - /// - public byte[] Scratch { get; } - - /// - /// Gets the short scratch buffer. - /// - public short[] Scratch2 { get; } - - /// - /// Gets the int scratch buffer. - /// - public int[] Scratch3 { get; } - - /// - /// Gets or sets the first reusable rate-distortion score accumulator. - /// uses the three accumulators as scratch state while it evaluates the - /// prediction modes of a macroblock, so mode evaluation does not allocate per macroblock. - /// exchanges this instance with the caller's accumulator - /// when the best mode ends up in the scratch instance, which is why the property has a setter. - /// - public Vp8ModeScore RdScratch { get; set; } - - /// - /// Gets the second reusable rate-distortion score accumulator. - /// - public Vp8ModeScore RdScratch2 { get; } - - /// - /// Gets the third reusable rate-distortion score accumulator. - /// - public Vp8ModeScore RdScratch3 { get; } - - /// - /// Gets the reusable residual used to cost the candidate modes of a macroblock. - /// - public Vp8Residual ResidualScratch { get; } - - public Vp8MacroBlockInfo CurrentMacroBlockInfo => this.Mb[this.currentMbIdx]; - - private Vp8MacroBlockInfo[] Mb { get; } - - public void Init() => this.Reset(); - - public static void InitFilter() - { - // TODO: add support for autofilter - } - - public void StartI4() - { - int i; - this.I4 = 0; // first 4x4 sub-block. - this.I4BoundaryIdx = this.vp8TopLeftI4[0]; - - // Import the boundary samples. - for (i = 0; i < 17; i++) - { - // left - this.I4Boundary[i] = this.YLeft[15 - i + 1]; - } - - Span yTop = this.YTop.AsSpan(this.yTopIdx); - for (i = 0; i < 16; i++) - { - // top - this.I4Boundary[17 + i] = yTop[i]; - } - - // top-right samples have a special case on the far right of the picture. - if (this.X < this.mbw - 1) - { - for (i = 16; i < 16 + 4; i++) - { - this.I4Boundary[17 + i] = yTop[i]; - } - } - else - { - // else, replicate the last valid pixel four times - for (i = 16; i < 16 + 4; i++) - { - this.I4Boundary[17 + i] = this.I4Boundary[17 + 15]; - } - } - - this.NzToBytes(); // import the non-zero context. - } - - // Import uncompressed samples from source. - public void Import(Span y, Span u, Span v, int yStride, int uvStride, int width, int height, bool importBoundarySamples) - { - int yStartIdx = ((this.Y * yStride) + this.X) * 16; - int uvStartIdx = ((this.Y * uvStride) + this.X) * 8; - Span ySrc = y[yStartIdx..]; - Span uSrc = u[uvStartIdx..]; - Span vSrc = v[uvStartIdx..]; - int w = Math.Min(width - (this.X * 16), 16); - int h = Math.Min(height - (this.Y * 16), 16); - int uvw = (w + 1) >> 1; - int uvh = (h + 1) >> 1; - - Span yuvIn = this.YuvIn.AsSpan(YOffEnc); - Span uIn = this.YuvIn.AsSpan(UOffEnc); - Span vIn = this.YuvIn.AsSpan(VOffEnc); - ImportBlock(ySrc, yStride, yuvIn, w, h, 16); - ImportBlock(uSrc, uvStride, uIn, uvw, uvh, 8); - ImportBlock(vSrc, uvStride, vIn, uvw, uvh, 8); - - if (!importBoundarySamples) - { - return; - } - - // Import source (uncompressed) samples into boundary. - if (this.X == 0) - { - this.InitLeft(); - } - else - { - Span yLeft = this.YLeft.AsSpan(); - Span uLeft = this.UvLeft.AsSpan(0, 16); - Span vLeft = this.UvLeft.AsSpan(16, 16); - if (this.Y == 0) - { - yLeft[0] = 127; - uLeft[0] = 127; - vLeft[0] = 127; - } - else - { - yLeft[0] = y[yStartIdx - 1 - yStride]; - uLeft[0] = u[uvStartIdx - 1 - uvStride]; - vLeft[0] = v[uvStartIdx - 1 - uvStride]; - } - - ImportLine(y[(yStartIdx - 1)..], yStride, yLeft[1..], h, 16); - ImportLine(u[(uvStartIdx - 1)..], uvStride, uLeft[1..], uvh, 8); - ImportLine(v[(uvStartIdx - 1)..], uvStride, vLeft[1..], uvh, 8); - } - - Span yTop = this.YTop.AsSpan(this.yTopIdx, 16); - if (this.Y == 0) - { - yTop.Fill(127); - this.UvTop.AsSpan(this.uvTopIdx, 16).Fill(127); - } - else - { - ImportLine(y[(yStartIdx - yStride)..], 1, yTop, w, 16); - ImportLine(u[(uvStartIdx - uvStride)..], 1, this.UvTop.AsSpan(this.uvTopIdx, 8), uvw, 8); - ImportLine(v[(uvStartIdx - uvStride)..], 1, this.UvTop.AsSpan(this.uvTopIdx + 8, 8), uvw, 8); - } - } - - public int FastMbAnalyze(uint quality) - { - // Empirical cut-off value, should be around 16 (~=block size). We use the - // [8-17] range and favor intra4 at high quality, intra16 for low quality. - uint q = quality; - uint kThreshold = 8 + ((17 - 8) * q / 100); - int k; - Span dc = stackalloc uint[16]; - uint m; - uint m2; - for (k = 0; k < 16; k += 4) - { - LossyUtils.Mean16x4(this.YuvIn.AsSpan(YOffEnc + (k * WebpConstants.Bps)), dc.Slice(k, 4)); - } - - for (m = 0, m2 = 0, k = 0; k < 16; k++) - { - m += dc[k]; - m2 += dc[k] * dc[k]; - } - - if (kThreshold * m2 < m * m) - { - this.SetIntra16Mode(0); // DC16 - } - else - { - Span modes = stackalloc byte[16]; // DC4 - this.SetIntra4Mode(modes); - } - - return 0; - } - - public int MbAnalyzeBestIntra16Mode() - { - const int maxMode = MaxIntra16Mode; - int mode; - int bestAlpha = DefaultAlpha; - int bestMode = 0; - - this.MakeLuma16Preds(); - for (mode = 0; mode < maxMode; mode++) - { - Vp8Histogram histo = new(); - histo.CollectHistogram(this.YuvIn.AsSpan(YOffEnc), this.YuvP.AsSpan(Vp8Encoding.Vp8I16ModeOffsets[mode]), 0, 16); - int alpha = histo.GetAlpha(); - if (alpha > bestAlpha) - { - bestAlpha = alpha; - bestMode = mode; - } - } - - this.SetIntra16Mode(bestMode); - return bestAlpha; - } - - public int MbAnalyzeBestIntra4Mode(int bestAlpha) - { - Span modes = stackalloc byte[16]; - const int maxMode = MaxIntra4Mode; - Vp8Histogram totalHisto = new(); - int curHisto = 0; - - // The two entries alternate between the candidate under test and the best candidate so far. - // CollectHistogram fully initializes an entry before it is read, so no per-block reset is needed. - Span histos = stackalloc Vp8Histogram[2]; - this.StartI4(); - do - { - int mode; - int bestModeAlpha = DefaultAlpha; - Span src = this.YuvIn.AsSpan(YOffEnc + WebpLookupTables.Vp8Scan[this.I4]); - - this.MakeIntra4Preds(); - for (mode = 0; mode < maxMode; ++mode) - { - histos[curHisto].CollectHistogram(src, this.YuvP.AsSpan(Vp8Encoding.Vp8I4ModeOffsets[mode]), 0, 1); - - int alpha = histos[curHisto].GetAlpha(); - if (alpha > bestModeAlpha) - { - bestModeAlpha = alpha; - modes[this.I4] = (byte)mode; - - // Keep track of best histo so far. - curHisto ^= 1; - } - } - - // Accumulate best histogram. - histos[curHisto ^ 1].Merge(ref totalHisto); - } - while (this.RotateI4(this.YuvIn.AsSpan(YOffEnc))); // Note: we reuse the original samples for predictors. - - int i4Alpha = totalHisto.GetAlpha(); - if (i4Alpha > bestAlpha) - { - this.SetIntra4Mode(modes); - bestAlpha = i4Alpha; - } - - return bestAlpha; - } - - public int MbAnalyzeBestUvMode() - { - int bestAlpha = DefaultAlpha; - int smallestAlpha = 0; - int bestMode = 0; - const int maxMode = MaxUvMode; - int mode; - - this.MakeChroma8Preds(); - for (mode = 0; mode < maxMode; ++mode) - { - Vp8Histogram histo = new(); - histo.CollectHistogram(this.YuvIn.AsSpan(UOffEnc), this.YuvP.AsSpan(Vp8Encoding.Vp8UvModeOffsets[mode]), 16, 16 + 4 + 4); - int alpha = histo.GetAlpha(); - if (alpha > bestAlpha) - { - bestAlpha = alpha; - } - - // The best prediction mode tends to be the one with the smallest alpha. - if (mode == 0 || alpha < smallestAlpha) - { - smallestAlpha = alpha; - bestMode = mode; - } - } - - this.SetIntraUvMode(bestMode); - return bestAlpha; - } - - public void SetIntra16Mode(int mode) - { - Span preds = this.Preds.AsSpan(this.PredIdx); - for (int y = 0; y < 4; y++) - { - preds[..4].Fill((byte)mode); - preds = preds[this.predsWidth..]; - } - - this.CurrentMacroBlockInfo.MacroBlockType = Vp8MacroBlockType.I16X16; - } - - public void SetIntra4Mode(ReadOnlySpan modes) - { - int modesIdx = 0; - int predIdx = this.PredIdx; - for (int y = 4; y > 0; y--) - { - modes.Slice(modesIdx, 4).CopyTo(this.Preds.AsSpan(predIdx)); - predIdx += this.predsWidth; - modesIdx += 4; - } - - this.CurrentMacroBlockInfo.MacroBlockType = Vp8MacroBlockType.I4X4; - } - - public int GetCostLuma16(Vp8ModeScore rd, Vp8EncProba proba, Vp8Residual res) - { - int r = 0; - - // re-import the non-zero context. - this.NzToBytes(); - - // DC - res.Init(0, 1, proba); - res.SetCoeffs(rd.YDcLevels); - r += res.GetResidualCost(this.TopNz[8] + this.LeftNz[8]); - - // AC - res.Init(1, 0, proba); - for (int y = 0; y < 4; y++) - { - for (int x = 0; x < 4; x++) - { - int ctx = this.TopNz[x] + this.LeftNz[y]; - res.SetCoeffs(rd.YAcLevels.AsSpan((x + (y * 4)) * 16, 16)); - r += res.GetResidualCost(ctx); - this.TopNz[x] = this.LeftNz[y] = res.Last >= 0 ? 1 : 0; - } - } - - return r; - } - - public short[] GetCostModeI4(byte[] modes) - { - int predsWidth = this.predsWidth; - int predIdx = this.PredIdx; - int x = this.I4 & 3; - int y = this.I4 >> 2; - int left = x == 0 ? this.Preds[predIdx + (y * predsWidth) - 1] : modes[this.I4 - 1]; - int top = y == 0 ? this.Preds[predIdx - predsWidth + x] : modes[this.I4 - 4]; - return WebpLookupTables.Vp8FixedCostsI4[top, left]; - } - - public int GetCostLuma4(Span levels, Vp8EncProba proba, Vp8Residual res) - { - int x = this.I4 & 3; - int y = this.I4 >> 2; - int r = 0; - - res.Init(0, 3, proba); - int ctx = this.TopNz[x] + this.LeftNz[y]; - res.SetCoeffs(levels); - r += res.GetResidualCost(ctx); - return r; - } - - public int GetCostUv(Vp8ModeScore rd, Vp8EncProba proba, Vp8Residual res) - { - int r = 0; - - // re-import the non-zero context. - this.NzToBytes(); - - res.Init(0, 2, proba); - for (int ch = 0; ch <= 2; ch += 2) - { - for (int y = 0; y < 2; y++) - { - for (int x = 0; x < 2; x++) - { - int ctx = this.TopNz[4 + ch + x] + this.LeftNz[4 + ch + y]; - res.SetCoeffs(rd.UvLevels.AsSpan(((ch * 2) + x + (y * 2)) * 16, 16)); - r += res.GetResidualCost(ctx); - this.TopNz[4 + ch + x] = this.LeftNz[4 + ch + y] = res.Last >= 0 ? 1 : 0; - } - } - } - - return r; - } - - public void SetIntraUvMode(int mode) => this.CurrentMacroBlockInfo.UvMode = mode; - - public void SetSkip(bool skip) => this.CurrentMacroBlockInfo.Skip = skip; - - public void SetSegment(int segment) => this.CurrentMacroBlockInfo.Segment = segment; - - public void StoreDiffusionErrors(Vp8ModeScore rd) - { - for (int ch = 0; ch <= 1; ++ch) - { - Span top = this.TopDerr.AsSpan((this.X * 4) + ch, 2); - Span left = this.LeftDerr.AsSpan(ch, 2); - - // restore err1 - left[0] = (sbyte)rd.Derr[ch, 0]; - - // 3/4th of err3 - left[1] = (sbyte)((3 * rd.Derr[ch, 2]) >> 2); - - // err2 - top[0] = (sbyte)rd.Derr[ch, 1]; - - // 1/4th of err3. - top[1] = (sbyte)(rd.Derr[ch, 2] - left[1]); - } - } - - /// - /// Returns true if iteration is finished. - /// - /// True if iterator is finished. - public bool IsDone() => this.CountDown <= 0; - - /// - /// Go to next macroblock. - /// - /// Returns false if not finished. - public bool Next() - { - if (++this.X == this.mbw) - { - this.SetRow(++this.Y); - } - else - { - this.currentMbIdx++; - this.nzIdx++; - this.PredIdx += 4; - this.yTopIdx += 16; - this.uvTopIdx += 16; - } - - return --this.CountDown > 0; - } - - public void SaveBoundary() - { - int x = this.X; - int y = this.Y; - Span ySrc = this.YuvOut.AsSpan(YOffEnc); - Span uvSrc = this.YuvOut.AsSpan(UOffEnc); - if (x < this.mbw - 1) - { - // left - for (int i = 0; i < 16; i++) - { - this.YLeft[i + 1] = ySrc[15 + (i * WebpConstants.Bps)]; - } - - for (int i = 0; i < 8; i++) - { - this.UvLeft[i + 1] = uvSrc[7 + (i * WebpConstants.Bps)]; - this.UvLeft[i + 16 + 1] = uvSrc[15 + (i * WebpConstants.Bps)]; - } - - // top-left (before 'top'!) - this.YLeft[0] = this.YTop[this.yTopIdx + 15]; - this.UvLeft[0] = this.UvTop[this.uvTopIdx + 0 + 7]; - this.UvLeft[16] = this.UvTop[this.uvTopIdx + 8 + 7]; - } - - if (y < this.mbh - 1) - { - // top - ySrc.Slice(15 * WebpConstants.Bps, 16).CopyTo(this.YTop.AsSpan(this.yTopIdx)); - uvSrc.Slice(7 * WebpConstants.Bps, 8 + 8).CopyTo(this.UvTop.AsSpan(this.uvTopIdx)); - } - } - - public bool RotateI4(Span yuvOut) - { - Span blk = yuvOut[WebpLookupTables.Vp8Scan[this.I4]..]; - Span top = this.I4Boundary.AsSpan(); - int topOffset = this.I4BoundaryIdx; - int i; - - // Update the cache with 7 fresh samples. - for (i = 0; i <= 3; i++) - { - top[topOffset - 4 + i] = blk[i + (3 * WebpConstants.Bps)]; // Store future top samples. - } - - if ((this.I4 & 3) != 3) - { - // if not on the right sub-blocks #3, #7, #11, #15 - for (i = 0; i <= 2; i++) - { - // store future left samples - top[topOffset + i] = blk[3 + ((2 - i) * WebpConstants.Bps)]; - } - } - else - { - // else replicate top-right samples, as says the specs. - for (i = 0; i <= 3; i++) - { - top[topOffset + i] = top[topOffset + i + 4]; - } - } - - // move pointers to next sub-block - ++this.I4; - if (this.I4 == 16) - { - // we're done - return false; - } - - this.I4BoundaryIdx = this.vp8TopLeftI4[this.I4]; - - return true; - } - - public void ResetAfterSkip() - { - if (this.CurrentMacroBlockInfo.MacroBlockType == Vp8MacroBlockType.I16X16) - { - // Reset all predictors. - this.Nz[this.nzIdx] = 0; - this.LeftNz[8] = 0; - } - else - { - // Preserve the dc_nz bit. - this.Nz[this.nzIdx] &= 1 << 24; - } - } - - public void MakeLuma16Preds() - { - Span left = this.X != 0 ? this.YLeft.AsSpan() : null; - Span top = this.Y != 0 ? this.YTop.AsSpan(this.yTopIdx) : null; - Vp8Encoding.EncPredLuma16(this.YuvP, left, top); - } - - public void MakeChroma8Preds() - { - Span left = this.X != 0 ? this.UvLeft.AsSpan() : null; - Span top = this.Y != 0 ? this.UvTop.AsSpan(this.uvTopIdx) : null; - Vp8Encoding.EncPredChroma8(this.YuvP, left, top); - } - - public void MakeIntra4Preds() => Vp8Encoding.EncPredLuma4(this.YuvP, this.I4Boundary, this.I4BoundaryIdx, this.Scratch.AsSpan(0, 4)); - - public void SwapOut() - { - // Tuple swap uses 2 more IL bytes -#pragma warning disable IDE0180 // Use tuple to swap values - byte[] tmp = this.YuvOut; - this.YuvOut = this.YuvOut2; - this.YuvOut2 = tmp; -#pragma warning restore IDE0180 // Use tuple to swap values - } - - public void NzToBytes() - { - Span nz = this.Nz.AsSpan(); - - uint lnz = nz[this.nzIdx - 1]; - uint tnz = nz[this.nzIdx]; - Span topNz = this.TopNz; - Span leftNz = this.LeftNz; - - // Top-Y - topNz[0] = Bit(tnz, 12); - topNz[1] = Bit(tnz, 13); - topNz[2] = Bit(tnz, 14); - topNz[3] = Bit(tnz, 15); - - // Top-U - topNz[4] = Bit(tnz, 18); - topNz[5] = Bit(tnz, 19); - - // Top-V - topNz[6] = Bit(tnz, 22); - topNz[7] = Bit(tnz, 23); - - // DC - topNz[8] = Bit(tnz, 24); - - // left-Y - leftNz[0] = Bit(lnz, 3); - leftNz[1] = Bit(lnz, 7); - leftNz[2] = Bit(lnz, 11); - leftNz[3] = Bit(lnz, 15); - - // left-U - leftNz[4] = Bit(lnz, 17); - leftNz[5] = Bit(lnz, 19); - - // left-V - leftNz[6] = Bit(lnz, 21); - leftNz[7] = Bit(lnz, 23); - - // left-DC is special, iterated separately. - } - - public void BytesToNz() - { - uint nz = 0; - int[] topNz = this.TopNz; - int[] leftNz = this.LeftNz; - - // top - nz |= (uint)((topNz[0] << 12) | (topNz[1] << 13)); - nz |= (uint)((topNz[2] << 14) | (topNz[3] << 15)); - nz |= (uint)((topNz[4] << 18) | (topNz[5] << 19)); - nz |= (uint)((topNz[6] << 22) | (topNz[7] << 23)); - nz |= (uint)(topNz[8] << 24); // we propagate the top bit, esp. for intra4 - - // left - nz |= (uint)((leftNz[0] << 3) | (leftNz[1] << 7)); - nz |= (uint)(leftNz[2] << 11); - nz |= (uint)((leftNz[4] << 17) | (leftNz[6] << 21)); - - this.Nz[this.nzIdx] = nz; - } - - private static void ImportBlock(Span src, int srcStride, Span dst, int w, int h, int size) - { - int dstIdx = 0; - int srcIdx = 0; - for (int i = 0; i < h; i++) - { - // memcpy(dst, src, w); - src.Slice(srcIdx, w).CopyTo(dst[dstIdx..]); - if (w < size) - { - // memset(dst + w, dst[w - 1], size - w); - dst.Slice(dstIdx + w, size - w).Fill(dst[dstIdx + w - 1]); - } - - dstIdx += WebpConstants.Bps; - srcIdx += srcStride; - } - - for (int i = h; i < size; i++) - { - // memcpy(dst, dst - BPS, size); - dst.Slice(dstIdx - WebpConstants.Bps, size).CopyTo(dst[dstIdx..]); - dstIdx += WebpConstants.Bps; - } - } - - private static void ImportLine(ReadOnlySpan src, int srcStride, Span dst, int len, int totalLen) - { - int i; - int srcIdx = 0; - for (i = 0; i < len; i++) - { - dst[i] = src[srcIdx]; - srcIdx += srcStride; - } - - for (; i < totalLen; i++) - { - dst[i] = dst[len - 1]; - } - } - - /// - /// Restart a scan. - /// - private void Reset() - { - this.SetRow(0); - this.SetCountDown(this.mbw * this.mbh); - this.InitTop(); - - Array.Clear(this.BitCount); - } - - /// - /// Reset iterator position to row 'y'. - /// - /// The y position. - private void SetRow(int y) - { - this.X = 0; - this.Y = y; - this.currentMbIdx = y * this.mbw; - this.nzIdx = 1; // note: in reference source nz starts at -1. - this.yTopIdx = 0; - this.uvTopIdx = 0; - this.PredIdx = this.predsWidth + (y * 4 * this.predsWidth); - - this.InitLeft(); - } - - private void InitLeft() - { - Span yLeft = this.YLeft.AsSpan(); - Span uLeft = this.UvLeft.AsSpan(0, 16); - Span vLeft = this.UvLeft.AsSpan(16, 16); - byte val = (byte)(this.Y > 0 ? 129 : 127); - yLeft[0] = val; - uLeft[0] = val; - vLeft[0] = val; - - yLeft.Slice(1, 16).Fill(129); - uLeft.Slice(1, 8).Fill(129); - vLeft.Slice(1, 8).Fill(129); - - this.LeftNz[8] = 0; - - this.LeftDerr.AsSpan().Clear(); - } - - private void InitTop() - { - int topSize = this.mbw * 16; - this.YTop.AsSpan(0, topSize).Fill(127); - this.UvTop.AsSpan().Fill(127); - this.Nz.AsSpan().Clear(); - - int predsW = (4 * this.mbw) + 1; - int predsH = (4 * this.mbh) + 1; - int predsSize = predsW * predsH; - this.Preds.AsSpan(predsSize + this.predsWidth, this.mbw).Clear(); - - this.TopDerr.AsSpan().Clear(); - } - - private static int Bit(uint nz, int n) => (nz & (1 << n)) != 0 ? 1 : 0; - - /// - /// Set count down. - /// - /// Number of iterations to go. - private void SetCountDown(int countDown) => this.CountDown = countDown; -} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncProba.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncProba.cs deleted file mode 100644 index 2619901c30..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncProba.cs +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossy; - -internal class Vp8EncProba -{ - /// - /// Last (inclusive) level with variable cost. - /// - private const int MaxVariableLevel = 67; - - /// - /// Value below which using skipProba is OK. - /// - private const int SkipProbaThreshold = 250; - - /// - /// Initializes a new instance of the class. - /// - public Vp8EncProba() - { - this.Dirty = true; - this.UseSkipProba = false; - this.Segments = new byte[3]; - this.Coeffs = new Vp8BandProbas[WebpConstants.NumTypes][]; - for (int i = 0; i < this.Coeffs.Length; i++) - { - this.Coeffs[i] = new Vp8BandProbas[WebpConstants.NumBands]; - for (int j = 0; j < this.Coeffs[i].Length; j++) - { - this.Coeffs[i][j] = new Vp8BandProbas(); - } - } - - this.Stats = new Vp8Stats[WebpConstants.NumTypes][]; - for (int i = 0; i < this.Coeffs.Length; i++) - { - this.Stats[i] = new Vp8Stats[WebpConstants.NumBands]; - for (int j = 0; j < this.Stats[i].Length; j++) - { - this.Stats[i][j] = new Vp8Stats(); - } - } - - this.LevelCost = new Vp8Costs[WebpConstants.NumTypes][]; - for (int i = 0; i < this.LevelCost.Length; i++) - { - this.LevelCost[i] = new Vp8Costs[WebpConstants.NumBands]; - for (int j = 0; j < this.LevelCost[i].Length; j++) - { - this.LevelCost[i][j] = new Vp8Costs(); - } - } - - this.RemappedCosts = new Vp8Costs[WebpConstants.NumTypes][]; - for (int i = 0; i < this.RemappedCosts.Length; i++) - { - this.RemappedCosts[i] = new Vp8Costs[16]; - for (int j = 0; j < this.RemappedCosts[i].Length; j++) - { - this.RemappedCosts[i][j] = new Vp8Costs(); - } - } - - // Initialize with default probabilities. - this.Segments.AsSpan().Fill(255); - for (int t = 0; t < WebpConstants.NumTypes; ++t) - { - for (int b = 0; b < WebpConstants.NumBands; ++b) - { - for (int c = 0; c < WebpConstants.NumCtx; ++c) - { - Vp8ProbaArray dst = this.Coeffs[t][b].Probabilities[c]; - for (int p = 0; p < WebpConstants.NumProbas; ++p) - { - dst.Probabilities[p] = WebpLookupTables.DefaultCoeffsProba[t, b, c, p]; - } - } - } - } - } - - /// - /// Gets the probabilities for segment tree. - /// - public byte[] Segments { get; } - - /// - /// Gets or sets the final probability of being skipped. - /// - public byte SkipProba { get; set; } - - /// - /// Gets or sets a value indicating whether to use the skip probability. - /// - public bool UseSkipProba { get; set; } - - public Vp8BandProbas[][] Coeffs { get; } - - public Vp8Stats[][] Stats { get; } - - public Vp8Costs[][] LevelCost { get; } - - public Vp8Costs[][] RemappedCosts { get; } - - /// - /// Gets or sets the number of skipped blocks. - /// - public int NbSkip { get; set; } - - /// - /// Gets or sets a value indicating whether CalculateLevelCosts() needs to be called. - /// - public bool Dirty { get; set; } - - public void CalculateLevelCosts() - { - if (!this.Dirty) - { - return; // Nothing to do. - } - - for (int ctype = 0; ctype < WebpConstants.NumTypes; ++ctype) - { - for (int band = 0; band < WebpConstants.NumBands; ++band) - { - for (int ctx = 0; ctx < WebpConstants.NumCtx; ++ctx) - { - Vp8ProbaArray p = this.Coeffs[ctype][band].Probabilities[ctx]; - Vp8CostArray table = this.LevelCost[ctype][band].Costs[ctx]; - int cost0 = ctx > 0 ? LossyUtils.Vp8BitCost(1, p.Probabilities[0]) : 0; - int costBase = LossyUtils.Vp8BitCost(1, p.Probabilities[1]) + cost0; - int v; - table.Costs[0] = (ushort)(LossyUtils.Vp8BitCost(0, p.Probabilities[1]) + cost0); - for (v = 1; v <= MaxVariableLevel; ++v) - { - table.Costs[v] = (ushort)(costBase + VariableLevelCost(v, p.Probabilities)); - } - - // Starting at level 67 and up, the variable part of the cost is actually constant - } - } - - for (int n = 0; n < 16; ++n) - { - for (int ctx = 0; ctx < WebpConstants.NumCtx; ++ctx) - { - Vp8CostArray dst = this.RemappedCosts[ctype][n].Costs[ctx]; - Vp8CostArray src = this.LevelCost[ctype][WebpConstants.Vp8EncBands[n]].Costs[ctx]; - src.Costs.CopyTo(dst.Costs.AsSpan()); - } - } - } - - this.Dirty = false; - } - - public int FinalizeTokenProbas() - { - bool hasChanged = false; - int size = 0; - for (int t = 0; t < WebpConstants.NumTypes; ++t) - { - for (int b = 0; b < WebpConstants.NumBands; ++b) - { - for (int c = 0; c < WebpConstants.NumCtx; ++c) - { - for (int p = 0; p < WebpConstants.NumProbas; ++p) - { - uint stats = this.Stats[t][b].Stats[c].Stats[p]; - int nb = (int)((stats >> 0) & 0xffff); - int total = (int)((stats >> 16) & 0xffff); - int updateProba = WebpLookupTables.CoeffsUpdateProba[t, b, c, p]; - int oldP = WebpLookupTables.DefaultCoeffsProba[t, b, c, p]; - int newP = CalcTokenProba(nb, total); - int oldCost = BranchCost(nb, total, oldP) + LossyUtils.Vp8BitCost(0, (byte)updateProba); - int newCost = BranchCost(nb, total, newP) + LossyUtils.Vp8BitCost(1, (byte)updateProba) + (8 * 256); - bool useNewP = oldCost > newCost; - size += LossyUtils.Vp8BitCost(useNewP ? 1 : 0, (byte)updateProba); - if (useNewP) - { - // Only use proba that seem meaningful enough. - this.Coeffs[t][b].Probabilities[c].Probabilities[p] = (byte)newP; - hasChanged |= newP != oldP; - size += 8 * 256; - } - else - { - this.Coeffs[t][b].Probabilities[c].Probabilities[p] = (byte)oldP; - } - } - } - } - } - - this.Dirty = hasChanged; - return size; - } - - public int FinalizeSkipProba(int mbw, int mbh) - { - int nbMbs = mbw * mbh; - int nbEvents = this.NbSkip; - this.SkipProba = (byte)CalcSkipProba(nbEvents, nbMbs); - this.UseSkipProba = this.SkipProba < SkipProbaThreshold; - - int size = 256; - if (this.UseSkipProba) - { - size += (nbEvents * LossyUtils.Vp8BitCost(1, this.SkipProba)) + ((nbMbs - nbEvents) * LossyUtils.Vp8BitCost(0, this.SkipProba)); - size += 8 * 256; // cost of signaling the skipProba itself. - } - - return size; - } - - public void ResetTokenStats() - { - for (int t = 0; t < WebpConstants.NumTypes; ++t) - { - for (int b = 0; b < WebpConstants.NumBands; ++b) - { - for (int c = 0; c < WebpConstants.NumCtx; ++c) - { - for (int p = 0; p < WebpConstants.NumProbas; ++p) - { - this.Stats[t][b].Stats[c].Stats[p] = 0; - } - } - } - } - } - - private static int CalcSkipProba(long nb, long total) => (int)(total != 0 ? (total - nb) * 255 / total : 255); - - private static int VariableLevelCost(int level, ReadOnlySpan probas) - { - int pattern = WebpLookupTables.Vp8LevelCodes[level - 1][0]; - int bits = WebpLookupTables.Vp8LevelCodes[level - 1][1]; - int cost = 0; - for (int i = 2; pattern != 0; i++) - { - if ((pattern & 1) != 0) - { - cost += LossyUtils.Vp8BitCost(bits & 1, probas[i]); - } - - bits >>= 1; - pattern >>= 1; - } - - return cost; - } - - // Collect statistics and deduce probabilities for next coding pass. - // Return the total bit-cost for coding the probability updates. - private static int CalcTokenProba(int nb, int total) => nb != 0 ? (255 - (nb * 255 / total)) : 255; - - // Cost of coding 'nb' 1's and 'total-nb' 0's using 'proba' probability. - private static int BranchCost(int nb, int total, int proba) - => (nb * LossyUtils.Vp8BitCost(1, (byte)proba)) + ((total - nb) * LossyUtils.Vp8BitCost(0, (byte)proba)); -} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs index 2e20eb6ec5..7d3a6b7294 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs @@ -9,6 +9,7 @@ using SixLabors.ImageSharp.Formats.Webp.BitWriter; using SixLabors.ImageSharp.Formats.Webp.Chunks; using SixLabors.ImageSharp.Formats.Webp.ColorConverters; +using SixLabors.ImageSharp.Formats.Webp.Lossless; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.Metadata; using SixLabors.ImageSharp.Metadata.Profiles.Exif; @@ -28,6 +29,12 @@ internal class Vp8Encoder : IDisposable /// private readonly MemoryAllocator memoryAllocator; + /// + /// The scratch copy of the macroblock rows that cross the end of a plane buffer, or null when each plane is one buffer. + /// The luma rows come first, then the U rows, then the V rows. + /// + private readonly IMemoryOwner rowsScratch; + /// /// The global configuration. /// @@ -68,10 +75,73 @@ internal class Vp8Encoder : IDisposable /// private readonly bool skipMetadata; - private readonly Vp8RdLevel rdOptLevel; + /// + /// The rate-distortion optimization level of the mode decision. The encoding method selects it. + /// + private readonly Vp8RateDistortionLevel rdOptLevel; + /// + /// The limit for the header bits of the 4x4 modes of one macroblock, in 1/256 bit units. When the first partition is too large, + /// the encoder halves the limit and repeats the pass. A value of 0 makes the current pass the last pass. + /// private int maxI4HeaderBits; + /// + /// The top luma samples, 16 for each macroblock column of the constructor size. + /// + private readonly IMemoryOwner yTop; + + /// + /// The top chroma samples, 8 U and 8 V for each macroblock column of the constructor size. + /// + private readonly IMemoryOwner uvTop; + + /// + /// The non-zero patterns, one for each macroblock column of the constructor size plus one for the left context. + /// + private readonly IMemoryOwner nz; + + /// + /// The macroblock infos, one for each macroblock of the constructor size. The current frame uses the first + /// * values in raster order. + /// + private readonly IMemoryOwner macroBlockInfos; + + /// + /// The intra mode predictors with the capacity of the constructor size. sets the part of the current frame. + /// + private readonly IMemoryOwner preds; + + /// + /// The work sample buffer of the macroblock iterators, with bytes. + /// + /// + /// The encoder owns the buffer and disposes it in . Each iterator divides it into its sample buffers and + /// sets the initial values when it is created. The encoder uses one iterator at a time, so all iterators share the buffer. + /// + private readonly IMemoryOwner iteratorSamples; + + /// + /// The coefficient scratch buffer of the macroblock iterators, with values. + /// + /// + /// The encoder owns the buffer and disposes it in . Each iterator clears it when it is created. + /// + private readonly IMemoryOwner iteratorCoefficients; + + /// + /// The top chroma diffusion errors, 4 for each macroblock column of the constructor size, or null when the encoder does not diffuse errors. + /// + /// + /// The encoder owns the buffer and disposes it in . Each iterator clears it when it is created. + /// + private readonly IMemoryOwner topDerr; + + /// + /// A value indicating whether the per-frame state holds the results of an encoded frame. + /// + private bool frameEncoded; + /// /// Global susceptibility. /// @@ -82,31 +152,81 @@ internal class Vp8Encoder : IDisposable /// private int uvAlpha; + /// + /// A value indicating whether the alpha channel is compressed with the lossless compression. + /// private readonly bool alphaCompression; + /// + /// The mode for the RGB values of transparent pixels. + /// + private readonly TransparentColorMode transparentColorMode; + + /// + /// The token buffer of the single pass loop, or null for the loop that runs a statistics pass and then a coding pass. + /// + private readonly Vp8TokenBuffer tokens; + + /// + /// The maximum number of segments. + /// private const int NumMbSegments = 4; + /// + /// The maximum number of k-means iterations of the segment assignment. + /// private const int MaxItersKMeans = 6; - // Convergence is considered reached if dq < DqLimit + /// + /// The quality step limit of the pass search. A step at or below this limit ends the search. + /// private const float DqLimit = 0.4f; + /// + /// The size limit of the first partition in 1/256 bit units. It is the maximum partition size minus a 2048-byte margin. + /// private const ulong Partition0SizeLimit = (WebpConstants.Vp8MaxPartition0Size - 2048UL) << 11; + /// + /// The estimated size in bytes of the RIFF header, the chunk header and the VP8 frame header. + /// private const long HeaderSizeEstimate = WebpConstants.RiffHeaderSize + WebpConstants.ChunkHeaderSize + WebpConstants.Vp8FrameHeaderSize; + /// + /// The minimum quality of the pass search. + /// private const int QMin = 0; + /// + /// The maximum quality of the pass search. + /// private const int QMax = 100; + /// + /// The minimum number of macroblocks between two probability refreshes in the token loop. + /// + private const int MinRefreshCount = 96; + + /// + /// The partition limit in percent. The 4x4 header bit limit is modulated with a quadratic curve of this value. + /// + /// + /// TODO: make the partition limit configurable. The limit is 100 minus the configured partition limit. + /// + private const int PartitionLimit = 100; + /// /// Initializes a new instance of the class. /// + /// + /// The instance can encode the frames of an animation one after the other. Each frame must fit in the constructor size, + /// and each frame gives the same output as a new instance for that frame. + /// /// The memory allocator. /// The global configuration. - /// The width of the input image. - /// The height of the input image. + /// The width of the input image. No frame is wider. + /// The height of the input image. No frame is higher. /// The encoding quality. /// Whether to skip metadata encoding. /// Quality/speed trade-off (0=fast, 6=slower-better). @@ -114,6 +234,7 @@ internal class Vp8Encoder : IDisposable /// The filter the strength of the deblocking filter, between 0 (no filtering) and 100 (maximum filtering). /// The spatial noise shaping. 0=off, 100=maximum. /// If true, the alpha channel will be compressed with the lossless compression. + /// The mode for the RGB values of transparent pixels. public Vp8Encoder( MemoryAllocator memoryAllocator, Configuration configuration, @@ -125,12 +246,11 @@ public Vp8Encoder( int entropyPasses, int filterStrength, int spatialNoiseShaping, - bool alphaCompression) + bool alphaCompression, + TransparentColorMode transparentColorMode) { this.memoryAllocator = memoryAllocator; this.configuration = configuration; - this.Width = width; - this.Height = height; this.quality = Math.Min(quality, 100); this.skipMetadata = skipMetadata; this.method = method; @@ -138,47 +258,61 @@ public Vp8Encoder( this.filterStrength = Math.Clamp(filterStrength, 0, 100); this.spatialNoiseShaping = Math.Clamp(spatialNoiseShaping, 0, 100); this.alphaCompression = alphaCompression; + this.transparentColorMode = transparentColorMode; if (method is WebpEncodingMethod.BestQuality) { - this.rdOptLevel = Vp8RdLevel.RdOptTrellisAll; + this.rdOptLevel = Vp8RateDistortionLevel.RdOptTrellisAll; } else if (method >= WebpEncodingMethod.Level5) { - this.rdOptLevel = Vp8RdLevel.RdOptTrellis; + this.rdOptLevel = Vp8RateDistortionLevel.RdOptTrellis; } else if (method >= WebpEncodingMethod.Level3) { - this.rdOptLevel = Vp8RdLevel.RdOptBasic; + this.rdOptLevel = Vp8RateDistortionLevel.RdOptBasic; } else { - this.rdOptLevel = Vp8RdLevel.RdOptNone; + this.rdOptLevel = Vp8RateDistortionLevel.RdOptNone; } + // The constructor size is the largest frame size. Each buffer that depends on the frame size gets the capacity of this size, + // so that all frames of an animation reuse the same buffers. int pixelCount = width * height; - this.Mbw = (width + 15) >> 4; - this.Mbh = (height + 15) >> 4; - int uvSize = ((width + 1) >> 1) * ((height + 1) >> 1); - this.Y = this.memoryAllocator.Allocate(pixelCount); - this.U = this.memoryAllocator.Allocate(uvSize); - this.V = this.memoryAllocator.Allocate(uvSize); - this.YTop = new byte[this.Mbw * 16]; - this.UvTop = new byte[this.Mbw * 16 * 2]; - this.Nz = new uint[this.Mbw + 1]; - this.MbHeaderLimit = 256 * 510 * 8 * 1024 / (this.Mbw * this.Mbh); - this.TopDerr = new sbyte[this.Mbw * 4]; - - // TODO: make partition_limit configurable? - const int limit = 100; // original code: limit = 100 - config->partition_limit; - this.maxI4HeaderBits = - 256 * 16 * 16 * limit * limit / (100 * 100); // ... modulated with a quadratic curve. - - this.MbInfo = new Vp8MacroBlockInfo[this.Mbw * this.Mbh]; - for (int i = 0; i < this.MbInfo.Length; i++) + int mbw = (width + 15) >> 4; + int mbh = (height + 15) >> 4; + + // The planes come from the pool in buffers of whole rows, so a large image causes no unpooled memory. The import reads a + // macroblock row that crosses a buffer end from a scratch copy: 17 luma rows and 9 rows of each chroma plane. + int uvWidth = (width + 1) >> 1; + int uvHeight = (height + 1) >> 1; + this.Y = this.memoryAllocator.Allocate2D(width, height); + this.U = this.memoryAllocator.Allocate2D(uvWidth, uvHeight); + this.V = this.memoryAllocator.Allocate2D(uvWidth, uvHeight); + if (this.Y.FastMemoryGroup.Count > 1 || this.U.FastMemoryGroup.Count > 1) { - this.MbInfo[i] = new Vp8MacroBlockInfo(); + this.rowsScratch = this.memoryAllocator.Allocate((17 * width) + (2 * 9 * uvWidth)); } + // The iterator writes the top samples and clears the non-zero patterns before it reads them, so these buffers need no clear. + this.yTop = this.memoryAllocator.Allocate(mbw * 16); + this.uvTop = this.memoryAllocator.Allocate(mbw * 16 * 2); + this.nz = this.memoryAllocator.Allocate(mbw + 1); + + // InitializeFrame sets the macroblock infos and the predictors of each frame before the first read. + this.macroBlockInfos = this.memoryAllocator.Allocate(mbw * mbh); + this.preds = this.memoryAllocator.Allocate(GetPredsLength(mbw, mbh)); + + // Chroma DC error diffusion runs only at quality 98 or lower, or with more than one pass. Above that, the quantizer is fine enough. + // Without diffusion, TopDerr is empty. The iterator clears the errors before it reads them, so the buffer needs no clear. + this.topDerr = this.quality <= 98 || this.entropyPasses > 1 ? this.memoryAllocator.Allocate(mbw * 4) : null; + + // The iterator sets the initial values of its work buffers when it is created, so these buffers need no clear. + this.iteratorSamples = this.memoryAllocator.Allocate(Vp8EncoderIterator.SampleBufferLength); + this.iteratorCoefficients = this.memoryAllocator.Allocate(Vp8EncoderIterator.CoefficientScratchLength); + + // The encoding passes set every field of the segment infos and of the filter header that the encoder changes before they read it, + // so all frames use the same instances, as all passes of one frame do. this.SegmentInfos = new Vp8SegmentInfo[4]; for (int i = 0; i < 4; i++) { @@ -186,33 +320,40 @@ public Vp8Encoder( } this.FilterHeader = new Vp8FilterHeader(); - int predSize = (((4 * this.Mbw) + 1) * ((4 * this.Mbh) + 1)) + this.PredsWidth + 1; - this.PredsWidth = (4 * this.Mbw) + 1; - this.Proba = new Vp8EncProba(); - this.Preds = new byte[predSize + this.PredsWidth + this.Mbw]; + this.Proba = new Vp8EncoderProbabilities(); - // Initialize with default values, which the reference c implementation uses, - // to be able to compare to the original and spot differences. - this.Preds.AsSpan().Fill(205); - this.Nz.AsSpan().Fill(3452816845); + // The token loop needs the rate-distortion statistics of the basic or a higher optimization level. + // The page size of the token buffer does not change the tokens, so the buffer of the constructor size serves all frames. + if (this.rdOptLevel >= Vp8RateDistortionLevel.RdOptBasic) + { + this.tokens = new Vp8TokenBuffer(memoryAllocator, mbw, mbh, this.quality); + } - this.ResetBoundaryPredictions(); + this.InitializeFrame(width, height); } - // This uses C#'s optimization to refer to the static data segment of the assembly, no allocation occurs. + /// + /// Gets the estimated number of bytes for one macroblock, for each range of 16 base quantizer values. The encoder uses it to size the bit writer buffer. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates no memory. + /// private static ReadOnlySpan AverageBytesPerMb => [50, 24, 16, 9, 7, 5, 3, 2]; + /// + /// Gets or sets the base quantizer index, from 0 to 127. It is the quantizer of segment 0. + /// public int BaseQuant { get; set; } /// /// Gets the probabilities. /// - public Vp8EncProba Proba { get; } + public Vp8EncoderProbabilities Proba { get; } /// /// Gets the segment features. /// - public Vp8EncSegmentHeader SegmentHeader { get; private set; } + public Vp8EncoderSegmentHeader SegmentHeader { get; private set; } /// /// Gets the segment infos. @@ -220,9 +361,9 @@ public Vp8Encoder( public Vp8SegmentInfo[] SegmentInfos { get; } /// - /// Gets the macro block info's. + /// Gets the macroblock infos. The current frame uses the first * values in raster order. /// - public Vp8MacroBlockInfo[] MbInfo { get; } + public Memory MbInfo => this.macroBlockInfos.Memory; /// /// Gets the filter header. @@ -235,84 +376,109 @@ public Vp8Encoder( public int Alpha { get; set; } /// - /// Gets the width of the image. + /// Gets the width of the current frame. /// - public int Width { get; } + public int Width { get; private set; } /// - /// Gets the height of the image. + /// Gets the height of the current frame. /// - public int Height { get; } + public int Height { get; private set; } /// - /// Gets the stride of the prediction plane (=4*mb_w + 1) + /// Gets the stride of the prediction plane of the current frame (=4*mb_w + 1). /// - public int PredsWidth { get; } + public int PredsWidth { get; private set; } /// - /// Gets the macroblock width. + /// Gets the macroblock width of the current frame. /// - public int Mbw { get; } + public int Mbw { get; private set; } /// - /// Gets the macroblock height. + /// Gets the macroblock height of the current frame. /// - public int Mbh { get; } + public int Mbh { get; private set; } + /// + /// Gets the quantizer index delta of the luma DC coefficients. + /// public int DqY1Dc { get; private set; } + /// + /// Gets the quantizer index delta of the Y2 AC coefficients. + /// public int DqY2Ac { get; private set; } + /// + /// Gets the quantizer index delta of the Y2 DC coefficients. + /// public int DqY2Dc { get; private set; } + /// + /// Gets the quantizer index delta of the chroma AC coefficients. The chroma susceptibility and the spatial noise shaping strength set it. + /// public int DqUvAc { get; private set; } + /// + /// Gets the quantizer index delta of the chroma DC coefficients. The spatial noise shaping strength sets it. + /// public int DqUvDc { get; private set; } /// - /// Gets the luma component. + /// Gets the luma plane. It has the size of the encoder. A frame uses the first rows and columns. + /// + private Buffer2D Y { get; } + + /// + /// Gets the chroma U plane, with half the size of the luma plane, rounded up. + /// + private Buffer2D U { get; } + + /// + /// Gets the chroma V plane, with half the size of the luma plane, rounded up. /// - private IMemoryOwner Y { get; } + private Buffer2D V { get; } /// - /// Gets the chroma U component. + /// Gets the top luma samples, 16 for each macroblock column. /// - private IMemoryOwner U { get; } + public Memory YTop => this.yTop.Memory; /// - /// Gets the chroma U component. + /// Gets the top u/v samples. U and V are packed into 16 bytes (8 U + 8 V) for each macroblock column. /// - private IMemoryOwner V { get; } + public Memory UvTop => this.uvTop.Memory; /// - /// Gets the top luma samples. + /// Gets the non-zero patterns, one for each macroblock column plus one for the left context. /// - public byte[] YTop { get; } + public Memory Nz => this.nz.Memory; /// - /// Gets the top u/v samples. U and V are packed into 16 bytes (8 U + 8 V). + /// Gets the prediction modes. The current frame uses (4*mbw+1) * (4*mbh+1) modes and the entries after them. /// - public byte[] UvTop { get; } + public Memory Preds => this.preds.Memory; /// - /// Gets the non-zero pattern. + /// Gets the top chroma diffusion errors, 4 for each macroblock column. The memory is empty when the encoder does not diffuse errors. /// - public uint[] Nz { get; } + public Memory TopDerr => this.topDerr?.Memory ?? Memory.Empty; /// - /// Gets the prediction modes: (4*mbw+1) * (4*mbh+1). + /// Gets the work sample buffer of the macroblock iterators, with bytes. /// - public byte[] Preds { get; } + public Memory IteratorSamples => this.iteratorSamples.Memory; /// - /// Gets the diffusion error. + /// Gets the coefficient scratch buffer of the macroblock iterators, with values. /// - public sbyte[] TopDerr { get; } + public Memory IteratorCoefficients => this.iteratorCoefficients.Memory; /// - /// Gets a rough limit for header bits per MB. + /// Gets or sets a rough limit for header bits per MB of the current frame. /// - private int MbHeaderLimit { get; } + private int MbHeaderLimit { get; set; } /// /// Writes the selected ICC profile and animation settings before lossy frame data. @@ -359,6 +525,16 @@ public WebpVp8X EncodeHeader( return vp8x; } + /// + /// Writes the EXIF and XMP chunks that follow the frame data, unless metadata is skipped, and finishes the RIFF container. + /// When the image has alpha and an extended header exists, the method sets the alpha flag of that header. + /// + /// The source pixel format. + /// The image supplying optional metadata. + /// The extended header that returned. + /// Whether the encoded image includes alpha. + /// The output stream. + /// The stream position of the start of the WebP resource. public void EncodeFooter(Image image, in WebpVp8X vp8x, bool hasAlpha, Stream stream, long initialPosition) where TPixel : unmanaged, IPixel { @@ -374,17 +550,16 @@ public void EncodeFooter(Image image, in WebpVp8X vp8x, bool has } /// - /// Encodes the animated image frame to the specified stream. + /// Encodes the animated image frame to the specified stream. One instance encodes all frames of an animation in order. /// /// The pixel format. /// The image frame to encode from. /// The stream to encode the image data to. - /// The region of interest within the frame to encode. + /// The region of interest within the frame to encode. It is at most the constructor size. /// The frame metadata. /// The profile selected for the complete WebP resource. /// The return transform from sRGB to the encoded profile, or null. - /// Reusable straight RGBA row scratch. - /// Reusable RGB transform scratch. + /// Reusable straight RGBA row scratch, empty when no transform and no clear is required. /// A indicating whether the frame contains an alpha channel. public bool EncodeAnimation( ImageFrame frame, @@ -393,10 +568,9 @@ public bool EncodeAnimation( WebpFrameMetadata frameMetadata, IccProfile iccProfile, ColorProfileConverter converter, - Span vectors, - Span rgb) + Span vectors) where TPixel : unmanaged, IPixel - => this.Encode(stream, frame, bounds, frameMetadata, true, null, iccProfile, converter, vectors, rgb); + => this.Encode(stream, frame, bounds, frameMetadata, true, null, iccProfile, converter, vectors); /// /// Encodes the static image frame to the specified stream. @@ -406,19 +580,17 @@ public bool EncodeAnimation( /// The image to encode from. /// The profile matching the encoded RGB samples, or null. /// The return transform from sRGB to the encoded profile, or null. - /// Reusable straight RGBA row scratch. - /// Reusable RGB transform scratch. + /// Reusable straight RGBA row scratch, empty when no transform and no clear is required. public void EncodeStatic( Stream stream, Image image, IccProfile iccProfile, ColorProfileConverter converter, - Span vectors, - Span rgb) + Span vectors) where TPixel : unmanaged, IPixel { ImageFrame frame = image.Frames.RootFrame; - this.Encode(stream, frame, image.Bounds, frame.Metadata.GetWebpMetadata(), false, image, iccProfile, converter, vectors, rgb); + this.Encode(stream, frame, image.Bounds, frame.Metadata.GetWebpMetadata(), false, image, iccProfile, converter, vectors); } /// @@ -427,14 +599,13 @@ public void EncodeStatic( /// The pixel format. /// The stream to encode the image data to. /// The image frame to encode from. - /// The region of interest within the frame to encode. + /// The region of interest within the frame to encode. It is at most the constructor size. /// The frame metadata. /// Flag indicating, if an animation parameter is present. /// The image to encode from. /// The profile matching the encoded RGB samples, or null. /// The return transform from sRGB to the encoded profile, or null. - /// Reusable straight RGBA row scratch. - /// Reusable RGB transform scratch. + /// Reusable straight RGBA row scratch, empty when no transform and no clear is required. /// A indicating whether the frame contains an alpha channel. private bool Encode( Stream stream, @@ -445,21 +616,28 @@ private bool Encode( Image image, IccProfile iccProfile, ColorProfileConverter converter, - Span vectors, - Span rgb) + Span vectors) where TPixel : unmanaged, IPixel { int width = bounds.Width; int height = bounds.Height; - int pixelCount = width * height; - Span y = this.Y.GetSpan(); - Span u = this.U.GetSpan(); - Span v = this.V.GetSpan(); + // The constructor prepares the per-frame state for one frame of its size. A later frame, or a frame of another size, + // starts from the same state again, so the output of each frame is the output of a new encoder. + if (this.frameEncoded || width != this.Width || height != this.Height) + { + this.Proba.Reset(); + this.InitializeFrame(width, height); + } + + this.frameEncoded = true; Buffer2DRegion pixels = frame.PixelBuffer.GetRegion(bounds); - WebpColorConverterBase colorConverter = WebpColorConverterBase.GetConverter(WebpColorType.Yuv); - bool hasAlpha = colorConverter.ConvertFromRgb(pixels, this.configuration, this.memoryAllocator, converter, vectors, rgb, y, u, v); + bool clearTransparentPixels = EncodingUtilities.ShouldReplaceTransparentPixels(this.transparentColorMode); + RgbToYuvConverter yuvConverter = new(this.configuration, this.memoryAllocator, converter, clearTransparentPixels); + using Buffer2D alphaPlane = yuvConverter.Convert(pixels, vectors, this.Y, this.U, this.V); + + bool hasAlpha = alphaPlane is not null; if (!hasAnimation) { @@ -467,37 +645,196 @@ private bool Encode( this.EncodeHeader(image, stream, hasAlpha, false, iccProfile, webpMetadata.BackgroundColor, webpMetadata.RepeatCount); } - int yStride = width; - int uvStride = (yStride + 1) >> 1; + // The planes have the size of the encoder, so a frame row is the start of a plane row, and the stride is the plane width. + int yStride = this.Y.Width; + int uvStride = this.U.Width; - Vp8EncIterator it = new(this); - Span alphas = stackalloc int[WebpConstants.MaxAlpha + 1]; - this.alpha = this.MacroBlockAnalysis(width, height, it, y, u, v, yStride, uvStride, alphas, out this.uvAlpha); + Vp8EncoderIterator it = new(this); + + // One clear buffer holds the susceptibility histogram, then the segment map of AssignSegments. Each part has one entry + // for each susceptibility from 0 to MaxAlpha. The histogram counts from zero, so the buffer must be clear. + const int alphaCount = WebpConstants.MaxAlpha + 1; + using IMemoryOwner alphaBuffer = this.memoryAllocator.Allocate(2 * alphaCount, AllocationOptions.Clean); + Span alphas = alphaBuffer.GetSpan()[..alphaCount]; + Span map = alphaBuffer.GetSpan().Slice(alphaCount, alphaCount); + this.alpha = this.MacroBlockAnalysis(width, height, it, yStride, uvStride, alphas, out this.uvAlpha); int totalMb = this.Mbw * this.Mbh; this.alpha /= totalMb; this.uvAlpha /= totalMb; // Analysis is done, proceed to actual encoding. - this.SegmentHeader = new Vp8EncSegmentHeader(4); - this.AssignSegments(alphas); + this.SegmentHeader = new Vp8EncoderSegmentHeader(4); + this.AssignSegments(alphas, map); this.SetLoopParams(this.quality); + if (this.tokens is null) + { + this.EncodeLoop(width, height, yStride, uvStride, it); + } + else + { + this.TokenLoop(width, height, yStride, uvStride, it); + } + + // Store filter stats. + this.AdjustFilterStrength(); + + // Extract and encode alpha channel data, if present. The compressed data is used only when it is smaller than the plane. + int compressedAlphaSize = 0; + using IMemoryOwner compressedAlpha = hasAlpha + ? AlphaEncoder.EncodeAlpha( + alphaPlane, + width, + height, + this.configuration, + this.memoryAllocator, + this.skipMetadata, + this.alphaCompression, + out compressedAlphaSize) + : null; + + this.bitWriter.Finish(); + + long prevPosition = 0; + + if (hasAnimation) + { + prevPosition = new WebpFrameData( + (uint)bounds.X, + (uint)bounds.Y, + (uint)bounds.Width, + (uint)bounds.Height, + frameMetadata.FrameDelay, + frameMetadata.BlendMode, + frameMetadata.DisposalMode) + .WriteHeaderTo(stream); + } + + if (compressedAlpha is not null) + { + BitWriterBase.WriteAlphaChunk(stream, compressedAlpha.GetSpan()[..compressedAlphaSize]); + } + else if (hasAlpha) + { + BitWriterBase.WriteAlphaChunk(stream, alphaPlane, width, height); + } + + this.bitWriter.WriteEncodedImageToStream(stream); + + if (hasAnimation) + { + RiffHelper.EndWriteChunk(stream, prevPosition); + } + + return hasAlpha; + } + + /// + /// Gets the rows of the planes that the import of one macroblock row reads: its 16 luma rows and 8 chroma rows, and the row above + /// them for the boundary samples. Each band is one span with the plane width as the stride. + /// + /// The macroblock row. + /// The frame height. + /// Receives the luma rows. + /// Receives the U rows. + /// Receives the V rows. + /// Receives the flat position of the first luma sample of the band. + /// Receives the flat position of the first chroma sample of the bands. + private void GetMacroblockRows(int mbY, int height, out Span y, out Span u, out Span v, out int yRowsStart, out int uvRowsStart) + { + int yFirstRow = mbY > 0 ? (mbY * 16) - 1 : 0; + int yLength = (Math.Min(height, (mbY * 16) + 16) - yFirstRow) * this.Y.Width; + int uvFirstRow = mbY > 0 ? (mbY * 8) - 1 : 0; + int uvLength = (Math.Min((height + 1) >> 1, (mbY * 8) + 8) - uvFirstRow) * this.U.Width; + yRowsStart = yFirstRow * this.Y.Width; + uvRowsStart = uvFirstRow * this.U.Width; + + Span scratch = this.rowsScratch is null ? default : this.rowsScratch.GetSpan(); + int uvScratchLength = 9 * this.U.Width; + y = GetPlaneRows(this.Y, yRowsStart, yLength, scratch); + u = GetPlaneRows(this.U, uvRowsStart, uvLength, scratch.IsEmpty ? default : scratch[(17 * this.Y.Width)..]); + v = GetPlaneRows(this.V, uvRowsStart, uvLength, scratch.IsEmpty ? default : scratch[((17 * this.Y.Width) + uvScratchLength)..]); + } + + /// + /// Gets a range of flat positions of a plane as one span. The range is usually in one buffer of the plane. A range that crosses a + /// buffer end is copied to the scratch. + /// + /// The plane. + /// The first flat position. + /// The number of samples. + /// The scratch for a range that crosses a buffer end. It is empty when the plane is one buffer. + /// The samples. + private static Span GetPlaneRows(Buffer2D plane, int start, int length, Span scratch) + { + if (LosslessUtils.TryGetPlaneRun(plane, start, length, out Span rows)) + { + return rows; + } + + Span copy = scratch[..length]; + LosslessUtils.CopyPlaneRun(plane, start, copy); + return copy; + } + + /// + public void Dispose() + { + this.Y.Dispose(); + this.U.Dispose(); + this.V.Dispose(); + this.rowsScratch?.Dispose(); + this.yTop.Dispose(); + this.uvTop.Dispose(); + this.nz.Dispose(); + this.macroBlockInfos.Dispose(); + this.preds.Dispose(); + this.iteratorSamples.Dispose(); + this.iteratorCoefficients.Dispose(); + this.topDerr?.Dispose(); + this.tokens?.Dispose(); + this.bitWriter?.Dispose(); + } + + /// + /// Runs the statistics loop and then codes each macroblock directly to the bit writer. + /// The coding pass runs the mode decision again for each macroblock. + /// + /// The image width. + /// The image height. + /// The y-luminance stride. + /// The uv stride. + /// The macroblock iterator. + private void EncodeLoop(int width, int height, int yStride, int uvStride, Vp8EncoderIterator it) + { + // The rows of the current macroblock row and the row above it. The loop gets them at the start of each macroblock row. + Span y = default; + Span u = default; + Span v = default; + int yRowsStart = 0; + int uvRowsStart = 0; + // Initialize the bitwriter. int averageBytesPerMacroBlock = AverageBytesPerMb[this.BaseQuant >> 4]; int expectedSize = this.Mbw * this.Mbh * averageBytesPerMacroBlock; - this.bitWriter = new Vp8BitWriter(expectedSize, this); + this.bitWriter?.Dispose(); + this.bitWriter = new Vp8BitWriter(this.memoryAllocator, expectedSize, this); // Stats-collection loop. - this.StatLoop(width, height, yStride, uvStride); - it.Init(); - Vp8EncIterator.InitFilter(); Vp8ModeScore info = new(); - Vp8Residual residual = new(); + Vp8Residual residual = it.ResidualScratch; + this.StatLoop(width, height, yStride, uvStride, it, ref info, residual); + it.Init(); + Vp8EncoderIterator.InitFilter(); do { bool dontUseSkip = !this.Proba.UseSkipProba; - info.Clear(); - it.Import(y, u, v, yStride, uvStride, width, height, false); + if (it.X == 0) + { + this.GetMacroblockRows(it.Y, height, out y, out u, out v, out yRowsStart, out uvRowsStart); + } + + it.Import(y, u, v, yRowsStart, uvRowsStart, yStride, uvStride, width, height, false); // Warning! order is important: first call Decimate() and // *then* decide how to code the skip decision if there's one. @@ -513,81 +850,132 @@ private bool Encode( it.SaveBoundary(); } while (it.Next()); + } - // Store filter stats. - this.AdjustFilterStrength(); + /// + /// Runs the mode decision once for each macroblock and records the coefficient tokens in the token buffer. + /// The probabilities are refreshed from the token statistics about eight times per pass, so that the + /// rate-distortion costs follow the image content. After the last pass, the final probabilities are + /// set and the tokens are written to the bit writer. + /// + /// The image width. + /// The image height. + /// The y-luminance stride. + /// The uv stride. + /// The macroblock iterator. + /// + /// The token loop does not use the skip probability: each macroblock codes all its blocks. + /// + private void TokenLoop(int width, int height, int yStride, int uvStride, Vp8EncoderIterator it) + { + const int targetSize = 0; // TODO: target size is hardcoded. + const float targetPsnr = 0.0f; // TODO: targetPsnr is hardcoded. + const bool doSearch = targetSize > 0 || targetPsnr > 0; + + // The rows of the current macroblock row and the row above it. The loop gets them at the start of each macroblock row. + Span y = default; + Span u = default; + Span v = default; + int yRowsStart = 0; + int uvRowsStart = 0; + Vp8EncoderProbabilities proba = this.Proba; + Vp8TokenBuffer tokens = this.tokens; + int numPassLeft = this.entropyPasses; + long pixelCount = (long)this.Mbw * this.Mbh * 384; - // Extract and encode alpha channel data, if present. - int alphaDataSize = 0; - bool alphaCompressionSucceeded = false; - Span alphaData = []; - IMemoryOwner encodedAlphaData = null; - try + // Roughly refresh the probabilities eight times per pass. + int maxCount = Math.Max((this.Mbw * this.Mbh) >> 3, MinRefreshCount); + + PassStatistics stats = new(targetSize, targetPsnr, QMin, QMax, this.quality); + Vp8ModeScore info = new(); + Vp8Residual residual = it.ResidualScratch; + while (numPassLeft-- > 0) { - if (hasAlpha) + bool isLastPass = (MathF.Abs(stats.Dq) <= DqLimit) || (numPassLeft == 0) || (this.maxI4HeaderBits == 0); + long sizeP0 = 0; + long distortion = 0; + int cnt = maxCount; + it.Init(); + this.SetLoopParams(stats.Q); + if (isLastPass) + { + // Only the last pass collects the statistics for the final probabilities. + proba.ResetTokenStats(); + Vp8EncoderIterator.InitFilter(); + } + + tokens.Clear(); + do { - // TODO: This can potentially run in an separate task. - encodedAlphaData = AlphaEncoder.EncodeAlpha( - pixels, - this.configuration, - this.memoryAllocator, - this.skipMetadata, - this.alphaCompression, - out alphaDataSize); - - alphaData = encodedAlphaData.GetSpan(); - if (alphaDataSize < pixelCount) + if (it.X == 0) { - // Only use compressed data, if the compressed data is actually smaller then the uncompressed data. - alphaCompressionSucceeded = true; + this.GetMacroblockRows(it.Y, height, out y, out u, out v, out yRowsStart, out uvRowsStart); } - } - this.bitWriter.Finish(); + it.Import(y, u, v, yRowsStart, uvRowsStart, yStride, uvStride, width, height, false); + if (--cnt < 0) + { + proba.FinalizeTokenProbas(); + + // Refresh the cost tables for the rate-distortion optimization. + proba.CalculateLevelCosts(); + cnt = maxCount; + } - long prevPosition = 0; + this.Decimate(it, ref info, this.rdOptLevel); + this.RecordTokens(it, info, residual); + sizeP0 += info.H; + distortion += info.D; + it.SaveBoundary(); + } + while (it.Next()); - if (hasAnimation) + sizeP0 += this.SegmentHeader.Size; + if (stats.DoSizeSearch) + { + long size = proba.FinalizeTokenProbas(); + size += tokens.EstimateSize(proba.Coeffs); + size = (size + sizeP0 + 1024) >> 11; // -> size in bytes + size += HeaderSizeEstimate; + stats.Value = size; + } + else { - prevPosition = new WebpFrameData( - (uint)bounds.X, - (uint)bounds.Y, - (uint)bounds.Width, - (uint)bounds.Height, - frameMetadata.FrameDelay, - frameMetadata.BlendMode, - frameMetadata.DisposalMode) - .WriteHeaderTo(stream); + stats.Value = GetPsnr(distortion, pixelCount); } - if (hasAlpha) + if (this.maxI4HeaderBits > 0 && sizeP0 > (long)Partition0SizeLimit) { - Span data = alphaData[..alphaDataSize]; - bool alphaDataIsCompressed = this.alphaCompression && alphaCompressionSucceeded; - BitWriterBase.WriteAlphaChunk(stream, data, alphaDataIsCompressed); + ++numPassLeft; + this.maxI4HeaderBits >>= 1; // strengthen header bit limitation... + continue; // ...and start over } - this.bitWriter.WriteEncodedImageToStream(stream); + if (isLastPass) + { + break; + } - if (hasAnimation) + if (doSearch) { - RiffHelper.EndWriteChunk(stream, prevPosition); + // Unreachable due to hardcoding above. +#pragma warning disable CS0162 // Unreachable code detected + stats.ComputeNextQ(); +#pragma warning restore CS0162 // Unreachable code detected } } - finally + + if (!stats.DoSizeSearch) { - encodedAlphaData?.Dispose(); + proba.FinalizeTokenProbas(); } - return hasAlpha; - } - - /// - public void Dispose() - { - this.Y.Dispose(); - this.U.Dispose(); - this.V.Dispose(); + // The bit writer is only needed now, when the base quantizer is final. + int averageBytesPerMacroBlock = AverageBytesPerMb[this.BaseQuant >> 4]; + int expectedSize = this.Mbw * this.Mbh * averageBytesPerMacroBlock; + this.bitWriter?.Dispose(); + this.bitWriter = new Vp8BitWriter(this.memoryAllocator, expectedSize, this); + tokens.Emit(this.bitWriter, proba.Coeffs); } /// @@ -599,17 +987,23 @@ public void Dispose() /// The image height. /// The y-luminance stride. /// The uv stride. - private void StatLoop(int width, int height, int yStride, int uvStride) + /// The macroblock iterator. + /// The score accumulator reused across the macroblocks. + /// The residual reused across the macroblocks. + private void StatLoop(int width, int height, int yStride, int uvStride, Vp8EncoderIterator it, ref Vp8ModeScore info, Vp8Residual residual) { const int targetSize = 0; // TODO: target size is hardcoded. const float targetPsnr = 0.0f; // TODO: targetPsnr is hardcoded. const bool doSearch = targetSize > 0 || targetPsnr > 0; bool fastProbe = (this.method == 0 || this.method == WebpEncodingMethod.Level3) && !doSearch; int numPassLeft = this.entropyPasses; - Vp8RdLevel rdOpt = this.method >= WebpEncodingMethod.Level3 || doSearch ? Vp8RdLevel.RdOptBasic : Vp8RdLevel.RdOptNone; + Vp8RateDistortionLevel rdOpt = this.method >= WebpEncodingMethod.Level3 || doSearch + ? Vp8RateDistortionLevel.RdOptBasic + : Vp8RateDistortionLevel.RdOptNone; + int nbMbs = this.Mbw * this.Mbh; - PassStats stats = new(targetSize, targetPsnr, QMin, QMax, this.quality); + PassStatistics stats = new(targetSize, targetPsnr, QMin, QMax, this.quality); this.Proba.ResetTokenStats(); // Fast mode: quick analysis pass over few mbs. Better than nothing. @@ -629,7 +1023,7 @@ private void StatLoop(int width, int height, int yStride, int uvStride) while (numPassLeft-- > 0) { bool isLastPass = (MathF.Abs(stats.Dq) <= DqLimit) || (numPassLeft == 0) || (this.maxI4HeaderBits == 0); - long sizeP0 = this.OneStatPass(width, height, yStride, uvStride, rdOpt, nbMbs, stats); + long sizeP0 = this.OneStatPass(width, height, yStride, uvStride, rdOpt, nbMbs, stats, it, ref info, residual); if (sizeP0 == 0) { return; @@ -672,12 +1066,38 @@ private void StatLoop(int width, int height, int yStride, int uvStride) this.Proba.CalculateLevelCosts(); } - private long OneStatPass(int width, int height, int yStride, int uvStride, Vp8RdLevel rdOpt, int nbMbs, PassStats stats) + /// + /// Runs one statistics pass over the first macroblocks. + /// + /// The image width. + /// The image height. + /// The y-luminance stride. + /// The uv stride. + /// The rate-distortion optimization level. + /// The number of macroblocks to analyze. + /// The pass statistics. + /// The macroblock iterator. + /// The score accumulator reused across the macroblocks. + /// The residual reused across the macroblocks. + /// The estimated size of partition 0 in 1/256 bit units. + private long OneStatPass( + int width, + int height, + int yStride, + int uvStride, + Vp8RateDistortionLevel rdOpt, + int nbMbs, + PassStatistics stats, + Vp8EncoderIterator it, + ref Vp8ModeScore info, + Vp8Residual residual) { - Span y = this.Y.GetSpan(); - Span u = this.U.GetSpan(); - Span v = this.V.GetSpan(); - Vp8EncIterator it = new(this); + // The rows of the current macroblock row and the row above it. The loop gets them at the start of each macroblock row. + Span y = default; + Span u = default; + Span v = default; + int yRowsStart = 0; + int uvRowsStart = 0; long size = 0; long sizeP0 = 0; long distortion = 0; @@ -685,12 +1105,14 @@ private long OneStatPass(int width, int height, int yStride, int uvStride, Vp8Rd it.Init(); this.SetLoopParams(stats.Q); - Vp8ModeScore info = new(); - Vp8Residual residual = new(); do { - info.Clear(); - it.Import(y, u, v, yStride, uvStride, width, height, false); + if (it.X == 0) + { + this.GetMacroblockRows(it.Y, height, out y, out u, out v, out yRowsStart, out uvRowsStart); + } + + it.Import(y, u, v, yRowsStart, uvRowsStart, yStride, uvStride, width, height, false); if (this.Decimate(it, ref info, rdOpt)) { // Just record the number of skips and act like skipProba is not used. @@ -722,6 +1144,11 @@ private long OneStatPass(int width, int height, int yStride, int uvStride, Vp8Rd return sizeP0; } + /// + /// Prepares one encoding pass. It sets the segment quantizers and filter strengths for the quality, sets the segment probabilities, + /// and resets the skip count and the level costs. + /// + /// The quality, from 0 to 100. private void SetLoopParams(float q) { // Setup segment quantizations and filters. @@ -733,7 +1160,11 @@ private void SetLoopParams(float q) this.ResetStats(); } - private unsafe void AdjustFilterStrength() + /// + /// Raises the filter strength of each segment to the level that the largest edge in the segment needs, and sets the frame filter level + /// to the largest segment strength. The method does nothing when the filter strength option is 0. + /// + private void AdjustFilterStrength() { if (this.filterStrength > 0) { @@ -760,10 +1191,57 @@ private unsafe void AdjustFilterStrength() } } + /// + /// Sets the size of the current frame and the per-frame state that a new encoder of this size has: the macroblock geometry, + /// the header bit limits, cleared macroblock infos, the predictors, the non-zero patterns and the boundary predictions. + /// + /// The frame width. It is at most the constructor width. + /// The frame height. It is at most the constructor height. + private void InitializeFrame(int width, int height) + { + this.Width = width; + this.Height = height; + this.Mbw = (width + 15) >> 4; + this.Mbh = (height + 15) >> 4; + this.PredsWidth = (4 * this.Mbw) + 1; + this.MbHeaderLimit = 256 * 510 * 8 * 1024 / (this.Mbw * this.Mbh); + + // The 4x4 header bit limit is modulated with a quadratic curve of the partition limit. + this.maxI4HeaderBits = 256 * 16 * 16 * PartitionLimit * PartitionLimit / (100 * 100); + + // The default macroblock info is the state of a new info. + this.MbInfo.Span[..(this.Mbw * this.Mbh)].Clear(); + + // Initialize with default values, which the reference c implementation uses, + // to be able to compare to the original and spot differences. + this.Preds.Span[..GetPredsLength(this.Mbw, this.Mbh)].Fill(205); + this.Nz.Span[..(this.Mbw + 1)].Fill(3452816845); + + this.ResetBoundaryPredictions(); + } + + /// + /// Gets the number of intra mode predictors for a frame size: the (4*mbw+1) * (4*mbh+1) modes, one more entry, and + /// (4*mbw+1) + mbw entries after them. The iterator clears mbw of these last entries. + /// + /// The macroblock width. + /// The macroblock height. + /// The number of predictors. + private static int GetPredsLength(int mbw, int mbh) + { + int predsWidth = (4 * mbw) + 1; + return (predsWidth * ((4 * mbh) + 1)) + 1 + predsWidth + mbw; + } + + /// + /// Sets the prediction modes above the first macroblock row and left of the first macroblock column to the DC mode. + /// These modes are the context of the 4x4 mode probabilities at the image border. + /// private void ResetBoundaryPredictions() { - Span top = this.Preds.AsSpan(); // original source top starts at: enc->preds_ - enc->preds_w_ - Span left = this.Preds.AsSpan(this.PredsWidth - 1); + Span preds = this.Preds.Span; + Span top = preds; // original source top starts at: enc->preds_ - enc->preds_w_ + Span left = preds[(this.PredsWidth - 1)..]; for (int i = 0; i < 4 * this.Mbw; i++) { top[i] = (int)IntraPredictionMode.DcPrediction; @@ -777,21 +1255,33 @@ private void ResetBoundaryPredictions() int predsW = (4 * this.Mbw) + 1; int predsH = (4 * this.Mbh) + 1; int predsSize = predsW * predsH; - this.Preds.AsSpan(predsSize + this.PredsWidth - 4, 4).Clear(); + preds.Slice(predsSize + this.PredsWidth - 4, 4).Clear(); - this.Nz[0] = 0; // constant + this.Nz.Span[0] = 0; // constant } - // Simplified k-Means, to assign Nb segments based on alpha-histogram. - private void AssignSegments(ReadOnlySpan alphas) + /// + /// Groups the macroblocks into segments by their susceptibility with a simple k-means clustering of the histogram. Each macroblock gets + /// the segment of the nearest center, and its susceptibility becomes that center. The method then sets the susceptibility of each segment. + /// + /// The histogram of the macroblock susceptibilities, with + 1 entries. + /// + /// The scratch map from a susceptibility to its segment, with + 1 entries. The method writes the entry of + /// each susceptibility in the histogram before it reads the entry. + /// + private void AssignSegments(ReadOnlySpan alphas, Span map) { int nb = this.SegmentHeader.NumSegments < NumMbSegments ? this.SegmentHeader.NumSegments : NumMbSegments; - Span centers = stackalloc int[NumMbSegments]; + + // One entry for each of the NumMbSegments segments. A default inline array is zero, as the stack buffers were. + InlineArray4 centersBuffer = default; + InlineArray4 accumBuffer = default; + InlineArray4 distAccumBuffer = default; + Span centers = centersBuffer; + Span accum = accumBuffer; + Span distAccum = distAccumBuffer; int weightedAverage = 0; - Span map = stackalloc int[WebpConstants.MaxAlpha + 1]; int n, k; - Span accum = stackalloc int[NumMbSegments]; - Span distAccum = stackalloc int[NumMbSegments]; // Bracket the input. for (n = 0; n <= WebpConstants.MaxAlpha && alphas[n] == 0; ++n) @@ -865,9 +1355,10 @@ private void AssignSegments(ReadOnlySpan alphas) } // Map each original value to the closest centroid - for (n = 0; n < this.Mbw * this.Mbh; ++n) + Span mbInfo = this.MbInfo.Span[..(this.Mbw * this.Mbh)]; + for (n = 0; n < mbInfo.Length; ++n) { - Vp8MacroBlockInfo mb = this.MbInfo[n]; + ref Vp8MacroBlockInfo mb = ref mbInfo[n]; int alpha = mb.Alpha; mb.Segment = map[alpha]; mb.Alpha = centers[map[alpha]]; @@ -877,6 +1368,12 @@ private void AssignSegments(ReadOnlySpan alphas) this.SetSegmentAlphas(centers, weightedAverage); } + /// + /// Maps the segment centers to the segment susceptibility (alpha) and complexity (beta). Alpha is the distance from the weighted mean, + /// scaled to [-127, 127]. Beta is the distance from the smallest center, scaled to [0, 255]. + /// + /// The susceptibility center of each segment. + /// The weighted mean of the centers. private void SetSegmentAlphas(ReadOnlySpan centers, int mid) { int nb = this.SegmentHeader.NumSegments; @@ -914,6 +1411,12 @@ private void SetSegmentAlphas(ReadOnlySpan centers, int mid) } } + /// + /// Sets the quantizer of each segment from the quality. The segment susceptibility and the spatial noise shaping strength change the exponent + /// of the compression curve, so each segment gets its own quantizer. The method also sets the quantizer deltas, the filter strengths and the + /// quantization matrices. + /// + /// The quality, from 0 to 100. private void SetSegmentParams(float quality) { int nb = this.SegmentHeader.NumSegments; @@ -960,6 +1463,10 @@ private void SetSegmentParams(float quality) this.SetupMatrices(dqm); } + /// + /// Sets the initial loop filter strength of each segment from its AC quantizer step, its complexity and the filter strength option. + /// The method also sets the frame filter level, type and sharpness. + /// private void SetupFilterStrength() { const int filterSharpness = 0; // TODO: filterSharpness is hardcoded @@ -997,15 +1504,19 @@ private void SetupFilterStrength() this.FilterHeader.Sharpness = filterSharpness; } + /// + /// Sets the segment tree probabilities from the number of macroblocks in each segment, and the estimated cost of the segment map. + /// When all probabilities are 255, the map has no information, so the method puts all macroblocks in segment 0 and does not write the map. + /// private void SetSegmentProbas() { - Span p = stackalloc int[NumMbSegments]; - int n; - - for (n = 0; n < this.Mbw * this.Mbh; ++n) + // One count for each of the NumMbSegments segments. A default inline array is zero, as the stack buffer was. + InlineArray4 countBuffer = default; + Span p = countBuffer; + Span mbInfo = this.MbInfo.Span[..(this.Mbw * this.Mbh)]; + for (int n = 0; n < mbInfo.Length; ++n) { - Vp8MacroBlockInfo mb = this.MbInfo[n]; - ++p[mb.Segment]; + ++p[mbInfo[n].Segment]; } if (this.SegmentHeader.NumSegments > 1) @@ -1034,23 +1545,34 @@ private void SetSegmentProbas() } } + /// + /// Puts all macroblocks in segment 0. + /// private void ResetSegments() { - int n; - for (n = 0; n < this.Mbw * this.Mbh; ++n) + Span mbInfo = this.MbInfo.Span[..(this.Mbw * this.Mbh)]; + for (int n = 0; n < mbInfo.Length; ++n) { - this.MbInfo[n].Segment = 0; + mbInfo[n].Segment = 0; } } + /// + /// Calculates the level costs from the current probabilities and clears the skip count. + /// private void ResetStats() { - Vp8EncProba proba = this.Proba; + Vp8EncoderProbabilities proba = this.Proba; proba.CalculateLevelCosts(); proba.NbSkip = 0; } - private unsafe void SetupMatrices(Vp8SegmentInfo[] dqm) + /// + /// Sets the quantization matrices of each segment from its quantizer and the quantizer deltas. The method also sets the rate-distortion + /// lambdas, the minimum distortion and the 4x4 mode penalty, which all grow with the quantizer step. + /// + /// The segment infos. + private void SetupMatrices(Vp8SegmentInfo[] dqm) { int tlambdaScale = this.method >= WebpEncodingMethod.Default ? this.spatialNoiseShaping : 0; for (int i = 0; i < dqm.Length; i++) @@ -1075,6 +1597,8 @@ private unsafe void SetupMatrices(Vp8SegmentInfo[] dqm) m.LambdaI4 = (3 * qi4 * qi4) >> 7; m.LambdaUv = (3 * quv * quv) >> 6; m.LambdaMode = (1 * qi4 * qi4) >> 7; + m.LambdaTrellisI4 = (7 * qi4 * qi4) >> 3; + m.LambdaTrellisI16 = (qi16 * qi16) >> 2; m.TLambda = (tlambdaScale * qi4) >> 5; // none of these constants should be < 1. @@ -1082,6 +1606,8 @@ private unsafe void SetupMatrices(Vp8SegmentInfo[] dqm) m.LambdaI4 = m.LambdaI4 < 1 ? 1 : m.LambdaI4; m.LambdaUv = m.LambdaUv < 1 ? 1 : m.LambdaUv; m.LambdaMode = m.LambdaMode < 1 ? 1 : m.LambdaMode; + m.LambdaTrellisI4 = m.LambdaTrellisI4 < 1 ? 1 : m.LambdaTrellisI4; + m.LambdaTrellisI16 = m.LambdaTrellisI16 < 1 ? 1 : m.LambdaTrellisI16; m.TLambda = m.TLambda < 1 ? 1 : m.TLambda; m.MinDisto = 20 * m.Y1.Q[0]; @@ -1091,13 +1617,22 @@ private unsafe void SetupMatrices(Vp8SegmentInfo[] dqm) } } + /// + /// Analyzes each macroblock from the iterator position to the end. It records the susceptibility of each macroblock in its info + /// and in the histogram. + /// + /// The image width. + /// The image height. + /// The macroblock iterator. + /// The y-luminance stride. + /// The uv stride. + /// The susceptibility histogram to add to. + /// The sum of the chroma susceptibilities. + /// The sum of the mixed susceptibilities. private int MacroBlockAnalysis( int width, int height, - Vp8EncIterator it, - Span y, - Span u, - Span v, + Vp8EncoderIterator it, int yStride, int uvStride, Span alphas, @@ -1105,11 +1640,23 @@ private int MacroBlockAnalysis( { int alpha = 0; uvAlpha = 0; + + // The rows of the current macroblock row and the row above it. The loop gets them at the start of each macroblock row. + Span y = default; + Span u = default; + Span v = default; + int yRowsStart = 0; + int uvRowsStart = 0; if (!it.IsDone()) { do { - it.Import(y, u, v, yStride, uvStride, width, height, true); + if (it.X == 0) + { + this.GetMacroblockRows(it.Y, height, out y, out u, out v, out yRowsStart, out uvRowsStart); + } + + it.Import(y, u, v, yRowsStart, uvRowsStart, yStride, uvStride, width, height, true); int bestAlpha = this.MbAnalyze(it, alphas, out int bestUvAlpha); // Accumulate for later complexity analysis. @@ -1122,7 +1669,15 @@ private int MacroBlockAnalysis( return alpha; } - private int MbAnalyze(Vp8EncIterator it, Span alphas, out int bestUvAlpha) + /// + /// Analyzes the current macroblock. It sets the default 16x16 DC mode, no skip and segment 0, and finds the susceptibility of the + /// luma and chroma samples. The mixed susceptibility weights luma 3 to 1 against chroma. + /// + /// The macroblock iterator. + /// The susceptibility histogram to add to. + /// The chroma susceptibility. + /// The mixed susceptibility, from 0 to . + private int MbAnalyze(Vp8EncoderIterator it, Span alphas, out int bestUvAlpha) { it.SetIntra16Mode(0); // default: Intra16, DC_PRED it.SetSkip(false); // not skipped. @@ -1155,8 +1710,21 @@ private int MbAnalyze(Vp8EncIterator it, Span alphas, out int bestUvAlpha) return bestAlpha; // Mixed susceptibility (not just luma). } - private bool Decimate(Vp8EncIterator it, ref Vp8ModeScore rd, Vp8RdLevel rdOpt) + /// + /// Selects the luma and chroma modes of the current macroblock and quantizes its residuals. With rate-distortion optimization, the method + /// compares the modes by rate and distortion. Without it, the method refines the analysis decision by distortion only. + /// + /// The macroblock iterator. + /// The score accumulator. The method writes the selected levels and scores to it. + /// The rate-distortion optimization level. + /// if all quantized coefficients are zero, so the macroblock can be skipped; otherwise . + private bool Decimate(Vp8EncoderIterator it, ref Vp8ModeScore rd, Vp8RateDistortionLevel rdOpt) { + // The callers reuse one score accumulator for all macroblocks and do not clear it. The mode decision + // writes all fields that a later step reads. The selected luma mode writes all luma AC levels, and also + // the luma DC levels for intra16. The residual writers read the DC levels only for intra16. The chroma + // mode decision writes all chroma levels and all six diffusion errors. The intra4 mode costs read only + // the modes that the current macroblock wrote before. rd.InitScore(); // We can perform predictions for Luma16x16 and Chroma8x8 already. @@ -1164,24 +1732,33 @@ private bool Decimate(Vp8EncIterator it, ref Vp8ModeScore rd, Vp8RdLevel rdOpt) it.MakeLuma16Preds(); it.MakeChroma8Preds(); - if (rdOpt > Vp8RdLevel.RdOptNone) + // The trellis quantization runs for every mode with the full level, and only for the selected modes with the trellis level. + it.DoTrellis = rdOpt >= Vp8RateDistortionLevel.RdOptTrellisAll; + if (rdOpt > Vp8RateDistortionLevel.RdOptNone) { - QuantEnc.PickBestIntra16(it, ref rd, this.SegmentInfos, this.Proba); + Vp8Quantization.PickBestIntra16(it, ref rd, this.SegmentInfos, this.Proba); if (this.method >= WebpEncodingMethod.Level2) { - QuantEnc.PickBestIntra4(it, ref rd, this.SegmentInfos, this.Proba, this.maxI4HeaderBits); + Vp8Quantization.PickBestIntra4(it, ref rd, this.SegmentInfos, this.Proba, this.maxI4HeaderBits); } - QuantEnc.PickBestUv(it, ref rd, this.SegmentInfos, this.Proba); + Vp8Quantization.PickBestUv(it, ref rd, this.SegmentInfos, this.Proba); + if (rdOpt == Vp8RateDistortionLevel.RdOptTrellis) + { + // Quantize the selected modes again, with the trellis. + it.DoTrellis = true; + Vp8Quantization.SimpleQuantize(it, rd, this.SegmentInfos, this.Proba); + } } else { // At this point we have heuristically decided intra16 / intra4. // For method >= 2, pick the best intra4/intra16 based on SSE (~tad slower). // For method <= 1, the encoder does not check the decision again. It goes directly to quantization and reconstruction. - QuantEnc.RefineUsingDistortion( + Vp8Quantization.RefineUsingDistortion( it, this.SegmentInfos, + this.Proba, rd, this.method >= WebpEncodingMethod.Level2, this.method >= WebpEncodingMethod.Level1, @@ -1194,7 +1771,14 @@ private bool Decimate(Vp8EncIterator it, ref Vp8ModeScore rd, Vp8RdLevel rdOpt) return isSkipped; } - private void CodeResiduals(Vp8EncIterator it, Vp8ModeScore rd, Vp8Residual residual) + /// + /// Writes the coefficient tokens of the current macroblock to the bit writer: the Y2 block for a 16x16 prediction, the 16 luma blocks + /// and the 8 chroma blocks. The method updates the non-zero contexts and the bit counts of the segment. + /// + /// The iterator. + /// The score accumulator with the quantized levels. + /// The residual reused across the macroblocks of one pass. + private void CodeResiduals(Vp8EncoderIterator it, Vp8ModeScore rd, Vp8Residual residual) { int x, y, ch; bool i16 = it.CurrentMacroBlockInfo.MacroBlockType == Vp8MacroBlockType.I16X16; @@ -1206,8 +1790,7 @@ private void CodeResiduals(Vp8EncIterator it, Vp8ModeScore rd, Vp8Residual resid if (i16) { residual.Init(0, 1, this.Proba); - residual.SetCoeffs(rd.YDcLevels); - int res = this.bitWriter.PutCoeffs(it.TopNz[8] + it.LeftNz[8], residual); + int res = this.bitWriter.PutCoeffs(it.TopNz[8] + it.LeftNz[8], residual, rd.YDcLevels); it.TopNz[8] = it.LeftNz[8] = res; residual.Init(1, 0, this.Proba); } @@ -1222,9 +1805,7 @@ private void CodeResiduals(Vp8EncIterator it, Vp8ModeScore rd, Vp8Residual resid for (x = 0; x < 4; x++) { int ctx = it.TopNz[x] + it.LeftNz[y]; - Span coeffs = rd.YAcLevels.AsSpan(16 * (x + (y * 4)), 16); - residual.SetCoeffs(coeffs); - int res = this.bitWriter.PutCoeffs(ctx, residual); + int res = this.bitWriter.PutCoeffs(ctx, residual, rd.YAcLevels.AsSpan(16 * (x + (y * 4)), 16)); it.TopNz[x] = it.LeftNz[y] = res; } } @@ -1240,8 +1821,7 @@ private void CodeResiduals(Vp8EncIterator it, Vp8ModeScore rd, Vp8Residual resid for (x = 0; x < 2; x++) { int ctx = it.TopNz[4 + ch + x] + it.LeftNz[4 + ch + y]; - residual.SetCoeffs(rd.UvLevels.AsSpan(16 * ((ch * 2) + x + (y * 2)), 16)); - int res = this.bitWriter.PutCoeffs(ctx, residual); + int res = this.bitWriter.PutCoeffs(ctx, residual, rd.UvLevels.AsSpan(16 * ((ch * 2) + x + (y * 2)), 16)); it.TopNz[4 + ch + x] = it.LeftNz[4 + ch + y] = res; } } @@ -1250,8 +1830,9 @@ private void CodeResiduals(Vp8EncIterator it, Vp8ModeScore rd, Vp8Residual resid int pos3 = this.bitWriter.NumBytes; it.LumaBits = pos2 - pos1; it.UvBits = pos3 - pos2; - it.BitCount[segment, i16 ? 1 : 0] += it.LumaBits; - it.BitCount[segment, 2] += it.UvBits; + Span bitCount = it.BitCount; + bitCount[(segment * 3) + (i16 ? 1 : 0)] += it.LumaBits; + bitCount[(segment * 3) + 2] += it.UvBits; it.BytesToNz(); } @@ -1262,19 +1843,81 @@ private void CodeResiduals(Vp8EncIterator it, Vp8ModeScore rd, Vp8Residual resid /// The iterator. /// The score accumulator. /// The residual reused across the macroblocks of one pass. - private void RecordResiduals(Vp8EncIterator it, Vp8ModeScore rd, Vp8Residual residual) + private void RecordResiduals(Vp8EncoderIterator it, Vp8ModeScore rd, Vp8Residual residual) + { + int x, y, ch; + bool i16 = it.CurrentMacroBlockInfo.MacroBlockType == Vp8MacroBlockType.I16X16; + + it.NzToBytes(); + + if (i16) + { + // i16x16 + residual.Init(0, 1, this.Proba); + int res = residual.RecordCoeffs(it.TopNz[8] + it.LeftNz[8], rd.YDcLevels); + it.TopNz[8] = res; + it.LeftNz[8] = res; + residual.Init(1, 0, this.Proba); + } + else + { + residual.Init(0, 3, this.Proba); + } + + // luma-AC + for (y = 0; y < 4; y++) + { + for (x = 0; x < 4; x++) + { + int ctx = it.TopNz[x] + it.LeftNz[y]; + int res = residual.RecordCoeffs(ctx, rd.YAcLevels.AsSpan(16 * (x + (y * 4)), 16)); + it.TopNz[x] = res; + it.LeftNz[y] = res; + } + } + + // U/V + residual.Init(0, 2, this.Proba); + for (ch = 0; ch <= 2; ch += 2) + { + for (y = 0; y < 2; y++) + { + for (x = 0; x < 2; x++) + { + int ctx = it.TopNz[4 + ch + x] + it.LeftNz[4 + ch + y]; + int res = residual.RecordCoeffs(ctx, rd.UvLevels.AsSpan(16 * ((ch * 2) + x + (y * 2)), 16)); + it.TopNz[4 + ch + x] = res; + it.LeftNz[4 + ch + y] = res; + } + } + } + + it.BytesToNz(); + } + + /// + /// Same as CodeResiduals, but records the tokens in the token buffer instead of writing them. + /// The tokens are written after the final probabilities are known. + /// + /// The iterator. + /// The score accumulator. + /// The residual reused across the macroblocks of one pass. + private void RecordTokens(Vp8EncoderIterator it, Vp8ModeScore rd, Vp8Residual residual) { int x, y, ch; bool i16 = it.CurrentMacroBlockInfo.MacroBlockType == Vp8MacroBlockType.I16X16; + // The span has space for the tokens of a full macroblock, so the blocks need no capacity checks. + Span tokens = this.tokens.GetMacroBlockSpan(); + int count = 0; + it.NzToBytes(); if (i16) { // i16x16 residual.Init(0, 1, this.Proba); - residual.SetCoeffs(rd.YDcLevels); - int res = residual.RecordCoeffs(it.TopNz[8] + it.LeftNz[8]); + int res = residual.RecordCoeffTokens(it.TopNz[8] + it.LeftNz[8], rd.YDcLevels, tokens, ref count); it.TopNz[8] = res; it.LeftNz[8] = res; residual.Init(1, 0, this.Proba); @@ -1290,9 +1933,7 @@ private void RecordResiduals(Vp8EncIterator it, Vp8ModeScore rd, Vp8Residual res for (x = 0; x < 4; x++) { int ctx = it.TopNz[x] + it.LeftNz[y]; - Span coeffs = rd.YAcLevels.AsSpan(16 * (x + (y * 4)), 16); - residual.SetCoeffs(coeffs); - int res = residual.RecordCoeffs(ctx); + int res = residual.RecordCoeffTokens(ctx, rd.YAcLevels.AsSpan(16 * (x + (y * 4)), 16), tokens, ref count); it.TopNz[x] = res; it.LeftNz[y] = res; } @@ -1307,17 +1948,22 @@ private void RecordResiduals(Vp8EncIterator it, Vp8ModeScore rd, Vp8Residual res for (x = 0; x < 2; x++) { int ctx = it.TopNz[4 + ch + x] + it.LeftNz[4 + ch + y]; - residual.SetCoeffs(rd.UvLevels.AsSpan(16 * ((ch * 2) + x + (y * 2)), 16)); - int res = residual.RecordCoeffs(ctx); + int res = residual.RecordCoeffTokens(ctx, rd.UvLevels.AsSpan(16 * ((ch * 2) + x + (y * 2)), 16), tokens, ref count); it.TopNz[4 + ch + x] = res; it.LeftNz[4 + ch + y] = res; } } } + this.tokens.Advance(count); it.BytesToNz(); } + /// + /// Inverts a susceptibility and clamps it to [0, ]. + /// + /// The susceptibility. + /// The final susceptibility. [MethodImpl(InliningOptions.ShortMethod)] private static int FinalAlphaValue(int alpha) { @@ -1331,6 +1977,7 @@ private static int FinalAlphaValue(int alpha) /// map accordingly using linear piece-wise function /// /// The compression level. + /// The compression factor. A level in the range 0 to 1 gives a factor in the range 0 to 1. [MethodImpl(InliningOptions.ShortMethod)] private static double QualityToCompression(double c) { @@ -1345,6 +1992,12 @@ private static double QualityToCompression(double c) return (double)Math.Pow(linearC, 1 / 3.0d); } + /// + /// Gets the loop filter level that smooths an edge step of at the given sharpness. + /// + /// The filter sharpness, from 0 to 7. + /// The edge step. Values above the table size use the last table entry. + /// The filter level. [MethodImpl(InliningOptions.ShortMethod)] private static int FilterStrengthFromDelta(int sharpness, int delta) { @@ -1352,9 +2005,21 @@ private static int FilterStrengthFromDelta(int sharpness, int delta) return WebpLookupTables.LevelsFromDelta[sharpness, pos]; } + /// + /// Calculates the peak signal-to-noise ratio of 8-bit samples. + /// + /// The sum of the squared errors. + /// The number of samples. + /// The PSNR in decibels, or 99 when there is no error or no sample. [MethodImpl(InliningOptions.ShortMethod)] private static double GetPsnr(long mse, long size) => mse > 0 && size > 0 ? 10.0f * Math.Log10(255.0f * 255.0f * size / mse) : 99; + /// + /// Calculates the rounded probability that a bit is 0, in units of 1/256, from the counts of 0 and 1 bits. + /// + /// The number of 0 bits. + /// The number of 1 bits. + /// The probability, from 0 to 255. With no bits, the default probability 255. [MethodImpl(InliningOptions.ShortMethod)] private static int GetProba(int a, int b) { diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderIterator.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderIterator.cs new file mode 100644 index 0000000000..925d0d22d1 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderIterator.cs @@ -0,0 +1,1435 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossy; + +/// +/// Iterator structure to iterate through macroblocks, pointing to the +/// right neighbouring data (samples, predictions, contexts, ...) +/// +internal class Vp8EncoderIterator +{ + /// + /// The offset of the luma block in the sample buffers. The row stride is . + /// + public const int YOffEnc = 0; + + /// + /// The offset of the U block in the sample buffers. It is to the right of the luma block. + /// + public const int UOffEnc = 16; + + /// + /// The offset of the V block in the sample buffers. It is to the right of the U block. + /// + public const int VOffEnc = 16 + 8; + + /// + /// The length of the work sample buffer of the iterator. The buffer holds , , , + /// and in this order. + /// + public const int SampleBufferLength = (4 * BlockBufferLength) + PredictionBufferLength; + + /// + /// The length of the coefficient scratch buffer : the 16 DC coefficients and the 16 blocks of 16 coefficients of a macroblock. + /// + public const int CoefficientScratchLength = 17 * 16; + + /// + /// The length of one sample block buffer. It has 16 rows with a stride of . + /// + private const int BlockBufferLength = WebpConstants.Bps * 16; + + /// + /// The length of the prediction buffer : the 16x16 luma, the chroma and the 4x4 luma predictions. + /// + private const int PredictionBufferLength = (32 * WebpConstants.Bps) + (16 * WebpConstants.Bps) + (8 * WebpConstants.Bps); + + /// + /// The number of 16x16 luma modes that the analysis tests. It tests only the DC and TrueMotion modes. + /// + private const int MaxIntra16Mode = 2; + + /// + /// The number of 4x4 luma modes that the analysis tests. It tests only the DC and TrueMotion modes. + /// + private const int MaxIntra4Mode = 2; + + /// + /// The number of chroma modes that the analysis tests. It tests only the DC and TrueMotion modes. + /// + private const int MaxUvMode = 2; + + /// + /// The start value of the best susceptibility search. It is lower than all valid susceptibilities. + /// + private const int DefaultAlpha = -1; + + /// + /// The image width in macroblocks. + /// + private readonly int mbw; + + /// + /// The image height in macroblocks. + /// + private readonly int mbh; + + /// + /// Stride of the prediction plane(=4*mbw + 1). + /// + private readonly int predsWidth; + + /// + /// The top luma samples of the encoder, 16 for each macroblock column. + /// + private readonly Memory yTop; + + /// + /// The top chroma samples of the encoder, 8 U and 8 V for each macroblock column. + /// + private readonly Memory uvTop; + + /// + /// The non-zero patterns of the encoder, one for each macroblock column plus one for the left context. + /// + private readonly Memory nz; + + /// + /// The macroblock infos of the encoder in raster order. + /// + private readonly Memory mb; + + /// + /// The intra mode predictors of the encoder. + /// + private readonly Memory preds; + + /// + /// The storage of . It is a part of the work sample buffer of the encoder. + /// + private readonly Memory yuvIn; + + /// + /// The storage of . It is a part of the work sample buffer of the encoder. + /// + private readonly Memory yuvP; + + /// + /// The storage of . It is a part of the work sample buffer of the encoder. + /// + private readonly Memory scratch; + + /// + /// The storage of . It is the coefficient scratch buffer of the encoder. + /// + private readonly Memory scratch2; + + /// + /// The storage of . It is empty when the encoder does not diffuse errors. + /// + private readonly Memory topDerr; + + /// + /// The storage of . It is a part of the work sample buffer of the encoder. + /// exchanges it with . + /// + private Memory yuvOut; + + /// + /// The storage of . It is a part of the work sample buffer of the encoder. + /// exchanges it with . + /// + private Memory yuvOut2; + + /// + /// The index of the current macroblock in raster order. + /// + private int currentMbIdx; + + /// + /// The index of the non-zero pattern of the current macroblock column in . Index 0 holds the left context of the first column. + /// + private int nzIdx; + + /// + /// The index of the top luma samples of the current macroblock in . + /// + private int yTopIdx; + + /// + /// The index of the top chroma samples of the current macroblock in . + /// + private int uvTopIdx; + + /// + /// The storage of . + /// + private InlineArray32 yLeft; + + /// + /// The storage of . + /// + private InlineArray32 uvLeft; + + /// + /// The storage of . The 9 contexts use the first 9 entries. No inline array type has exactly 9 entries. + /// + private InlineArray10 topNz; + + /// + /// The storage of . The 9 contexts use the first 9 entries. No inline array type has exactly 9 entries. + /// + private InlineArray10 leftNz; + + /// + /// The storage of . The 37 boundary samples use the first 37 entries. No inline array type has exactly 37 entries. + /// + private InlineArray64 i4Boundary; + + /// + /// The storage of : three counters for each of the four segments. + /// + private InlineArray12 bitCount; + + /// + /// The storage of . + /// + private InlineArray16 scratch3; + + /// + /// The storage of : one sum for each 4x4 luma block. + /// + private InlineArray16 sourceSums; + + /// + /// The storage of : two errors for each chroma channel. + /// + private InlineArray4 leftDerr; + + /// + /// Initializes a new instance of the class that shares the macroblock state and the work buffers + /// of the encoder. The iterator starts at the first macroblock. + /// + /// The encoder. + public Vp8EncoderIterator(Vp8Encoder enc) + : this(enc.YTop, enc.UvTop, enc.Nz, enc.MbInfo, enc.Preds, enc.TopDerr, enc.IteratorSamples, enc.IteratorCoefficients, enc.Mbw, enc.Mbh) + { + } + + /// + /// Initializes a new instance of the class. The iterator starts at the first macroblock. + /// + /// + /// The iterator does not own the buffers. The caller owns them and keeps them alive while it uses the iterator. + /// The constructor sets the initial values of the work buffers, so the iterators of one owner must not be used at the same time. + /// + /// The top luma samples, 16 for each macroblock column. + /// The top chroma samples, 8 U and 8 V for each macroblock column. + /// The non-zero patterns, one for each macroblock column plus one for the left context. + /// The macroblock infos in raster order. + /// The intra mode predictors. + /// The top chroma diffusion errors, 4 for each macroblock column, or empty when the encoder does not diffuse errors. + /// The work sample buffer of bytes. The constructor sets all samples to 204. + /// The coefficient scratch buffer of values. The constructor clears it. + /// The image width in macroblocks. + /// The image height in macroblocks. + public Vp8EncoderIterator( + Memory yTop, + Memory uvTop, + Memory nz, + Memory mb, + Memory preds, + Memory topDerr, + Memory samples, + Memory coefficients, + int mbw, + int mbh) + { + this.yTop = yTop; + this.uvTop = uvTop; + this.nz = nz; + this.mb = mb; + this.preds = preds; + this.topDerr = topDerr; + this.mbw = mbw; + this.mbh = mbh; + this.currentMbIdx = 0; + this.nzIdx = 1; + this.yTopIdx = 0; + this.uvTopIdx = 0; + this.predsWidth = (4 * mbw) + 1; + this.PredIdx = this.predsWidth; + + // The sample buffer holds four block buffers and then the prediction buffer (I16 + chroma + I4 predictions). + this.yuvIn = samples[..BlockBufferLength]; + this.yuvOut = samples.Slice(BlockBufferLength, BlockBufferLength); + this.yuvOut2 = samples.Slice(2 * BlockBufferLength, BlockBufferLength); + this.scratch = samples.Slice(3 * BlockBufferLength, BlockBufferLength); + this.yuvP = samples.Slice(4 * BlockBufferLength, PredictionBufferLength); + this.scratch2 = coefficients[..CoefficientScratchLength]; + this.RdScratch = new Vp8ModeScore(); + this.RdScratch2 = new Vp8ModeScore(); + this.RdScratch3 = new Vp8ModeScore(); + this.ResidualScratch = new Vp8Residual(); + + // To match the C initial values of the reference implementation, initialize all with 204. + // One fill covers YuvIn, YuvOut, YuvOut2, Scratch and YuvP, because they are the parts of the sample buffer. + const byte defaultInitVal = 204; + samples.Span[..SampleBufferLength].Fill(defaultInitVal); + this.YLeft.Fill(defaultInitVal); + this.UvLeft.Fill(defaultInitVal); + + // The pooled coefficient buffer can hold the values of an earlier iterator. Each iterator starts with zero coefficients. + this.Scratch2.Clear(); + + this.Init(); + } + + /// + /// Gets the position of the top sample A of each 4x4 block in , in raster order of the blocks. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates no memory. + /// + private static ReadOnlySpan TopLeftI4 => + [ + 17, 21, 25, 29, + 13, 17, 21, 25, + 9, 13, 17, 21, + 5, 9, 13, 17 + ]; + + /// + /// Gets or sets the current macroblock X value. + /// + public int X { get; set; } + + /// + /// Gets or sets the current macroblock Y. + /// + public int Y { get; set; } + + /// + /// Gets the input samples of the current macroblock. The row stride is . + /// + /// + /// Each access gets the span from pooled memory. Callers get the span once for a method. + /// + public Span YuvIn => this.yuvIn.Span; + + /// + /// Gets the output samples: the best reconstruction of the current macroblock. The row stride is . + /// + /// + /// exchanges this buffer with . Callers get the span again after a swap. + /// + public Span YuvOut => this.yuvOut.Span; + + /// + /// Gets the secondary output samples that the mode search writes. The row stride is . + /// + /// + /// exchanges this buffer with . Callers get the span again after a swap. + /// + public Span YuvOut2 => this.yuvOut2.Span; + + /// + /// Gets the prediction samples: the 16x16 luma, the chroma and the 4x4 luma predictions. The row stride is . + /// + public Span YuvP => this.yuvP.Span; + + /// + /// Gets the 32 left luma samples. Entry 0 is the top-left sample, and entries 1 to 16 are the left samples. + /// + public Span YLeft => this.yLeft; + + /// + /// Gets the 32 left uv samples: 16 for U, then 16 for V. In each half, entry 0 is the top-left sample, and entries 1 to 8 are the left samples. + /// + public Span UvLeft => this.uvLeft; + + /// + /// Gets the left chroma diffusion errors: 2 for U, then 2 for V. + /// + public Span LeftDerr => this.leftDerr; + + /// + /// Gets the top luma samples, 16 for each macroblock column. + /// + public Span YTop => this.yTop.Span; + + /// + /// Gets the top u/v samples, packed as 16 bytes (8 U + 8 V) for each macroblock column. + /// + public Span UvTop => this.uvTop.Span; + + /// + /// Gets the intra mode predictors (4x4 blocks). + /// + public Span Preds => this.preds.Span; + + /// + /// Gets the current start index of the intra mode predictors. + /// + public int PredIdx { get; private set; } + + /// + /// Gets the non-zero patterns, one for each macroblock column plus one for the left context at index 0. + /// + public Span Nz => this.nz.Span; + + /// + /// Gets the top chroma diffusion errors, 4 for each macroblock column: 2 for U, then 2 for V. + /// The span is empty when the encoder does not diffuse errors. + /// + public Span TopDerr => this.topDerr.Span; + + /// + /// Gets a value indicating whether the encoder diffuses the chroma DC errors to the next macroblocks. + /// + /// + /// The value comes from the length of the top error buffer, so it does not get a span from pooled memory. + /// + public bool UsesErrorDiffusion => !this.topDerr.IsEmpty; + + /// + /// Gets the boundary samples needed by intra4x4. The 32+5 samples are the first 37 entries of the span. + /// + public Span I4Boundary => this.i4Boundary; + + /// + /// Gets or sets the index to the current top boundary sample. + /// + public int I4BoundaryIdx { get; set; } + + /// + /// Gets or sets the current intra4x4 mode being tested. + /// + public int I4 { get; set; } + + /// + /// Gets or sets a value indicating whether the luma reconstructions of the current macroblock use the trellis quantization. + /// + public bool DoTrellis { get; set; } + + /// + /// Gets the top-non-zero context. Entries 0 to 8 are the contexts; entry 9 is not used. + /// + public Span TopNz => this.topNz; + + /// + /// Gets the left-non-zero context. Entries 0 to 8 are the contexts; entry 9 is not used. leftNz[8] is independent. + /// + public Span LeftNz => this.leftNz; + + /// + /// Gets or sets the macroblock bit-cost for luma. + /// + public long LumaBits { get; set; } + + /// + /// Gets the bit counters for coded levels. Segment s has the counters at 3 * s: the 4x4 luma bits, the 16x16 luma bits and the chroma bits. + /// + public Span BitCount => this.bitCount; + + /// + /// Gets or sets the macroblock bit-cost for chroma. + /// + public long UvBits { get; set; } + + /// + /// Gets or sets the number of mb still to be processed. + /// + public int CountDown { get; set; } + + /// + /// Gets the byte scratch buffer of * 16 bytes. + /// + public Span Scratch => this.scratch.Span; + + /// + /// Gets the coefficient scratch buffer of values. + /// + public Span Scratch2 => this.scratch2.Span; + + /// + /// Gets the int scratch buffer of 16 values. + /// + public Span Scratch3 => this.scratch3; + + /// + /// Gets the weighted Hadamard sums of the 16 source luma blocks of the macroblock, for the spectral distortion. + /// + /// + /// computes them, and reads them for the same + /// macroblock. The source does not change between the two searches, so the sums are computed once. + /// + public Span SourceSums => this.sourceSums; + + /// + /// Gets or sets the first reusable rate-distortion score accumulator. + /// uses the three accumulators as scratch state while it evaluates the + /// prediction modes of a macroblock, so mode evaluation does not allocate per macroblock. + /// exchanges this instance with the caller's accumulator + /// when the best mode ends up in the scratch instance, which is why the property has a setter. + /// + public Vp8ModeScore RdScratch { get; set; } + + /// + /// Gets the second reusable rate-distortion score accumulator. + /// + public Vp8ModeScore RdScratch2 { get; } + + /// + /// Gets the third reusable rate-distortion score accumulator. + /// + public Vp8ModeScore RdScratch3 { get; } + + /// + /// Gets the reusable residual used to cost the candidate modes of a macroblock. + /// + public Vp8Residual ResidualScratch { get; } + + /// + /// Gets a reference to the info of the current macroblock. + /// + public ref Vp8MacroBlockInfo CurrentMacroBlockInfo => ref this.mb.Span[this.currentMbIdx]; + + /// + /// Prepares the statistics for the automatic loop filter selection. The encoder does not support it yet, so the method does nothing. + /// + public static void InitFilter() + { + // TODO: add support for autofilter + } + + /// + /// Starts the 4x4 block iteration of the current macroblock at the first block. The method loads the left, top and top-right boundary samples + /// into and loads the non-zero context. At the right image edge, the top-right samples repeat the last top sample. + /// + public void StartI4() + { + int i; + this.I4 = 0; // first 4x4 sub-block. + this.I4BoundaryIdx = TopLeftI4[0]; + Span boundary = this.I4Boundary; + Span yLeft = this.YLeft; + + // Import the boundary samples. + for (i = 0; i < 17; i++) + { + // left + boundary[i] = yLeft[15 - i + 1]; + } + + Span yTop = this.YTop[this.yTopIdx..]; + for (i = 0; i < 16; i++) + { + // top + boundary[17 + i] = yTop[i]; + } + + // top-right samples have a special case on the far right of the picture. + if (this.X < this.mbw - 1) + { + for (i = 16; i < 16 + 4; i++) + { + boundary[17 + i] = yTop[i]; + } + } + else + { + // else, replicate the last valid pixel four times + for (i = 16; i < 16 + 4; i++) + { + boundary[17 + i] = boundary[17 + 15]; + } + } + + this.NzToBytes(); // import the non-zero context. + } + + /// + /// Copies the source samples of the current macroblock to . At the right and bottom image edges, the method repeats + /// the last row and column to fill the block. + /// + /// The luma rows of the macroblock row and the row above it. + /// The U rows of the macroblock row and the row above it. + /// The V rows of the macroblock row and the row above it. + /// The flat position in the luma plane of the first sample of . + /// The flat position in the chroma planes of the first sample of and . + /// The y-luminance stride. + /// The uv stride. + /// The image width. + /// The image height. + /// + /// to also copy the left and top source samples to the boundary buffers. The analysis uses source samples + /// as boundaries. The encoding uses the reconstructed samples that stores. + /// + public void Import( + Span y, + Span u, + Span v, + int yRowsStart, + int uvRowsStart, + int yStride, + int uvStride, + int width, + int height, + bool importBoundarySamples) + { + int yStartIdx = (((this.Y * yStride) + this.X) * 16) - yRowsStart; + int uvStartIdx = (((this.Y * uvStride) + this.X) * 8) - uvRowsStart; + Span ySrc = y[yStartIdx..]; + Span uSrc = u[uvStartIdx..]; + Span vSrc = v[uvStartIdx..]; + int w = Math.Min(width - (this.X * 16), 16); + int h = Math.Min(height - (this.Y * 16), 16); + int uvw = (w + 1) >> 1; + int uvh = (h + 1) >> 1; + + Span yuvIn = this.YuvIn; + ImportBlock(ySrc, yStride, yuvIn[YOffEnc..], w, h, 16); + ImportBlock(uSrc, uvStride, yuvIn[UOffEnc..], uvw, uvh, 8); + ImportBlock(vSrc, uvStride, yuvIn[VOffEnc..], uvw, uvh, 8); + + if (!importBoundarySamples) + { + return; + } + + // Import source (uncompressed) samples into boundary. + if (this.X == 0) + { + this.InitLeft(); + } + else + { + Span yLeft = this.YLeft; + Span uLeft = this.UvLeft[..16]; + Span vLeft = this.UvLeft.Slice(16, 16); + if (this.Y == 0) + { + yLeft[0] = 127; + uLeft[0] = 127; + vLeft[0] = 127; + } + else + { + yLeft[0] = y[yStartIdx - 1 - yStride]; + uLeft[0] = u[uvStartIdx - 1 - uvStride]; + vLeft[0] = v[uvStartIdx - 1 - uvStride]; + } + + ImportLine(y[(yStartIdx - 1)..], yStride, yLeft[1..], h, 16); + ImportLine(u[(uvStartIdx - 1)..], uvStride, uLeft[1..], uvh, 8); + ImportLine(v[(uvStartIdx - 1)..], uvStride, vLeft[1..], uvh, 8); + } + + Span yTop = this.YTop.Slice(this.yTopIdx, 16); + Span uvTop = this.UvTop.Slice(this.uvTopIdx, 16); + if (this.Y == 0) + { + yTop.Fill(127); + uvTop.Fill(127); + } + else + { + ImportLine(y[(yStartIdx - yStride)..], 1, yTop, w, 16); + ImportLine(u[(uvStartIdx - uvStride)..], 1, uvTop[..8], uvw, 8); + ImportLine(v[(uvStartIdx - uvStride)..], 1, uvTop.Slice(8, 8), uvw, 8); + } + } + + /// + /// Selects between the 16x16 DC mode and the 4x4 DC modes from the variance of the means of the sixteen 4x4 luma blocks. + /// A flat macroblock gets the 16x16 mode. A higher quality favors the 4x4 modes. + /// + /// The encoding quality, from 0 to 100. + /// The susceptibility, which is always 0 for this fast analysis. + public int FastMbAnalyze(uint quality) + { + // Empirical cut-off value, should be around 16 (~=block size). We use the + // [8-17] range and favor intra4 at high quality, intra16 for low quality. + uint q = quality; + uint kThreshold = 8 + ((17 - 8) * q / 100); + int k; + + // The 16 means of the 4x4 luma blocks. Mean16x4 writes all of them. + InlineArray16 dcBuffer = default; + Span dc = dcBuffer; + uint m; + uint m2; + Span yuvIn = this.YuvIn; + for (k = 0; k < 16; k += 4) + { + LossyUtils.Mean16x4(yuvIn[(YOffEnc + (k * WebpConstants.Bps))..], dc.Slice(k, 4)); + } + + for (m = 0, m2 = 0, k = 0; k < 16; k++) + { + m += dc[k]; + m2 += dc[k] * dc[k]; + } + + if (kThreshold * m2 < m * m) + { + this.SetIntra16Mode(0); // DC16 + } + else + { + // A default inline array holds 16 zero modes, the DC4 mode for each 4x4 block. + InlineArray16 modes = default; + this.SetIntra4Mode(modes); + } + + return 0; + } + + /// + /// Selects the 16x16 luma mode with the highest susceptibility of the prediction residual, and sets it on the current macroblock. + /// + /// The susceptibility of the selected mode. + public int MbAnalyzeBestIntra16Mode() + { + const int maxMode = MaxIntra16Mode; + int mode; + int bestAlpha = DefaultAlpha; + int bestMode = 0; + + this.MakeLuma16Preds(); + Span yuvIn = this.YuvIn; + Span yuvP = this.YuvP; + for (mode = 0; mode < maxMode; mode++) + { + Vp8Histogram histo = new(); + histo.CollectHistogram(yuvIn[YOffEnc..], yuvP[Vp8Encoding.Vp8I16ModeOffsets[mode]..], 0, 16); + int alpha = histo.GetAlpha(); + if (alpha > bestAlpha) + { + bestAlpha = alpha; + bestMode = mode; + } + } + + this.SetIntra16Mode(bestMode); + return bestAlpha; + } + + /// + /// Selects the 4x4 luma mode with the highest susceptibility for each 4x4 block. The predictions use the source samples as boundaries. + /// When the merged susceptibility of the 4x4 modes is higher than , the method sets the 4x4 modes on the + /// current macroblock. + /// + /// The susceptibility of the best 16x16 mode. + /// The higher of the 4x4 susceptibility and . + public int MbAnalyzeBestIntra4Mode(int bestAlpha) + { + // The best mode of each 4x4 block in raster order. Every block writes its entry, because the first mode always improves the default alpha. + InlineArray16 modesBuffer = default; + Span modes = modesBuffer; + const int maxMode = MaxIntra4Mode; + Vp8Histogram totalHisto = new(); + int curHisto = 0; + + // The two entries alternate between the candidate under test and the best candidate so far. + // CollectHistogram fully initializes an entry before it is read, so no per-block reset is needed. + InlineArray2 histosBuffer = default; + Span histos = histosBuffer; + Span yuvIn = this.YuvIn; + Span yuvP = this.YuvP; + this.StartI4(); + do + { + int mode; + int bestModeAlpha = DefaultAlpha; + Span src = yuvIn[(YOffEnc + WebpLookupTables.Vp8Scan[this.I4])..]; + + this.MakeIntra4Preds(); + for (mode = 0; mode < maxMode; ++mode) + { + histos[curHisto].CollectHistogram(src, yuvP[Vp8Encoding.Vp8I4ModeOffsets[mode]..], 0, 1); + + int alpha = histos[curHisto].GetAlpha(); + if (alpha > bestModeAlpha) + { + bestModeAlpha = alpha; + modes[this.I4] = (byte)mode; + + // Keep track of best histo so far. + curHisto ^= 1; + } + } + + // Accumulate best histogram. + histos[curHisto ^ 1].Merge(ref totalHisto); + } + while (this.RotateI4(yuvIn[YOffEnc..])); // Note: we reuse the original samples for predictors. + + int i4Alpha = totalHisto.GetAlpha(); + if (i4Alpha > bestAlpha) + { + this.SetIntra4Mode(modes); + bestAlpha = i4Alpha; + } + + return bestAlpha; + } + + /// + /// Selects the chroma mode with the lowest susceptibility of the prediction residual, and sets it on the current macroblock. + /// + /// The highest susceptibility of the tested modes. + public int MbAnalyzeBestUvMode() + { + int bestAlpha = DefaultAlpha; + int smallestAlpha = 0; + int bestMode = 0; + const int maxMode = MaxUvMode; + int mode; + + this.MakeChroma8Preds(); + Span yuvIn = this.YuvIn; + Span yuvP = this.YuvP; + for (mode = 0; mode < maxMode; ++mode) + { + Vp8Histogram histo = new(); + histo.CollectHistogram(yuvIn[UOffEnc..], yuvP[Vp8Encoding.Vp8UvModeOffsets[mode]..], 16, 16 + 4 + 4); + int alpha = histo.GetAlpha(); + if (alpha > bestAlpha) + { + bestAlpha = alpha; + } + + // The best prediction mode tends to be the one with the smallest alpha. + if (mode == 0 || alpha < smallestAlpha) + { + smallestAlpha = alpha; + bestMode = mode; + } + } + + this.SetIntraUvMode(bestMode); + return bestAlpha; + } + + /// + /// Sets the 16x16 luma mode on the current macroblock. All 16 entries of the macroblock in get the mode. + /// + /// The 16x16 luma mode. + public void SetIntra16Mode(int mode) + { + Span preds = this.Preds[this.PredIdx..]; + for (int y = 0; y < 4; y++) + { + preds[..4].Fill((byte)mode); + preds = preds[this.predsWidth..]; + } + + this.CurrentMacroBlockInfo.MacroBlockType = Vp8MacroBlockType.I16X16; + } + + /// + /// Sets the 4x4 luma modes on the current macroblock. The modes go to the entries of the macroblock in . + /// + /// The 16 modes of the 4x4 blocks in raster order. + public void SetIntra4Mode(ReadOnlySpan modes) + { + int modesIdx = 0; + int predIdx = this.PredIdx; + Span preds = this.Preds; + for (int y = 4; y > 0; y--) + { + modes.Slice(modesIdx, 4).CopyTo(preds[predIdx..]); + predIdx += this.predsWidth; + modesIdx += 4; + } + + this.CurrentMacroBlockInfo.MacroBlockType = Vp8MacroBlockType.I4X4; + } + + /// + /// Calculates the bit cost of the luma levels of a 16x16 prediction: the Y2 block and the 16 AC blocks. The method loads the non-zero + /// context first and updates and with the result of each AC block. + /// + /// The score with the quantized luma levels. + /// The probabilities with the level costs. + /// The residual to reuse. + /// The cost in 1/256 bit units. + public int GetCostLuma16(Vp8ModeScore rd, Vp8EncoderProbabilities proba, Vp8Residual res) + { + int r = 0; + + // re-import the non-zero context. + this.NzToBytes(); + + // DC + Span topNz = this.TopNz; + Span leftNz = this.LeftNz; + res.Init(0, 1, proba); + r += res.GetResidualCost(topNz[8] + leftNz[8], ref MemoryMarshal.GetArrayDataReference(rd.YDcLevels)); + + // AC. The level array holds 16 blocks of 16 levels in raster order. + res.Init(1, 0, proba); + ref short levels = ref MemoryMarshal.GetArrayDataReference(rd.YAcLevels); + for (int y = 0; y < 4; y++) + { + for (int x = 0; x < 4; x++) + { + int ctx = topNz[x] + leftNz[y]; + r += res.GetResidualCost(ctx, ref Unsafe.Add(ref levels, (uint)((x + (y * 4)) * 16))); + topNz[x] = leftNz[y] = res.Last >= 0 ? 1 : 0; + } + } + + return r; + } + + /// + /// Gets the fixed mode costs of the current 4x4 block. The costs depend on the modes of the top and left blocks. Inside the macroblock, + /// these come from . At the macroblock edge, they come from . + /// + /// The modes that the current macroblock selected for the previous 4x4 blocks. + /// The cost of each 4x4 mode in 1/256 bit units. + public short[] GetCostModeI4(byte[] modes) + { + int predsWidth = this.predsWidth; + int predIdx = this.PredIdx; + int x = this.I4 & 3; + int y = this.I4 >> 2; + Span preds = this.Preds; + int left = x == 0 ? preds[predIdx + (y * predsWidth) - 1] : modes[this.I4 - 1]; + int top = y == 0 ? preds[predIdx - predsWidth + x] : modes[this.I4 - 4]; + return WebpLookupTables.Vp8FixedCostsI4[top, left]; + } + + /// + /// Calculates the bit cost of the chroma levels: the 4 U blocks and the 4 V blocks. The method loads the non-zero context first and + /// updates and with the result of each block. + /// + /// The score with the quantized chroma levels. + /// The probabilities with the level costs. + /// The residual to reuse. + /// The cost in 1/256 bit units. + public int GetCostUv(Vp8ModeScore rd, Vp8EncoderProbabilities proba, Vp8Residual res) + { + int r = 0; + + // re-import the non-zero context. + this.NzToBytes(); + + // The level array holds the 4 U blocks, then the 4 V blocks, each in raster order. + Span topNz = this.TopNz; + Span leftNz = this.LeftNz; + res.Init(0, 2, proba); + ref short levels = ref MemoryMarshal.GetArrayDataReference(rd.UvLevels); + for (int ch = 0; ch <= 2; ch += 2) + { + for (int y = 0; y < 2; y++) + { + for (int x = 0; x < 2; x++) + { + int ctx = topNz[4 + ch + x] + leftNz[4 + ch + y]; + r += res.GetResidualCost(ctx, ref Unsafe.Add(ref levels, (uint)(((ch * 2) + x + (y * 2)) * 16))); + topNz[4 + ch + x] = leftNz[4 + ch + y] = res.Last >= 0 ? 1 : 0; + } + } + } + + return r; + } + + /// + /// Sets the chroma mode on the current macroblock. + /// + /// The chroma mode. + public void SetIntraUvMode(int mode) => this.CurrentMacroBlockInfo.UvMode = mode; + + /// + /// Sets the skip flag on the current macroblock. + /// + /// if the macroblock has no non-zero coefficient. + public void SetSkip(bool skip) => this.CurrentMacroBlockInfo.Skip = skip; + + /// + /// Sets the segment on the current macroblock. + /// + /// The segment, from 0 to 3. + public void SetSegment(int segment) => this.CurrentMacroBlockInfo.Segment = segment; + + /// + /// Stores the chroma DC diffusion errors of the current macroblock for the next macroblocks. The right neighbor gets the first error and + /// 3/4 of the third error. The macroblock below gets the second error and the rest of the third error. + /// + /// The score with the diffusion errors of the U and V channels. + public void StoreDiffusionErrors(Vp8ModeScore rd) + { + Span topDerr = this.TopDerr; + Span leftDerr = this.LeftDerr; + for (int ch = 0; ch <= 1; ++ch) + { + // Each macroblock column keeps 2 top errors for each channel, and the left errors keep 2 for each channel. + Span top = topDerr.Slice((this.X * 4) + (ch * 2), 2); + Span left = leftDerr.Slice(ch * 2, 2); + + // restore err1 + left[0] = (sbyte)rd.Derr[ch, 0]; + + // 3/4th of err3 + left[1] = (sbyte)((3 * rd.Derr[ch, 2]) >> 2); + + // err2 + top[0] = (sbyte)rd.Derr[ch, 1]; + + // 1/4th of err3. + top[1] = (sbyte)(rd.Derr[ch, 2] - left[1]); + } + } + + /// + /// Returns true if iteration is finished. + /// + /// True if iterator is finished. + public bool IsDone() => this.CountDown <= 0; + + /// + /// Go to next macroblock. + /// + /// Returns false if not finished. + public bool Next() + { + if (++this.X == this.mbw) + { + this.SetRow(++this.Y); + } + else + { + this.currentMbIdx++; + this.nzIdx++; + this.PredIdx += 4; + this.yTopIdx += 16; + this.uvTopIdx += 16; + } + + return --this.CountDown > 0; + } + + /// + /// Stores the reconstructed right column and bottom row of the current macroblock from . The next macroblock uses + /// the right column as its left samples, and the macroblock below uses the bottom row as its top samples. + /// + public void SaveBoundary() + { + int x = this.X; + int y = this.Y; + Span yuvOut = this.YuvOut; + Span ySrc = yuvOut[YOffEnc..]; + Span uvSrc = yuvOut[UOffEnc..]; + Span yTop = this.YTop; + Span uvTop = this.UvTop; + if (x < this.mbw - 1) + { + // left + Span yLeft = this.YLeft; + Span uvLeft = this.UvLeft; + for (int i = 0; i < 16; i++) + { + yLeft[i + 1] = ySrc[15 + (i * WebpConstants.Bps)]; + } + + for (int i = 0; i < 8; i++) + { + uvLeft[i + 1] = uvSrc[7 + (i * WebpConstants.Bps)]; + uvLeft[i + 16 + 1] = uvSrc[15 + (i * WebpConstants.Bps)]; + } + + // top-left (before 'top'!) + yLeft[0] = yTop[this.yTopIdx + 15]; + uvLeft[0] = uvTop[this.uvTopIdx + 0 + 7]; + uvLeft[16] = uvTop[this.uvTopIdx + 8 + 7]; + } + + if (y < this.mbh - 1) + { + // top + ySrc.Slice(15 * WebpConstants.Bps, 16).CopyTo(yTop[this.yTopIdx..]); + uvSrc.Slice(7 * WebpConstants.Bps, 8 + 8).CopyTo(uvTop[this.uvTopIdx..]); + } + } + + /// + /// Moves to the next 4x4 block. The method stores the bottom row and the right column of the finished block in , + /// so that they become the top and left samples of the next blocks. + /// + /// The luma samples of the macroblock that hold the finished block. + /// if a next block exists; after the last block. + public bool RotateI4(Span yuvOut) + { + Span blk = yuvOut[WebpLookupTables.Vp8Scan[this.I4]..]; + Span top = this.I4Boundary; + int topOffset = this.I4BoundaryIdx; + int i; + + // Update the cache with 7 fresh samples. + for (i = 0; i <= 3; i++) + { + top[topOffset - 4 + i] = blk[i + (3 * WebpConstants.Bps)]; // Store future top samples. + } + + if ((this.I4 & 3) != 3) + { + // if not on the right sub-blocks #3, #7, #11, #15 + for (i = 0; i <= 2; i++) + { + // store future left samples + top[topOffset + i] = blk[3 + ((2 - i) * WebpConstants.Bps)]; + } + } + else + { + // else replicate top-right samples, as says the specs. + for (i = 0; i <= 3; i++) + { + top[topOffset + i] = top[topOffset + i + 4]; + } + } + + // move pointers to next sub-block + ++this.I4; + if (this.I4 == 16) + { + // we're done + return false; + } + + this.I4BoundaryIdx = TopLeftI4[this.I4]; + + return true; + } + + /// + /// Clears the non-zero pattern of a skipped macroblock. For a 4x4 prediction, the method keeps the Y2 bit. Such a macroblock has no Y2 block, + /// so the Y2 context of the macroblock above passes through. + /// + public void ResetAfterSkip() + { + if (this.CurrentMacroBlockInfo.MacroBlockType == Vp8MacroBlockType.I16X16) + { + // Reset all predictors. + this.Nz[this.nzIdx] = 0; + this.LeftNz[8] = 0; + } + else + { + // Preserve the dc_nz bit. + this.Nz[this.nzIdx] &= 1 << 24; + } + } + + /// + /// Writes the 16x16 luma predictions of the current macroblock to . At the image border, the left or top samples do not exist. + /// + public void MakeLuma16Preds() + { + Span left = this.X != 0 ? this.YLeft : null; + Span top = this.Y != 0 ? this.YTop[this.yTopIdx..] : null; + Vp8Encoding.EncPredLuma16(this.YuvP, left, top); + } + + /// + /// Writes the chroma predictions of the current macroblock to . At the image border, the left or top samples do not exist. + /// + public void MakeChroma8Preds() + { + Span left = this.X != 0 ? this.UvLeft : null; + Span top = this.Y != 0 ? this.UvTop[this.uvTopIdx..] : null; + Vp8Encoding.EncPredChroma8(this.YuvP, left, top); + } + + /// + /// Writes the 4x4 luma predictions of the current 4x4 block to from the samples in . + /// + public void MakeIntra4Preds() => Vp8Encoding.EncPredLuma4(this.YuvP, this.I4Boundary, this.I4BoundaryIdx, this.Scratch[..4]); + + /// + /// Exchanges and , so that the best reconstruction so far stays in . + /// + /// + /// The method exchanges the two memory regions, not the samples, so no data is copied. + /// + public void SwapOut() + { + // Tuple swap uses 2 more IL bytes +#pragma warning disable IDE0180 // Use tuple to swap values + Memory tmp = this.yuvOut; + this.yuvOut = this.yuvOut2; + this.yuvOut2 = tmp; +#pragma warning restore IDE0180 // Use tuple to swap values + } + + /// + /// Unpacks the non-zero context of the current macroblock into and . The top flags come from the + /// pattern of the macroblock above, and the left flags from the pattern of the macroblock to the left. The left Y2 flag stays unchanged. + /// + public void NzToBytes() + { + Span nz = this.Nz; + + uint lnz = nz[this.nzIdx - 1]; + uint tnz = nz[this.nzIdx]; + Span topNz = this.TopNz; + Span leftNz = this.LeftNz; + + // Top-Y + topNz[0] = Bit(tnz, 12); + topNz[1] = Bit(tnz, 13); + topNz[2] = Bit(tnz, 14); + topNz[3] = Bit(tnz, 15); + + // Top-U + topNz[4] = Bit(tnz, 18); + topNz[5] = Bit(tnz, 19); + + // Top-V + topNz[6] = Bit(tnz, 22); + topNz[7] = Bit(tnz, 23); + + // DC + topNz[8] = Bit(tnz, 24); + + // left-Y + leftNz[0] = Bit(lnz, 3); + leftNz[1] = Bit(lnz, 7); + leftNz[2] = Bit(lnz, 11); + leftNz[3] = Bit(lnz, 15); + + // left-U + leftNz[4] = Bit(lnz, 17); + leftNz[5] = Bit(lnz, 19); + + // left-V + leftNz[6] = Bit(lnz, 21); + leftNz[7] = Bit(lnz, 23); + + // left-DC is special, iterated separately. + } + + /// + /// Packs and into the non-zero pattern of the current macroblock, for the macroblocks below and to the right. + /// + public void BytesToNz() + { + uint nz = 0; + Span topNz = this.TopNz; + Span leftNz = this.LeftNz; + + // top + nz |= (uint)((topNz[0] << 12) | (topNz[1] << 13)); + nz |= (uint)((topNz[2] << 14) | (topNz[3] << 15)); + nz |= (uint)((topNz[4] << 18) | (topNz[5] << 19)); + nz |= (uint)((topNz[6] << 22) | (topNz[7] << 23)); + nz |= (uint)(topNz[8] << 24); // we propagate the top bit, esp. for intra4 + + // left + nz |= (uint)((leftNz[0] << 3) | (leftNz[1] << 7)); + nz |= (uint)(leftNz[2] << 11); + nz |= (uint)((leftNz[4] << 17) | (leftNz[6] << 21)); + + this.Nz[this.nzIdx] = nz; + } + + /// + /// Copies a block of x source samples to a square block of samples. + /// The method fills the rest of each row with the last sample of the row, and the rows below with the last row. + /// + /// The source samples. + /// The source row stride. + /// The destination block. The row stride is . + /// The number of source columns, from 1 to . + /// The number of source rows, from 1 to . + /// The block size: 16 for luma or 8 for chroma. + private static void ImportBlock(Span src, int srcStride, Span dst, int w, int h, int size) + { + if (w == size && h == size) + { + // A full block needs no edge replication. One range check for each buffer covers the whole block, then each row + // is copied with one load and one store: 16 luma samples as one 128-bit vector, 8 chroma samples as one 64-bit word. + ref byte srcRef = ref MemoryMarshal.GetReference(src[..(((size - 1) * srcStride) + size)]); + ref byte dstRef = ref MemoryMarshal.GetReference(dst[..(((size - 1) * WebpConstants.Bps) + size)]); + nuint srcOffset = 0; + nuint stride = (nuint)srcStride; + if (size == 16) + { + if (Vector128.IsHardwareAccelerated) + { + for (nuint dstOffset = 0; dstOffset < 16 * WebpConstants.Bps; dstOffset += WebpConstants.Bps) + { + Vector128.LoadUnsafe(ref srcRef, srcOffset).StoreUnsafe(ref dstRef, dstOffset); + srcOffset += stride; + } + } + else + { + // Without 128-bit vectors, two 64-bit words copy the same 16 samples of each row. + for (nuint dstOffset = 0; dstOffset < 16 * WebpConstants.Bps; dstOffset += WebpConstants.Bps) + { + ref byte srcRow = ref Unsafe.Add(ref srcRef, srcOffset); + ref byte dstRow = ref Unsafe.Add(ref dstRef, dstOffset); + Unsafe.WriteUnaligned(ref dstRow, Unsafe.ReadUnaligned(ref srcRow)); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dstRow, 8U), Unsafe.ReadUnaligned(ref Unsafe.Add(ref srcRow, 8U))); + srcOffset += stride; + } + } + } + else + { + for (nuint dstOffset = 0; dstOffset < 8 * WebpConstants.Bps; dstOffset += WebpConstants.Bps) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dstRef, dstOffset), Unsafe.ReadUnaligned(ref Unsafe.Add(ref srcRef, srcOffset))); + srcOffset += stride; + } + } + + return; + } + + int dstIdx = 0; + int srcIdx = 0; + for (int i = 0; i < h; i++) + { + // memcpy(dst, src, w); + src.Slice(srcIdx, w).CopyTo(dst[dstIdx..]); + if (w < size) + { + // memset(dst + w, dst[w - 1], size - w); + dst.Slice(dstIdx + w, size - w).Fill(dst[dstIdx + w - 1]); + } + + dstIdx += WebpConstants.Bps; + srcIdx += srcStride; + } + + for (int i = h; i < size; i++) + { + // memcpy(dst, dst - BPS, size); + dst.Slice(dstIdx - WebpConstants.Bps, size).CopyTo(dst[dstIdx..]); + dstIdx += WebpConstants.Bps; + } + } + + /// + /// Copies samples with a step of , and fills the destination to + /// samples with the last copied sample. + /// + /// The source samples. + /// The step between two source samples: 1 for a row, or the row stride for a column. + /// The destination samples. + /// The number of samples to copy. + /// The number of destination samples. + private static void ImportLine(ReadOnlySpan src, int srcStride, Span dst, int len, int totalLen) + { + int i; + int srcIdx = 0; + for (i = 0; i < len; i++) + { + dst[i] = src[srcIdx]; + srcIdx += srcStride; + } + + for (; i < totalLen; i++) + { + dst[i] = dst[len - 1]; + } + } + + /// + /// Moves the iterator to the first macroblock and resets the top context, the non-zero patterns and the bit counts. + /// + public void Init() + { + this.SetRow(0); + this.SetCountDown(this.mbw * this.mbh); + this.InitTop(); + + this.BitCount.Clear(); + } + + /// + /// Reset iterator position to row 'y'. + /// + /// The y position. + private void SetRow(int y) + { + this.X = 0; + this.Y = y; + this.currentMbIdx = y * this.mbw; + this.nzIdx = 1; // note: in reference source nz starts at -1. + this.yTopIdx = 0; + this.uvTopIdx = 0; + this.PredIdx = this.predsWidth + (y * 4 * this.predsWidth); + + this.InitLeft(); + } + + /// + /// Sets the left boundary for the first macroblock of a row. The left samples get 129. The top-left sample gets 127 in the first row + /// and 129 in the other rows. The method also clears the left Y2 flag and the left diffusion errors. + /// + private void InitLeft() + { + Span yLeft = this.YLeft; + Span uLeft = this.UvLeft[..16]; + Span vLeft = this.UvLeft.Slice(16, 16); + byte val = (byte)(this.Y > 0 ? 129 : 127); + yLeft[0] = val; + uLeft[0] = val; + vLeft[0] = val; + + yLeft.Slice(1, 16).Fill(129); + uLeft.Slice(1, 8).Fill(129); + vLeft.Slice(1, 8).Fill(129); + + this.LeftNz[8] = 0; + + this.LeftDerr.Clear(); + } + + /// + /// Sets the top boundary for the first macroblock row. The top samples get 127. The method also clears the non-zero patterns, + /// a part of the prediction mode buffer after the mode plane, and the top diffusion errors. + /// + private void InitTop() + { + // The encoder buffers have the capacity of the largest frame. The current frame uses mbw columns of them. + int topSize = this.mbw * 16; + this.YTop[..topSize].Fill(127); + this.UvTop[..(topSize * 2)].Fill(127); + this.Nz[..(this.mbw + 1)].Clear(); + + int predsW = (4 * this.mbw) + 1; + int predsH = (4 * this.mbh) + 1; + int predsSize = predsW * predsH; + this.Preds.Slice(predsSize + this.predsWidth, this.mbw).Clear(); + + this.TopDerr.Clear(); + } + + /// + /// Gets one bit of a non-zero pattern. + /// + /// The non-zero pattern. + /// The bit position. + /// The bit, 0 or 1. + private static int Bit(uint nz, int n) => (nz & (1 << n)) != 0 ? 1 : 0; + + /// + /// Sets the number of macroblocks that remain to be encoded. + /// + /// The number of macroblocks to go. + private void SetCountDown(int countDown) => this.CountDown = countDown; +} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderProbabilities.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderProbabilities.cs new file mode 100644 index 0000000000..9979ff8262 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderProbabilities.cs @@ -0,0 +1,330 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossy; + +/// +/// Holds the frame-persistent coefficient probabilities, the token statistics and the level cost tables of the encoder. +/// +/// +/// Each table is one contiguous array in [type][band][context][...] order, so that one integer offset selects one entry. +/// The probability index of (type, band, context) is also the token id that the token buffer records. +/// +internal class Vp8EncoderProbabilities +{ + /// + /// The number of probabilities for one coefficient type: bands * contexts * probabilities. + /// + public const int ProbasPerType = WebpConstants.NumBands * WebpConstants.NumCtx * WebpConstants.NumProbas; + + /// + /// The number of level costs for one (type, band, context) entry. The levels go from 0 to . + /// + public const int CostsPerContext = MaxVariableLevel + 1; + + /// + /// The number of level costs for one coefficient type: bands * contexts * levels. + /// + public const int CostsPerType = WebpConstants.NumBands * WebpConstants.NumCtx * CostsPerContext; + + /// + /// The number of probabilities for all coefficient types. + /// + private const int ProbaCount = WebpConstants.NumTypes * ProbasPerType; + + /// + /// Last (inclusive) level with variable cost. + /// + private const int MaxVariableLevel = WebpConstants.MaxVariableLevel; + + /// + /// Value below which using skipProba is OK. + /// + private const int SkipProbaThreshold = 250; + + /// + /// Initializes a new instance of the class with the state that sets. + /// + public Vp8EncoderProbabilities() + { + this.Segments = new byte[3]; + this.Coeffs = new byte[ProbaCount]; + this.Stats = new uint[ProbaCount]; + this.LevelCost = new ushort[WebpConstants.NumTypes * CostsPerType]; + this.Reset(); + } + + /// + /// Gets the offsets of the level cost tables inside one coefficient type, for each coefficient position and context. + /// + /// + /// The entry at (position * contexts) + context is ((band of position * contexts) + context) * . + /// The band of a position is constant, so the map is constant. It lets the cost loop go from one position to the next + /// with one load and no band lookup. The bands of the positions 0 to 15 are 0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7. + /// + public static ReadOnlySpan RemappedCostOffsets => + [ + 0, 68, 136, + 204, 272, 340, + 408, 476, 544, + 612, 680, 748, + 1224, 1292, 1360, + 816, 884, 952, + 1020, 1088, 1156, + 1224, 1292, 1360, + 1224, 1292, 1360, + 1224, 1292, 1360, + 1224, 1292, 1360, + 1224, 1292, 1360, + 1224, 1292, 1360, + 1224, 1292, 1360, + 1224, 1292, 1360, + 1428, 1496, 1564 + ]; + + /// + /// Gets the default coefficient probabilities as one flat span in [type][band][context][proba] order. + /// + public static ReadOnlySpan DefaultProbas + => MemoryMarshal.CreateReadOnlySpan(ref MemoryMarshal.GetArrayDataReference(WebpLookupTables.DefaultCoeffsProba), ProbaCount); + + /// + /// Gets the probabilities of the probability updates as one flat span in [type][band][context][proba] order. + /// + public static ReadOnlySpan UpdateProbas + => MemoryMarshal.CreateReadOnlySpan(ref MemoryMarshal.GetArrayDataReference(WebpLookupTables.CoeffsUpdateProba), ProbaCount); + + /// + /// Gets the probabilities for segment tree. + /// + public byte[] Segments { get; } + + /// + /// Gets or sets the final probability of being skipped. + /// + public byte SkipProba { get; set; } + + /// + /// Gets or sets a value indicating whether to use the skip probability. + /// + public bool UseSkipProba { get; set; } + + /// + /// Gets the coefficient probabilities in [type][band][context][proba] order. + /// + public byte[] Coeffs { get; } + + /// + /// Gets the token statistics in [type][band][context][proba] order. + /// The lower 16 bits of an entry count the 1 bits. The upper 16 bits count all bits. + /// + public uint[] Stats { get; } + + /// + /// Gets the level costs in [type][band][context][level] order. + /// + public ushort[] LevelCost { get; } + + /// + /// Gets or sets the number of skipped blocks. + /// + public int NbSkip { get; set; } + + /// + /// Gets or sets a value indicating whether CalculateLevelCosts() needs to be called. + /// + public bool Dirty { get; set; } + + /// + /// Gets the index of the first probability of (band, context) inside one coefficient type. + /// + /// The band. + /// The context. + /// The index. + [MethodImpl(InliningOptions.ShortMethod)] + public static int ProbaIndex(int band, int ctx) => ((band * WebpConstants.NumCtx) + ctx) * WebpConstants.NumProbas; + + /// + /// Calculates the level cost tables from the current probabilities, if the probabilities changed. + /// + public void CalculateLevelCosts() + { + if (!this.Dirty) + { + return; // Nothing to do. + } + + ReadOnlySpan coeffs = this.Coeffs; + Span levelCost = this.LevelCost; + int entry = 0; + for (int ctype = 0; ctype < WebpConstants.NumTypes; ++ctype) + { + for (int band = 0; band < WebpConstants.NumBands; ++band) + { + for (int ctx = 0; ctx < WebpConstants.NumCtx; ++ctx, ++entry) + { + ReadOnlySpan p = coeffs.Slice(entry * WebpConstants.NumProbas, WebpConstants.NumProbas); + Span table = levelCost.Slice(entry * CostsPerContext, CostsPerContext); + int cost0 = ctx > 0 ? LossyUtils.Vp8BitCost(1, p[0]) : 0; + int costBase = LossyUtils.Vp8BitCost(1, p[1]) + cost0; + table[0] = (ushort)(LossyUtils.Vp8BitCost(0, p[1]) + cost0); + for (int v = 1; v <= MaxVariableLevel; ++v) + { + table[v] = (ushort)(costBase + VariableLevelCost(v, p)); + } + + // Starting at level 67 and up, the variable part of the cost is actually constant. + } + } + } + + // The band of each coefficient position is constant, so the position-to-table map (RemappedCostOffsets) needs no update. + this.Dirty = false; + } + + /// + /// Selects for each probability the default value or the value from the token statistics, whichever costs fewer bits. + /// + /// The bit cost (in 1/256 bit units) to signal the probability updates. + public int FinalizeTokenProbas() + { + bool hasChanged = false; + int size = 0; + ReadOnlySpan statsSpan = this.Stats; + ReadOnlySpan defaults = DefaultProbas; + ReadOnlySpan updates = UpdateProbas; + Span coeffs = this.Coeffs; + for (int i = 0; i < coeffs.Length; i++) + { + uint stats = statsSpan[i]; + int nb = (int)((stats >> 0) & 0xffff); + int total = (int)((stats >> 16) & 0xffff); + byte updateProba = updates[i]; + int oldP = defaults[i]; + int newP = CalcTokenProba(nb, total); + int oldCost = BranchCost(nb, total, oldP) + LossyUtils.Vp8BitCost(0, updateProba); + int newCost = BranchCost(nb, total, newP) + LossyUtils.Vp8BitCost(1, updateProba) + (8 * 256); + bool useNewP = oldCost > newCost; + size += LossyUtils.Vp8BitCost(useNewP ? 1 : 0, updateProba); + if (useNewP) + { + // Only use proba that seem meaningful enough. + coeffs[i] = (byte)newP; + hasChanged |= newP != oldP; + size += 8 * 256; + } + else + { + coeffs[i] = (byte)oldP; + } + } + + this.Dirty = hasChanged; + return size; + } + + /// + /// Calculates the skip probability from the number of skipped macroblocks. + /// + /// The number of macroblocks in a row. + /// The number of macroblock rows. + /// The bit cost (in 1/256 bit units) to signal the skip flags. + public int FinalizeSkipProba(int mbw, int mbh) + { + int nbMbs = mbw * mbh; + int nbEvents = this.NbSkip; + this.SkipProba = (byte)CalcSkipProba(nbEvents, nbMbs); + this.UseSkipProba = this.SkipProba < SkipProbaThreshold; + + int size = 256; + if (this.UseSkipProba) + { + size += (nbEvents * LossyUtils.Vp8BitCost(1, this.SkipProba)) + ((nbMbs - nbEvents) * LossyUtils.Vp8BitCost(0, this.SkipProba)); + size += 8 * 256; // cost of signaling the skipProba itself. + } + + return size; + } + + /// + /// Sets all token statistics to zero. + /// + public void ResetTokenStats() => Array.Clear(this.Stats); + + /// + /// Sets the state for the start of a frame: the default coefficient and segment probabilities, no skip probability, + /// no skipped blocks and zero token statistics. + /// + /// + /// The encoder keeps one instance for all frames of an animation, and each frame starts from this state. + /// The method sets , so writes every level cost again + /// before the first read. The level costs therefore need no clear. + /// + public void Reset() + { + this.Dirty = true; + this.UseSkipProba = false; + this.SkipProba = 0; + this.NbSkip = 0; + this.Segments.AsSpan().Fill(255); + + // The default table has the same [type][band][context][proba] order. + DefaultProbas.CopyTo(this.Coeffs); + this.ResetTokenStats(); + } + + /// + /// Calculates the probability that a macroblock is not skipped, in units of 1/256. + /// + /// The number of skipped macroblocks. + /// The number of macroblocks. + /// The probability, from 0 to 255. With no macroblocks, 255. + private static int CalcSkipProba(long nb, long total) => (int)(total != 0 ? (total - nb) * 255 / total : 255); + + /// + /// Calculates the cost of the tree bits that code a level after the non-zero branch. The level code table gives the bits and which + /// tree probabilities from index 2 they use. + /// + /// The level, from 1 to the maximum variable level. + /// The probabilities of one band and context. + /// The cost in 1/256 bit units. + private static int VariableLevelCost(int level, ReadOnlySpan probas) + { + int pattern = WebpLookupTables.Vp8LevelCodes[level - 1][0]; + int bits = WebpLookupTables.Vp8LevelCodes[level - 1][1]; + int cost = 0; + for (int i = 2; pattern != 0; i++) + { + if ((pattern & 1) != 0) + { + cost += LossyUtils.Vp8BitCost(bits & 1, probas[i]); + } + + bits >>= 1; + pattern >>= 1; + } + + return cost; + } + + /// + /// Calculates the probability that a token bit is 0, in units of 1/256. + /// + /// The number of 1 bits. + /// The number of bits. + /// The probability, from 0 to 255. With no 1 bits, 255. + private static int CalcTokenProba(int nb, int total) => nb != 0 ? (255 - (nb * 255 / total)) : 255; + + /// + /// Calculates the cost of coding 1 bits and - 0 bits with one probability. + /// + /// The number of 1 bits. + /// The number of bits. + /// The probability that a bit is 0, in units of 1/256. + /// The cost in 1/256 bit units. + private static int BranchCost(int nb, int total, int proba) + => (nb * LossyUtils.Vp8BitCost(1, (byte)proba)) + ((total - nb) * LossyUtils.Vp8BitCost(0, (byte)proba)); +} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncSegmentHeader.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderSegmentHeader.cs similarity index 72% rename from src/ImageSharp/Formats/Webp/Lossy/Vp8EncSegmentHeader.cs rename to src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderSegmentHeader.cs index 07bfe25b7d..71d21b0a83 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncSegmentHeader.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderSegmentHeader.cs @@ -3,13 +3,16 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy; -internal class Vp8EncSegmentHeader +/// +/// Holds the segment header values that the lossy encoder writes and the estimated cost of the segment map. +/// +internal class Vp8EncoderSegmentHeader { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// Number of segments. - public Vp8EncSegmentHeader(int numSegments) + public Vp8EncoderSegmentHeader(int numSegments) { this.NumSegments = numSegments; this.UpdateMap = this.NumSegments > 1; diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.Operators.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.Operators.cs new file mode 100644 index 0000000000..3b78569d84 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.Operators.cs @@ -0,0 +1,136 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossy; + +/// +/// Contains the row operators that the 16x16 luma and 8x8 chroma intra predictors read and write a block with, +/// and the source row operators that the forward transform of two 4x4 blocks reads the source samples with. +/// +internal static partial class Vp8Encoding +{ + /// + /// Loads one source row of two 4x4 blocks for . + /// + /// + /// The two blocks are transformed against two predictions that are side by side: the second prediction starts + /// 4 samples after the first. The source of the second block starts samples after + /// the source of the first block. + /// + public interface ISourceRowOperator + { + /// + /// Gets the offset of the source of the second block from the source of the first block. + /// + static abstract nuint SecondBlockOffset { get; } + + /// + /// Loads one source row: byte lanes 0 to 3 hold the row of the first block, byte lanes 4 to 7 hold the row of + /// the second block. The other lanes are not used. + /// + /// The first source sample of the row of the first block. + /// The row samples. + static abstract Vector128 Load(ref byte row); + } + + /// + /// Loads and stores one row of a prediction block in the low byte lanes of a vector. + /// + /// + /// A prediction block has rows of samples, with a row stride of + /// . Each form reads or writes exactly the samples of one row. Thus a store does not + /// change the block to the right, for example the V block next to the U block. + /// + private interface IPredictionRowOperator + { + /// + /// Gets the sample count of one row, which is also the row count of the block. + /// + static abstract int Size { get; } + + /// + /// Loads the samples of one row to the low lanes. The other lanes are zero. + /// + /// The first sample of the row. + /// The row samples. + static abstract Vector128 Load(ref byte row); + + /// + /// Stores the low lanes as the samples of one row. No other sample changes. + /// + /// The first sample of the row. + /// The row samples. + static abstract void Store(ref byte row, Vector128 value); + } + + /// + /// Loads and stores rows of 8 samples: the low 64 bits of the vector. Chroma blocks use this form. + /// + private readonly struct Row8Operator : IPredictionRowOperator + { + /// + public static int Size => 8; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 Load(ref byte row) + => Vector128.CreateScalar(Unsafe.ReadUnaligned(ref row)).AsByte(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Store(ref byte row, Vector128 value) + => Unsafe.WriteUnaligned(ref row, value.AsUInt64().ToScalar()); + } + + /// + /// Loads and stores rows of 16 samples: the full vector. Luma blocks use this form. + /// + private readonly struct Row16Operator : IPredictionRowOperator + { + /// + public static int Size => 16; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 Load(ref byte row) + => Vector128.LoadUnsafe(ref row); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Store(ref byte row, Vector128 value) + => value.StoreUnsafe(ref row); + } + + /// + /// Reads the source of two adjacent 4x4 blocks: one row is 8 adjacent samples. + /// The 16x16 luma and 8x8 chroma reconstructions transform the blocks of a macroblock in pairs with this form. + /// + public readonly struct AdjacentSourceOperator : ISourceRowOperator + { + /// + public static nuint SecondBlockOffset => 4; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 Load(ref byte row) + => Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref row)).AsByte(); + } + + /// + /// Reads the source of one 4x4 block two times: one row is the 4 samples of the block, repeated. + /// The 4x4 luma mode search transforms one source block against two predictions with this form. + /// + public readonly struct RepeatedSourceOperator : ISourceRowOperator + { + /// + public static nuint SecondBlockOffset => 0; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 Load(ref byte row) + => Vector128.Create(Unsafe.ReadUnaligned(ref row)).AsByte(); + } +} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.cs index 696b103aa2..42d339a37a 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.cs @@ -13,57 +13,134 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy; /// /// Methods for encoding a VP8 frame. /// -internal static unsafe class Vp8Encoding +internal static partial class Vp8Encoding { + /// + /// The inverse transform multiplier sqrt(2) * cos(pi / 8) in 16.16 fixed point. + /// private const int KC1 = 20091 + (1 << 16); + /// + /// The inverse transform multiplier sqrt(2) * sin(pi / 8) in 16.16 fixed point. + /// private const int KC2 = 35468; + /// + /// The clip table: entry 255 + v is v clamped to 0 to 255, for v from -255 to 510. + /// private static readonly byte[] Clip1 = GetClip1(); // clips [-255,510] to [0,255] + /// + /// The offset of the intra 16x16 DC prediction in the prediction buffer. + /// private const int I16DC16 = 0 * 16 * WebpConstants.Bps; + /// + /// The offset of the intra 16x16 true motion prediction in the prediction buffer. + /// private const int I16TM16 = I16DC16 + 16; + /// + /// The offset of the intra 16x16 vertical prediction in the prediction buffer. + /// private const int I16VE16 = 1 * 16 * WebpConstants.Bps; + /// + /// The offset of the intra 16x16 horizontal prediction in the prediction buffer. + /// private const int I16HE16 = I16VE16 + 16; + /// + /// The offset of the chroma DC prediction in the prediction buffer. The V prediction starts 8 samples after the U prediction. + /// private const int C8DC8 = 2 * 16 * WebpConstants.Bps; + /// + /// The offset of the chroma true motion prediction in the prediction buffer. + /// private const int C8TM8 = C8DC8 + (1 * 16); + /// + /// The offset of the chroma vertical prediction in the prediction buffer. + /// private const int C8VE8 = (2 * 16 * WebpConstants.Bps) + (8 * WebpConstants.Bps); + /// + /// The offset of the chroma horizontal prediction in the prediction buffer. + /// private const int C8HE8 = C8VE8 + (1 * 16); + /// + /// The offsets of the intra 16x16 predictions in the prediction buffer, indexed by the intra 16x16 mode. + /// public static readonly int[] Vp8I16ModeOffsets = [I16DC16, I16TM16, I16VE16, I16HE16]; + /// + /// The offsets of the chroma predictions in the prediction buffer, indexed by the chroma mode. + /// public static readonly int[] Vp8UvModeOffsets = [C8DC8, C8TM8, C8VE8, C8HE8]; + /// + /// The offset of the intra 4x4 DC prediction in the prediction buffer. + /// private const int I4DC4 = (3 * 16 * WebpConstants.Bps) + 0; + /// + /// The offset of the intra 4x4 true motion prediction in the prediction buffer. + /// private const int I4TM4 = I4DC4 + 4; + /// + /// The offset of the intra 4x4 vertical prediction in the prediction buffer. + /// private const int I4VE4 = I4DC4 + 8; + /// + /// The offset of the intra 4x4 horizontal prediction in the prediction buffer. + /// private const int I4HE4 = I4DC4 + 12; + /// + /// The offset of the intra 4x4 down-right prediction in the prediction buffer. + /// private const int I4RD4 = I4DC4 + 16; + /// + /// The offset of the intra 4x4 vertical-right prediction in the prediction buffer. + /// private const int I4VR4 = I4DC4 + 20; + /// + /// The offset of the intra 4x4 down-left prediction in the prediction buffer. + /// private const int I4LD4 = I4DC4 + 24; + /// + /// The offset of the intra 4x4 vertical-left prediction in the prediction buffer. + /// private const int I4VL4 = I4DC4 + 28; + /// + /// The offset of the intra 4x4 horizontal-down prediction in the prediction buffer. + /// private const int I4HD4 = (3 * 16 * WebpConstants.Bps) + (4 * WebpConstants.Bps); + /// + /// The offset of the intra 4x4 horizontal-up prediction in the prediction buffer. + /// private const int I4HU4 = I4HD4 + 4; + /// + /// The offsets of the intra 4x4 predictions in the prediction buffer, indexed by the intra 4x4 mode. + /// Modes 2k and 2k + 1 are side by side, so the prediction of mode 2k + 1 starts 4 samples after the prediction of mode 2k. + /// public static readonly int[] Vp8I4ModeOffsets = [I4DC4, I4TM4, I4VE4, I4HE4, I4RD4, I4VR4, I4LD4, I4VL4, I4HD4, I4HU4 ]; + /// + /// Creates the clip table . + /// + /// The 766 entries: entry 255 + v is v clamped to 0 to 255. private static byte[] GetClip1() { byte[] clip1 = new byte[255 + 510 + 1]; @@ -77,8 +154,18 @@ private static byte[] GetClip1() } // Transforms (Paragraph 14.4) - // Does two inverse transforms. - public static void ITransformTwo(Span reference, Span input, Span dst, Span scratch) + + /// + /// Adds the inverse transforms of two horizontally adjacent 4x4 blocks to their predictions. + /// + /// + /// The first prediction sample. Each row has the 4 samples of the left block, then the 4 samples of the right block. + /// The rows have a stride of . + /// + /// The first of the 32 coefficients: 16 of the left block, then 16 of the right block. + /// The first destination sample, with the same layout as . + /// The first of the 16 scratch integers of the scalar path. + public static void ITransformTwo(ref byte reference, ref short input, ref byte dst, ref int scratch) { if (Vector128.IsHardwareAccelerated) { @@ -99,414 +186,241 @@ public static void ITransformTwo(Span reference, Span input, Span> 16 = (x * (k + (1 << 16))) >> 16 = ((x * k ) >> 16) + x - // Load and concatenate the transform coefficients (we'll do two inverse - // transforms in parallel). In the case of only one inverse transform, the - // second half of the vectors will just contain random value we'll never - // use nor store. - ref short inputRef = ref MemoryMarshal.GetReference(input); - Vector128 in0 = Vector128.Create(Unsafe.As(ref inputRef), 0); - Vector128 in1 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref inputRef, 4)), 0); - Vector128 in2 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref inputRef, 8)), 0); - Vector128 in3 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref inputRef, 12)), 0); - - // a00 a10 a20 a30 x x x x - // a01 a11 a21 a31 x x x x - // a02 a12 a22 a32 x x x x - // a03 a13 a23 a33 x x x x - Vector128 inb0 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref inputRef, 16)), 0); - Vector128 inb1 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref inputRef, 20)), 0); - Vector128 inb2 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref inputRef, 24)), 0); - Vector128 inb3 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref inputRef, 28)), 0); - - in0 = Vector128_.UnpackLow(in0, inb0); - in1 = Vector128_.UnpackLow(in1, inb1); - in2 = Vector128_.UnpackLow(in2, inb2); - in3 = Vector128_.UnpackLow(in3, inb3); - - // a00 a10 a20 a30 b00 b10 b20 b30 - // a01 a11 a21 a31 b01 b11 b21 b31 - // a02 a12 a22 a32 b02 b12 b22 b32 - // a03 a13 a23 a33 b03 b13 b23 b33 - - // Vertical pass and subsequent transpose. - // First pass, c and d calculations are longer because of the "trick" multiplications. - InverseTransformVerticalPassVector128( - in0, - in2, - in1, - in3, - out Vector128 tmp0, - out Vector128 tmp1, - out Vector128 tmp2, - out Vector128 tmp3); - - // Transpose the two 4x4. - LossyUtils.Vp8Transpose_2_4x4_16bVector128( - tmp0, - tmp1, - tmp2, - tmp3, - out Vector128 t0, - out Vector128 t1, - out Vector128 t2, - out Vector128 t3); - - // Horizontal pass and subsequent transpose. - // First pass, c and d calculations are longer because of the "trick" multiplications. - InverseTransformHorizontalPassVector128( - t0, - t2, - t1, - t3, - out Vector128 shifted0, - out Vector128 shifted1, - out Vector128 shifted2, - out Vector128 shifted3); - - // Transpose the two 4x4. - LossyUtils.Vp8Transpose_2_4x4_16bVector128(shifted0, shifted1, shifted2, shifted3, out t0, out t1, out t2, out t3); - - // Add inverse transform to 'ref' and store. - // Load the reference(s). - ref byte referenceRef = ref MemoryMarshal.GetReference(reference); - - // Load eight bytes/pixels per line. - Vector128 ref0 = Vector128.Create(Unsafe.As(ref referenceRef), 0).AsByte(); - Vector128 ref1 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref referenceRef, WebpConstants.Bps)), 0).AsByte(); - Vector128 ref2 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref referenceRef, WebpConstants.Bps * 2)), 0).AsByte(); - Vector128 ref3 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref referenceRef, WebpConstants.Bps * 3)), 0).AsByte(); - - // Convert to 16b. - ref0 = Vector128_.UnpackLow(ref0, Vector128.Zero); - ref1 = Vector128_.UnpackLow(ref1, Vector128.Zero); - ref2 = Vector128_.UnpackLow(ref2, Vector128.Zero); - ref3 = Vector128_.UnpackLow(ref3, Vector128.Zero); - - // Add the inverse transform(s). - Vector128 ref0InvAdded = ref0.AsInt16() + t0.AsInt16(); - Vector128 ref1InvAdded = ref1.AsInt16() + t1.AsInt16(); - Vector128 ref2InvAdded = ref2.AsInt16() + t2.AsInt16(); - Vector128 ref3InvAdded = ref3.AsInt16() + t3.AsInt16(); - - // Unsigned saturate to 8b. - ref0 = Vector128_.PackUnsignedSaturate(ref0InvAdded, ref0InvAdded); - ref1 = Vector128_.PackUnsignedSaturate(ref1InvAdded, ref1InvAdded); - ref2 = Vector128_.PackUnsignedSaturate(ref2InvAdded, ref2InvAdded); - ref3 = Vector128_.PackUnsignedSaturate(ref3InvAdded, ref3InvAdded); - - // Store eight bytes/pixels per line. - ref byte outputRef = ref MemoryMarshal.GetReference(dst); - Unsafe.As>(ref outputRef) = ref0.GetLower(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, WebpConstants.Bps)) = ref1.GetLower(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, WebpConstants.Bps * 2)) = ref2.GetLower(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, WebpConstants.Bps * 3)) = ref3.GetLower(); + // Coefficient row r of the left block goes to lanes 0 to 3, and row r of the right block to lanes 4 to 7. Then residual row r holds the + // 8 residuals of sample row r, because the two blocks are side by side in the row. + LossyUtils.InverseTransform( + Vector128.Create(LossyUtils.ReadCoefficientRow(ref input, 0), LossyUtils.ReadCoefficientRow(ref input, 16)).AsInt16(), + Vector128.Create(LossyUtils.ReadCoefficientRow(ref input, 4), LossyUtils.ReadCoefficientRow(ref input, 20)).AsInt16(), + Vector128.Create(LossyUtils.ReadCoefficientRow(ref input, 8), LossyUtils.ReadCoefficientRow(ref input, 24)).AsInt16(), + Vector128.Create(LossyUtils.ReadCoefficientRow(ref input, 12), LossyUtils.ReadCoefficientRow(ref input, 28)).AsInt16(), + out Vector128 row0, + out Vector128 row1, + out Vector128 row2, + out Vector128 row3); + + // Each row of the predictions is 8 bytes: 4 of the left block, then 4 of the right block. + AddResiduals8(ref reference, ref dst, 0, row0); + AddResiduals8(ref reference, ref dst, WebpConstants.Bps, row1); + AddResiduals8(ref reference, ref dst, 2 * WebpConstants.Bps, row2); + AddResiduals8(ref reference, ref dst, 3 * WebpConstants.Bps, row3); } else { - ITransformOne(reference, input, dst, scratch); - ITransformOne(reference[4..], input[16..], dst[4..], scratch); + ITransformOne(ref reference, ref input, ref dst, ref scratch); + ITransformOne(ref Unsafe.Add(ref reference, (nuint)4), ref Unsafe.Add(ref input, (nuint)16), ref Unsafe.Add(ref dst, (nuint)4), ref scratch); } } - public static void ITransformOne(Span reference, Span input, Span dst, Span scratch) + /// + /// Adds the inverse transform of one 4x4 block to its prediction. + /// + /// The first prediction sample. The rows have a stride of . + /// The first of the 16 coefficients. + /// The first destination sample, with the same layout as . + /// The first of the 16 scratch integers of the scalar path. + public static void ITransformOne(ref byte reference, ref short input, ref byte dst, ref int scratch) { if (Vector128.IsHardwareAccelerated) { - // Load and concatenate the transform coefficients (we'll do two inverse - // transforms in parallel). In the case of only one inverse transform, the - // second half of the vectors will just contain random value we'll never - // use nor store. - ref short inputRef = ref MemoryMarshal.GetReference(input); - Vector128 in0 = Vector128.Create(Unsafe.As(ref inputRef), 0); - Vector128 in1 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref inputRef, 4)), 0); - Vector128 in2 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref inputRef, 8)), 0); - Vector128 in3 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref inputRef, 12)), 0); - - // a00 a10 a20 a30 x x x x - // a01 a11 a21 a31 x x x x - // a02 a12 a22 a32 x x x x - // a03 a13 a23 a33 x x x x - - // Vertical pass and subsequent transpose. - // First pass, c and d calculations are longer because of the "trick" multiplications. - InverseTransformVerticalPassVector128( - in0, - in2, - in1, - in3, - out Vector128 tmp0, - out Vector128 tmp1, - out Vector128 tmp2, - out Vector128 tmp3); - - // Transpose the two 4x4. - LossyUtils.Vp8Transpose_2_4x4_16bVector128( - tmp0, - tmp1, - tmp2, - tmp3, - out Vector128 t0, - out Vector128 t1, - out Vector128 t2, - out Vector128 t3); - - // Horizontal pass and subsequent transpose. - // First pass, c and d calculations are longer because of the "trick" multiplications. - InverseTransformHorizontalPassVector128( - t0, - t2, - t1, - t3, - out Vector128 shifted0, - out Vector128 shifted1, - out Vector128 shifted2, - out Vector128 shifted3); - - // Transpose the two 4x4. - LossyUtils.Vp8Transpose_2_4x4_16bVector128(shifted0, shifted1, shifted2, shifted3, out t0, out t1, out t2, out t3); - - // Add inverse transform to 'ref' and store. - // Load the reference(s). - ref byte referenceRef = ref MemoryMarshal.GetReference(reference); - - // Load four bytes/pixels per line. - Vector128 ref0 = Vector128.CreateScalar(Unsafe.ReadUnaligned(ref referenceRef)).AsByte(); - Vector128 ref1 = Vector128.CreateScalar(Unsafe.ReadUnaligned(ref Unsafe.Add(ref referenceRef, WebpConstants.Bps))).AsByte(); - Vector128 ref2 = Vector128.CreateScalar(Unsafe.ReadUnaligned(ref Unsafe.Add(ref referenceRef, WebpConstants.Bps * 2))).AsByte(); - Vector128 ref3 = Vector128.CreateScalar(Unsafe.ReadUnaligned(ref Unsafe.Add(ref referenceRef, WebpConstants.Bps * 3))).AsByte(); - - // Convert to 16b. - ref0 = Vector128_.UnpackLow(ref0, Vector128.Zero); - ref1 = Vector128_.UnpackLow(ref1, Vector128.Zero); - ref2 = Vector128_.UnpackLow(ref2, Vector128.Zero); - ref3 = Vector128_.UnpackLow(ref3, Vector128.Zero); - - // Add the inverse transform(s). - Vector128 ref0InvAdded = ref0.AsInt16() + t0.AsInt16(); - Vector128 ref1InvAdded = ref1.AsInt16() + t1.AsInt16(); - Vector128 ref2InvAdded = ref2.AsInt16() + t2.AsInt16(); - Vector128 ref3InvAdded = ref3.AsInt16() + t3.AsInt16(); - - // Unsigned saturate to 8b. - ref0 = Vector128_.PackUnsignedSaturate(ref0InvAdded, ref0InvAdded); - ref1 = Vector128_.PackUnsignedSaturate(ref1InvAdded, ref1InvAdded); - ref2 = Vector128_.PackUnsignedSaturate(ref2InvAdded, ref2InvAdded); - ref3 = Vector128_.PackUnsignedSaturate(ref3InvAdded, ref3InvAdded); - - // Unsigned saturate to 8b. - ref byte outputRef = ref MemoryMarshal.GetReference(dst); - - // Store four bytes/pixels per line. - int output0 = ref0.AsInt32().ToScalar(); - int output1 = ref1.AsInt32().ToScalar(); - int output2 = ref2.AsInt32().ToScalar(); - int output3 = ref3.AsInt32().ToScalar(); - - Unsafe.WriteUnaligned(ref outputRef, output0); - Unsafe.WriteUnaligned(ref Unsafe.Add(ref outputRef, WebpConstants.Bps), output1); - Unsafe.WriteUnaligned(ref Unsafe.Add(ref outputRef, WebpConstants.Bps * 2), output2); - Unsafe.WriteUnaligned(ref Unsafe.Add(ref outputRef, WebpConstants.Bps * 3), output3); + // Coefficient row r goes to lanes 0 to 3. Lanes 4 to 7 are not defined. The transform does not mix them into lanes 0 to 3, and the store + // below keeps only the 4 bytes of lanes 0 to 3. + LossyUtils.InverseTransform( + Vector128.CreateScalarUnsafe(LossyUtils.ReadCoefficientRow(ref input, 0)).AsInt16(), + Vector128.CreateScalarUnsafe(LossyUtils.ReadCoefficientRow(ref input, 4)).AsInt16(), + Vector128.CreateScalarUnsafe(LossyUtils.ReadCoefficientRow(ref input, 8)).AsInt16(), + Vector128.CreateScalarUnsafe(LossyUtils.ReadCoefficientRow(ref input, 12)).AsInt16(), + out Vector128 row0, + out Vector128 row1, + out Vector128 row2, + out Vector128 row3); + + AddResiduals4(ref reference, ref dst, 0, row0); + AddResiduals4(ref reference, ref dst, WebpConstants.Bps, row1); + AddResiduals4(ref reference, ref dst, 2 * WebpConstants.Bps, row2); + AddResiduals4(ref reference, ref dst, 3 * WebpConstants.Bps, row3); } else { - int i; - Span tmp = scratch[..16]; - for (i = 0; i < 4; i++) + // The vertical pass writes all 16 entries of tmp before the horizontal pass reads them. + ref int tmp = ref scratch; + for (nuint i = 0; i < 4; i++) { // vertical pass. - int a = input[0] + input[8]; - int b = input[0] - input[8]; - int c = Mul(input[4], KC2) - Mul(input[12], KC1); - int d = Mul(input[4], KC1) + Mul(input[12], KC2); - tmp[0] = a + d; - tmp[1] = b + c; - tmp[2] = b - c; - tmp[3] = a - d; - tmp = tmp[4..]; - input = input[1..]; + int i0 = Unsafe.Add(ref input, i); + int i4 = Unsafe.Add(ref input, i + 4); + int i8 = Unsafe.Add(ref input, i + 8); + int i12 = Unsafe.Add(ref input, i + 12); + int a = i0 + i8; + int b = i0 - i8; + int c = Mul(i4, KC2) - Mul(i12, KC1); + int d = Mul(i4, KC1) + Mul(i12, KC2); + Unsafe.Add(ref tmp, (i * 4) + 0) = a + d; + Unsafe.Add(ref tmp, (i * 4) + 1) = b + c; + Unsafe.Add(ref tmp, (i * 4) + 2) = b - c; + Unsafe.Add(ref tmp, (i * 4) + 3) = a - d; } - tmp = scratch; - for (i = 0; i < 4; i++) + for (nuint i = 0; i < 4; i++) { // horizontal pass. - int dc = tmp[0] + 4; - int a = dc + tmp[8]; - int b = dc - tmp[8]; - int c = Mul(tmp[4], KC2) - Mul(tmp[12], KC1); - int d = Mul(tmp[4], KC1) + Mul(tmp[12], KC2); - Store(dst, reference, 0, i, a + d); - Store(dst, reference, 1, i, b + c); - Store(dst, reference, 2, i, b - c); - Store(dst, reference, 3, i, a - d); - tmp = tmp[1..]; + int t4 = Unsafe.Add(ref tmp, i + 4); + int t12 = Unsafe.Add(ref tmp, i + 12); + int dc = Unsafe.Add(ref tmp, i) + 4; + int a = dc + Unsafe.Add(ref tmp, i + 8); + int b = dc - Unsafe.Add(ref tmp, i + 8); + int c = Mul(t4, KC2) - Mul(t12, KC1); + int d = Mul(t4, KC1) + Mul(t12, KC2); + nuint row = i * WebpConstants.Bps; + Store(ref dst, ref reference, row, a + d); + Store(ref dst, ref reference, row + 1, b + c); + Store(ref dst, ref reference, row + 2, b - c); + Store(ref dst, ref reference, row + 3, a - d); } } } - private static void InverseTransformVerticalPassVector128( - Vector128 in0, - Vector128 in2, - Vector128 in1, - Vector128 in3, - out Vector128 tmp0, - out Vector128 tmp1, - out Vector128 tmp2, - out Vector128 tmp3) + /// + /// Adds the 8 residuals of one row to the 8 prediction samples of the row, with the clamp to [0, 255], and stores the 8 results. + /// + /// + /// The widen gives the samples in 16-bit lanes. Each sum is a sample of 0 to 255 plus a residual of a 16-bit lane, so the unsigned saturating pack + /// gives the same clamp as the scalar path. The pack puts the 8 results in bytes 0 to 7. + /// + /// The first prediction sample of the block. + /// The first destination sample of the block. + /// The offset of the row from the first sample. + /// The residuals of the row in 16-bit lanes 0 to 7. + [MethodImpl(InliningOptions.ShortMethod)] + private static void AddResiduals8(ref byte reference, ref byte dst, nuint offset, Vector128 residuals) { - Vector128 a = in0.AsInt16() + in2.AsInt16(); - Vector128 b = in0.AsInt16() - in2.AsInt16(); - - Vector128 k1 = Vector128.Create((short)20091).AsInt16(); - Vector128 k2 = Vector128.Create((short)-30068).AsInt16(); - - // c = MUL(in1, K2) - MUL(in3, K1) = MUL(in1, k2) - MUL(in3, k1) + in1 - in3 - Vector128 c1 = Vector128_.MultiplyHigh(in1.AsInt16(), k2); - Vector128 c2 = Vector128_.MultiplyHigh(in3.AsInt16(), k1); - Vector128 c3 = in1.AsInt16() - in3.AsInt16(); - Vector128 c4 = c1 - c2; - Vector128 c = c3 + c4; - - // d = MUL(in1, K1) + MUL(in3, K2) = MUL(in1, k1) + MUL(in3, k2) + in1 + in3 - Vector128 d1 = Vector128_.MultiplyHigh(in1.AsInt16(), k1); - Vector128 d2 = Vector128_.MultiplyHigh(in3.AsInt16(), k2); - Vector128 d3 = in1.AsInt16() + in3.AsInt16(); - Vector128 d4 = d1 + d2; - Vector128 d = d3 + d4; - - // Second pass. - tmp0 = a + d; - tmp1 = b + c; - tmp2 = b - c; - tmp3 = a - d; + Vector128 prediction = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref Unsafe.Add(ref reference, offset))).AsByte(); + Vector128 sum = Vector128.WidenLower(prediction).AsInt16() + residuals; + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, offset), Vector128_.PackUnsignedSaturate(sum, sum).AsUInt64().ToScalar()); } - private static void InverseTransformHorizontalPassVector128( - Vector128 t0, - Vector128 t2, - Vector128 t1, - Vector128 t3, - out Vector128 shifted0, - out Vector128 shifted1, - out Vector128 shifted2, - out Vector128 shifted3) + /// + /// Adds the 4 residuals of one row to the 4 prediction samples of the row, with the clamp to [0, 255], and stores the 4 results. + /// + /// + /// The lanes are those of . Lanes 4 to 7 are not defined, and the store keeps only bytes 0 to 3. + /// + /// The first prediction sample of the block. + /// The first destination sample of the block. + /// The offset of the row from the first sample. + /// The residuals of the row in 16-bit lanes 0 to 3. + [MethodImpl(InliningOptions.ShortMethod)] + private static void AddResiduals4(ref byte reference, ref byte dst, nuint offset, Vector128 residuals) { - Vector128 dc = t0.AsInt16() + Vector128.Create((short)4); - Vector128 a = dc + t2.AsInt16(); - Vector128 b = dc - t2.AsInt16(); - - Vector128 k1 = Vector128.Create((short)20091).AsInt16(); - Vector128 k2 = Vector128.Create((short)-30068).AsInt16(); - - // c = MUL(T1, K2) - MUL(T3, K1) = MUL(T1, k2) - MUL(T3, k1) + T1 - T3 - Vector128 c1 = Vector128_.MultiplyHigh(t1.AsInt16(), k2); - Vector128 c2 = Vector128_.MultiplyHigh(t3.AsInt16(), k1); - Vector128 c3 = t1.AsInt16() - t3.AsInt16(); - Vector128 c4 = c1 - c2; - Vector128 c = c3 + c4; - - // d = MUL(T1, K1) + MUL(T3, K2) = MUL(T1, k1) + MUL(T3, k2) + T1 + T3 - Vector128 d1 = Vector128_.MultiplyHigh(t1.AsInt16(), k1); - Vector128 d2 = Vector128_.MultiplyHigh(t3.AsInt16(), k2); - Vector128 d3 = t1.AsInt16() + t3.AsInt16(); - Vector128 d4 = d1 + d2; - Vector128 d = d3 + d4; - - // Second pass. - Vector128 tmp0 = a + d; - Vector128 tmp1 = b + c; - Vector128 tmp2 = b - c; - Vector128 tmp3 = a - d; - shifted0 = Vector128.ShiftRightArithmetic(tmp0, 3); - shifted1 = Vector128.ShiftRightArithmetic(tmp1, 3); - shifted2 = Vector128.ShiftRightArithmetic(tmp2, 3); - shifted3 = Vector128.ShiftRightArithmetic(tmp3, 3); + Vector128 prediction = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref Unsafe.Add(ref reference, offset))).AsByte(); + Vector128 sum = Vector128.WidenLower(prediction).AsInt16() + residuals; + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, offset), Vector128_.PackUnsignedSaturate(sum, sum).AsInt32().ToScalar()); } - public static void FTransform2(Span src, Span reference, Span output, Span output2, Span scratch) + /// + /// Computes the forward transforms of two 4x4 residual blocks: the source minus two predictions that are side by side. + /// + /// The source row operator that sets where the source of the second block is. + /// The first source sample of the first block. The rows have a stride of . + /// + /// The first prediction sample. Each row has the 4 samples of the first prediction, then the 4 samples of the second prediction. + /// The rows have a stride of . + /// + /// The first of the 16 coefficients of the first block. + /// The first of the 16 coefficients of the second block. + /// The first of the 16 scratch integers of the scalar path. + public static void FTransform2(ref byte src, ref byte reference, ref short output, ref short output2, ref int scratch) + where TSource : struct, ISourceRowOperator { if (Vector128.IsHardwareAccelerated) { - ref byte srcRef = ref MemoryMarshal.GetReference(src); - ref byte referenceRef = ref MemoryMarshal.GetReference(reference); - - // Load src. - Vector128 src0 = Vector128.Create(Unsafe.As(ref srcRef), 0); - Vector128 src1 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, WebpConstants.Bps)), 0); - Vector128 src2 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, WebpConstants.Bps * 2)), 0); - Vector128 src3 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, WebpConstants.Bps * 3)), 0); - - // Load ref. - Vector128 ref0 = Vector128.Create(Unsafe.As(ref referenceRef), 0); - Vector128 ref1 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref referenceRef, WebpConstants.Bps)), 0); - Vector128 ref2 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref referenceRef, WebpConstants.Bps * 2)), 0); - Vector128 ref3 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref referenceRef, WebpConstants.Bps * 3)), 0); - - // Convert both to 16 bit. - Vector128 srcLow0 = Vector128_.UnpackLow(src0.AsByte(), Vector128.Zero); - Vector128 srcLow1 = Vector128_.UnpackLow(src1.AsByte(), Vector128.Zero); - Vector128 srcLow2 = Vector128_.UnpackLow(src2.AsByte(), Vector128.Zero); - Vector128 srcLow3 = Vector128_.UnpackLow(src3.AsByte(), Vector128.Zero); - Vector128 refLow0 = Vector128_.UnpackLow(ref0.AsByte(), Vector128.Zero); - Vector128 refLow1 = Vector128_.UnpackLow(ref1.AsByte(), Vector128.Zero); - Vector128 refLow2 = Vector128_.UnpackLow(ref2.AsByte(), Vector128.Zero); - Vector128 refLow3 = Vector128_.UnpackLow(ref3.AsByte(), Vector128.Zero); - - // Compute difference. -> 00 01 02 03 00' 01' 02' 03' - Vector128 diff0 = srcLow0.AsInt16() - refLow0.AsInt16(); - Vector128 diff1 = srcLow1.AsInt16() - refLow1.AsInt16(); - Vector128 diff2 = srcLow2.AsInt16() - refLow2.AsInt16(); - Vector128 diff3 = srcLow3.AsInt16() - refLow3.AsInt16(); - - // Unpack and shuffle. - // 00 01 02 03 0 0 0 0 - // 10 11 12 13 0 0 0 0 - // 20 21 22 23 0 0 0 0 - // 30 31 32 33 0 0 0 0 + // Compute the difference of each row in 16-bit lanes: lanes 0 to 3 hold the first block, lanes 4 to 7 the second. + // 00 01 02 03 00' 01' 02' 03' + Vector128 diff0 = FTransformRowDifference(ref src, ref reference, 0); + Vector128 diff1 = FTransformRowDifference(ref src, ref reference, WebpConstants.Bps); + Vector128 diff2 = FTransformRowDifference(ref src, ref reference, WebpConstants.Bps * 2); + Vector128 diff3 = FTransformRowDifference(ref src, ref reference, WebpConstants.Bps * 3); + + // Unpack and shuffle. The low result holds the rows of the first block, the high result the rows of the second block. + // 00 01 10 11 02 03 12 13 + // 20 21 30 31 22 23 32 33 Vector128 shuf01l = Vector128_.UnpackLow(diff0.AsInt32(), diff1.AsInt32()); Vector128 shuf23l = Vector128_.UnpackLow(diff2.AsInt32(), diff3.AsInt32()); Vector128 shuf01h = Vector128_.UnpackHigh(diff0.AsInt32(), diff1.AsInt32()); Vector128 shuf23h = Vector128_.UnpackHigh(diff2.AsInt32(), diff3.AsInt32()); - // First pass. - FTransformPass1Vector128(shuf01l.AsInt16(), shuf23l.AsInt16(), out Vector128 v01l, out Vector128 v32l); - FTransformPass1Vector128(shuf01h.AsInt16(), shuf23h.AsInt16(), out Vector128 v01h, out Vector128 v32h); - - // Second pass. - FTransformPass2Vector128(v01l, v32l, output); - FTransformPass2Vector128(v01h, v32h, output2); + if (Vector256.IsHardwareAccelerated) + { + // The 128-bit lane 0 holds the first block and lane 1 the second block. Each step of the passes keeps the + // values in their 128-bit lane, so this is the same as two runs of the 128-bit passes. + FTransformPass1( + Vector256.Create(shuf01l, shuf01h).AsInt16(), + Vector256.Create(shuf23l, shuf23h).AsInt16(), + out Vector256 v01, + out Vector256 v32); + + FTransformPass2(v01, v32, ref output, ref output2); + } + else + { + FTransformPass1(shuf01l.AsInt16(), shuf23l.AsInt16(), out Vector128 v01l, out Vector128 v32l); + FTransformPass1(shuf01h.AsInt16(), shuf23h.AsInt16(), out Vector128 v01h, out Vector128 v32h); + FTransformPass2(v01l, v32l, ref output); + FTransformPass2(v01h, v32h, ref output2); + } } else { - FTransform(src, reference, output, scratch); - FTransform(src[4..], reference[4..], output2, scratch); + FTransform(ref src, ref reference, ref output, ref scratch); + FTransform(ref Unsafe.Add(ref src, TSource.SecondBlockOffset), ref Unsafe.Add(ref reference, (nuint)4), ref output2, ref scratch); } } - public static void FTransform(Span src, Span reference, Span output, Span scratch) + /// + /// Returns the source minus the prediction for one row of two 4x4 blocks. + /// + /// The source row operator. + /// The first source sample of the first block. + /// The first prediction sample. + /// The offset of the row. + /// The differences: 16-bit lanes 0 to 3 for the first block, 4 to 7 for the second block. + [MethodImpl(InliningOptions.ShortMethod)] + private static Vector128 FTransformRowDifference(ref byte src, ref byte reference, nuint row) + where TSource : struct, ISourceRowOperator + { + // Each sample is 0 to 255, so each difference is -255 to 255 and fits a signed 16-bit lane. + Vector128 s = Vector128.WidenLower(TSource.Load(ref Unsafe.Add(ref src, row))); + Vector128 r = Vector128.WidenLower(AdjacentSourceOperator.Load(ref Unsafe.Add(ref reference, row))); + return (s - r).AsInt16(); + } + + /// + /// Computes the forward transform of one 4x4 residual block: the source minus the prediction. + /// + /// The first source sample. The rows have a stride of . + /// The first prediction sample, with the same layout as . + /// The first of the 16 coefficients. + /// The first of the 16 scratch integers of the scalar path. + public static void FTransform(ref byte src, ref byte reference, ref short output, ref int scratch) { if (Vector128.IsHardwareAccelerated) { - ref byte srcRef = ref MemoryMarshal.GetReference(src); - ref byte referenceRef = ref MemoryMarshal.GetReference(reference); - // Load src. - Vector128 src0 = Vector128.Create(Unsafe.As(ref srcRef), 0); - Vector128 src1 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, WebpConstants.Bps)), 0); - Vector128 src2 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, WebpConstants.Bps * 2)), 0); - Vector128 src3 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref srcRef, WebpConstants.Bps * 3)), 0); + Vector128 src0 = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref src)); + Vector128 src1 = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref Unsafe.Add(ref src, (nuint)WebpConstants.Bps))); + Vector128 src2 = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref Unsafe.Add(ref src, (nuint)(WebpConstants.Bps * 2)))); + Vector128 src3 = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref Unsafe.Add(ref src, (nuint)(WebpConstants.Bps * 3)))); // Load ref. - Vector128 ref0 = Vector128.Create(Unsafe.As(ref referenceRef), 0); - Vector128 ref1 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref referenceRef, WebpConstants.Bps)), 0); - Vector128 ref2 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref referenceRef, WebpConstants.Bps * 2)), 0); - Vector128 ref3 = Vector128.Create(Unsafe.As(ref Unsafe.Add(ref referenceRef, WebpConstants.Bps * 3)), 0); + Vector128 ref0 = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref reference)); + Vector128 ref1 = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref Unsafe.Add(ref reference, (nuint)WebpConstants.Bps))); + Vector128 ref2 = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref Unsafe.Add(ref reference, (nuint)(WebpConstants.Bps * 2)))); + Vector128 ref3 = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref Unsafe.Add(ref reference, (nuint)(WebpConstants.Bps * 3)))); // 00 01 02 03 * // 10 11 12 13 * // 20 21 22 23 * // 30 31 32 33 * - // Shuffle. + // Shuffle. Only the low 4 bytes of each row are used. Vector128 srcLow0 = Vector128_.UnpackLow(src0.AsInt16(), src1.AsInt16()); Vector128 srcLow1 = Vector128_.UnpackLow(src2.AsInt16(), src3.AsInt16()); Vector128 refLow0 = Vector128_.UnpackLow(ref0.AsInt16(), ref1.AsInt16()); @@ -526,56 +440,66 @@ public static void FTransform(Span src, Span reference, Span Vector128 row23 = src1_16b.AsInt16() - ref1_16b.AsInt16(); // First pass. - FTransformPass1Vector128(row01, row23, out Vector128 v01, out Vector128 v32); + FTransformPass1(row01, row23, out Vector128 v01, out Vector128 v32); // Second pass. - FTransformPass2Vector128(v01, v32, output); + FTransformPass2(v01, v32, ref output); } else { - int i; - Span tmp = scratch[..16]; - - int srcIdx = 0; - int refIdx = 0; - for (i = 0; i < 4; i++) + // The first pass writes all 16 entries of tmp before the second pass reads them. + ref int tmp = ref scratch; + nuint offset = 0; + for (nuint i = 0; i < 4; i++) { - int d3 = src[srcIdx + 3] - reference[refIdx + 3]; - int d2 = src[srcIdx + 2] - reference[refIdx + 2]; - int d1 = src[srcIdx + 1] - reference[refIdx + 1]; - int d0 = src[srcIdx] - reference[refIdx]; // 9bit dynamic range ([-255,255]) + int d3 = Unsafe.Add(ref src, offset + 3) - Unsafe.Add(ref reference, offset + 3); + int d2 = Unsafe.Add(ref src, offset + 2) - Unsafe.Add(ref reference, offset + 2); + int d1 = Unsafe.Add(ref src, offset + 1) - Unsafe.Add(ref reference, offset + 1); + int d0 = Unsafe.Add(ref src, offset) - Unsafe.Add(ref reference, offset); // 9bit dynamic range ([-255,255]) int a0 = d0 + d3; // 10b [-510,510] int a1 = d1 + d2; int a2 = d1 - d2; int a3 = d0 - d3; - tmp[3 + (i * 4)] = ((a3 * 2217) - (a2 * 5352) + 937) >> 9; - tmp[2 + (i * 4)] = (a0 - a1) * 8; - tmp[1 + (i * 4)] = ((a2 * 2217) + (a3 * 5352) + 1812) >> 9; // [-7536,7542] - tmp[0 + (i * 4)] = (a0 + a1) * 8; // 14b [-8160,8160] + Unsafe.Add(ref tmp, 3 + (i * 4)) = ((a3 * 2217) - (a2 * 5352) + 937) >> 9; + Unsafe.Add(ref tmp, 2 + (i * 4)) = (a0 - a1) * 8; + Unsafe.Add(ref tmp, 1 + (i * 4)) = ((a2 * 2217) + (a3 * 5352) + 1812) >> 9; // [-7536,7542] + Unsafe.Add(ref tmp, 0 + (i * 4)) = (a0 + a1) * 8; // 14b [-8160,8160] - srcIdx += WebpConstants.Bps; - refIdx += WebpConstants.Bps; + offset += WebpConstants.Bps; } - for (i = 0; i < 4; i++) + for (nuint i = 0; i < 4; i++) { - int t12 = tmp[12 + i]; // 15b - int t8 = tmp[8 + i]; - - int a1 = tmp[4 + i] + t8; - int a2 = tmp[4 + i] - t8; - int a0 = tmp[0 + i] + t12; // 15b - int a3 = tmp[0 + i] - t12; - - output[12 + i] = (short)(((a3 * 2217) - (a2 * 5352) + 51000) >> 16); - output[8 + i] = (short)((a0 - a1 + 7) >> 4); - output[4 + i] = (short)((((a2 * 2217) + (a3 * 5352) + 12000) >> 16) + (a3 != 0 ? 1 : 0)); - output[0 + i] = (short)((a0 + a1 + 7) >> 4); // 12b + int t12 = Unsafe.Add(ref tmp, 12 + i); // 15b + int t8 = Unsafe.Add(ref tmp, 8 + i); + int t4 = Unsafe.Add(ref tmp, 4 + i); + int t0 = Unsafe.Add(ref tmp, i); + + int a1 = t4 + t8; + int a2 = t4 - t8; + int a0 = t0 + t12; // 15b + int a3 = t0 - t12; + + Unsafe.Add(ref output, 12 + i) = (short)(((a3 * 2217) - (a2 * 5352) + 51000) >> 16); + Unsafe.Add(ref output, 8 + i) = (short)((a0 - a1 + 7) >> 4); + Unsafe.Add(ref output, 4 + i) = (short)((((a2 * 2217) + (a3 * 5352) + 12000) >> 16) + (a3 != 0 ? 1 : 0)); + Unsafe.Add(ref output, i) = (short)((a0 + a1 + 7) >> 4); // 12b } } } - public static void FTransformPass1Vector128(Vector128 row01, Vector128 row23, out Vector128 out01, out Vector128 out32) + /// + /// Runs the first pass of the forward transform on the 16 differences of one 4x4 block. The pass transforms each row. + /// + /// + /// The results are the same as the first loop of the scalar path: (a0 + a1) * 8, (a0 - a1) * 8 and the rounded products + /// with 2217 and 5352, shifted right by 9 bits. + /// + /// Rows 0 and 1: 00 01 10 11 02 03 12 13. + /// Rows 2 and 3: 20 21 30 31 22 23 32 33. + /// The first pass values 0 and 1 of each row. + /// The first pass values 3 and 2 of each row. + public static void FTransformPass1(Vector128 row01, Vector128 row23, out Vector128 out01, out Vector128 out32) { // *in01 = 00 01 10 11 02 03 12 13 // *in23 = 20 21 30 31 22 23 32 33 @@ -602,12 +526,15 @@ public static void FTransformPass1Vector128(Vector128 row01, Vector128 tmp2 = Vector128_.MultiplyAddAdjacent( a01, Vector128.Create(8, 0, 248, 255, 8, 0, 248, 255, 8, 0, 248, 255, 8, 0, 248, 255).AsInt16()); // K88m + Vector128 tmp11 = Vector128_.MultiplyAddAdjacent( a32, Vector128.Create(232, 20, 169, 8, 232, 20, 169, 8, 232, 20, 169, 8, 232, 20, 169, 8).AsInt16()); // K5352_2217p + Vector128 tmp31 = Vector128_.MultiplyAddAdjacent( a32, Vector128.Create(169, 8, 24, 235, 169, 8, 24, 235, 169, 8, 24, 235, 169, 8, 24, 235).AsInt16()); // K5352_2217m + Vector128 tmp12 = tmp11 + Vector128.Create(1812); Vector128 tmp32 = tmp31 + Vector128.Create(937); Vector128 tmp1 = Vector128.ShiftRightArithmetic(tmp12, 9); @@ -621,7 +548,17 @@ public static void FTransformPass1Vector128(Vector128 row01, Vector128 v01, Vector128 v32, Span output) + /// + /// Runs the second pass of the forward transform on the first pass values of one 4x4 block and stores the coefficients. + /// The pass transforms each column. + /// + /// + /// The results are the same as the second loop of the scalar path, including the extra 1 that coefficient row 1 gets when a3 is not zero. + /// + /// The first pass values 0 and 1 of each row. + /// The first pass values 3 and 2 of each row. + /// The first of the 16 coefficients, in raster order. + public static void FTransformPass2(Vector128 v01, Vector128 v32, ref short output) { // Same operations are done on the (0,3) and (1,2) pairs. // a3 = v0 - v3 @@ -633,9 +570,11 @@ public static void FTransformPass2Vector128(Vector128 v01, Vector128 v Vector128 c1 = Vector128_.MultiplyAddAdjacent( b23, Vector128.Create(169, 8, 232, 20, 169, 8, 232, 20, 169, 8, 232, 20, 169, 8, 232, 20).AsInt16()); // K5352_2217 + Vector128 c3 = Vector128_.MultiplyAddAdjacent( b23, Vector128.Create(24, 235, 169, 8, 24, 235, 169, 8, 24, 235, 169, 8, 24, 235, 169, 8).AsInt16()); // K2217_5352 + Vector128 d1 = c1 + Vector128.Create(12000 + (1 << 16)); // K12000PlusOne Vector128 d3 = c3 + Vector128.Create(51000); Vector128 e1 = Vector128.ShiftRightArithmetic(d1, 16); @@ -668,70 +607,251 @@ public static void FTransformPass2Vector128(Vector128 v01, Vector128 v Vector128 d0g1 = Vector128_.UnpackLow(d0.AsInt64(), g1.AsInt64()); Vector128 d2f3 = Vector128_.UnpackLow(d2.AsInt64(), f3.AsInt64()); - ref short outputRef = ref MemoryMarshal.GetReference(output); - Unsafe.As>(ref outputRef) = d0g1.AsInt16(); - Unsafe.As>(ref Unsafe.Add(ref outputRef, 8)) = d2f3.AsInt16(); + d0g1.AsInt16().StoreUnsafe(ref output); + d2f3.AsInt16().StoreUnsafe(ref output, 8); } - public static void FTransformWht(ReadOnlySpan input, Span output, Span scratch) + /// + /// Runs the first pass of the forward transform on two 4x4 blocks at once. + /// + /// + /// The 128-bit lane 0 of each vector holds the first block and lane 1 the second block, in the layout of + /// . Each operation below + /// keeps the values in their 128-bit lane, so the results are the same as two runs of the 128-bit form. + /// + /// Rows 0 and 1: 00 01 10 11 02 03 12 13 in each 128-bit lane. + /// Rows 2 and 3: 20 21 30 31 22 23 32 33 in each 128-bit lane. + /// The first pass values 0 and 1 of each row. + /// The first pass values 3 and 2 of each row. + private static void FTransformPass1(Vector256 row01, Vector256 row23, out Vector256 out01, out Vector256 out32) { - Span tmp = scratch[..16]; + // Swap the 16-bit pairs in the high 64 bits of each 128-bit lane. + // 00 01 10 11 03 02 13 12 + // 20 21 30 31 23 22 33 32 + Vector256 swapHigh = Vector256.Create((short)0, 1, 2, 3, 5, 4, 7, 6, 8, 9, 10, 11, 13, 12, 15, 14); + Vector256 shuf01_p = Vector256.Shuffle(row01, swapHigh); + Vector256 shuf32_p = Vector256.Shuffle(row23, swapHigh); - int i; - int inputIdx = 0; - for (i = 0; i < 4; i++) + // 00 01 10 11 20 21 30 31 + // 03 02 13 12 23 22 33 32 + Vector256 s01 = Vector256_.UnpackLow(shuf01_p.AsInt64(), shuf32_p.AsInt64()); + Vector256 s32 = Vector256_.UnpackHigh(shuf01_p.AsInt64(), shuf32_p.AsInt64()); + + // [d0 + d3 | d1 + d2 | ...] = [a0 a1 | a0' a1' | ... ] + // [d0 - d3 | d1 - d2 | ...] = [a3 a2 | a3' a2' | ... ] + Vector256 a01 = s01.AsInt16() + s32.AsInt16(); + Vector256 a32 = s01.AsInt16() - s32.AsInt16(); + + // Each 32-bit constant holds the multiplier of the even 16-bit lane in its low half and of the odd lane in its high half. + // tmp0 = (a0 + a1) << 3, tmp2 = (a0 - a1) << 3, tmp1 = a2 * 2217 + a3 * 5352, tmp3 = a3 * 2217 - a2 * 5352. + Vector256 tmp0 = Vector256_.MultiplyAddAdjacent(a01, Vector256.Create(8 | (8 << 16)).AsInt16()); + Vector256 tmp2 = Vector256_.MultiplyAddAdjacent(a01, Vector256.Create(8 | (-8 << 16)).AsInt16()); + Vector256 tmp11 = Vector256_.MultiplyAddAdjacent(a32, Vector256.Create(5352 | (2217 << 16)).AsInt16()); + Vector256 tmp31 = Vector256_.MultiplyAddAdjacent(a32, Vector256.Create(2217 | (-5352 << 16)).AsInt16()); + Vector256 tmp1 = Vector256.ShiftRightArithmetic(tmp11 + Vector256.Create(1812), 9); + Vector256 tmp3 = Vector256.ShiftRightArithmetic(tmp31 + Vector256.Create(937), 9); + + // The saturating pack works in each 128-bit lane, as the 128-bit narrow does. + Vector256 s03 = Vector256_.PackSignedSaturate(tmp0, tmp2); + Vector256 s12 = Vector256_.PackSignedSaturate(tmp1, tmp3); + Vector256 slo = Vector256_.UnpackLow(s03, s12); // 0 1 0 1 0 1... + Vector256 shi = Vector256_.UnpackHigh(s03, s12); // 2 3 2 3 2 3 + Vector256 v23 = Vector256_.UnpackHigh(slo.AsInt32(), shi.AsInt32()); + out01 = Vector256_.UnpackLow(slo.AsInt32(), shi.AsInt32()); + + // Swap the 64-bit halves of each 128-bit lane. + out32 = Vector256.Shuffle(v23, Vector256.Create(2, 3, 0, 1, 6, 7, 4, 5)); + } + + /// + /// Runs the second pass of the forward transform on two 4x4 blocks at once and stores the coefficients. + /// + /// + /// The 128-bit lane 0 of each vector holds the first block and lane 1 the second block. Each operation keeps the + /// values in their 128-bit lane, so the results are the same as two runs of + /// . + /// + /// The first pass values 0 and 1 of each row. + /// The first pass values 3 and 2 of each row. + /// The first of the 16 coefficients of the first block. + /// The first of the 16 coefficients of the second block. + private static void FTransformPass2(Vector256 v01, Vector256 v32, ref short output, ref short output2) + { + // a3 = v0 - v3, a2 = v1 - v2. + Vector256 a32 = v01.AsInt16() - v32.AsInt16(); + Vector256 a22 = Vector256_.UnpackHigh(a32.AsInt64(), a32.AsInt64()); + Vector256 b23 = Vector256_.UnpackLow(a22.AsInt16(), a32.AsInt16()); + + // c1 = b2 * 2217 + b3 * 5352, c3 = b3 * 2217 - b2 * 5352. The low half of each 32-bit constant multiplies the even lane. + Vector256 c1 = Vector256_.MultiplyAddAdjacent(b23, Vector256.Create(2217 | (5352 << 16)).AsInt16()); + Vector256 c3 = Vector256_.MultiplyAddAdjacent(b23, Vector256.Create((-5352 & 0xFFFF) | (2217 << 16)).AsInt16()); + + // f1 = ((b3 * 5352 + b2 * 2217 + 12000) >> 16) + 1 + // f3 = ((b3 * 2217 - b2 * 5352 + 51000) >> 16) + Vector256 e1 = Vector256.ShiftRightArithmetic(c1 + Vector256.Create(12000 + (1 << 16)), 16); + Vector256 e3 = Vector256.ShiftRightArithmetic(c3 + Vector256.Create(51000), 16); + Vector256 f1 = Vector256_.PackSignedSaturate(e1, e1); + Vector256 f3 = Vector256_.PackSignedSaturate(e3, e3); + + // g1 = f1 + (a3 != 0) = f1 + 1 - (a3 == 0). The one is in the rounding constant above. + Vector256 g1 = f1 + Vector256.Equals(a32, Vector256.Zero); + + // a0 = v0 + v3, a1 = v1 + v2. + // d0 = (a0 + a1 + 7) >> 4, d2 = (a0 - a1 + 7) >> 4. + Vector256 a01 = v01.AsInt16() + v32.AsInt16(); + Vector256 a01Plus7 = a01 + Vector256.Create((short)7); + Vector256 a11 = Vector256_.UnpackHigh(a01.AsInt64(), a01.AsInt64()).AsInt16(); + Vector256 d0 = Vector256.ShiftRightArithmetic(a01Plus7 + a11, 4); + Vector256 d2 = Vector256.ShiftRightArithmetic(a01Plus7 - a11, 4); + + // Each 128-bit lane of d0g1 holds the coefficients 0 to 7 of its block, and of d2f3 the coefficients 8 to 15. + Vector256 d0g1 = Vector256_.UnpackLow(d0.AsInt64(), g1.AsInt64()); + Vector256 d2f3 = Vector256_.UnpackLow(d2.AsInt64(), f3.AsInt64()); + + d0g1.GetLower().AsInt16().StoreUnsafe(ref output); + d2f3.GetLower().AsInt16().StoreUnsafe(ref output, 8); + d0g1.GetUpper().AsInt16().StoreUnsafe(ref output2); + d2f3.GetUpper().AsInt16().StoreUnsafe(ref output2, 8); + } + + /// + /// Computes the forward Walsh-Hadamard transform of the 16 DC coefficients of a 16x16 luma block. + /// + /// The first of the 256 coefficients of the 16 luma blocks. The DC of block n is at index 16n. + /// The first of the 16 transformed DC coefficients. + /// The first of the 16 scratch integers of the scalar path. + public static void FTransformWht(ref short input, ref short output, ref int scratch) + { + if (Vector128.IsHardwareAccelerated) { - int a1 = input[inputIdx + (1 * 16)] + input[inputIdx + (3 * 16)]; - int a2 = input[inputIdx + (1 * 16)] - input[inputIdx + (3 * 16)]; - int a0 = input[inputIdx + (0 * 16)] + input[inputIdx + (2 * 16)]; // 13b - int a3 = input[inputIdx + (0 * 16)] - input[inputIdx + (2 * 16)]; - tmp[3 + (i * 4)] = a0 - a1; - tmp[2 + (i * 4)] = a3 - a2; - tmp[1 + (i * 4)] = a3 + a2; - tmp[0 + (i * 4)] = a0 + a1; // 14b + // The input holds the coefficients of 16 luma blocks. The DC of block (i, k) is input[(64 * i) + (16 * k)]. + // The vectors in0 to in3 hold the columns k = 0 to 3 of the 4x4 DC matrix: lane i is the DC of block (i, k). + // The lanes are 32-bit, as the scalar arithmetic is, so all sums and differences are exact. + ref short dc = ref input; + Vector128 in0 = Vector128.Create((int)dc, Unsafe.Add(ref dc, 64U), Unsafe.Add(ref dc, 128U), Unsafe.Add(ref dc, 192U)); + Vector128 in1 = Vector128.Create((int)Unsafe.Add(ref dc, 16U), Unsafe.Add(ref dc, 80U), Unsafe.Add(ref dc, 144U), Unsafe.Add(ref dc, 208U)); + Vector128 in2 = Vector128.Create((int)Unsafe.Add(ref dc, 32U), Unsafe.Add(ref dc, 96U), Unsafe.Add(ref dc, 160U), Unsafe.Add(ref dc, 224U)); + Vector128 in3 = Vector128.Create((int)Unsafe.Add(ref dc, 48U), Unsafe.Add(ref dc, 112U), Unsafe.Add(ref dc, 176U), Unsafe.Add(ref dc, 240U)); + + // First pass, on all four rows at once. Lane i of t0 to t3 is tmp[(4 * i) + 0] to tmp[(4 * i) + 3] of the scalar path. + Vector128 a0 = in0 + in2; + Vector128 a1 = in1 + in3; + Vector128 a2 = in1 - in3; + Vector128 a3 = in0 - in2; + Vector128 t0 = a0 + a1; + Vector128 t1 = a3 + a2; + Vector128 t2 = a3 - a2; + Vector128 t3 = a0 - a1; + + // Transpose the 4x4 matrix. After this, lane c of r0 to r3 is tmp[0 + c] to tmp[12 + c] of the scalar path. + Vector128 t01Low = Vector128_.UnpackLow(t0, t1); + Vector128 t23Low = Vector128_.UnpackLow(t2, t3); + Vector128 t01High = Vector128_.UnpackHigh(t0, t1); + Vector128 t23High = Vector128_.UnpackHigh(t2, t3); + Vector128 r0 = Vector128_.UnpackLow(t01Low.AsInt64(), t23Low.AsInt64()).AsInt32(); + Vector128 r1 = Vector128_.UnpackHigh(t01Low.AsInt64(), t23Low.AsInt64()).AsInt32(); + Vector128 r2 = Vector128_.UnpackLow(t01High.AsInt64(), t23High.AsInt64()).AsInt32(); + Vector128 r3 = Vector128_.UnpackHigh(t01High.AsInt64(), t23High.AsInt64()).AsInt32(); + + // Second pass, on all four columns at once. Lane i of b0 to b3 is the scalar b0 >> 1 to b3 >> 1 of column i. + a0 = r0 + r2; + a1 = r1 + r3; + a2 = r1 - r3; + a3 = r0 - r2; + Vector128 b0 = Vector128.ShiftRightArithmetic(a0 + a1, 1); + Vector128 b1 = Vector128.ShiftRightArithmetic(a3 + a2, 1); + Vector128 b2 = Vector128.ShiftRightArithmetic(a3 - a2, 1); + Vector128 b3 = Vector128.ShiftRightArithmetic(a0 - a1, 1); + + // The narrow keeps the low 16 bits of each lane, as the scalar cast to short does. + // output[0..3] is b0, output[4..7] is b1, output[8..11] is b2 and output[12..15] is b3. + Vector128.Narrow(b0, b1).StoreUnsafe(ref output); + Vector128.Narrow(b2, b3).StoreUnsafe(ref output, 8); + return; + } + + // The first pass writes all 16 entries of tmp before the second pass reads them. + ref int tmp = ref scratch; + nuint inputIdx = 0; + for (nuint i = 0; i < 4; i++) + { + int in0 = Unsafe.Add(ref input, inputIdx); + int in16 = Unsafe.Add(ref input, inputIdx + 16); + int in32 = Unsafe.Add(ref input, inputIdx + 32); + int in48 = Unsafe.Add(ref input, inputIdx + 48); + int a1 = in16 + in48; + int a2 = in16 - in48; + int a0 = in0 + in32; // 13b + int a3 = in0 - in32; + Unsafe.Add(ref tmp, 3 + (i * 4)) = a0 - a1; + Unsafe.Add(ref tmp, 2 + (i * 4)) = a3 - a2; + Unsafe.Add(ref tmp, 1 + (i * 4)) = a3 + a2; + Unsafe.Add(ref tmp, 0 + (i * 4)) = a0 + a1; // 14b inputIdx += 64; } - for (i = 0; i < 4; i++) + for (nuint i = 0; i < 4; i++) { - int t12 = tmp[12 + i]; - int t8 = tmp[8 + i]; + int t12 = Unsafe.Add(ref tmp, 12 + i); + int t8 = Unsafe.Add(ref tmp, 8 + i); + int t4 = Unsafe.Add(ref tmp, 4 + i); + int t0 = Unsafe.Add(ref tmp, i); - int a1 = tmp[4 + i] + t12; - int a2 = tmp[4 + i] - t12; - int a0 = tmp[0 + i] + t8; // 15b - int a3 = tmp[0 + i] - t8; + int a1 = t4 + t12; + int a2 = t4 - t12; + int a0 = t0 + t8; // 15b + int a3 = t0 - t8; int b0 = a0 + a1; // 16b int b1 = a3 + a2; int b2 = a3 - a2; int b3 = a0 - a1; - output[12 + i] = (short)(b3 >> 1); - output[8 + i] = (short)(b2 >> 1); - output[4 + i] = (short)(b1 >> 1); - output[0 + i] = (short)(b0 >> 1); // 15b + Unsafe.Add(ref output, 12 + i) = (short)(b3 >> 1); + Unsafe.Add(ref output, 8 + i) = (short)(b2 >> 1); + Unsafe.Add(ref output, 4 + i) = (short)(b1 >> 1); + Unsafe.Add(ref output, i) = (short)(b0 >> 1); // 15b } } - // luma 16x16 prediction (paragraph 12.3). + /// + /// Writes the four intra 16x16 predictions of a macroblock to the prediction buffer, at . + /// + /// + /// See RFC 6386, section 12.3. + /// + /// The prediction buffer. The rows have a stride of . + /// The top-left sample followed by the 16 left samples, or an empty span when no left column exists. + /// The 16 top samples, or an empty span when no top row exists. public static void EncPredLuma16(Span dst, Span left, Span top) { - DcMode(dst, left, top, 16, 16, 5); - VerticalPred(dst[I16VE16..], top, 16); - HorizontalPred(dst[I16HE16..], left, 16); - TrueMotion(dst[I16TM16..], left, top, 16); + DcMode(dst, left, top, 16, 5); + VerticalPred(dst[I16VE16..], top); + HorizontalPred(dst[I16HE16..], left); + TrueMotion(dst[I16TM16..], left, top); } - // Chroma 8x8 prediction (paragraph 12.2). + /// + /// Writes the four chroma predictions of the U and V blocks of a macroblock to the prediction buffer, at . + /// Each V prediction starts 8 samples after the U prediction of the same mode. + /// + /// + /// See RFC 6386, section 12.2. + /// + /// The prediction buffer. The rows have a stride of . + /// + /// The U top-left sample followed by the 8 U left samples, then the V samples in the same layout from index 16, + /// or an empty span when no left column exists. + /// + /// The 8 U top samples followed by the 8 V top samples, or an empty span when no top row exists. public static void EncPredChroma8(Span dst, Span left, Span top) { // U block. - DcMode(dst[C8DC8..], left, top, 8, 8, 4); - VerticalPred(dst[C8VE8..], top, 8); - HorizontalPred(dst[C8HE8..], left, 8); - TrueMotion(dst[C8TM8..], left, top, 8); + DcMode(dst[C8DC8..], left, top, 8, 4); + VerticalPred(dst[C8VE8..], top); + HorizontalPred(dst[C8HE8..], left); + TrueMotion(dst[C8TM8..], left, top); // V block. dst = dst[8..]; @@ -745,16 +865,46 @@ public static void EncPredChroma8(Span dst, Span left, Span to left = left[16..]; } - DcMode(dst[C8DC8..], left, top, 8, 8, 4); - VerticalPred(dst[C8VE8..], top, 8); - HorizontalPred(dst[C8HE8..], left, 8); - TrueMotion(dst[C8TM8..], left, top, 8); + DcMode(dst[C8DC8..], left, top, 8, 4); + VerticalPred(dst[C8VE8..], top); + HorizontalPred(dst[C8HE8..], left); + TrueMotion(dst[C8TM8..], left, top); } - // Left samples are top[-5 .. -2], top_left is top[-1], top are - // located at top[0..3], and top right is top[4..7] + /// + /// Writes the ten intra 4x4 predictions of the current 4x4 block to the prediction buffer, at . + /// + /// + /// The left samples are at top[-5..-2], the top-left sample at top[-1], the top samples at top[0..3] and the top-right samples at top[4..7]. + /// + /// The prediction buffer. The rows have a stride of . + /// + /// The boundary samples. From - 5, they are the left samples L K J I from bottom to top, + /// the top-left sample X, the top samples A B C D and the top-right samples E F G H. + /// + /// The index of the top sample A in . + /// A scratch buffer of 4 samples. Only the scalar path uses it. public static void EncPredLuma4(Span dst, ReadOnlySpan top, int topOffset, Span vals) { + if (Vector128.IsHardwareAccelerated) + { + // One range check covers the 13 boundary samples that the 4x4 predictors read, in this order: + // the left samples L K J I, the top-left sample X, the top samples A B C D and the top-right samples E F G H. + // DC, HE, HD and HU have no useful lane layout, so they use the scalar forms. + ReadOnlySpan boundary = top.Slice(topOffset - 5, 13); + Dc4(dst[I4DC4..], top, topOffset); + Tm4(dst[I4TM4..], boundary); + Ve4(dst[I4VE4..], boundary); + He4(dst[I4HE4..], top, topOffset); + Rd4(dst[I4RD4..], boundary); + Vr4(dst[I4VR4..], boundary); + Ld4(dst[I4LD4..], boundary); + Vl4(dst[I4VL4..], boundary); + Hd4(dst[I4HD4..], top, topOffset); + Hu4(dst[I4HU4..], top, topOffset); + return; + } + Dc4(dst[I4DC4..], top, topOffset); Tm4(dst[I4TM4..], top, topOffset); Ve4(dst[I4VE4..], top, topOffset, vals); @@ -767,58 +917,126 @@ public static void EncPredLuma4(Span dst, ReadOnlySpan top, int topO Hu4(dst[I4HU4..], top, topOffset); } - private static void VerticalPred(Span dst, Span top, int size) + /// + /// Fills a block with copies of the top row. Without a top row, the block gets the value 127. + /// + /// The row operator that sets the block size. + /// The first sample of the block. + /// The top row, or an empty span when no top row exists. + private static void VerticalPred(Span dst, Span top) + where TRow : struct, IPredictionRowOperator { + int size = TRow.Size; if (!top.IsEmpty) { - for (int j = 0; j < size; j++) + if (Vector128.IsHardwareAccelerated) { - top[..size].CopyTo(dst[(j * WebpConstants.Bps)..]); + // One load of the top row, then one store of it to each row of the block. + StoreRows(dst, TRow.Load(ref MemoryMarshal.GetReference(top[..size]))); + } + else + { + for (int j = 0; j < size; j++) + { + top[..size].CopyTo(dst[(j * WebpConstants.Bps)..]); + } } } else { - Fill(dst, 127, size); + Fill(dst, 127); } } - public static void HorizontalPred(Span dst, Span left, int size) + /// + /// Fills each row of a block with the left sample of that row. Without a left column, the block gets the value 129. + /// + /// The row operator that sets the block size. + /// The first sample of the block. + /// The top-left sample followed by the left column, or an empty span when no left column exists. + private static void HorizontalPred(Span dst, Span left) + where TRow : struct, IPredictionRowOperator { + int size = TRow.Size; if (!left.IsEmpty) { left = left[1..]; // in the reference implementation, left starts at - 1. - for (int j = 0; j < size; j++) + if (Vector128.IsHardwareAccelerated) + { + // Each row is the left sample of that row in all lanes. + ref byte leftRef = ref MemoryMarshal.GetReference(left[..size]); + ref byte dstRef = ref GetBlockReference(dst); + for (nuint y = 0; y < (nuint)size; y++) + { + TRow.Store(ref Unsafe.Add(ref dstRef, y * WebpConstants.Bps), Vector128.Create(Unsafe.Add(ref leftRef, y))); + } + } + else { - dst.Slice(j * WebpConstants.Bps, size).Fill(left[j]); + for (int j = 0; j < size; j++) + { + dst.Slice(j * WebpConstants.Bps, size).Fill(left[j]); + } } } else { - Fill(dst, 129, size); + Fill(dst, 129); } } - public static void TrueMotion(Span dst, Span left, Span top, int size) + /// + /// Fills a block with the true motion prediction: the top sample plus the left sample, less the top-left sample, + /// clamped to 0 to 255. Without a top row or a left column, the prediction is the same as another mode. + /// + /// The row operator that sets the block size. + /// The first sample of the block. + /// The top-left sample followed by the left column, or an empty span when no left column exists. + /// The top row, or an empty span when no top row exists. + private static void TrueMotion(Span dst, Span left, Span top) + where TRow : struct, IPredictionRowOperator { + int size = TRow.Size; if (!left.IsEmpty) { if (!top.IsEmpty) { - Span clip = Clip1.AsSpan(255 - left[0]); // left [0] instead of left[-1], original left starts at -1 - for (int y = 0; y < size; y++) + if (Vector128.IsHardwareAccelerated) { - Span clipTable = clip[left[y + 1]..]; // left[y] - for (int x = 0; x < size; x++) + // The top row is widened to 16-bit lanes: topLow holds samples 0 to 7 and topHigh holds samples 8 to 15. + // For an 8 sample row, topHigh is zero and its result is not stored. In row y, each lane adds + // left[y] - topLeft, which is -255 to 255. Thus each sum is -255 to 510 and fits a signed 16-bit lane. + // The unsigned saturating pack clamps each sum to 0 to 255. This gives the same value as the clip table. + Vector128 topValues = TRow.Load(ref MemoryMarshal.GetReference(top[..size])); + Vector128 topLow = Vector128.WidenLower(topValues).AsInt16(); + Vector128 topHigh = Vector128.WidenUpper(topValues).AsInt16(); + ref byte leftRef = ref MemoryMarshal.GetReference(left[..(size + 1)]); + int topLeft = leftRef; + ref byte dstRef = ref GetBlockReference(dst); + for (nuint y = 0; y < (nuint)size; y++) { - dst[x] = clipTable[top[x]]; + Vector128 delta = Vector128.Create((short)(Unsafe.Add(ref leftRef, y + 1) - topLeft)); + TRow.Store(ref Unsafe.Add(ref dstRef, y * WebpConstants.Bps), Vector128_.PackUnsignedSaturate(topLow + delta, topHigh + delta)); } + } + else + { + Span clip = Clip1.AsSpan(255 - left[0]); // left [0] instead of left[-1], original left starts at -1 + for (int y = 0; y < size; y++) + { + Span clipTable = clip[left[y + 1]..]; // left[y] + for (int x = 0; x < size; x++) + { + dst[x] = clipTable[top[x]]; + } - dst = dst[WebpConstants.Bps..]; + dst = dst[WebpConstants.Bps..]; + } } } else { - HorizontalPred(dst, left, size); + HorizontalPred(dst, left); } } else @@ -829,34 +1047,37 @@ public static void TrueMotion(Span dst, Span left, Span top, i // then 129, and not 127 as in the VerticalPred case. if (!top.IsEmpty) { - VerticalPred(dst, top, size); + VerticalPred(dst, top); } else { - Fill(dst, 129, size); + Fill(dst, 129); } } } - private static void DcMode(Span dst, Span left, ReadOnlySpan top, int size, int round, int shift) + /// + /// Fills a block with the rounded mean of the top row and the left column. When only one of them exists, its sum + /// counts twice. Without both, the block gets the value 128. + /// + /// The row operator that sets the block size. + /// The first sample of the block. + /// The top-left sample followed by the left column, or an empty span when no left column exists. + /// The top row, or an empty span when no top row exists. + /// The rounding term added to the sum: the block size. + /// The right shift that divides the sum by two times the block size. + private static void DcMode(Span dst, Span left, ReadOnlySpan top, int round, int shift) + where TRow : struct, IPredictionRowOperator { - int dc = 0; - int j; + int dc; if (!top.IsEmpty) { - for (j = 0; j < size; j++) - { - dc += top[j]; - } + dc = SumRow(top); if (!left.IsEmpty) { // top and left present. - left = left[1..]; // in the reference implementation, left starts at -1. - for (j = 0; j < size; j++) - { - dc += left[j]; - } + dc += SumRow(left[1..]); // in the reference implementation, left starts at -1. } else { @@ -869,12 +1090,7 @@ private static void DcMode(Span dst, Span left, ReadOnlySpan t else if (!left.IsEmpty) { // left but no top. - left = left[1..]; // in the reference implementation, left starts at -1. - for (j = 0; j < size; j++) - { - dc += left[j]; - } - + dc = SumRow(left[1..]); // in the reference implementation, left starts at -1. dc += dc; dc = (dc + round) >> shift; } @@ -884,9 +1100,263 @@ private static void DcMode(Span dst, Span left, ReadOnlySpan t dc = 0x80; } - Fill(dst, dc, size); + Fill(dst, dc); + } + + /// + /// Returns the sum of the first samples. + /// + /// The row operator that sets the sample count. + /// The samples. + /// The sum. + [MethodImpl(InliningOptions.ShortMethod)] + private static int SumRow(ReadOnlySpan samples) + where TRow : struct, IPredictionRowOperator + { + int size = TRow.Size; + if (Vector128.IsHardwareAccelerated) + { + // The load sets the lanes after the row to zero. The absolute difference against zero is the sample itself, + // so the horizontal sum of the result is the sum of the row. + Vector128 values = TRow.Load(ref MemoryMarshal.GetReference(samples[..size])); + return (int)Vector128.Sum(Vector128_.SumAbsoluteDifferences(values, Vector128.Zero, Vector128.Zero)); + } + + int sum = 0; + for (int j = 0; j < size; j++) + { + sum += samples[j]; + } + + return sum; } + /// + /// Fills all samples of a block with one value. + /// + /// The row operator that sets the block size. + /// The first sample of the block. + /// The value, 0 to 255. + [MethodImpl(InliningOptions.ShortMethod)] + private static void Fill(Span dst, int value) + where TRow : struct, IPredictionRowOperator + { + if (Vector128.IsHardwareAccelerated) + { + StoreRows(dst, Vector128.Create((byte)value)); + } + else + { + Fill(dst, value, TRow.Size); + } + } + + /// + /// Stores one row of samples to each row of a block. + /// + /// The row operator that sets the block size. + /// The first sample of the block. + /// The row samples in the low lanes. + [MethodImpl(InliningOptions.ShortMethod)] + private static void StoreRows(Span dst, Vector128 values) + where TRow : struct, IPredictionRowOperator + { + ref byte dstRef = ref GetBlockReference(dst); + for (nuint y = 0; y < (nuint)TRow.Size; y++) + { + TRow.Store(ref Unsafe.Add(ref dstRef, y * WebpConstants.Bps), values); + } + } + + /// + /// Returns a reference to the first sample of a block, after one range check that covers all rows of the block. + /// + /// The row operator that sets the block size. + /// The first sample of the block. + /// The reference to the first sample. + [MethodImpl(InliningOptions.ShortMethod)] + private static ref byte GetBlockReference(Span dst) + where TRow : struct, IPredictionRowOperator + => ref MemoryMarshal.GetReference(dst[..(((TRow.Size - 1) * WebpConstants.Bps) + TRow.Size)]); + + /// + /// Stores the four rows of a 4x4 block. Byte x of each row value is the sample in column x. + /// + /// The first sample of the block. + /// Row 0. + /// Row 1. + /// Row 2. + /// Row 3. + [MethodImpl(InliningOptions.ShortMethod)] + private static void Store4X4(Span dst, uint row0, uint row1, uint row2, uint row3) + { + ref byte dstRef = ref MemoryMarshal.GetReference(dst[..((3 * WebpConstants.Bps) + 4)]); + Unsafe.WriteUnaligned(ref dstRef, row0); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dstRef, (nuint)WebpConstants.Bps), row1); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dstRef, (nuint)(2 * WebpConstants.Bps)), row2); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dstRef, (nuint)(3 * WebpConstants.Bps)), row3); + } + + /// + /// Returns (a + (2 * b) + c + 2) >> 2 in each byte lane, the same value as . + /// + /// The first outer samples. + /// The center samples. + /// The second outer samples. + /// The weighted averages. + [MethodImpl(InliningOptions.ShortMethod)] + private static Vector128 Avg3(Vector128 a, Vector128 b, Vector128 c) + { + // The rounded average of a and c, less the low bit of a + c, is ac = (a + c) >> 1. Let a + c = (2 * ac) + r, with r + // 0 or 1, and m = ac + b + 1. Then (a + (2 * b) + c + 2) >> 2 = ((2 * m) + r) >> 2 = m >> 1, because r cannot + // carry into bit 1. The second rounded average gives m >> 1. No lane overflows 8 bits. + Vector128 ac = Vector128_.Average(a, c) - ((a ^ c) & Vector128.One); + return Vector128_.Average(ac, b); + } + + /// + /// Writes the 4x4 true motion prediction. Each sample is the top sample plus the left sample, less the top-left + /// sample, clamped to 0 to 255. + /// + /// The first sample of the block. + /// The 13 boundary samples L K J I X A B C D E F G H. + private static void Tm4(Span dst, ReadOnlySpan boundary) + { + ref byte b = ref MemoryMarshal.GetReference(boundary); + + // The four top samples A B C D go in 16-bit lanes 0 to 3 and again in lanes 4 to 7. Thus one register holds two rows. + ulong top = Unsafe.ReadUnaligned(ref Unsafe.Add(ref b, (nuint)5)); + Vector128 topBase = Vector128.WidenLower(Vector128.CreateScalar(top | (top << 32)).AsByte()).AsInt16(); + + // The left sample of row y is boundary[3 - y]. Each delta is -255 to 255, so each sum is -255 to 510 and fits + // a signed 16-bit lane. The unsigned saturating pack clamps the sums, as the clip table of the scalar path does. + int topLeft = Unsafe.Add(ref b, (nuint)4); + short d0 = (short)(Unsafe.Add(ref b, (nuint)3) - topLeft); + short d1 = (short)(Unsafe.Add(ref b, (nuint)2) - topLeft); + short d2 = (short)(Unsafe.Add(ref b, (nuint)1) - topLeft); + short d3 = (short)(b - topLeft); + Vector128 rows01 = topBase + Vector128.Create(d0, d0, d0, d0, d1, d1, d1, d1); + Vector128 rows23 = topBase + Vector128.Create(d2, d2, d2, d2, d3, d3, d3, d3); + + // The pack gives four rows of four bytes: 32-bit lane y is row y. + Vector128 rows = Vector128_.PackUnsignedSaturate(rows01, rows23).AsUInt32(); + Store4X4(dst, rows.ToScalar(), rows.GetElement(1), rows.GetElement(2), rows.GetElement(3)); + } + + /// + /// Writes the 4x4 vertical prediction. Each column is the smoothed top sample of that column. + /// + /// The first sample of the block. + /// The 13 boundary samples L K J I X A B C D E F G H. + private static void Ve4(Span dst, ReadOnlySpan boundary) + { + // Byte lanes 0 to 7 hold X A B C D E F G. Lane x of the result is Avg3(top[x - 1], top[x], top[x + 1]). + ulong xabcdefg = Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetReference(boundary), (nuint)4)); + Vector128 avg = Avg3( + Vector128.CreateScalar(xabcdefg).AsByte(), + Vector128.CreateScalar(xabcdefg >> 8).AsByte(), + Vector128.CreateScalar(xabcdefg >> 16).AsByte()); + + uint vals = avg.AsUInt32().ToScalar(); + Store4X4(dst, vals, vals, vals, vals); + } + + /// + /// Writes the 4x4 down-right prediction. Each diagonal from top-left to bottom-right has one value. + /// + /// The first sample of the block. + /// The 13 boundary samples L K J I X A B C D E F G H. + private static void Rd4(Span dst, ReadOnlySpan boundary) + { + // The edge runs from the bottom-left sample L to the top sample D: L K J I X A B C D. Lane i of the result is + // Avg3(edge[i], edge[i + 1], edge[i + 2]). Lanes 0 to 7 hold the first 8 edge samples, and D enters at the top. + ref byte b = ref MemoryMarshal.GetReference(boundary); + ulong edge = Unsafe.ReadUnaligned(ref b); + ulong d = Unsafe.Add(ref b, (nuint)8); + Vector128 avg = Avg3( + Vector128.CreateScalar(edge).AsByte(), + Vector128.CreateScalar((edge >> 8) | (d << 56)).AsByte(), + Vector128.CreateScalar((edge >> 16) | (d << 48)).AsByte()); + + // Row y is lanes 3 - y to 6 - y. + ulong r = avg.AsUInt64().ToScalar(); + Store4X4(dst, (uint)(r >> 24), (uint)(r >> 16), (uint)(r >> 8), (uint)r); + } + + /// + /// Writes the 4x4 vertical-right prediction. + /// + /// The first sample of the block. + /// The 13 boundary samples L K J I X A B C D E F G H. + private static void Vr4(Span dst, ReadOnlySpan boundary) + { + ref byte b = ref MemoryMarshal.GetReference(boundary); + byte i = Unsafe.Add(ref b, (nuint)3); + byte j = Unsafe.Add(ref b, (nuint)2); + byte k = Unsafe.Add(ref b, (nuint)1); + byte x = Unsafe.Add(ref b, (nuint)4); + + // Byte lanes 0 to 7 hold X A B C D E F G. Lane n of abcd is Avg2(edge[n], edge[n + 1]): X A, A B, B C, C D. + // The edge with I in front is I X A B C D E F. Lane n of efgh is Avg3 of three adjacent edge samples: I X A, + // X A B, A B C, B C D. + ulong xabcdefg = Unsafe.ReadUnaligned(ref Unsafe.Add(ref b, (nuint)4)); + Vector128 xa = Vector128.CreateScalar(xabcdefg).AsByte(); + Vector128 ab = Vector128.CreateScalar(xabcdefg >> 8).AsByte(); + uint abcd = Vector128_.Average(xa, ab).AsUInt32().ToScalar(); + uint efgh = Avg3(Vector128.CreateScalar((xabcdefg << 8) | i).AsByte(), xa, ab).AsUInt32().ToScalar(); + + // Rows 2 and 3 are rows 0 and 1 moved one column to the right. Column 0 of these rows does not fit the pattern. + Store4X4(dst, abcd, efgh, (abcd << 8) | LossyUtils.Avg3(j, i, x), (efgh << 8) | LossyUtils.Avg3(k, j, i)); + } + + /// + /// Writes the 4x4 down-left prediction. Each diagonal from top-right to bottom-left has one value. + /// + /// The first sample of the block. + /// The 13 boundary samples L K J I X A B C D E F G H. + private static void Ld4(Span dst, ReadOnlySpan boundary) + { + // Byte lanes 0 to 7 hold A B C D E F G H. Lane n of the result is Avg3(top[n], top[n + 1], top[n + 2]). + // The third operand repeats H in lane 6, so lane 6 is Avg3(G, H, H). + ulong abcdefgh = Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetReference(boundary), (nuint)5)); + Vector128 avg = Avg3( + Vector128.CreateScalar(abcdefgh).AsByte(), + Vector128.CreateScalar(abcdefgh >> 8).AsByte(), + Vector128.CreateScalar((abcdefgh >> 16) | ((abcdefgh >> 56) << 48)).AsByte()); + + // Row y is lanes y to y + 3. + ulong r = avg.AsUInt64().ToScalar(); + Store4X4(dst, (uint)r, (uint)(r >> 8), (uint)(r >> 16), (uint)(r >> 24)); + } + + /// + /// Writes the 4x4 vertical-left prediction. + /// + /// The first sample of the block. + /// The 13 boundary samples L K J I X A B C D E F G H. + private static void Vl4(Span dst, ReadOnlySpan boundary) + { + // Byte lanes 0 to 7 hold A B C D E F G H. Lane n of avg2 is Avg2(top[n], top[n + 1]). + // Lane n of avg3 is Avg3(top[n], top[n + 1], top[n + 2]). + ulong abcdefgh = Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetReference(boundary), (nuint)5)); + Vector128 a = Vector128.CreateScalar(abcdefgh).AsByte(); + Vector128 bc = Vector128.CreateScalar(abcdefgh >> 8).AsByte(); + ulong avg2 = Vector128_.Average(a, bc).AsUInt64().ToScalar(); + ulong avg3 = Avg3(a, bc, Vector128.CreateScalar(abcdefgh >> 16).AsByte()).AsUInt64().ToScalar(); + + // Rows 2 and 3 are rows 0 and 1 moved one column to the left. Column 3 of these rows does not fit the pattern: + // it is avg3 lane 4 in row 2 and avg3 lane 5 in row 3. + uint row2 = ((uint)(avg2 >> 8) & 0x00FFFFFFu) | ((uint)(avg3 >> 32) << 24); + uint row3 = ((uint)(avg3 >> 8) & 0x00FFFFFFu) | ((uint)(avg3 >> 40) << 24); + Store4X4(dst, (uint)avg2, (uint)avg3, row2, row3); + } + + /// + /// Writes the 4x4 DC prediction: the rounded mean of the 4 top samples and the 4 left samples. + /// + /// The first sample of the block. + /// The boundary samples, in the layout of . + /// The index of the top sample A in . private static void Dc4(Span dst, ReadOnlySpan top, int topOffset) { uint dc = 4; @@ -899,6 +1369,13 @@ private static void Dc4(Span dst, ReadOnlySpan top, int topOffset) Fill(dst, (int)(dc >> 3), 4); } + /// + /// Writes the 4x4 true motion prediction. Each sample is the top sample plus the left sample, less the top-left sample, + /// clamped to 0 to 255. This is the scalar form. + /// + /// The first sample of the block. + /// The boundary samples, in the layout of . + /// The index of the top sample A in . private static void Tm4(Span dst, ReadOnlySpan top, int topOffset) { Span clip = Clip1.AsSpan(255 - top[topOffset - 1]); @@ -914,6 +1391,13 @@ private static void Tm4(Span dst, ReadOnlySpan top, int topOffset) } } + /// + /// Writes the 4x4 vertical prediction. Each column is the smoothed top sample of that column. This is the scalar form. + /// + /// The first sample of the block. + /// The boundary samples, in the layout of . + /// The index of the top sample A in . + /// A scratch buffer of 4 samples that gets the smoothed top row. private static void Ve4(Span dst, ReadOnlySpan top, int topOffset, Span vals) { // vertical @@ -927,6 +1411,12 @@ private static void Ve4(Span dst, ReadOnlySpan top, int topOffset, S } } + /// + /// Writes the 4x4 horizontal prediction. Each row is the smoothed left sample of that row. + /// + /// The first sample of the block. + /// The boundary samples, in the layout of . + /// The index of the top sample A in . private static void He4(Span dst, ReadOnlySpan top, int topOffset) { // horizontal @@ -946,6 +1436,12 @@ private static void He4(Span dst, ReadOnlySpan top, int topOffset) BinaryPrimitives.WriteUInt32BigEndian(dst[(3 * WebpConstants.Bps)..], val); } + /// + /// Writes the 4x4 down-right prediction. Each diagonal from top-left to bottom-right has one value. This is the scalar form. + /// + /// The first sample of the block. + /// The boundary samples, in the layout of . + /// The index of the top sample A in . private static void Rd4(Span dst, ReadOnlySpan top, int topOffset) { byte x = top[topOffset - 1]; @@ -981,6 +1477,12 @@ private static void Rd4(Span dst, ReadOnlySpan top, int topOffset) LossyUtils.Dst(dst, 3, 0, LossyUtils.Avg3(d, c, b)); } + /// + /// Writes the 4x4 vertical-right prediction. This is the scalar form. + /// + /// The first sample of the block. + /// The boundary samples, in the layout of . + /// The index of the top sample A in . private static void Vr4(Span dst, ReadOnlySpan top, int topOffset) { byte x = top[topOffset - 1]; @@ -1016,6 +1518,12 @@ private static void Vr4(Span dst, ReadOnlySpan top, int topOffset) LossyUtils.Dst(dst, 3, 1, LossyUtils.Avg3(b, c, d)); } + /// + /// Writes the 4x4 down-left prediction. Each diagonal from top-right to bottom-left has one value. This is the scalar form. + /// + /// The first sample of the block. + /// The boundary samples, in the layout of . + /// The index of the top sample A in . private static void Ld4(Span dst, ReadOnlySpan top, int topOffset) { byte a = top[topOffset + 0]; @@ -1050,6 +1558,12 @@ private static void Ld4(Span dst, ReadOnlySpan top, int topOffset) LossyUtils.Dst(dst, 3, 3, LossyUtils.Avg3(g, h, h)); } + /// + /// Writes the 4x4 vertical-left prediction. This is the scalar form. + /// + /// The first sample of the block. + /// The boundary samples, in the layout of . + /// The index of the top sample A in . private static void Vl4(Span dst, ReadOnlySpan top, int topOffset) { byte a = top[topOffset + 0]; @@ -1085,6 +1599,12 @@ private static void Vl4(Span dst, ReadOnlySpan top, int topOffset) LossyUtils.Dst(dst, 3, 3, LossyUtils.Avg3(f, g, h)); } + /// + /// Writes the 4x4 horizontal-down prediction. + /// + /// The first sample of the block. + /// The boundary samples, in the layout of . + /// The index of the top sample A in . private static void Hd4(Span dst, ReadOnlySpan top, int topOffset) { byte x = top[topOffset - 1]; @@ -1120,6 +1640,12 @@ private static void Hd4(Span dst, ReadOnlySpan top, int topOffset) LossyUtils.Dst(dst, 1, 3, LossyUtils.Avg3(l, k, j)); } + /// + /// Writes the 4x4 horizontal-up prediction. It reads only the left samples. The samples below the left column repeat L. + /// + /// The first sample of the block. + /// The boundary samples, in the layout of . + /// The index of the top sample A in . private static void Hu4(Span dst, ReadOnlySpan top, int topOffset) { byte i = top[topOffset - 2]; @@ -1149,6 +1675,12 @@ private static void Hu4(Span dst, ReadOnlySpan top, int topOffset) LossyUtils.Dst(dst, 3, 3, l); } + /// + /// Fills a square block with one value. + /// + /// The first sample of the block. The rows have a stride of . + /// The value of each sample. + /// The width and the height of the block. [MethodImpl(InliningOptions.ShortMethod)] private static void Fill(Span dst, int value, int size) { @@ -1158,13 +1690,31 @@ private static void Fill(Span dst, int value, int size) } } + /// + /// Clamps a value to 0 to 255. + /// + /// The value. + /// The clamped value. [MethodImpl(InliningOptions.ShortMethod)] private static byte Clip8b(int v) => (v & ~0xff) == 0 ? (byte)v : v < 0 ? (byte)0 : (byte)255; + /// + /// Adds one descaled inverse transform value to a prediction sample, clamps the sum to 0 to 255 and stores it. + /// + /// The first destination sample of the block. + /// The first prediction sample of the block. + /// The offset of the sample in the block. + /// The inverse transform value before the descale by 8. [MethodImpl(InliningOptions.ShortMethod)] - private static void Store(Span dst, ReadOnlySpan reference, int x, int y, int v) - => dst[x + (y * WebpConstants.Bps)] = LossyUtils.Clip8B(reference[x + (y * WebpConstants.Bps)] + (v >> 3)); - + private static void Store(ref byte dst, ref byte reference, nuint offset, int v) + => Unsafe.Add(ref dst, offset) = Numerics.ClampToByte(Unsafe.Add(ref reference, offset) + (v >> 3)); + + /// + /// Multiplies a value by a 16.16 fixed-point multiplier. + /// + /// The value. + /// The multiplier in 16.16 fixed point. + /// (a * b) >> 16. [MethodImpl(InliningOptions.ShortMethod)] private static int Mul(int a, int b) => (a * b) >> 16; } diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8FilterInfo.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8FilterInfo.cs index e5169a41d2..447704e431 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8FilterInfo.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8FilterInfo.cs @@ -6,58 +6,21 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy; /// /// Filter information. /// -internal class Vp8FilterInfo : IDeepCloneable +/// +/// The decoder computes one value for each segment and macroblock type, and copies it for each macroblock. A struct makes the copy an assignment with no +/// allocation. clamps the levels, so each value is in its range. +/// +internal struct Vp8FilterInfo { - private byte limit; - - private byte innerLevel; - - private byte highEdgeVarianceThreshold; - - /// - /// Initializes a new instance of the class. - /// - public Vp8FilterInfo() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The filter info to create a copy from. - public Vp8FilterInfo(Vp8FilterInfo other) - { - this.Limit = other.Limit; - this.HighEdgeVarianceThreshold = other.HighEdgeVarianceThreshold; - this.InnerLevel = other.InnerLevel; - this.UseInnerFiltering = other.UseInnerFiltering; - } - /// /// Gets or sets the filter limit in [3..189], or 0 if no filtering. /// - public byte Limit - { - get => this.limit; - set - { - Guard.MustBeBetweenOrEqualTo(value, (byte)0, (byte)189, nameof(this.Limit)); - this.limit = value; - } - } + public byte Limit { get; set; } /// /// Gets or sets the inner limit in [1..63], or 0 if no filtering. /// - public byte InnerLevel - { - get => this.innerLevel; - set - { - Guard.MustBeBetweenOrEqualTo(value, (byte)0, (byte)63, nameof(this.InnerLevel)); - this.innerLevel = value; - } - } + public byte InnerLevel { get; set; } /// /// Gets or sets a value indicating whether to do inner filtering. @@ -67,16 +30,5 @@ public byte InnerLevel /// /// Gets or sets the high edge variance threshold in [0..2]. /// - public byte HighEdgeVarianceThreshold - { - get => this.highEdgeVarianceThreshold; - set - { - Guard.MustBeBetweenOrEqualTo(value, (byte)0, (byte)2, nameof(this.HighEdgeVarianceThreshold)); - this.highEdgeVarianceThreshold = value; - } - } - - /// - public IDeepCloneable DeepClone() => new Vp8FilterInfo(this); + public byte HighEdgeVarianceThreshold { get; set; } } diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Histogram.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Histogram.cs index a8d6d8b6e8..9017211eec 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Histogram.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Histogram.cs @@ -4,7 +4,6 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; -using System.Runtime.Intrinsics.X86; namespace SixLabors.ImageSharp.Formats.Webp.Lossy; @@ -22,8 +21,14 @@ internal struct Vp8Histogram /// private const int MaxCoeffThresh = 31; + /// + /// The largest count of any bin. + /// private int maxValue; + /// + /// The index of the last bin with a non-zero count. The value is at least 1. + /// private int lastNonZero; /// @@ -35,6 +40,10 @@ public Vp8Histogram() this.lastNonZero = 1; } + /// + /// Gets the alpha of the histogram: AlphaScale * lastNonZero / maxValue, or 0 when the largest bin count is at most 1. + /// + /// The alpha value. This method does not clip it. public readonly int GetAlpha() { // 'alpha' will later be clipped to [0..MAX_ALPHA] range, clamping outer @@ -46,54 +55,115 @@ public readonly int GetAlpha() return alpha; } + /// + /// Sets this histogram from the forward transform coefficients of the difference between the reference and the + /// prediction, for the 4x4 blocks from up to, but not including, . + /// + /// + /// The luma blocks 0 to 15 and the chroma blocks 16 to 23 come in pairs of horizontally adjacent blocks, from an even index. Each pair uses one + /// two-block forward transform. A range of one block uses the one-block transform. + /// + /// The source samples. + /// The predicted samples. + /// The index of the first 4x4 block. + /// The index after the last 4x4 block. public void CollectHistogram(Span reference, Span pred, int startBlock, int endBlock) { - Span scratch = stackalloc int[16]; - Span output = stackalloc short[16]; - Span distribution = stackalloc int[MaxCoeffThresh + 1]; - - int j; - for (j = startBlock; j < endBlock; j++) + // The forward transforms write all entries of scratch and output before they read them. The default value of an + // inline array is zero, which the distribution counts need. MaxCoeffThresh + 1 is 32 bins. + InlineArray16 scratch = default; + InlineArray32 output = default; + InlineArray32 distribution = default; + + ref byte referenceRef = ref MemoryMarshal.GetReference(reference); + ref byte predRef = ref MemoryMarshal.GetReference(pred); + ref short outputRef = ref output[0]; + ref int scratchRef = ref scratch[0]; + for (int j = startBlock; j < endBlock; j += 2) { - Vp8Encoding.FTransform(reference[WebpLookupTables.Vp8DspScan[j]..], pred[WebpLookupTables.Vp8DspScan[j]..], output, scratch); - - // Convert coefficients to bin. - if (Avx2.IsSupported) + nuint offset = (nuint)WebpLookupTables.Vp8DspScan[j]; + nuint coefficients = 16; + if (endBlock - j >= 2) { - // Load. - ref short outputRef = ref MemoryMarshal.GetReference(output); - Vector256 out0 = Unsafe.As>(ref outputRef); - - // v = abs(out) >> 3 - Vector256 abs0 = Avx2.Abs(out0.AsInt16()); - Vector256 v0 = Avx2.ShiftRightArithmetic(abs0.AsInt16(), 3); - - // bin = min(v, MAX_COEFF_THRESH) - Vector256 min0 = Avx2.Min(v0, Vector256.Create((short)MaxCoeffThresh)); + Vp8Encoding.FTransform2( + ref Unsafe.Add(ref referenceRef, offset), + ref Unsafe.Add(ref predRef, offset), + ref outputRef, + ref Unsafe.Add(ref outputRef, (nuint)16), + ref scratchRef); + + coefficients = 32; + } + else + { + Vp8Encoding.FTransform(ref Unsafe.Add(ref referenceRef, offset), ref Unsafe.Add(ref predRef, offset), ref outputRef, ref scratchRef); + } - // Store. - Unsafe.As>(ref outputRef) = min0; + // Replace each coefficient with its bin. The coefficients of one or two blocks are contiguous, so the widest + // accelerated width takes them all: a 512-bit vector holds two blocks and a 256-bit vector one block. + nuint k = 0; + if (Vector512.IsHardwareAccelerated) + { + for (; k + (uint)Vector512.Count <= coefficients; k += (uint)Vector512.Count) + { + Bin(Vector512.LoadUnsafe(ref outputRef, k)).StoreUnsafe(ref outputRef, k); + } + } - // Convert coefficients to bin. - for (int k = 0; k < 16; ++k) + if (Vector256.IsHardwareAccelerated) + { + for (; k + (uint)Vector256.Count <= coefficients; k += (uint)Vector256.Count) { - ++distribution[output[k]]; + Bin(Vector256.LoadUnsafe(ref outputRef, k)).StoreUnsafe(ref outputRef, k); } } - else + + if (Vector128.IsHardwareAccelerated) { - for (int k = 0; k < 16; ++k) + for (; k + (uint)Vector128.Count <= coefficients; k += (uint)Vector128.Count) { - int v = Math.Abs(output[k]) >> 3; - int clippedValue = ClipMax(v, MaxCoeffThresh); - ++distribution[clippedValue]; + Bin(Vector128.LoadUnsafe(ref outputRef, k)).StoreUnsafe(ref outputRef, k); } } + + for (; k < coefficients; k++) + { + ref short coefficient = ref Unsafe.Add(ref outputRef, k); + coefficient = (short)ClipMax(Math.Abs(coefficient) >> 3, MaxCoeffThresh); + } + + for (nuint i = 0; i < coefficients; i++) + { + ++distribution[Unsafe.Add(ref outputRef, i)]; + } } this.SetHistogramData(distribution); } + /// + /// Gets the bin of each coefficient: min(abs(coefficient) >> 3, MaxCoeffThresh). + /// + /// + /// The absolute value is read as unsigned 16-bit. Thus the absolute value of -32768 is 32768, as in the 32-bit + /// scalar arithmetic, and its bin is MaxCoeffThresh. + /// + /// The coefficients, one in each lane. + /// The bins, one in each lane. + [MethodImpl(InliningOptions.ShortMethod)] + private static Vector128 Bin(Vector128 coefficients) + => Vector128.Min(Vector128.Abs(coefficients).AsUInt16() >>> 3, Vector128.Create((ushort)MaxCoeffThresh)).AsInt16(); + + /// + [MethodImpl(InliningOptions.ShortMethod)] + private static Vector256 Bin(Vector256 coefficients) + => Vector256.Min(Vector256.Abs(coefficients).AsUInt16() >>> 3, Vector256.Create((ushort)MaxCoeffThresh)).AsInt16(); + + /// + [MethodImpl(InliningOptions.ShortMethod)] + private static Vector512 Bin(Vector512 coefficients) + => Vector512.Min(Vector512.Abs(coefficients).AsUInt16() >>> 3, Vector512.Create((ushort)MaxCoeffThresh)).AsInt16(); + /// /// Raises the maximum value and the last-non-zero index of to those of this /// histogram, so that accumulates the best candidate of every block. @@ -112,6 +182,11 @@ public readonly void Merge(ref Vp8Histogram other) } } + /// + /// Sets the largest bin count and the index of the last non-zero bin from . + /// The last-non-zero index is 1 when no bin above 0 is non-zero. + /// + /// The count of each bin. It holds at least MaxCoeffThresh + 1 entries. private void SetHistogramData(ReadOnlySpan distribution) { int maxValue = 0; @@ -134,6 +209,12 @@ private void SetHistogramData(ReadOnlySpan distribution) this.lastNonZero = lastNonZero; } + /// + /// Limits to at most . + /// + /// The value to limit. + /// The upper limit. + /// The smaller of and . [MethodImpl(InliningOptions.ShortMethod)] private static int ClipMax(int v, int max) => v > max ? max : v; } diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Io.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Io.cs deleted file mode 100644 index fdfca0c3d8..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Io.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossy; - -internal ref struct Vp8Io -{ - /// - /// Gets or sets the picture width in pixels (invariable). - /// The actual area passed to put() is stored in /> field. - /// - public int Width { get; set; } - - /// - /// Gets or sets the picture height in pixels (invariable). - /// The actual area passed to put() is stored in /> field. - /// - public int Height { get; set; } - - /// - /// Gets or sets the y-position of the current macroblock. - /// - public int MbY { get; set; } - - /// - /// Gets or sets number of columns in the sample. - /// - public int MbW { get; set; } - - /// - /// Gets or sets number of rows in the sample. - /// - public int MbH { get; set; } - - /// - /// Gets or sets the luma component. - /// - public Span Y { get; set; } - - /// - /// Gets or sets the U chroma component. - /// - public Span U { get; set; } - - /// - /// Gets or sets the V chroma component. - /// - public Span V { get; set; } - - /// - /// Gets or sets the row stride for luma. - /// - public int YStride { get; set; } - - /// - /// Gets or sets the row stride for chroma. - /// - public int UvStride { get; set; } - - public bool UseScaling { get; set; } - - public int ScaledWidth { get; set; } - - public int ScaledHeight { get; set; } -} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8MacroBlock.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8MacroBlock.cs index 03e5526a7c..b9c02c49e0 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8MacroBlock.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8MacroBlock.cs @@ -6,7 +6,11 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy; /// /// Contextual macroblock information. /// -internal class Vp8MacroBlock +/// +/// The decoder keeps one value for each macroblock column in a pooled buffer, and one value for the macroblock to the left. A struct needs no +/// allocation for each column, and the decoder changes each value in place through a reference. +/// +internal struct Vp8MacroBlock { /// /// Gets or sets non-zero AC/DC coeffs (4bit for luma + 4bit for chroma). diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8MacroBlockData.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8MacroBlockData.cs index f233e178c6..53fdd73b3e 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8MacroBlockData.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8MacroBlockData.cs @@ -6,32 +6,23 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy; /// /// Data needed to reconstruct a macroblock. /// -internal class Vp8MacroBlockData +/// +/// The coefficients of the macroblock are in , so the decoder allocates them once in pooled memory. +/// The decoder keeps one value for each macroblock column in the pooled buffer . A struct with inline +/// modes needs no allocation for each column, and the decoder changes each value in place through a reference. +/// +internal struct Vp8MacroBlockData { /// - /// Initializes a new instance of the class. + /// The modes. One 16x16 mode (#0) or sixteen 4x4 modes. This is a field, so that the decoder can write the modes in place. /// - public Vp8MacroBlockData() - { - this.Modes = new byte[16]; - this.Coeffs = new short[384]; - } - - /// - /// Gets or sets the coefficients. 384 coeffs = (16+4+4) * 4*4. - /// - public short[] Coeffs { get; set; } + public InlineArray16 Modes; /// /// Gets or sets a value indicating whether its intra4x4. /// public bool IsI4x4 { get; set; } - /// - /// Gets the modes. One 16x16 mode (#0) or sixteen 4x4 modes. - /// - public byte[] Modes { get; } - /// /// Gets or sets the chroma prediction mode. /// @@ -59,7 +50,13 @@ public Vp8MacroBlockData() /// public uint NonZeroUv { get; set; } + /// + /// Gets or sets a value indicating whether the macroblock has no non-zero coefficients. + /// public bool Skip { get; set; } + /// + /// Gets or sets the segment of the macroblock. It selects the quantizer and the filter strength. + /// public byte Segment { get; set; } } diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8MacroBlockInfo.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8MacroBlockInfo.cs index f2fa852f80..a61e6b491c 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8MacroBlockInfo.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8MacroBlockInfo.cs @@ -5,16 +5,38 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy; +/// +/// Holds the mode decisions and the segment data of one macroblock for the encoder. +/// +/// +/// The encoder keeps one value for each macroblock in one pooled buffer, so the type is a struct. The default value is +/// a 4x4 prediction, chroma mode 0, no skip, segment 0 and susceptibility 0. +/// [DebuggerDisplay("Type: {MacroBlockType}, Alpha: {Alpha}, UvMode: {UvMode}")] -internal class Vp8MacroBlockInfo +internal struct Vp8MacroBlockInfo { + /// + /// Gets or sets the luma prediction type: 16x16 or 4x4. + /// public Vp8MacroBlockType MacroBlockType { get; set; } + /// + /// Gets or sets the chroma prediction mode. + /// public int UvMode { get; set; } + /// + /// Gets or sets a value indicating whether all quantized coefficients are zero, so the macroblock can be skipped. + /// public bool Skip { get; set; } + /// + /// Gets or sets the segment, from 0 to 3. + /// public int Segment { get; set; } + /// + /// Gets or sets the susceptibility. The analysis stores the mixed susceptibility, and the segment assignment replaces it with the segment center. + /// public int Alpha { get; set; } } diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8ModeScore.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8ModeScore.cs index 4f52db0fe9..61736ff0ca 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8ModeScore.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8ModeScore.cs @@ -8,6 +8,9 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy; /// internal class Vp8ModeScore { + /// + /// The score that marks a mode as not evaluated. Any evaluated score is lower. + /// public const long MaxCost = 0x7fffffffffffffL; /// @@ -15,6 +18,11 @@ internal class Vp8ModeScore /// private const int RdDistoMult = 256; + /// + /// The chroma DC diffusion errors. The chroma reconstruction writes all six errors before any read. + /// + private Vp8DiffusionErrors derr; + /// /// Initializes a new instance of the class. /// @@ -25,7 +33,6 @@ public Vp8ModeScore() this.UvLevels = new short[(4 + 4) * 16]; this.ModesI4 = new byte[16]; - this.Derr = new int[2, 3]; } /// @@ -89,19 +96,13 @@ public Vp8ModeScore() public uint Nz { get; set; } /// - /// Gets the diffusion errors. + /// Gets a reference to the chroma DC diffusion errors. /// - public int[,] Derr { get; } - - public void Clear() - { - Array.Clear(this.YDcLevels); - Array.Clear(this.YAcLevels); - Array.Clear(this.UvLevels); - Array.Clear(this.ModesI4); - Array.Clear(this.Derr); - } + public ref Vp8DiffusionErrors Derr => ref this.derr; + /// + /// Sets the distortions, the rate, the header bits and the non-zero flags to 0, and sets the score to . + /// public void InitScore() { this.D = 0; @@ -112,6 +113,11 @@ public void InitScore() this.Score = MaxCost; } + /// + /// Copies the distortions, the rate, the header bits, the non-zero flags and the score from . + /// The levels and the modes do not change. + /// + /// The score to copy from. public void CopyScore(Vp8ModeScore other) { this.D = other.D; @@ -122,6 +128,11 @@ public void CopyScore(Vp8ModeScore other) this.Score = other.Score; } + /// + /// Adds the distortions, the rate, the header bits and the score of to this score. + /// The non-zero flags of are combined with a bitwise OR. + /// + /// The score to add. public void AddScore(Vp8ModeScore other) { this.D += other.D; @@ -132,5 +143,9 @@ public void AddScore(Vp8ModeScore other) this.Score += other.Score; } + /// + /// Sets the rate-distortion score: (rate + header bits) * lambda + RdDistoMult * (distortion + spectral distortion). + /// + /// The weight of the rate and the header bits against the distortion. public void SetRdScore(int lambda) => this.Score = ((this.R + this.H) * lambda) + (RdDistoMult * (this.D + this.SD)); } diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8PictureHeader.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8PictureHeader.cs index 627f036cec..2e29e258eb 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8PictureHeader.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8PictureHeader.cs @@ -15,16 +15,6 @@ internal class Vp8PictureHeader /// public uint Height { get; set; } - /// - /// Gets or sets the horizontal scale. - /// - public sbyte XScale { get; set; } - - /// - /// Gets or sets the vertical scale. - /// - public sbyte YScale { get; set; } - /// /// Gets or sets the colorspace. /// 0 - YUV color space similar to the YCrCb color space defined in. diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Proba.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Proba.cs deleted file mode 100644 index b69d3a7443..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Proba.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossy; - -/// -/// Data for all frame-persistent probabilities. -/// -internal class Vp8Proba -{ - private const int MbFeatureTreeProbs = 3; - - /// - /// Initializes a new instance of the class. - /// - public Vp8Proba() - { - // A frame that does not send the segment map probabilities uses 255 for each, as libwebp does. - this.Segments = new uint[MbFeatureTreeProbs]; - this.Segments.AsSpan().Fill(255); - this.Bands = new Vp8BandProbas[WebpConstants.NumTypes, WebpConstants.NumBands]; - this.BandsPtr = new Vp8BandProbas[WebpConstants.NumTypes][]; - - for (int i = 0; i < WebpConstants.NumTypes; i++) - { - for (int j = 0; j < WebpConstants.NumBands; j++) - { - this.Bands[i, j] = new Vp8BandProbas(); - } - } - - for (int i = 0; i < WebpConstants.NumTypes; i++) - { - this.BandsPtr[i] = new Vp8BandProbas[16 + 1]; - } - } - - public uint[] Segments { get; } - - public Vp8BandProbas[,] Bands { get; } - - public Vp8BandProbas[][] BandsPtr { get; } -} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8ProbaArray.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8ProbaArray.cs deleted file mode 100644 index 3375275424..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8ProbaArray.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossy; - -/// -/// Probabilities associated to one of the contexts. -/// -internal class Vp8ProbaArray -{ - /// - /// Initializes a new instance of the class. - /// - public Vp8ProbaArray() => this.Probabilities = new byte[WebpConstants.NumProbas]; - - /// - /// Gets the probabilities. - /// - public byte[] Probabilities { get; } -} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Probabilities.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Probabilities.cs new file mode 100644 index 0000000000..79c3d58a45 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Probabilities.cs @@ -0,0 +1,59 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.ImageSharp.Formats.Webp.Lossy; + +/// +/// The probabilities of a VP8 frame: the segment map tree and the coefficient tokens. +/// +internal class Vp8Probabilities +{ + /// + /// The number of token positions in the coefficient table: the 16 coefficients, and one more for the read after the last coefficient. + /// + public const int NumPositions = 16 + 1; + + /// + /// The distance between the probabilities of two contexts. + /// + public const int ContextStride = WebpConstants.NumProbas; + + /// + /// The distance between the probabilities of two token positions. + /// + public const int PositionStride = WebpConstants.NumCtx * ContextStride; + + /// + /// The distance between the probabilities of two block types. + /// + public const int TypeStride = NumPositions * PositionStride; + + /// + /// The number of probabilities in the segment tree. + /// + private const int MbFeatureTreeProbs = 3; + + /// + /// Initializes a new instance of the class. + /// + public Vp8Probabilities() + { + this.Segments = new uint[MbFeatureTreeProbs]; + this.Segments.AsSpan().Fill(255); + this.Coefficients = new byte[WebpConstants.NumTypes * TypeStride]; + } + + /// + /// Gets the probabilities of the segment map tree. + /// + public uint[] Segments { get; } + + /// + /// Gets the coefficient token probabilities, in the layout [type][position][context][probability]. + /// + /// + /// The frame header gives the probabilities for each of the 8 bands. The table holds a copy for each token position, with the band of the position. Thus + /// the token loop reads a probability with one offset, with no lookup of the band. See RFC 6386, section 13. + /// + public byte[] Coefficients { get; } +} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8QuantMatrix.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8QuantMatrix.cs deleted file mode 100644 index 27fc29f6e3..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8QuantMatrix.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossy; - -internal class Vp8QuantMatrix -{ - private int dither; - - public int[] Y1Mat { get; } = new int[2]; - - public int[] Y2Mat { get; } = new int[2]; - - public int[] UvMat { get; } = new int[2]; - - /// - /// Gets or sets the U/V quantizer value. - /// - public int UvQuant { get; set; } - - /// - /// Gets or sets the dithering amplitude (0 = off, max=255). - /// - public int Dither - { - get => this.dither; - set - { - Guard.MustBeBetweenOrEqualTo(value, 0, 255, nameof(this.Dither)); - this.dither = value; - } - } -} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Quantization.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Quantization.cs new file mode 100644 index 0000000000..cdcbb152cb --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Quantization.cs @@ -0,0 +1,1594 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Common.Helpers; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossy; + +/// +/// Quantization methods. +/// +internal static class Vp8Quantization +{ + /// + /// The largest magnitude of a quantized level. + /// + private const int MaxLevel = 2047; + + /// + /// The coefficient type of the AC coefficients of an intra 16x16 block. The DC coefficient of these blocks is in the Y2 block. + /// + private const int TypeI16Ac = 0; + + /// + /// The coefficient type of an intra 4x4 block. + /// + private const int TypeI4Ac = 3; + + /// + /// The number of levels that the trellis tests for each coefficient: the level with a neutral rounding, and that level plus one. + /// + private const int TrellisNodes = 2; + + /// + /// The weight, in units of 1 / (1 << DSHIFT), of the DC error that goes to the 4x4 block below. + /// + /// + /// The weights diffuse 15/16 of the error, a small under-correction. This prevents a chessboard pattern of blocks near q = 0. + /// + private const int C1 = 7; // fraction of error sent to the 4x4 block below + + /// + /// The weight, in units of 1 / (1 << DSHIFT), of the DC error that goes to the 4x4 block on the right. + /// + private const int C2 = 8; // fraction of error sent to the 4x4 block on the right + + /// + /// The number of fraction bits of the diffusion weights and . + /// + private const int DSHIFT = 4; + + /// + /// The right shift that is applied to a stored DC error, so that the error fits a signed byte. + /// + private const int DSCALE = 1; // storage descaling, needed to make the error fit byte + + /// + /// The offset between the two reconstruction buffers of the 4x4 mode pairs in . + /// Each buffer has 4 rows of 8 samples: the reconstructions of the two modes of a pair side by side. + /// + private const int PairBufferOffset = 8; + + /// + /// Gets the luma weights of the spectral distortion, one for each coefficient of a 4x4 block in raster order. + /// Low frequencies have larger weights. + /// + /// + /// The weights form a symmetric 4x4 matrix in row-major order. The data comes from the static data of the assembly, so the property allocates no memory. + /// + private static ReadOnlySpan WeightY => [38, 32, 20, 9, 32, 28, 17, 7, 20, 17, 10, 4, 9, 7, 4, 2]; + + /// + /// Gets the weights of the quantization error of the trellis, one for each coefficient of a 4x4 block in raster order. + /// Low frequencies have larger weights. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates no memory. + /// + private static ReadOnlySpan WeightTrellis => [30, 27, 19, 11, 27, 24, 17, 10, 19, 17, 12, 8, 11, 10, 8, 6]; + + /// + /// Selects the intra 16x16 mode with the lowest rate-distortion score for the current macroblock and sets it on the iterator. + /// + /// + /// The luma reconstruction of the selected mode goes to the output buffer of the iterator. The final score uses the mode lambda + /// of the segment. The method also computes the spectral distortion sums of the source, which reads. + /// When only the DC levels are non-zero and the distortion is above the segment minimum, the segment records the largest DC delta. + /// + /// The iterator at the current macroblock. + /// + /// The score that gets the selected mode, its levels and its score. On return, it can refer to a different instance: + /// the method exchanges it with the scratch score of the iterator when the scratch score holds the best result. + /// + /// The segment parameters. The segment of the macroblock selects the entry. + /// The probabilities that give the coefficient costs. + public static void PickBestIntra16(Vp8EncoderIterator it, ref Vp8ModeScore rd, Vp8SegmentInfo[] segmentInfos, Vp8EncoderProbabilities proba) + { + const int numBlocks = 16; + Vp8SegmentInfo dqm = segmentInfos[it.CurrentMacroBlockInfo.Segment]; + int lambda = dqm.LambdaI16; + int tlambda = dqm.TLambda; + Span src = it.YuvIn[Vp8EncoderIterator.YOffEnc..]; + ref int scratch = ref MemoryMarshal.GetReference(it.Scratch3); + ref ushort weights = ref MemoryMarshal.GetReference(WeightY); + + // The spectral distortion compares the weighted Hadamard sums of the source blocks and of the reconstructed + // blocks. The source does not change between the modes, or between this search and PickBestIntra4, so its sums + // are computed once for the macroblock. The segment setup keeps tlambda at 1 or more, so the spectral distortion always applies. + ref int srcSums = ref MemoryMarshal.GetReference(it.SourceSums); + LossyUtils.TTransformSums16X16(ref MemoryMarshal.GetReference(src), ref weights, ref srcSums, ref scratch); + + // Reuse the iterator scratch accumulator instead of allocating one per macroblock. + // No clear is necessary. For each mode, the reconstruction writes all luma DC and AC levels + // before the cost and flatness checks read them, and all score fields are set before SetRdScore. + Vp8ModeScore rdTmp = it.RdScratch; + Vp8Residual res = it.ResidualScratch; + Vp8ModeScore rdCur = rdTmp; + Vp8ModeScore rdBest = rd; + int mode; + bool isFlat = IsFlatSource16(src); + rd.ModeI16 = -1; + for (mode = 0; mode < WebpConstants.NumPredModes; ++mode) + { + // Scratch buffer. SwapOut below exchanges the output buffers, so each mode gets YuvOut2 again. + Span tmpDst = it.YuvOut2[Vp8EncoderIterator.YOffEnc..]; + ref byte tmpDstRef = ref MemoryMarshal.GetReference(tmpDst); + rdCur.ModeI16 = mode; + + // Reconstruct. + rdCur.Nz = (uint)ReconstructIntra16(it, dqm, rdCur, proba, ref tmpDstRef, mode); + + // Measure RD-score. + rdCur.D = LossyUtils.Vp8_Sse16x16(src, tmpDst); + rdCur.SD = Mult8B(tlambda, LossyUtils.Vp8Disto16X16(ref srcSums, ref tmpDstRef, ref weights, ref scratch)); + rdCur.H = WebpConstants.Vp8FixedCostsI16[mode]; + rdCur.R = it.GetCostLuma16(rdCur, proba, res); + + if (isFlat) + { + // Refine the first impression (which was in pixel space). + isFlat = IsFlat(ref MemoryMarshal.GetArrayDataReference(rdCur.YAcLevels), numBlocks, WebpConstants.FlatnessLimitI16); + if (isFlat) + { + // Block is very flat. We put emphasis on the distortion being very low! + rdCur.D *= 2; + rdCur.SD *= 2; + } + } + + // The search always checks Intra16 first, so it can overwrite *rd directly. + rdCur.SetRdScore(lambda); + + if (mode == 0 || rdCur.Score < rdBest.Score) + { + RuntimeUtility.Swap(ref rdBest, ref rdCur); + it.SwapOut(); + } + } + + // The rejected accumulator becomes the scratch instance for the next macroblock. When the + // best result lives in the scratch instance, the caller's reference is exchanged for it so + // that no levels need to be copied. + it.RdScratch = rdCur; + if (rdBest != rd) + { + rd = rdBest; + } + + // Finalize score for mode decision. + rd.SetRdScore(dqm.LambdaMode); + it.SetIntra16Mode(rd.ModeI16); + + // We have a blocky macroblock (only DCs are non-zero) with fairly high + // distortion, record max delta so we can later adjust the minimal filtering + // strength needed to smooth these blocks out. + if ((rd.Nz & 0x100ffff) == 0x1000000 && rd.D > dqm.MinDisto) + { + dqm.StoreMaxDelta(rd.YDcLevels); + } + } + + /// + /// Selects the intra 4x4 mode with the lowest rate-distortion score for each 4x4 block of the current macroblock. + /// The method compares the total score with the score in . + /// + /// + /// The search stops early when the accumulated score reaches the score in , or when the header bits + /// exceed . Call first: it computes the spectral distortion sums. + /// + /// The iterator at the current macroblock. + /// + /// The score of the intra 16x16 decision. When the method returns , it gets the intra 4x4 modes, levels and score. + /// When the method returns , the intra 4x4 modes can be partly written. + /// + /// The segment parameters. The segment of the macroblock selects the entry. + /// The probabilities that give the coefficient costs. + /// The largest total header bits of the 16 modes. The value 0 disables intra 4x4. + /// if intra 4x4 has the lower score and the iterator now uses it; otherwise, . + public static bool PickBestIntra4( + Vp8EncoderIterator it, + ref Vp8ModeScore rd, + Vp8SegmentInfo[] segmentInfos, + Vp8EncoderProbabilities proba, + int maxI4HeaderBits) + { + const int numBlocks = 1; + Vp8SegmentInfo dqm = segmentInfos[it.CurrentMacroBlockInfo.Segment]; + int lambda = dqm.LambdaI4; + int tlambda = dqm.TLambda; + int totalHeaderBits = 0; + + // Reuse the iterator scratch accumulators instead of allocating per macroblock. rdBest collects + // the winning levels of every 4x4 block. Mode 0 always wins first, so each block writes its 16 levels + // before the end. The levels are read only after all 16 blocks complete, thus no clear is necessary. + Vp8ModeScore rdBest = it.RdScratch2; + + if (maxI4HeaderBits == 0) + { + return false; + } + + rdBest.InitScore(); + rdBest.H = 211; // '211' is the value of LossyUtils.Vp8BitCost(0, 145) + rdBest.SetRdScore(dqm.LambdaMode); + it.StartI4(); + + // Only the score fields of rdi4 and rdTmp are used, and their level arrays are never read. + // rdi4 starts each block with InitScore. Each mode sets all score fields of rdTmp before SetRdScore reads them. + Vp8ModeScore rdi4 = it.RdScratch3; + Vp8ModeScore rdTmp = it.RdScratch; + Vp8Residual res = it.ResidualScratch; + + // The base references are taken once for the macroblock. The kernels get references at known offsets from them. + // - recon holds two pair buffers at offsets 0 and PairBufferOffset. Each mode pair writes its two reconstructions + // side by side into one buffer. The buffer with the best reconstruction of the block so far is kept, so the next + // pair writes into the other buffer. No clear is necessary: each pair writes its buffer before it is read. + // - coeffs holds the 32 coefficients of a mode pair, and levels the 32 quantized levels after them. + // The quantizer writes all levels before the flatness and cost checks read them. + // - bestBlocks is YuvOut2 from the luma offset. No swap occurs in the loop, so the span stays valid for the whole loop. + ref byte src0 = ref Unsafe.Add(ref MemoryMarshal.GetReference(it.YuvIn), (nuint)Vp8EncoderIterator.YOffEnc); + ref byte preds = ref MemoryMarshal.GetReference(it.YuvP); + Span bestBlocks = it.YuvOut2[Vp8EncoderIterator.YOffEnc..]; + ref byte bestBlocksRef = ref MemoryMarshal.GetReference(bestBlocks); + ref byte recon = ref MemoryMarshal.GetReference(it.Scratch); + ref short coeffs = ref MemoryMarshal.GetReference(it.Scratch2); + ref short levels = ref Unsafe.Add(ref coeffs, (nuint)32); + ref short bestLevels = ref MemoryMarshal.GetArrayDataReference(rdBest.YAcLevels); + ref int scratch = ref MemoryMarshal.GetReference(it.Scratch3); + ref ushort weights = ref MemoryMarshal.GetReference(WeightY); + + // PickBestIntra16 computed the source sums of the spectral distortion for this macroblock. + Span srcSums = it.SourceSums; + + // All blocks have the coefficient type of intra 4x4 luma. + res.Init(0, 3, proba); + do + { + int i4 = it.I4; + int bestMode = -1; + nuint blockOffset = (nuint)WebpLookupTables.Vp8Scan[i4]; + ref byte src = ref Unsafe.Add(ref src0, blockOffset); + short[] modeCosts = it.GetCostModeI4(rd.ModesI4); + int ctx = it.TopNz[i4 & 3] + it.LeftNz[i4 >> 2]; + int srcSum = srcSums[i4]; + nuint freeBuffer = 0; + nuint bestRecon = 0; + + rdi4.InitScore(); + it.MakeIntra4Preds(); + + // The predictions of modes 2k and 2k + 1 are side by side: the second one starts 4 samples after the first. + // Thus each pair is transformed, quantized, reconstructed and measured in one pass. The results of a mode do + // not depend on the decision for other modes, so the decision then runs in mode order, as for one mode at a time. + for (int pair = 0; pair < WebpConstants.NumBModes; pair += 2) + { + ref byte pred = ref Unsafe.Add(ref preds, (uint)Vp8Encoding.Vp8I4ModeOffsets[pair]); + ref byte pairRecon = ref Unsafe.Add(ref recon, freeBuffer); + + // Reconstruct. Each 4x4 block has its own non-zero bit. + Vp8Encoding.FTransform2(ref src, ref pred, ref coeffs, ref Unsafe.Add(ref coeffs, (nuint)16), ref scratch); + int nz01; + if (it.DoTrellis) + { + // Both modes are candidates for the same block, so both get the context of the block. + int lambdaTrellis = dqm.LambdaTrellisI4; + nz01 = TrellisQuantizeBlock(proba, ref coeffs, ref levels, ctx, TypeI4Ac, ref dqm.Y1, lambdaTrellis); + nz01 |= TrellisQuantizeBlock( + proba, + ref Unsafe.Add(ref coeffs, (nuint)16), + ref Unsafe.Add(ref levels, (nuint)16), + ctx, + TypeI4Ac, + ref dqm.Y1, + lambdaTrellis) << 1; + } + else + { + nz01 = Quantize2Blocks(ref coeffs, ref levels, ref dqm.Y1); + } + + int nz0 = nz01 & 1; + int nz1 = nz01 >> 1; + if ((nz0 | nz1) != 0) + { + Vp8Encoding.ITransformTwo(ref pred, ref coeffs, ref pairRecon, ref scratch); + } + else + { + CopyPrediction8X4(ref pred, ref pairRecon); + } + + // Compute the distortions of both modes. + LossyUtils.Vp8_Sse4x4Pair(ref src, ref pairRecon, out int d0, out int d1); + LossyUtils.TTransformSums2(ref pairRecon, ref weights, ref scratch, out int sum0, out int sum1); + int sd0 = Mult8B(tlambda, Math.Abs(srcSum - sum0) >> 5); + int sd1 = Mult8B(tlambda, Math.Abs(srcSum - sum1) >> 5); + + bool pairHasBest = false; + ref short modeLevels = ref levels; + for (int mode = pair; mode < pair + 2; mode++) + { + rdTmp.Nz = (uint)nz0 << i4; + rdTmp.D = d0; + rdTmp.SD = sd0; + rdTmp.H = modeCosts[mode]; + + // Add flatness penalty, to avoid flat area to be mispredicted by a complex mode. + rdTmp.R = (mode > 0 && IsFlat(ref modeLevels, numBlocks, WebpConstants.FlatnessLimitI4)) ? WebpConstants.FlatnessPenality * numBlocks : 0; + + // Early-out check: the rate cost is computed only when the score without it is better. + rdTmp.SetRdScore(lambda); + if (bestMode < 0 || rdTmp.Score < rdi4.Score) + { + // Finish computing score. + rdTmp.R += res.GetResidualCost(ctx, ref modeLevels); + rdTmp.SetRdScore(lambda); + + if (bestMode < 0 || rdTmp.Score < rdi4.Score) + { + rdi4.CopyScore(rdTmp); + bestMode = mode; + bestRecon = freeBuffer + (nuint)((mode - pair) * 4); + pairHasBest = true; + Unsafe.CopyBlockUnaligned( + ref Unsafe.As(ref Unsafe.Add(ref bestLevels, (uint)(i4 * 16))), + ref Unsafe.As(ref modeLevels), + 16 * sizeof(short)); + } + } + + // The second mode of the pair uses the second results. + nz0 = nz1; + d0 = d1; + sd0 = sd1; + modeLevels = ref Unsafe.Add(ref modeLevels, (nuint)16); + } + + // Keep the buffer with the best reconstruction. The next pair writes into the other buffer. + if (pairHasBest) + { + freeBuffer ^= PairBufferOffset; + } + } + + rdi4.SetRdScore(dqm.LambdaMode); + rdBest.AddScore(rdi4); + if (rdBest.Score >= rd.Score) + { + return false; + } + + totalHeaderBits += (int)rdi4.H; // <- equal to modeCosts[bestMode]; + if (totalHeaderBits > maxI4HeaderBits) + { + return false; + } + + // Copy the selected samples to the right place. + LossyUtils.Vp8Copy4X4(ref Unsafe.Add(ref recon, bestRecon), ref Unsafe.Add(ref bestBlocksRef, blockOffset)); + + rd.ModesI4[i4] = (byte)bestMode; + it.TopNz[i4 & 3] = it.LeftNz[i4 >> 2] = rdi4.Nz != 0 ? 1 : 0; + } + while (it.RotateI4(bestBlocks)); + + // Finalize state. + rd.CopyScore(rdBest); + it.SetIntra4Mode(rd.ModesI4); + it.SwapOut(); + rdBest.YAcLevels.AsSpan().CopyTo(rd.YAcLevels); + + // Select intra4x4 over intra16x16. + return true; + } + + /// + /// Selects the chroma mode with the lowest rate-distortion score for the current macroblock and sets it on the iterator. + /// + /// + /// The chroma reconstruction of the selected mode goes to the output buffer of the iterator. When the iterator diffuses + /// the chroma DC errors, the method also stores the errors of the selected mode for the next blocks. + /// + /// The iterator at the current macroblock. + /// The score that gets the selected mode, its levels and its diffusion errors. The method adds the chroma score to it. + /// The segment parameters. The segment of the macroblock selects the entry. + /// The probabilities that give the coefficient costs. + public static void PickBestUv(Vp8EncoderIterator it, ref Vp8ModeScore rd, Vp8SegmentInfo[] segmentInfos, Vp8EncoderProbabilities proba) + { + const int numBlocks = 8; + Vp8SegmentInfo dqm = segmentInfos[it.CurrentMacroBlockInfo.Segment]; + int lambda = dqm.LambdaUv; + Span src = it.YuvIn[Vp8EncoderIterator.UOffEnc..]; + Span tmpDst = it.YuvOut2[Vp8EncoderIterator.UOffEnc..]; + Span dst0 = it.YuvOut[Vp8EncoderIterator.UOffEnc..]; + bool usesErrorDiffusion = it.UsesErrorDiffusion; + Span dst = dst0; + + // Reuse the iterator scratch accumulators instead of allocating per macroblock. Only the scores of rdBest + // are read. rdUv needs no clear: for each mode, the reconstruction writes all chroma levels and diffusion + // errors before they are read, and all score fields are set before SetRdScore. + Vp8ModeScore rdBest = it.RdScratch2; + Vp8ModeScore rdUv = it.RdScratch3; + Vp8Residual res = it.ResidualScratch; + int mode; + + rd.ModeUv = -1; + rdBest.InitScore(); + for (mode = 0; mode < WebpConstants.NumPredModes; ++mode) + { + // Reconstruct + rdUv.Nz = (uint)ReconstructUv(it, dqm, rdUv, ref MemoryMarshal.GetReference(tmpDst), mode); + + // Compute RD-score + rdUv.D = LossyUtils.Vp8_Sse16x8(src, tmpDst); + rdUv.SD = 0; // not calling TDisto here: it tends to flatten areas. + rdUv.H = WebpConstants.Vp8FixedCostsUv[mode]; + rdUv.R = it.GetCostUv(rdUv, proba, res); + if (mode > 0 && IsFlat(ref MemoryMarshal.GetArrayDataReference(rdUv.UvLevels), numBlocks, WebpConstants.FlatnessLimitIUv)) + { + rdUv.R += WebpConstants.FlatnessPenality * numBlocks; + } + + rdUv.SetRdScore(lambda); + if (mode == 0 || rdUv.Score < rdBest.Score) + { + rdBest.CopyScore(rdUv); + rd.ModeUv = mode; + rdUv.UvLevels.CopyTo(rd.UvLevels.AsSpan()); + if (usesErrorDiffusion) + { + rd.Derr = rdUv.Derr; + } + + RuntimeUtility.Swap(ref tmpDst, ref dst); + } + } + + it.SetIntraUvMode(rd.ModeUv); + rd.AddScore(rdBest); + if (dst != dst0) + { + // copy 16x8 block if needed. + LossyUtils.Vp8Copy16X8(ref MemoryMarshal.GetReference(dst), ref MemoryMarshal.GetReference(dst0)); + } + + // Store diffusion errors for next block. + if (usesErrorDiffusion) + { + it.StoreDiffusionErrors(rd); + } + } + + /// + /// Reconstructs the 16x16 luma block of the current macroblock with one intra 16x16 mode. + /// + /// The iterator. + /// The segment of the macroblock. + /// The score that gets the DC and AC levels. + /// The probabilities that give the coefficient costs of the trellis quantization. + /// The first sample of the reconstructed block. The rows have a stride of . + /// The intra 16x16 mode. + /// The non-zero bits: bit n for AC block n, bit 24 for the DC block. + public static int ReconstructIntra16(Vp8EncoderIterator it, Vp8SegmentInfo dqm, Vp8ModeScore rd, Vp8EncoderProbabilities proba, ref byte yuvOut, int mode) + { + ref byte reference = ref Unsafe.Add(ref MemoryMarshal.GetReference(it.YuvP), (uint)Vp8Encoding.Vp8I16ModeOffsets[mode]); + ref byte src = ref Unsafe.Add(ref MemoryMarshal.GetReference(it.YuvIn), (nuint)Vp8EncoderIterator.YOffEnc); + ref short yAcLevels = ref MemoryMarshal.GetArrayDataReference(rd.YAcLevels); + Span scratchBuffer = it.Scratch3; + ref int scratch = ref MemoryMarshal.GetReference(scratchBuffer); + ReadOnlySpan scan = WebpLookupTables.Vp8Scan; + int nz = 0; + int n; + + // No clear is necessary. The forward transforms write all 16 DC and 256 AC coefficients before they are read. + // Each transform that uses the int scratch writes all 16 entries before it reads them. + // The coefficient buffer holds the 16 DC coefficients, then the 16 blocks of 16 AC coefficients. + Span coefficients = it.Scratch2; + ref short dcTmp = ref MemoryMarshal.GetReference(coefficients); + ref short tmp = ref Unsafe.Add(ref dcTmp, (nuint)16); + + for (n = 0; n < 16; n += 2) + { + nuint offset = (nuint)scan[n]; + Vp8Encoding.FTransform2( + ref Unsafe.Add(ref src, offset), + ref Unsafe.Add(ref reference, offset), + ref Unsafe.Add(ref tmp, (uint)(n * 16)), + ref Unsafe.Add(ref tmp, (uint)((n + 1) * 16)), + ref scratch); + } + + Vp8Encoding.FTransformWht(ref tmp, ref dcTmp, ref scratch); + nz |= QuantizeBlock(ref dcTmp, ref MemoryMarshal.GetArrayDataReference(rd.YDcLevels), ref dqm.Y2) << 24; + + if (it.DoTrellis) + { + // The context of a block is the sum of the non-zero flags of the blocks above and to the left. The trellis keeps the DC + // coefficient of each block, and the inverse WHT below writes it. The DC level is in the Y2 block, so level 0 is zero. + it.NzToBytes(); + Span topNz = it.TopNz; + Span leftNz = it.LeftNz; + int lambdaTrellis = dqm.LambdaTrellisI16; + for (int y = 0; y < 4; y++) + { + for (int x = 0; x < 4; x++) + { + n = x + (y * 4); + ref short levels = ref Unsafe.Add(ref yAcLevels, (uint)(n * 16)); + int ctx = topNz[x] + leftNz[y]; + int nonZero = TrellisQuantizeBlock(proba, ref Unsafe.Add(ref tmp, (uint)(n * 16)), ref levels, ctx, TypeI16Ac, ref dqm.Y1, lambdaTrellis); + topNz[x] = leftNz[y] = nonZero; + levels = 0; + nz |= nonZero << n; + } + } + } + else + { + for (n = 0; n < 16; n += 2) + { + // Zero-out the first coeff, so that: a) nz is correct below, and + // b) finding 'last' non-zero coeffs in SetResidualCoeffs() is simplified. + Unsafe.Add(ref tmp, (uint)(n * 16)) = Unsafe.Add(ref tmp, (uint)((n + 1) * 16)) = 0; + nz |= Quantize2Blocks(ref Unsafe.Add(ref tmp, (uint)(n * 16)), ref Unsafe.Add(ref yAcLevels, (uint)(n * 16)), ref dqm.Y1) << n; + } + } + + // Transform back. + LossyUtils.TransformWht(coefficients[..16], coefficients.Slice(16, 16 * 16), scratchBuffer); + for (n = 0; n < 16; n += 2) + { + // The DC coefficients come from the inverse WHT, so a pair is all zero only when its AC levels and both DC coefficients are zero. + nuint offset = (nuint)scan[n]; + if (((nz >> n) & 3) != 0 || Unsafe.Add(ref tmp, (uint)(n * 16)) != 0 || Unsafe.Add(ref tmp, (uint)((n + 1) * 16)) != 0) + { + Vp8Encoding.ITransformTwo( + ref Unsafe.Add(ref reference, offset), + ref Unsafe.Add(ref tmp, (uint)(n * 16)), + ref Unsafe.Add(ref yuvOut, offset), + ref scratch); + } + else + { + CopyPrediction8X4(ref Unsafe.Add(ref reference, offset), ref Unsafe.Add(ref yuvOut, offset)); + } + } + + return nz; + } + + /// + /// Reconstructs one 4x4 luma block of the current macroblock with one intra 4x4 mode. + /// + /// The iterator. Its 4x4 predictions are for the current block. + /// The segment of the macroblock. + /// The probabilities that give the coefficient costs of the trellis quantization. + /// The first of the 16 levels of the block. + /// The first source sample of the block. The rows have a stride of . + /// The first sample of the reconstructed block, with the same layout as . + /// The intra 4x4 mode. + /// 1 if a level is not zero, else 0. + public static int ReconstructIntra4( + Vp8EncoderIterator it, + Vp8SegmentInfo dqm, + Vp8EncoderProbabilities proba, + ref short levels, + ref byte src, + ref byte yuvOut, + int mode) + { + ref byte reference = ref Unsafe.Add(ref MemoryMarshal.GetReference(it.YuvP), (uint)Vp8Encoding.Vp8I4ModeOffsets[mode]); + ref short tmp = ref MemoryMarshal.GetReference(it.Scratch2); + ref int scratch = ref MemoryMarshal.GetReference(it.Scratch3); + Vp8Encoding.FTransform(ref src, ref reference, ref tmp, ref scratch); + int nz; + if (it.DoTrellis) + { + int i4 = it.I4; + int ctx = it.TopNz[i4 & 3] + it.LeftNz[i4 >> 2]; + nz = TrellisQuantizeBlock(proba, ref tmp, ref levels, ctx, TypeI4Ac, ref dqm.Y1, dqm.LambdaTrellisI4); + } + else + { + nz = QuantizeBlock(ref tmp, ref levels, ref dqm.Y1); + } + + Vp8Encoding.ITransformOne(ref reference, ref tmp, ref yuvOut, ref scratch); + + return nz; + } + + /// + /// Reconstructs the two 8x8 chroma blocks of the current macroblock with one chroma mode. + /// + /// The iterator. + /// The segment of the macroblock. + /// The score that gets the chroma levels and the diffusion errors. + /// + /// The first sample of the reconstructed U block. The V block starts 8 samples after it. The rows have a stride of + /// . + /// + /// The chroma mode. + /// The non-zero bits: bits 16 to 23 for the 8 chroma blocks. + public static int ReconstructUv(Vp8EncoderIterator it, Vp8SegmentInfo dqm, Vp8ModeScore rd, ref byte yuvOut, int mode) + { + ref byte reference = ref Unsafe.Add(ref MemoryMarshal.GetReference(it.YuvP), (uint)Vp8Encoding.Vp8UvModeOffsets[mode]); + ref byte src = ref Unsafe.Add(ref MemoryMarshal.GetReference(it.YuvIn), (nuint)Vp8EncoderIterator.UOffEnc); + ref short uvLevels = ref MemoryMarshal.GetArrayDataReference(rd.UvLevels); + ref int scratch = ref MemoryMarshal.GetReference(it.Scratch3); + ReadOnlySpan scan = WebpLookupTables.Vp8ScanUv; + int nz = 0; + int n; + ref short tmp = ref MemoryMarshal.GetReference(it.Scratch2); + + for (n = 0; n < 8; n += 2) + { + nuint offset = (nuint)scan[n]; + Vp8Encoding.FTransform2( + ref Unsafe.Add(ref src, offset), + ref Unsafe.Add(ref reference, offset), + ref Unsafe.Add(ref tmp, (uint)(n * 16)), + ref Unsafe.Add(ref tmp, (uint)((n + 1) * 16)), + ref scratch); + } + + if (it.UsesErrorDiffusion) + { + CorrectDcValues(it, ref dqm.Uv, ref tmp, rd); + } + + for (n = 0; n < 8; n += 2) + { + nz |= Quantize2Blocks(ref Unsafe.Add(ref tmp, (uint)(n * 16)), ref Unsafe.Add(ref uvLevels, (uint)(n * 16)), ref dqm.Uv) << n; + } + + for (n = 0; n < 8; n += 2) + { + // The two bits of a pair include its DC levels, so zero bits mean that all coefficients of the pair are zero. + nuint offset = (nuint)scan[n]; + if (((nz >> n) & 3) != 0) + { + Vp8Encoding.ITransformTwo( + ref Unsafe.Add(ref reference, offset), + ref Unsafe.Add(ref tmp, (uint)(n * 16)), + ref Unsafe.Add(ref yuvOut, offset), + ref scratch); + } + else + { + CopyPrediction8X4(ref Unsafe.Add(ref reference, offset), ref Unsafe.Add(ref yuvOut, offset)); + } + } + + return nz << 16; + } + + /// + /// Copies the prediction of a pair of 4x4 blocks to the reconstruction, for a pair whose coefficients are all zero. + /// + /// + /// With zero coefficients, the inverse transform adds (0 + 4) >> 3 = 0 to each sample. Thus the reconstruction is the prediction, and the copy + /// gives the same samples as the inverse transform. + /// + /// + /// The first prediction sample. Each row has the 8 samples of the pair, and the rows have a stride of . + /// + /// The first reconstruction sample, with the same layout as . + [MethodImpl(InliningOptions.ShortMethod)] + private static void CopyPrediction8X4(ref byte prediction, ref byte destination) + { + for (nuint row = 0; row < 4 * WebpConstants.Bps; row += WebpConstants.Bps) + { + Unsafe.WriteUnaligned(ref Unsafe.Add(ref destination, row), Unsafe.ReadUnaligned(ref Unsafe.Add(ref prediction, row))); + } + } + + /// + /// Selects the luma modes, and optionally the chroma mode, of the current macroblock from the distortion and fixed mode costs. + /// The method does not compute the coefficient rate. Then it reconstructs the macroblock with the selected modes. + /// + /// The iterator at the current macroblock. + /// The segment parameters. The segment of the macroblock selects the entry. + /// The probabilities that give the coefficient costs of the trellis quantization. + /// The score that gets the levels, the intra 4x4 modes, the non-zero bits and the distortion score. + /// + /// to compare intra 16x16 with intra 4x4. to refine only the current macroblock type. + /// + /// to select the chroma mode again; to keep the current one. + /// The largest mode header bits when is . + public static void RefineUsingDistortion( + Vp8EncoderIterator it, + Vp8SegmentInfo[] segmentInfos, + Vp8EncoderProbabilities proba, + Vp8ModeScore rd, + bool tryBothModes, + bool refineUvMode, + int mbHeaderLimit) + { + long bestScore = Vp8ModeScore.MaxCost; + int nz = 0; + int mode; + bool isI16 = tryBothModes || it.CurrentMacroBlockInfo.MacroBlockType == Vp8MacroBlockType.I16X16; + Vp8SegmentInfo dqm = segmentInfos[it.CurrentMacroBlockInfo.Segment]; + + // Some empiric constants, of approximate order of magnitude. + const int lambdaDi16 = 106; + const int lambdaDi4 = 11; + const int lambdaDuv = 120; + long scoreI4 = dqm.I4Penalty; + long i4BitSum = 0; + long bitLimit = tryBothModes + ? mbHeaderLimit + : Vp8ModeScore.MaxCost; // no early-out allowed. + + // The input and prediction buffers do not change their memory in this method, so the method gets their spans once. + Span yuvIn = it.YuvIn; + Span yuvP = it.YuvP; + if (isI16) + { + int bestMode = -1; + Span src = yuvIn[Vp8EncoderIterator.YOffEnc..]; + for (mode = 0; mode < WebpConstants.NumPredModes; ++mode) + { + Span reference = yuvP[Vp8Encoding.Vp8I16ModeOffsets[mode]..]; + long score = (LossyUtils.Vp8_Sse16x16(src, reference) * WebpConstants.RdDistoMult) + (WebpConstants.Vp8FixedCostsI16[mode] * lambdaDi16); + + if (mode > 0 && WebpConstants.Vp8FixedCostsI16[mode] > bitLimit) + { + continue; + } + + if (score < bestScore) + { + bestMode = mode; + bestScore = score; + } + } + + if (it.X == 0 || it.Y == 0) + { + // Avoid starting a checkerboard resonance from the border. See bug #432 of libwebp. + if (IsFlatSource16(src)) + { + bestMode = it.X == 0 ? 0 : 2; + tryBothModes = false; // Stick to i16. + } + } + + it.SetIntra16Mode(bestMode); + + // We'll reconstruct later, if i16 mode actually gets selected. + } + + // Next, evaluate Intra4. + if (tryBothModes || !isI16) + { + // We don't evaluate the rate here, but just account for it through a + // constant penalty (i4 mode usually needs more bits compared to i16). + isI16 = false; + + // The luma part of YuvOut2 gets the partial reconstruction. No swap occurs in the loop, so the span stays valid for the whole loop. + Span yOut2 = it.YuvOut2[Vp8EncoderIterator.YOffEnc..]; + it.StartI4(); + do + { + int bestI4Mode = -1; + long bestI4Score = Vp8ModeScore.MaxCost; + Span src = yuvIn[(Vp8EncoderIterator.YOffEnc + WebpLookupTables.Vp8Scan[it.I4])..]; + short[] modeCosts = it.GetCostModeI4(rd.ModesI4); + + it.MakeIntra4Preds(); + for (mode = 0; mode < WebpConstants.NumBModes; ++mode) + { + Span reference = yuvP[Vp8Encoding.Vp8I4ModeOffsets[mode]..]; + long score = (LossyUtils.Vp8_Sse4x4(src, reference) * WebpConstants.RdDistoMult) + (modeCosts[mode] * lambdaDi4); + if (score < bestI4Score) + { + bestI4Mode = mode; + bestI4Score = score; + } + } + + i4BitSum += modeCosts[bestI4Mode]; + rd.ModesI4[it.I4] = (byte)bestI4Mode; + scoreI4 += bestI4Score; + if (scoreI4 >= bestScore || i4BitSum > bitLimit) + { + // Intra4 won't be better than Intra16. Bail out and pick Intra16. + isI16 = true; + break; + } + else + { + // Reconstruct partial block inside YuvOut2 buffer + Span tmpDst = yOut2[WebpLookupTables.Vp8Scan[it.I4]..]; + ref short levels = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(rd.YAcLevels), (uint)(it.I4 * 16)); + ref byte srcRef = ref MemoryMarshal.GetReference(src); + nz |= ReconstructIntra4(it, dqm, proba, ref levels, ref srcRef, ref MemoryMarshal.GetReference(tmpDst), bestI4Mode) << it.I4; + } + } + while (it.RotateI4(yOut2)); + } + + // Final reconstruction, depending on which mode is selected. + if (!isI16) + { + it.SetIntra4Mode(rd.ModesI4); + it.SwapOut(); + bestScore = scoreI4; + } + else + { + int intra16Mode = it.Preds[it.PredIdx]; + nz = ReconstructIntra16( + it, + dqm, + rd, + proba, + ref Unsafe.Add(ref MemoryMarshal.GetReference(it.YuvOut), (nuint)Vp8EncoderIterator.YOffEnc), + intra16Mode); + } + + // ... and UV! + if (refineUvMode) + { + int bestMode = -1; + long bestUvScore = Vp8ModeScore.MaxCost; + Span src = yuvIn[Vp8EncoderIterator.UOffEnc..]; + for (mode = 0; mode < WebpConstants.NumPredModes; ++mode) + { + Span reference = yuvP[Vp8Encoding.Vp8UvModeOffsets[mode]..]; + long score = (LossyUtils.Vp8_Sse16x8(src, reference) * WebpConstants.RdDistoMult) + (WebpConstants.Vp8FixedCostsUv[mode] * lambdaDuv); + if (score < bestUvScore) + { + bestMode = mode; + bestUvScore = score; + } + } + + it.SetIntraUvMode(bestMode); + } + + // SwapOut above can exchange the output buffers, so YuvOut is read after it. + ref byte uvOut = ref Unsafe.Add(ref MemoryMarshal.GetReference(it.YuvOut), (nuint)Vp8EncoderIterator.UOffEnc); + nz |= ReconstructUv(it, dqm, rd, ref uvOut, it.CurrentMacroBlockInfo.UvMode); + + rd.Nz = (uint)nz; + rd.Score = bestScore; + } + + /// + /// Quantizes and reconstructs the current macroblock again with its selected modes. The mode decision does not change. + /// + /// + /// With the trellis level, the mode decision uses the plain quantization, and this method then quantizes the selected modes with the + /// trellis. The intra 4x4 blocks keep the non-zero contexts that the start of the blocks imports. + /// + /// The iterator at the current macroblock, with its selected modes. + /// The score that gets the levels and the non-zero bits. The score value does not change. + /// The segment parameters. The segment of the macroblock selects the entry. + /// The probabilities that give the coefficient costs of the trellis quantization. + public static void SimpleQuantize(Vp8EncoderIterator it, Vp8ModeScore rd, Vp8SegmentInfo[] segmentInfos, Vp8EncoderProbabilities proba) + { + Vp8SegmentInfo dqm = segmentInfos[it.CurrentMacroBlockInfo.Segment]; + Span yuvOut = it.YuvOut[Vp8EncoderIterator.YOffEnc..]; + ref byte yOut = ref MemoryMarshal.GetReference(yuvOut); + int nz; + if (it.CurrentMacroBlockInfo.MacroBlockType == Vp8MacroBlockType.I16X16) + { + nz = ReconstructIntra16(it, dqm, rd, proba, ref yOut, it.Preds[it.PredIdx]); + } + else + { + nz = 0; + ref byte src0 = ref Unsafe.Add(ref MemoryMarshal.GetReference(it.YuvIn), (nuint)Vp8EncoderIterator.YOffEnc); + ref short yAcLevels = ref MemoryMarshal.GetArrayDataReference(rd.YAcLevels); + it.StartI4(); + do + { + // The rotation copies the reconstructed samples to the boundary of the next block, so each prediction reads the final samples. + int i4 = it.I4; + nuint offset = (nuint)WebpLookupTables.Vp8Scan[i4]; + it.MakeIntra4Preds(); + nz |= ReconstructIntra4( + it, + dqm, + proba, + ref Unsafe.Add(ref yAcLevels, (uint)(i4 * 16)), + ref Unsafe.Add(ref src0, offset), + ref Unsafe.Add(ref yOut, offset), + rd.ModesI4[i4]) << i4; + } + while (it.RotateI4(yuvOut)); + } + + ref byte uvOut = ref Unsafe.Add(ref MemoryMarshal.GetReference(it.YuvOut), (nuint)Vp8EncoderIterator.UOffEnc); + nz |= ReconstructUv(it, dqm, rd, ref uvOut, it.CurrentMacroBlockInfo.UvMode); + rd.Nz = (uint)nz; + } + + /// + /// Quantizes one 4x4 block with the levels that give the lowest rate-distortion score, and stores the dequantized coefficients in place. + /// + /// + /// + /// The trellis has one stage for each coefficient in zigzag order, and two nodes for each stage: the level with a neutral rounding, and + /// that level plus one. A node keeps the best score of a path that reaches it and the node of the previous stage on that path. The rate + /// of a level depends on the context that the previous level gives, so each node scores both nodes of the previous stage. The score of a + /// path that ends at a node adds the cost of the end-of-block flag. The best end node then gives the levels, from the last coefficient + /// back to the first. + /// + /// + /// The distortion is the weighted change of the squared error of each coefficient, relative to the error of a zero level. The rates come + /// from the level cost tables of the probabilities. A score is rate * lambda + * distortion. + /// + /// + /// The method does not test the coefficients after the last coefficient whose square is more than a quarter of the square of the first AC + /// step. It tests one coefficient after that one. + /// + /// + /// The probabilities. Their level costs must be up to date. + /// + /// The first of the 16 coefficients in raster order. On return, the dequantized coefficients. For , coefficient 0 + /// does not change. + /// + /// + /// The first of the 16 levels in zigzag order. For , level 0 does not change. The other levels are set. + /// + /// The context of the block: the sum of the non-zero flags of the blocks above and to the left. + /// The coefficient type: or . + /// The quantization matrix. + /// The rate weight. + /// 1 if a level is not zero, else 0. + private static int TrellisQuantizeBlock( + Vp8EncoderProbabilities proba, + ref short input, + ref short output, + int ctx0, + int coeffType, + ref Vp8Matrix mtx, + int lambda) + { + ReadOnlySpan probas = proba.Coeffs.AsSpan(coeffType * Vp8EncoderProbabilities.ProbasPerType, Vp8EncoderProbabilities.ProbasPerType); + ReadOnlySpan costs = proba.LevelCost.AsSpan(coeffType * Vp8EncoderProbabilities.CostsPerType, Vp8EncoderProbabilities.CostsPerType); + ReadOnlySpan costOffsets = Vp8EncoderProbabilities.RemappedCostOffsets; + ReadOnlySpan bands = WebpConstants.Vp8EncBands; + ReadOnlySpan zigzag = WebpConstants.Zigzag; + ReadOnlySpan weights = WeightTrellis; + int first = coeffType == TypeI16Ac ? 1 : 0; + + // Node n * TrellisNodes + m is node m of the stage of coefficient n. The unwind reads only the nodes on the best path, and the loop writes + // each of them first. The clear keeps the other nodes defined. + InlineArray32 nodesBuffer = default; + Span nodes = nodesBuffer; + + // The score states of two stages: the score of each node and the offset of the cost table of the next coefficient after the node. + // The current stage starts at currentState, and the previous stage at the other half. + InlineArray4 stateScoresBuffer = default; + InlineArray4 stateCostsBuffer = default; + Span stateScores = stateScoresBuffer; + Span stateCosts = stateCostsBuffer; + int currentState = 0; + int previousState = TrellisNodes; + + // The last coefficient that is worth a test. + int threshold = mtx.Q[1] * mtx.Q[1] / 4; + int last = first - 1; + for (int n = 15; n >= first; n--) + { + int coefficient = Unsafe.Add(ref input, (uint)zigzag[n]); + if (coefficient * coefficient > threshold) + { + last = n; + break; + } + } + + if (last < 15) + { + last++; + } + + // The score of a block without levels is the best score at the start. + byte lastProba = probas[Vp8EncoderProbabilities.ProbaIndex(bands[first], ctx0)]; + long bestScore = RdScoreTrellis(lambda, LossyUtils.Vp8BitCost(0, lastProba), 0); + int bestEnd = -1; + int bestNode = 0; + int bestPrevious = 0; + + // The source nodes. A block with context 0 pays for the flag that says it is not empty. Otherwise, the level costs include that flag. + long sourceScore = RdScoreTrellis(lambda, ctx0 == 0 ? LossyUtils.Vp8BitCost(1, lastProba) : 0, 0); + int sourceCosts = costOffsets[(first * WebpConstants.NumCtx) + ctx0]; + for (int m = 0; m < TrellisNodes; m++) + { + stateScores[currentState + m] = sourceScore; + stateCosts[currentState + m] = sourceCosts; + } + + for (int n = first; n <= last; n++) + { + int j = zigzag[n]; + int q = mtx.Q[j]; + uint iq = mtx.IQ[j]; + + // The sign is the sign of the original coefficient, so the levels are never negative. The sharpening raises the high frequencies. + int coefficient = Unsafe.Add(ref input, (uint)j); + bool sign = coefficient < 0; + int coeff0 = (sign ? -coefficient : coefficient) + mtx.Sharpen[j]; + int level0 = Math.Min(QuantDiv((uint)coeff0, iq, 0), MaxLevel); + int thresholdLevel = Math.Min(QuantDiv((uint)coeff0, iq, 0x80 << (WebpConstants.QFix - 8)), MaxLevel); + + (currentState, previousState) = (previousState, currentState); + + for (int m = 0; m < TrellisNodes; m++) + { + int level = level0 + m; + int ctx = level > 2 ? 2 : level; + + // The cost table of the next coefficient depends on the context of this level. The last stage has no next coefficient. + stateCosts[currentState + m] = n + 1 < 16 ? costOffsets[((n + 1) * WebpConstants.NumCtx) + ctx] : 0; + + // A level is never negative, so only the upper limit can make a node dead. + if (level > thresholdLevel) + { + stateScores[currentState + m] = Vp8ModeScore.MaxCost; + continue; + } + + // The change of the squared error relative to a zero level: (|coeff| - level * q)^2 - |coeff|^2. + int newError = coeff0 - (level * q); + int deltaError = weights[j] * ((newError * newError) - (coeff0 * coeff0)); + long baseScore = RdScoreTrellis(lambda, 0, deltaError); + + // Keep the better of the two previous nodes. A dead node has the largest score, so it never wins over a live node. + long bestCurrentScore = stateScores[previousState] + RdScoreTrellis(lambda, LevelCost(costs, stateCosts[previousState], level), 0); + int bestCurrentPrevious = 0; + long score = stateScores[previousState + 1] + RdScoreTrellis(lambda, LevelCost(costs, stateCosts[previousState + 1], level), 0); + if (score < bestCurrentScore) + { + bestCurrentScore = score; + bestCurrentPrevious = 1; + } + + bestCurrentScore += baseScore; + ref TrellisNode node = ref nodes[(n * TrellisNodes) + m]; + node.Sign = sign; + node.Level = (short)level; + node.Previous = (sbyte)bestCurrentPrevious; + stateScores[currentState + m] = bestCurrentScore; + + // A path can end at a node with a level that is not zero. The end adds the cost of the end-of-block flag. + if (level != 0 && bestCurrentScore < bestScore) + { + int lastPositionCost = n < 15 ? LossyUtils.Vp8BitCost(0, probas[Vp8EncoderProbabilities.ProbaIndex(bands[n + 1], ctx)]) : 0; + score = bestCurrentScore + RdScoreTrellis(lambda, lastPositionCost, 0); + if (score < bestScore) + { + bestScore = score; + bestEnd = n; + bestNode = m; + bestPrevious = bestCurrentPrevious; + } + } + } + } + + // Clear the block. The DC coefficient and level of an intra 16x16 block stay, because the Y2 block holds them. + int clearStart = coeffType == TypeI16Ac ? 1 : 0; + MemoryMarshal.CreateSpan(ref Unsafe.Add(ref input, (uint)clearStart), 16 - clearStart).Clear(); + MemoryMarshal.CreateSpan(ref Unsafe.Add(ref output, (uint)clearStart), 16 - clearStart).Clear(); + if (bestEnd == -1) + { + return 0; + } + + // Unwind the best path. The best previous node of an end node can differ from the one of the same node inside a longer path, so the + // end node gets the previous node of the best end. + bool nonZero = false; + nodes[(bestEnd * TrellisNodes) + bestNode].Previous = (sbyte)bestPrevious; + for (int n = bestEnd; n >= first; n--) + { + TrellisNode node = nodes[(n * TrellisNodes) + bestNode]; + int j = zigzag[n]; + int level = node.Sign ? -node.Level : node.Level; + Unsafe.Add(ref output, (uint)n) = (short)level; + nonZero |= node.Level != 0; + Unsafe.Add(ref input, (uint)j) = (short)(level * mtx.Q[j]); + bestNode = node.Previous; + } + + return nonZero ? 1 : 0; + } + + /// + /// Gets the rate-distortion score of the trellis. + /// + /// The rate weight. + /// The rate. + /// The distortion. + /// The score. + [MethodImpl(InliningOptions.ShortMethod)] + private static long RdScoreTrellis(int lambda, long rate, long distortion) => (rate * lambda) + (WebpConstants.RdDistoMult * distortion); + + /// + /// Gets the cost of one level: the fixed cost of the level plus the cost from the level cost table of its position and context. + /// + /// The level cost tables of the coefficient type. + /// The offset of the table of the position and context. + /// The level, from 0 to 2047. + /// The cost. + [MethodImpl(InliningOptions.ShortMethod)] + private static int LevelCost(ReadOnlySpan costs, int offset, int level) + => WebpLookupTables.Vp8LevelFixedCosts[level] + costs[offset + Math.Min(level, WebpConstants.MaxVariableLevel)]; + + /// + /// Quantizes two 4x4 blocks. See . + /// + /// The first of the 32 coefficients: 16 of the first block, then 16 of the second block. + /// The first of the 32 levels, in the same block order. + /// The quantization matrix. + /// The non-zero bits: bit 0 for the first block, bit 1 for the second block. + [MethodImpl(InliningOptions.ShortMethod)] + public static int Quantize2Blocks(ref short input, ref short output, ref Vp8Matrix mtx) + { + if (Vector512.IsHardwareAccelerated) + { + // Lanes 0 to 15 hold the first block and lanes 16 to 31 the second block, both in raster order. Both blocks use + // the same matrix, so each matrix vector holds the 16 entries twice. The widen of the coefficients gives the + // first block in the low result and the second block in the high result, so both bias vectors are the 16 biases. + Vector256 sharpen = Vector256.LoadUnsafe(ref mtx.Sharpen[0]); + Vector256 iq = Vector256.LoadUnsafe(ref mtx.IQ[0]); + Vector256 q = Vector256.LoadUnsafe(ref mtx.Q[0]).AsInt16(); + Vector512 bias = Vector512.LoadUnsafe(ref mtx.Bias[0]); + Vector512 level = Quantize( + Vector512.LoadUnsafe(ref input), + Vector512.Create(sharpen, sharpen), + Vector512.Create(iq, iq), + bias, + bias, + Vector512.Create(q, q), + out Vector512 dequantized); + + dequantized.StoreUnsafe(ref input); + Vector256 level0 = level.GetLower(); + Vector256 level1 = level.GetUpper(); + StoreZigzag(level0.GetLower(), level0.GetUpper(), ref output); + StoreZigzag(level1.GetLower(), level1.GetUpper(), ref Unsafe.Add(ref output, (nuint)16)); + return (Vector256.EqualsAll(level0, Vector256.Zero) ? 0 : 1) | (Vector256.EqualsAll(level1, Vector256.Zero) ? 0 : 2); + } + + int nz = QuantizeBlock(ref input, ref output, ref mtx); + nz |= QuantizeBlock(ref Unsafe.Add(ref input, (nuint)16), ref Unsafe.Add(ref output, (nuint)16), ref mtx) << 1; + return nz; + } + + /// + /// Quantizes one 4x4 block. Each level is (|coefficient| + sharpen) * iQ + bias, shifted right by QFix bits and + /// limited to 2047, with the sign of the coefficient. The input gets the dequantized coefficient level * q. + /// + /// The first of the 16 coefficients in raster order. On return, the dequantized coefficients. + /// The first of the 16 levels in zigzag order. + /// The quantization matrix. + /// 1 if a level is not zero, else 0. + public static int QuantizeBlock(ref short input, ref short output, ref Vp8Matrix mtx) + { + if (Vector256.IsHardwareAccelerated) + { + // Lane i holds coefficient i in raster order. The widen of the coefficients gives the coefficients 0 to 7 in the + // low result and 8 to 15 in the high result, so the bias vectors are the first 8 and the last 8 biases. + ref uint bias = ref mtx.Bias[0]; + Vector256 level = Quantize( + Vector256.LoadUnsafe(ref input), + Vector256.LoadUnsafe(ref mtx.Sharpen[0]), + Vector256.LoadUnsafe(ref mtx.IQ[0]), + Vector256.LoadUnsafe(ref bias), + Vector256.LoadUnsafe(ref bias, 8), + Vector256.LoadUnsafe(ref mtx.Q[0]).AsInt16(), + out Vector256 dequantized); + + dequantized.StoreUnsafe(ref input); + StoreZigzag(level.GetLower(), level.GetUpper(), ref output); + return Vector256.EqualsAll(level, Vector256.Zero) ? 0 : 1; + } + + if (Vector128.IsHardwareAccelerated) + { + // The first call takes the coefficients 0 to 7 and the second call the coefficients 8 to 15. + ref short sharpen = ref mtx.Sharpen[0]; + ref ushort iq = ref mtx.IQ[0]; + ref uint bias = ref mtx.Bias[0]; + ref short q = ref Unsafe.As(ref mtx.Q[0]); + Vector128 level0 = Quantize( + Vector128.LoadUnsafe(ref input), + Vector128.LoadUnsafe(ref sharpen), + Vector128.LoadUnsafe(ref iq), + Vector128.LoadUnsafe(ref bias), + Vector128.LoadUnsafe(ref bias, 4), + Vector128.LoadUnsafe(ref q), + out Vector128 dequantized0); + + Vector128 level8 = Quantize( + Vector128.LoadUnsafe(ref input, 8), + Vector128.LoadUnsafe(ref sharpen, 8), + Vector128.LoadUnsafe(ref iq, 8), + Vector128.LoadUnsafe(ref bias, 8), + Vector128.LoadUnsafe(ref bias, 12), + Vector128.LoadUnsafe(ref q, 8), + out Vector128 dequantized8); + + dequantized0.StoreUnsafe(ref input); + dequantized8.StoreUnsafe(ref input, 8); + StoreZigzag(level0, level8, ref output); + return Vector128.EqualsAll(level0 | level8, Vector128.Zero) ? 0 : 1; + } + + int last = -1; + ref byte zigzag = ref MemoryMarshal.GetReference(WebpConstants.Zigzag); + for (nuint n = 0; n < 16; ++n) + { + int j = Unsafe.Add(ref zigzag, n); + ref short inJ = ref Unsafe.Add(ref input, (nuint)j); + bool sign = inJ < 0; + uint coeff = (uint)((sign ? -inJ : inJ) + mtx.Sharpen[j]); + if (coeff > mtx.ZThresh[j]) + { + uint q = mtx.Q[j]; + uint iQ = mtx.IQ[j]; + uint b = mtx.Bias[j]; + int level = QuantDiv(coeff, iQ, b); + if (level > MaxLevel) + { + level = MaxLevel; + } + + if (sign) + { + level = -level; + } + + inJ = (short)(level * (int)q); + Unsafe.Add(ref output, n) = (short)level; + if (level != 0) + { + last = (int)n; + } + } + else + { + Unsafe.Add(ref output, n) = 0; + inJ = 0; + } + } + + return last >= 0 ? 1 : 0; + } + + /// + /// Quantizes the coefficients of a vector, one coefficient in each lane. + /// + /// + /// + /// The vector forms do not test the zero threshold of the scalar path. The threshold is the largest magnitude that + /// gives a zero level, so the levels are the same. A zero coefficient gives a zero level: Vp8Matrix.Expand keeps the + /// sharpening bias far below q, so (sharpen * iQ) + bias is less than 1 << QFix, and the sign step keeps the level zero. + /// + /// + /// Each magnitude plus its sharpening bias is less than 1 << 16, iQ is less than 1 << 16 and the bias is less + /// than 1 << QFix. Thus each sum fits an unsigned 32-bit lane without wrap, as in the scalar path, and each level is + /// less than 1 << 15 before the limit, so the narrow keeps it exactly. + /// + /// + /// The coefficients. + /// The sharpening biases, one for each lane. + /// The fixed-point reciprocals of the steps, one for each lane. + /// The rounding biases of the lanes in the low half. + /// The rounding biases of the lanes in the high half. + /// The steps, one for each lane. + /// The dequantized coefficients, level * q. The product keeps the low 16 bits, as the scalar cast to short does. + /// The signed levels, limited to 2047 in magnitude. + [MethodImpl(InliningOptions.ShortMethod)] + private static Vector128 Quantize( + Vector128 coefficients, + Vector128 sharpen, + Vector128 iq, + Vector128 biasLow, + Vector128 biasHigh, + Vector128 q, + out Vector128 dequantized) + { + // level = ((|coefficient| + sharpen) * iQ + bias) >> QFix, in 32-bit lanes. The widen keeps the lane order. + (Vector128 magnitudeLow, Vector128 magnitudeHigh) = Vector128.Widen((Vector128.Abs(coefficients) + sharpen).AsUInt16()); + (Vector128 iqLow, Vector128 iqHigh) = Vector128.Widen(iq); + Vector128 levelLow = Vector128.ShiftRightLogical((magnitudeLow * iqLow) + biasLow, WebpConstants.QFix); + Vector128 levelHigh = Vector128.ShiftRightLogical((magnitudeHigh * iqHigh) + biasHigh, WebpConstants.QFix); + Vector128 level = Vector128.Min(Vector128.Narrow(levelLow, levelHigh), Vector128.Create((ushort)MaxLevel)).AsInt16(); + + // The sign mask is -1 for a negative coefficient, else 0. (level ^ -1) - (-1) is -level. + Vector128 sign = Vector128.ShiftRightArithmetic(coefficients, 15); + level = (level ^ sign) - sign; + dequantized = level * q; + return level; + } + + /// + /// Quantizes the coefficients of a vector, one coefficient in each lane, with the steps of the 128-bit form. + /// + /// The coefficients. + /// The sharpening biases, one for each lane. + /// The fixed-point reciprocals of the steps, one for each lane. + /// The rounding biases of the lanes in the low half. + /// The rounding biases of the lanes in the high half. + /// The steps, one for each lane. + /// The dequantized coefficients, level * q, in the low 16 bits. + /// The signed levels, limited to 2047 in magnitude. + [MethodImpl(InliningOptions.ShortMethod)] + private static Vector256 Quantize( + Vector256 coefficients, + Vector256 sharpen, + Vector256 iq, + Vector256 biasLow, + Vector256 biasHigh, + Vector256 q, + out Vector256 dequantized) + { + (Vector256 magnitudeLow, Vector256 magnitudeHigh) = Vector256.Widen((Vector256.Abs(coefficients) + sharpen).AsUInt16()); + (Vector256 iqLow, Vector256 iqHigh) = Vector256.Widen(iq); + Vector256 levelLow = Vector256.ShiftRightLogical((magnitudeLow * iqLow) + biasLow, WebpConstants.QFix); + Vector256 levelHigh = Vector256.ShiftRightLogical((magnitudeHigh * iqHigh) + biasHigh, WebpConstants.QFix); + Vector256 level = Vector256.Min(Vector256.Narrow(levelLow, levelHigh), Vector256.Create((ushort)MaxLevel)).AsInt16(); + Vector256 sign = Vector256.ShiftRightArithmetic(coefficients, 15); + level = (level ^ sign) - sign; + dequantized = level * q; + return level; + } + + /// + /// Quantizes the coefficients of a vector, one coefficient in each lane, with the steps of the 128-bit form. + /// + /// The coefficients. + /// The sharpening biases, one for each lane. + /// The fixed-point reciprocals of the steps, one for each lane. + /// The rounding biases of the lanes in the low half. + /// The rounding biases of the lanes in the high half. + /// The steps, one for each lane. + /// The dequantized coefficients, level * q, in the low 16 bits. + /// The signed levels, limited to 2047 in magnitude. + [MethodImpl(InliningOptions.ShortMethod)] + private static Vector512 Quantize( + Vector512 coefficients, + Vector512 sharpen, + Vector512 iq, + Vector512 biasLow, + Vector512 biasHigh, + Vector512 q, + out Vector512 dequantized) + { + (Vector512 magnitudeLow, Vector512 magnitudeHigh) = Vector512.Widen((Vector512.Abs(coefficients) + sharpen).AsUInt16()); + (Vector512 iqLow, Vector512 iqHigh) = Vector512.Widen(iq); + Vector512 levelLow = Vector512.ShiftRightLogical((magnitudeLow * iqLow) + biasLow, WebpConstants.QFix); + Vector512 levelHigh = Vector512.ShiftRightLogical((magnitudeHigh * iqHigh) + biasHigh, WebpConstants.QFix); + Vector512 level = Vector512.Min(Vector512.Narrow(levelLow, levelHigh), Vector512.Create((ushort)MaxLevel)).AsInt16(); + Vector512 sign = Vector512.ShiftRightArithmetic(coefficients, 15); + level = (level ^ sign) - sign; + dequantized = level * q; + return level; + } + + /// + /// Stores 16 levels in zigzag order: output n gets the level of coefficient Zigzag[n]. + /// + /// The levels of the coefficients 0 to 7. + /// The levels of the coefficients 8 to 15. + /// The first of the 16 zigzag ordered levels. + [MethodImpl(InliningOptions.ShortMethod)] + private static void StoreZigzag(Vector128 out0, Vector128 out8, ref short output) + { + // The re-ordering is: + // 0 1 2 3 4 5 6 7 | 8 9 10 11 12 13 14 15 + // -> 0 1 4[8]5 2 3 6 | 9 12 13 10 [7]11 14 15 + // Only two entries ([8] and [7]) cross the halves. Each half is one shuffle of its own levels and one shuffle + // for the crossing entry. The shuffle index 8 is out of range and gives zero, so an OR merges the two shuffles. + Vector128 zigzag0 = Vector128.Shuffle(out0, Vector128.Create((short)0, 1, 4, 8, 5, 2, 3, 6)) | + Vector128.Shuffle(out8, Vector128.Create((short)8, 8, 8, 0, 8, 8, 8, 8)); + + Vector128 zigzag8 = Vector128.Shuffle(out8, Vector128.Create((short)1, 4, 5, 2, 8, 3, 6, 7)) | + Vector128.Shuffle(out0, Vector128.Create((short)8, 8, 8, 8, 7, 8, 8, 8)); + + zigzag0.StoreUnsafe(ref output); + zigzag8.StoreUnsafe(ref output, 8); + } + + /// + /// Quantizes one DC coefficient with the first entry of and gets the quantization error. + /// + /// The coefficient. On return, the dequantized coefficient. + /// The quantization matrix. + /// The coefficient minus the dequantized coefficient, shifted right by DSCALE bits. + public static int QuantizeSingle(ref short v, ref Vp8Matrix mtx) + { + int v0 = v; + bool sign = v0 < 0; + if (sign) + { + v0 = -v0; + } + + if (v0 > (int)mtx.ZThresh[0]) + { + int qV = QuantDiv((uint)v0, mtx.IQ[0], mtx.Bias[0]) * mtx.Q[0]; + int err = v0 - qV; + v = (short)(sign ? -qV : qV); + return (sign ? -err : err) >> DSCALE; + } + + v = 0; + return (sign ? -v0 : v0) >> DSCALE; + } + + /// + /// Adds the diffused DC errors of the neighbor blocks to the DC coefficients of the chroma blocks, quantizes them and + /// keeps the new errors. + /// + /// The iterator with the top and left errors. + /// The chroma quantization matrix. + /// The first of the 128 coefficients of the 4 U blocks and the 4 V blocks. + /// The score that gets the new errors. + public static void CorrectDcValues(Vp8EncoderIterator it, ref Vp8Matrix mtx, ref short tmp, Vp8ModeScore rd) + { +#pragma warning disable SA1005 // Single line comments should begin with single space + // | top[0] | top[1] + // --------+--------+--------- + // left[0] | tmp[0] tmp[1] <-> err0 err1 + // left[1] | tmp[2] tmp[3] err2 err3 + // + // Final errors {err1,err2,err3} are preserved and later restored + // as top[]/left[] on the next block. +#pragma warning restore SA1005 // Single line comments should begin with single space + Span topDerr = it.TopDerr; + Span leftDerr = it.LeftDerr; + for (int ch = 0; ch <= 1; ++ch) + { + // Each macroblock column keeps 2 top errors for each channel, and the left errors keep 2 for each channel. + Span top = topDerr.Slice((it.X * 4) + (ch * 2), 2); + Span left = leftDerr.Slice(ch * 2, 2); + ref short c = ref Unsafe.Add(ref tmp, (uint)(ch * 4 * 16)); + c += (short)(((C1 * top[0]) + (C2 * left[0])) >> (DSHIFT - DSCALE)); + int err0 = QuantizeSingle(ref c, ref mtx); + ref short c1 = ref Unsafe.Add(ref c, (nuint)(1 * 16)); + c1 += (short)(((C1 * top[1]) + (C2 * err0)) >> (DSHIFT - DSCALE)); + int err1 = QuantizeSingle(ref c1, ref mtx); + ref short c2 = ref Unsafe.Add(ref c, (nuint)(2 * 16)); + c2 += (short)(((C1 * err0) + (C2 * left[1])) >> (DSHIFT - DSCALE)); + int err2 = QuantizeSingle(ref c2, ref mtx); + ref short c3 = ref Unsafe.Add(ref c, (nuint)(3 * 16)); + c3 += (short)(((C1 * err1) + (C2 * err2)) >> (DSHIFT - DSCALE)); + int err3 = QuantizeSingle(ref c3, ref mtx); + + rd.Derr[ch, 0] = err1; + rd.Derr[ch, 1] = err2; + rd.Derr[ch, 2] = err3; + } + } + + /// + /// Returns a value indicating whether all 256 samples of a 16x16 luma block are equal to its first sample. + /// + /// The block. It has 16 rows of 16 samples, with a row stride of . + /// if the block is flat; otherwise, . + [MethodImpl(InliningOptions.ShortMethod)] + private static bool IsFlatSource16(Span src) + { + // One range check for the whole block lets the loops below read rows without more checks. + ref byte srcRef = ref MemoryMarshal.GetReference(src[..((15 * WebpConstants.Bps) + 16)]); + + if (Vector128.IsHardwareAccelerated) + { + // Each row fills one 16-byte register. One compare against the first sample in all lanes tests the row. + Vector128 v = Vector128.Create(srcRef); + for (nuint y = 0; y < 16 * WebpConstants.Bps; y += WebpConstants.Bps) + { + if (Vector128.LoadUnsafe(ref srcRef, y) != v) + { + return false; + } + } + + return true; + } + + // Each row is two 8-byte words. Each word is compared against the first sample in all bytes. + ulong w = srcRef * 0x0101010101010101UL; + for (nuint y = 0; y < 16 * WebpConstants.Bps; y += WebpConstants.Bps) + { + if (Unsafe.ReadUnaligned(ref Unsafe.Add(ref srcRef, y)) != w || Unsafe.ReadUnaligned(ref Unsafe.Add(ref srcRef, y + 8)) != w) + { + return false; + } + } + + return true; + } + + /// + /// Returns a value indicating whether the blocks have at most non-zero AC levels. + /// + /// The first level of the first block. Each block has 16 levels. + /// The block count. + /// The largest non-zero AC level count of a flat area. + /// if the area is flat; otherwise, . + [MethodImpl(InliningOptions.ShortMethod)] + private static bool IsFlat(ref short levels, int numBlocks, int thresh) + { + int score = 0; + nuint offset = 0; + while (numBlocks-- > 0) + { + for (nuint i = 1; i < 16; i++) + { + // omit DC, we're only interested in AC + score += Unsafe.Add(ref levels, offset + i) != 0 ? 1 : 0; + if (score > thresh) + { + return false; + } + } + + offset += 16; + } + + return true; + } + + /// + /// Multiplies two values and divides the product by 256, rounded to the nearest integer. + /// + /// The first value. + /// The second value. + /// ((a * b) + 128) >> 8. + [MethodImpl(InliningOptions.ShortMethod)] + private static int Mult8B(int a, int b) => ((a * b) + 128) >> 8; + + /// + /// Divides a magnitude by a quantizer step through its fixed-point reciprocal. + /// + /// The magnitude. + /// The fixed-point reciprocal of the step, with QFix fraction bits. + /// The rounding bias, with QFix fraction bits. + /// ((n * iQ) + b) >> QFix. + [MethodImpl(InliningOptions.ShortMethod)] + private static int QuantDiv(uint n, uint iQ, uint b) => (int)(((n * iQ) + b) >> WebpConstants.QFix); + + /// + /// One node of the trellis: a level of one coefficient and the best node of the previous coefficient. + /// + private struct TrellisNode + { + /// + /// The node of the previous coefficient on the best path to this node. + /// + public sbyte Previous; + + /// + /// A value indicating whether the original coefficient is negative. + /// + public bool Sign; + + /// + /// The magnitude of the level. + /// + public short Level; + } +} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8QuantizationMatrix.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8QuantizationMatrix.cs new file mode 100644 index 0000000000..9150a9d065 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8QuantizationMatrix.cs @@ -0,0 +1,25 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.ImageSharp.Formats.Webp.Lossy; + +/// +/// Holds the dequantization factors of one segment for the lossy decoder. +/// +internal class Vp8QuantizationMatrix +{ + /// + /// Gets the luma dequantization factors: index 0 is the DC factor and index 1 is the AC factor. + /// + public int[] Y1Mat { get; } = new int[2]; + + /// + /// Gets the luma second-order (Y2) dequantization factors: index 0 is the DC factor and index 1 is the AC factor. + /// + public int[] Y2Mat { get; } = new int[2]; + + /// + /// Gets the chroma dequantization factors: index 0 is the DC factor and index 1 is the AC factor. + /// + public int[] UvMat { get; } = new int[2]; +} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8RDLevel.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8RateDistortionLevel.cs similarity index 94% rename from src/ImageSharp/Formats/Webp/Lossy/Vp8RDLevel.cs rename to src/ImageSharp/Formats/Webp/Lossy/Vp8RateDistortionLevel.cs index 30e5e77eeb..28e678aac8 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8RDLevel.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8RateDistortionLevel.cs @@ -6,7 +6,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy; /// /// Rate-distortion optimization levels /// -internal enum Vp8RdLevel +internal enum Vp8RateDistortionLevel { /// /// No rd-opt. diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Residual.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Residual.cs index cdd18b5a26..6829f30e45 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Residual.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Residual.cs @@ -6,59 +6,95 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; -using System.Runtime.Intrinsics.X86; namespace SixLabors.ImageSharp.Formats.Webp.Lossy; /// /// On-the-fly info about the current set of residuals. /// +/// +/// The residual does not keep the coefficients. Each operation gets the 16 coefficients of one block as a span, +/// sets from them, and then reads them in place. +/// internal class Vp8Residual { + /// + /// The token id flag that marks a constant probability. The lower 8 bits of such a token hold the probability. + /// + public const int FixedProbaBit = 1 << 14; + + /// + /// The probabilities and statistics of the current coefficient type. + /// + private Vp8EncoderProbabilities proba; + + /// + /// The start of the current coefficient type in the flat probability and statistics tables. + /// + private int probaOffset; + + /// + /// The start of the current coefficient type in the flat level cost table. + /// + private int costOffset; + + /// + /// Gets or sets the position of the first coefficient to code: 1 for the AC blocks of an intra 16x16 macroblock, else 0. + /// public int First { get; set; } + /// + /// Gets or sets the position of the last non-zero coefficient, or -1 if all coefficients are zero. + /// public int Last { get; set; } + /// + /// Gets or sets the coefficient type: 0 for i16 AC, 1 for i16 DC, 2 for chroma, 3 for i4. + /// public int CoeffType { get; set; } - public short[] Coeffs { get; } = new short[16]; - - public Vp8BandProbas[] Prob { get; set; } - - public Vp8Stats[] Stats { get; set; } - - public Vp8Costs[] Costs { get; set; } - - public void Init(int first, int coeffType, Vp8EncProba prob) + /// + /// Gets the probabilities of the current coefficient type in [band][context][proba] order. + /// + public ReadOnlySpan Probas => this.proba.Coeffs.AsSpan(this.probaOffset, Vp8EncoderProbabilities.ProbasPerType); + + /// + /// Selects the coefficient type and the first position for the next blocks. + /// + /// The position of the first coefficient to code. + /// The coefficient type. + /// The encoder probabilities. + public void Init(int first, int coeffType, Vp8EncoderProbabilities prob) { this.First = first; this.CoeffType = coeffType; - this.Prob = prob.Coeffs[this.CoeffType]; - this.Stats = prob.Stats[this.CoeffType]; - this.Costs = prob.RemappedCosts[this.CoeffType]; - this.Coeffs.AsSpan().Clear(); + this.proba = prob; + this.probaOffset = coeffType * Vp8EncoderProbabilities.ProbasPerType; + this.costOffset = coeffType * Vp8EncoderProbabilities.CostsPerType; } - public void SetCoeffs(Span coeffs) + /// + /// Sets to the position of the last non-zero coefficient of one block. + /// + /// The 16 coefficients of the block. If is 1, the first coefficient is 0. + [MethodImpl(InliningOptions.ShortMethod)] + public void SetCoeffs(ReadOnlySpan coeffs) { - if (Sse2.IsSupported) + if (Vector128.IsHardwareAccelerated) { ref short coeffsRef = ref MemoryMarshal.GetReference(coeffs); - Vector128 c0 = Unsafe.As>(ref coeffsRef); - Vector128 c1 = Unsafe.As>(ref Unsafe.Add(ref coeffsRef, 8)); - - // Use SSE2 to compare 16 values with a single instruction. - Vector128 m0 = Sse2.PackSignedSaturate(c0.AsInt16(), c1.AsInt16()); - Vector128 m1 = Sse2.CompareEqual(m0, Vector128.Zero); - - // Get the comparison results as a bitmask into 16bits. Negate the mask to get - // the position of entries that are not equal to zero. We don't need to mask - // out least significant bits according to res->first, since coeffs[0] is 0 - // if res->first > 0. - uint mask = 0x0000ffffu ^ (uint)Sse2.MoveMask(m1); - - // The position of the most significant non-zero bit indicates the position of - // the last non-zero value. + Vector128 c0 = Vector128.LoadUnsafe(ref coeffsRef); + Vector128 c1 = Vector128.LoadUnsafe(ref coeffsRef, 8); + + // Each 16-bit lane of the compare result is 0xFFFF for a zero coefficient and 0 else. + // The narrow keeps the low byte of each lane, so the 16 byte lanes hold the 16 results in coefficient order. + Vector128 zero = Vector128.Narrow( + Vector128.Equals(c0, Vector128.Zero).AsUInt16(), + Vector128.Equals(c1, Vector128.Zero).AsUInt16()); + + // Bit n of the mask is set when coefficient n is not zero. The coefficients before First are zero, + // so they need no mask. The highest set bit is the position of the last non-zero coefficient. + uint mask = 0x0000ffffu ^ zero.ExtractMostSignificantBits(); this.Last = mask != 0 ? BitOperations.Log2(mask) : -1; } else @@ -74,38 +110,45 @@ public void SetCoeffs(Span coeffs) } } } - - coeffs[..16].CopyTo(this.Coeffs); } - // Simulate block coding, but only record statistics. - // Note: no need to record the fixed probas. - public int RecordCoeffs(int ctx) + /// + /// Records the statistics of the tokens that code one block, without writing the tokens. + /// + /// The context of the first token. + /// The 16 coefficients of the block. + /// 1 if the block has a non-zero coefficient, else 0. + /// The fixed probabilities need no statistics. + public int RecordCoeffs(int ctx, ReadOnlySpan coeffs) { + this.SetCoeffs(coeffs); + Span stats = this.proba.Stats.AsSpan(this.probaOffset, Vp8EncoderProbabilities.ProbasPerType); int n = this.First; - Vp8StatsArray s = this.Stats[n].Stats[ctx]; + + // The band of the positions 0 and 1 is the position itself. + int s = Vp8EncoderProbabilities.ProbaIndex(n, ctx); if (this.Last < 0) { - RecordStats(0, s, 0); + RecordStats(0, ref stats[s]); return 0; } while (n <= this.Last) { int v; - RecordStats(1, s, 0); // order of record doesn't matter - while ((v = this.Coeffs[n++]) == 0) + RecordStats(1, ref stats[s]); // order of record doesn't matter + while ((v = coeffs[n++]) == 0) { - RecordStats(0, s, 1); - s = this.Stats[WebpConstants.Vp8EncBands[n]].Stats[0]; + RecordStats(0, ref stats[s + 1]); + s = Vp8EncoderProbabilities.ProbaIndex(WebpConstants.Vp8EncBands[n], 0); } - RecordStats(1, s, 1); + RecordStats(1, ref stats[s + 1]); bool bit = (uint)(v + 1) > 2u; - if (RecordStats(bit ? 1 : 0, s, 2) == 0) + if (RecordStats(bit ? 1 : 0, ref stats[s + 2]) == 0) { // v = -1 or 1 - s = this.Stats[WebpConstants.Vp8EncBands[n]].Stats[1]; + s = Vp8EncoderProbabilities.ProbaIndex(WebpConstants.Vp8EncBands[n], 1); } else { @@ -123,132 +166,295 @@ public int RecordCoeffs(int ctx) int mask = 2 << i; if ((pattern & 1) != 0) { - RecordStats((bits & mask) != 0 ? 1 : 0, s, 3 + i); + RecordStats((bits & mask) != 0 ? 1 : 0, ref stats[s + 3 + i]); } } - s = this.Stats[WebpConstants.Vp8EncBands[n]].Stats[2]; + s = Vp8EncoderProbabilities.ProbaIndex(WebpConstants.Vp8EncBands[n], 2); } } if (n < 16) { - RecordStats(0, s, 0); + RecordStats(0, ref stats[s]); } return 1; } - public int GetResidualCost(int ctx0) + /// + /// Records the tokens that code one block and their statistics. + /// + /// The context of the first token. + /// The 16 coefficients of the block. + /// The destination of the tokens. + /// The number of tokens in . The method adds the new tokens after them. + /// 1 if the block has a non-zero coefficient, else 0. + /// + /// A token holds the bit in bit 15. A token with a variable probability holds the index of the probability in the flat + /// probability table in bits 0 to 13. A token with a constant probability holds and the probability. + /// The emitted bits are the same as the bits that writes, so the tokens + /// can be written after the final probabilities are known. + /// + public int RecordCoeffTokens(int ctx, ReadOnlySpan coeffs, Span tokens, ref int count) { + this.SetCoeffs(coeffs); + Span stats = this.proba.Stats; + int last = this.Last; int n = this.First; - int p0 = this.Prob[n].Probabilities[ctx0].Probabilities[0]; - Vp8Costs[] costs = this.Costs; - Vp8CostArray t = costs[n].Costs[ctx0]; - // bitCost(1, p0) is already incorporated in t[] tables, but only if ctx != 0 - // (as required by the syntax). For ctx0 == 0, we need to add it here or it'll - // be missing during the loop. - int cost = ctx0 == 0 ? LossyUtils.Vp8BitCost(1, (byte)p0) : 0; - - if (this.Last < 0) + // The band of the positions 0 and 1 is the position itself. + int baseId = this.probaOffset + Vp8EncoderProbabilities.ProbaIndex(n, ctx); + if (!AddToken(tokens, ref count, stats, last >= 0, baseId)) { - return LossyUtils.Vp8BitCost(0, (byte)p0); + return 0; } - if (Sse2.IsSupported) + while (n < 16) { - Span scratch = stackalloc byte[32]; - Span ctxs = scratch.Slice(0, 16); - Span levels = scratch.Slice(16); - Span absLevels = stackalloc ushort[16]; - - // Precompute clamped levels and contexts, packed to 8b. - ref short outputRef = ref MemoryMarshal.GetReference(this.Coeffs); - Vector128 c0 = Unsafe.As>(ref outputRef).AsInt16(); - Vector128 c1 = Unsafe.As>(ref Unsafe.Add(ref outputRef, 8)).AsInt16(); - Vector128 d0 = Sse2.Subtract(Vector128.Zero, c0); - Vector128 d1 = Sse2.Subtract(Vector128.Zero, c1); - Vector128 e0 = Sse2.Max(c0, d0); // abs(v), 16b - Vector128 e1 = Sse2.Max(c1, d1); - Vector128 f = Sse2.PackSignedSaturate(e0, e1); - Vector128 g = Sse2.Min(f.AsByte(), Vector128.Create((byte)2)); // context = 0, 1, 2 - Vector128 h = Sse2.Min(f.AsByte(), Vector128.Create((byte)67)); // clampLevel in [0..67] - - ref byte ctxsRef = ref MemoryMarshal.GetReference(ctxs); - ref byte levelsRef = ref MemoryMarshal.GetReference(levels); - ref ushort absLevelsRef = ref MemoryMarshal.GetReference(absLevels); - Unsafe.As>(ref ctxsRef) = g; - Unsafe.As>(ref levelsRef) = h; - Unsafe.As>(ref absLevelsRef) = e0.AsUInt16(); - Unsafe.As>(ref Unsafe.Add(ref absLevelsRef, 8)) = e1.AsUInt16(); - - int level; - int flevel; - for (; n < this.Last; ++n) + int c = coeffs[n++]; + bool sign = c < 0; + int v = sign ? -c : c; + if (!AddToken(tokens, ref count, stats, v != 0, baseId + 1)) { - int ctx = ctxs[n]; - level = levels[n]; - flevel = absLevels[n]; - cost += WebpLookupTables.Vp8LevelFixedCosts[flevel] + t.Costs[level]; - t = costs[n + 1].Costs[ctx]; + baseId = this.probaOffset + Vp8EncoderProbabilities.ProbaIndex(WebpConstants.Vp8EncBands[n], 0); + continue; } - // Last coefficient is always non-zero. - level = levels[n]; - flevel = absLevels[n]; - cost += WebpLookupTables.Vp8LevelFixedCosts[flevel] + t.Costs[level]; - if (n < 15) + if (!AddToken(tokens, ref count, stats, v > 1, baseId + 2)) { - int b = WebpConstants.Vp8EncBands[n + 1]; - int ctx = ctxs[n]; - int lastP0 = this.Prob[b].Probabilities[ctx].Probabilities[0]; - cost += LossyUtils.Vp8BitCost(0, (byte)lastP0); + baseId = this.probaOffset + Vp8EncoderProbabilities.ProbaIndex(WebpConstants.Vp8EncBands[n], 1); } + else + { + if (!AddToken(tokens, ref count, stats, v > 4, baseId + 3)) + { + if (AddToken(tokens, ref count, stats, v != 2, baseId + 4)) + { + AddToken(tokens, ref count, stats, v == 4, baseId + 5); + } + } + else if (!AddToken(tokens, ref count, stats, v > 10, baseId + 6)) + { + if (!AddToken(tokens, ref count, stats, v > 6, baseId + 7)) + { + AddConstantToken(tokens, ref count, v == 6, 159); + } + else + { + AddConstantToken(tokens, ref count, v >= 9, 165); + AddConstantToken(tokens, ref count, (v & 1) == 0, 145); + } + } + else + { + int mask; + ReadOnlySpan tab; + int residue = v - 3; + if (residue < (8 << 1)) + { + // Cat3 (3b) + AddToken(tokens, ref count, stats, false, baseId + 8); + AddToken(tokens, ref count, stats, false, baseId + 9); + residue -= 8 << 0; + mask = 1 << 2; + tab = WebpConstants.Cat3; + } + else if (residue < (8 << 2)) + { + // Cat4 (4b) + AddToken(tokens, ref count, stats, false, baseId + 8); + AddToken(tokens, ref count, stats, true, baseId + 9); + residue -= 8 << 1; + mask = 1 << 3; + tab = WebpConstants.Cat4; + } + else if (residue < (8 << 3)) + { + // Cat5 (5b) + AddToken(tokens, ref count, stats, true, baseId + 8); + AddToken(tokens, ref count, stats, false, baseId + 10); + residue -= 8 << 2; + mask = 1 << 4; + tab = WebpConstants.Cat5; + } + else + { + // Cat6 (11b) + AddToken(tokens, ref count, stats, true, baseId + 8); + AddToken(tokens, ref count, stats, true, baseId + 10); + residue -= 8 << 3; + mask = 1 << 10; + tab = WebpConstants.Cat6; + } + + int tabIdx = 0; + while (mask != 0) + { + AddConstantToken(tokens, ref count, (residue & mask) != 0, tab[tabIdx++]); + mask >>= 1; + } + } - return cost; + baseId = this.probaOffset + Vp8EncoderProbabilities.ProbaIndex(WebpConstants.Vp8EncBands[n], 2); + } + + // The sign bit has the probability 128. This gives the same bits as a uniform bit. + AddConstantToken(tokens, ref count, sign, 128); + if (n == 16 || !AddToken(tokens, ref count, stats, n <= last, baseId)) + { + return 1; // EOB + } } + return 1; + } + + /// + /// Calculates the cost (in 1/256 bit units) to code one block and sets . + /// + /// The context of the first token. + /// The first of the 16 coefficients of the block. The absolute values are not more than 2047. + /// The cost of the block. + public int GetResidualCost(int ctx0, ref short coeffs) + { + this.SetCoeffs(MemoryMarshal.CreateReadOnlySpan(ref coeffs, 16)); + int n = this.First; + + // The band of the positions 0 and 1 is the position itself. + ref byte probas = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(this.proba.Coeffs), (uint)this.probaOffset); + byte p0 = Unsafe.Add(ref probas, (uint)Vp8EncoderProbabilities.ProbaIndex(n, ctx0)); + if (this.Last < 0) { - int v; - for (; n < this.Last; ++n) + return LossyUtils.Vp8BitCost(0, p0); + } + + // bitCost(1, p0) is already incorporated in t[] tables, but only if ctx != 0 + // (as required by the syntax). For ctx0 == 0, we need to add it here or it'll + // be missing during the loop. + int cost = ctx0 == 0 ? LossyUtils.Vp8BitCost(1, p0) : 0; + int last = this.Last; + + // All table reads below are in range: + // - The cost table offsets come from the constant remap table, and every table has MaxVariableLevel + 1 entries. + // - The fixed cost table has 2048 entries, and the quantizer limits the absolute levels to 2047. + ref ushort costs = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(this.proba.LevelCost), (uint)this.costOffset); + ref ushort remap = ref MemoryMarshal.GetReference(Vp8EncoderProbabilities.RemappedCostOffsets); + ref short fixedCosts = ref MemoryMarshal.GetReference(WebpLookupTables.Vp8LevelFixedCosts); + ref ushort t = ref Unsafe.Add(ref costs, (uint)Unsafe.Add(ref remap, (uint)((n * WebpConstants.NumCtx) + ctx0))); + + if (Vector128.IsHardwareAccelerated) + { + // Precompute the absolute levels, the clamped levels and the contexts of all 16 coefficients. + // The 16-bit lanes hold the absolute levels in coefficient order: lanes 0 to 7 of e0 hold the + // coefficients 0 to 7, the lanes of e1 hold the coefficients 8 to 15. The absolute levels are + // not more than 2047, so the signed absolute value is also the unsigned value. + Vector128 e0 = Vector128.Abs(Vector128.LoadUnsafe(ref coeffs)).AsUInt16(); + Vector128 e1 = Vector128.Abs(Vector128.LoadUnsafe(ref coeffs, 8)).AsUInt16(); + + // The clamp to 2 gives the context of the next coefficient (0, 1 or 2). The clamp to 67 gives the + // index into the level cost table. Both clamped values fit in a byte, so the narrow keeps them exactly + // and gives 16 byte lanes in coefficient order. + Vector128 maxCtx = Vector128.Create((ushort)2); + Vector128 maxLevel = Vector128.Create((ushort)WebpConstants.MaxVariableLevel); + Vector128 ctxsV = Vector128.Narrow(Vector128.Min(e0, maxCtx), Vector128.Min(e1, maxCtx)); + Vector128 levelsV = Vector128.Narrow(Vector128.Min(e0, maxLevel), Vector128.Min(e1, maxLevel)); + + Unsafe.SkipInit(out InlineArray16 ctxs); + Unsafe.SkipInit(out InlineArray16 levels); + Unsafe.SkipInit(out InlineArray16 absLevels); + ref byte ctxsRef = ref Unsafe.As, byte>(ref ctxs); + ref byte levelsRef = ref Unsafe.As, byte>(ref levels); + ref ushort absLevelsRef = ref Unsafe.As, ushort>(ref absLevels); + ctxsV.StoreUnsafe(ref ctxsRef); + levelsV.StoreUnsafe(ref levelsRef); + e0.StoreUnsafe(ref absLevelsRef); + e1.StoreUnsafe(ref absLevelsRef, 8); + + // Same as the scalar loop below, with the precomputed values. + for (; n < last; ++n) + { + int ctx = Unsafe.Add(ref ctxsRef, (uint)n); + int level = Unsafe.Add(ref levelsRef, (uint)n); + int flevel = Unsafe.Add(ref absLevelsRef, (uint)n); + cost += Unsafe.Add(ref fixedCosts, (uint)flevel) + Unsafe.Add(ref t, (uint)level); + t = ref Unsafe.Add(ref costs, (uint)Unsafe.Add(ref remap, (uint)(((n + 1) * WebpConstants.NumCtx) + ctx))); + } + } + else + { + for (; n < last; ++n) { - v = Math.Abs(this.Coeffs[n]); + int v = Math.Abs(Unsafe.Add(ref coeffs, (uint)n)); int ctx = v >= 2 ? 2 : v; - cost += LevelCost(t.Costs, v); - t = costs[n + 1].Costs[ctx]; + cost += Unsafe.Add(ref fixedCosts, (uint)v) + Unsafe.Add(ref t, (uint)Math.Min(v, WebpConstants.MaxVariableLevel)); + t = ref Unsafe.Add(ref costs, (uint)Unsafe.Add(ref remap, (uint)(((n + 1) * WebpConstants.NumCtx) + ctx))); } + } - // Last coefficient is always non-zero - v = Math.Abs(this.Coeffs[n]); - cost += LevelCost(t.Costs, v); + // Last coefficient is always non-zero. + { + int v = Math.Abs(Unsafe.Add(ref coeffs, (uint)n)); + cost += Unsafe.Add(ref fixedCosts, (uint)v) + Unsafe.Add(ref t, (uint)Math.Min(v, WebpConstants.MaxVariableLevel)); if (n < 15) { int b = WebpConstants.Vp8EncBands[n + 1]; int ctx = v == 1 ? 1 : 2; - int lastP0 = this.Prob[b].Probabilities[ctx].Probabilities[0]; - cost += LossyUtils.Vp8BitCost(0, (byte)lastP0); + byte lastP0 = Unsafe.Add(ref probas, (uint)Vp8EncoderProbabilities.ProbaIndex(b, ctx)); + cost += LossyUtils.Vp8BitCost(0, lastP0); } - - return cost; } + + return cost; } + /// + /// Adds a token with a variable probability and records its statistics. + /// + /// The destination of the tokens. + /// The number of tokens in . + /// The flat statistics table. + /// The bit value. + /// The index of the probability in the flat probability table. + /// The value of . [MethodImpl(InliningOptions.ShortMethod)] - private static int LevelCost(ReadOnlySpan table, int level) - => WebpLookupTables.Vp8LevelFixedCosts[level] + table[level > WebpConstants.MaxVariableLevel ? WebpConstants.MaxVariableLevel : level]; + private static bool AddToken(Span tokens, ref int count, Span stats, bool bit, int probaIndex) + { + int b = bit ? 1 : 0; + tokens[count++] = (ushort)((b << 15) | probaIndex); + RecordStats(b, ref stats[probaIndex]); + return bit; + } - private static int RecordStats(int bit, Vp8StatsArray statsArr, int idx) + /// + /// Adds a token with a constant probability. + /// + /// The destination of the tokens. + /// The number of tokens in . + /// The bit value. + /// The probability. + [MethodImpl(InliningOptions.ShortMethod)] + private static void AddConstantToken(Span tokens, ref int count, bool bit, int proba) + => tokens[count++] = (ushort)(((bit ? 1 : 0) << 15) | FixedProbaBit | proba); + + /// + /// Records one bit in a statistics entry. + /// + /// The bit value. + /// The statistics entry. The lower 16 bits count the 1 bits. The upper 16 bits count all bits. + /// The value of . + [MethodImpl(InliningOptions.ShortMethod)] + private static int RecordStats(int bit, ref uint stats) { // An overflow is inbound. Note we handle this at 0xfffe0000u instead of // 0xffff0000u to make sure p + 1u does not overflow. - if (statsArr.Stats[idx] >= 0xfffe0000u) + if (stats >= 0xfffe0000u) { - statsArr.Stats[idx] = ((statsArr.Stats[idx] + 1u) >> 1) & 0x7fff7fffu; // -> divide the stats by 2. + stats = ((stats + 1u) >> 1) & 0x7fff7fffu; // -> divide the stats by 2. } // Record bit count (lower 16 bits) and increment total count (upper 16 bits). - statsArr.Stats[idx] += 0x00010000u + (uint)bit; + stats += 0x00010000u + (uint)bit; return bit; } diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8SegmentHeader.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8SegmentHeader.cs index 15e2917cf5..922a7bcdd9 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8SegmentHeader.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8SegmentHeader.cs @@ -11,6 +11,9 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy; /// internal class Vp8SegmentHeader { + /// + /// The number of macroblock segments in a VP8 frame. See RFC 6386, section 9.3: https://www.rfc-editor.org/rfc/rfc6386#section-9.3. + /// private const int NumMbSegments = 4; /// diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8SegmentInfo.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8SegmentInfo.cs index c187a553e1..debedac62e 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8SegmentInfo.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8SegmentInfo.cs @@ -3,21 +3,24 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy; +/// +/// Holds the quantization and rate-distortion parameters of one segment of a lossy frame. +/// internal class Vp8SegmentInfo { /// - /// Gets the quantization matrix y1. + /// The quantization matrix of the luma blocks: the intra 4x4 blocks and the AC coefficients of the intra 16x16 blocks. /// #pragma warning disable SA1401 // Fields should be private public Vp8Matrix Y1; /// - /// Gets the quantization matrix y2. + /// The quantization matrix of the Y2 block: the DC coefficients of the intra 16x16 blocks. /// public Vp8Matrix Y2; /// - /// Gets the quantization matrix uv. + /// The quantization matrix of the chroma blocks. /// public Vp8Matrix Uv; #pragma warning restore SA1401 // Fields should be private @@ -57,16 +60,49 @@ internal class Vp8SegmentInfo /// public int MinDisto { get; set; } + /// + /// Gets or sets the rate weight of the intra 16x16 mode decision. + /// public int LambdaI16 { get; set; } + /// + /// Gets or sets the rate weight of the intra 4x4 mode decision. + /// public int LambdaI4 { get; set; } + /// + /// Gets or sets the weight of the spectral distortion. The segment setup keeps the value at 1 or more. + /// public int TLambda { get; set; } + /// + /// Gets or sets the rate weight of the chroma mode decision. + /// public int LambdaUv { get; set; } + /// + /// Gets or sets the rate weight of the intra 4x4 mode headers. + /// public int LambdaMode { get; set; } + /// + /// Gets or sets the rate weight of the trellis quantization of the intra 4x4 blocks. + /// + public int LambdaTrellisI4 { get; set; } + + /// + /// Gets or sets the rate weight of the trellis quantization of the AC coefficients of the intra 16x16 blocks. + /// + public int LambdaTrellisI16 { get; set; } + + /// + /// Raises to the largest magnitude of the first three AC coefficients of the Y2 block, when it is larger. + /// + /// + /// The Y2 coefficients 1, 2 and 4 are the lowest frequencies of the DC values of the 16 luma blocks. Their size gives the average + /// difference between the 4x4 blocks, which the filter strength selection uses. + /// + /// The 16 Y2 coefficients of a macroblock. public void StoreMaxDelta(ReadOnlySpan dcs) { // We look at the first three AC coefficients to determine what is the average diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Stats.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Stats.cs deleted file mode 100644 index dda921a7c7..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Stats.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossy; - -internal class Vp8Stats -{ - /// - /// Initializes a new instance of the class. - /// - public Vp8Stats() - { - this.Stats = new Vp8StatsArray[WebpConstants.NumCtx]; - for (int i = 0; i < WebpConstants.NumCtx; i++) - { - this.Stats[i] = new Vp8StatsArray(); - } - } - - public Vp8StatsArray[] Stats { get; } -} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8StatsArray.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8StatsArray.cs deleted file mode 100644 index 2fbba6996d..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8StatsArray.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossy; - -internal class Vp8StatsArray -{ - /// - /// Initializes a new instance of the class. - /// - public Vp8StatsArray() => this.Stats = new uint[WebpConstants.NumProbas]; - - public uint[] Stats { get; } -} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8TokenBuffer.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8TokenBuffer.cs new file mode 100644 index 0000000000..caa5220f06 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8TokenBuffer.cs @@ -0,0 +1,183 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Buffers; +using SixLabors.ImageSharp.Formats.Webp.BitWriter; +using SixLabors.ImageSharp.Memory; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossy; + +/// +/// Keeps the coefficient tokens of a frame until the final probabilities are known. +/// +/// +/// A token is one bit with a probability. The token holds the bit in bit 15. A token with a variable probability holds the +/// index of the probability in the flat probability table in bits 0 to 13. A token with a constant probability holds +/// and the probability in bits 0 to 7. +/// The tokens are kept in pages from the memory allocator. The pages stay allocated until the buffer is disposed, +/// so the passes of one frame use the same pages again. +/// +internal sealed class Vp8TokenBuffer : IDisposable +{ + /// + /// The maximum number of tokens of one macroblock. + /// + /// + /// A macroblock has not more than 25 blocks (1 DC, 16 luma and 8 chroma blocks). + /// A block has 1 token for the first coefficient check. Each of its 16 coefficients has not more than 19 tokens: + /// 4 tokens for the zero, one, four and ten checks, 2 category tokens, 11 extra bits, 1 sign token and 1 end of block token. + /// + private const int MaxTokensPerMacroBlock = 25 * (1 + (16 * 19)); + + /// + /// The minimum number of tokens in one page. This is also more than . + /// + private const int MinPageSize = 8192; + + /// + /// The memory allocator for the pages. + /// + private readonly MemoryAllocator memoryAllocator; + + /// + /// The number of tokens in one page. + /// + private readonly int pageSize; + + /// + /// The allocated pages. The pages with an index below are in use. + /// + private readonly List> pages = []; + + /// + /// The number of tokens in each full page. The entry count is - 1. + /// + private readonly List pageLengths = []; + + /// + /// The number of pages in use. The last page in use is the current page. + /// + private int pageCount; + + /// + /// The number of tokens in the current page. + /// + private int position; + + /// + /// Initializes a new instance of the class. + /// + /// The memory allocator for the pages. + /// The number of macroblocks in a row. + /// The number of macroblock rows. + /// The encoding quality in [0..100]. + public Vp8TokenBuffer(MemoryAllocator memoryAllocator, int mbw, int mbh, uint quality) + { + this.memoryAllocator = memoryAllocator; + + // A lower quality gives fewer tokens. The page size is a rough first order guess of the token count. + float scale = 1f + (quality * 5f / 100f); + this.pageSize = Math.Max((int)(mbw * mbh * 4 * scale), MinPageSize); + } + + /// + /// Removes all tokens. The allocated pages stay for the next pass. + /// + public void Clear() + { + this.pageCount = 0; + this.position = 0; + this.pageLengths.Clear(); + } + + /// + /// Gets the free part of the current page. The span has space for the tokens of one macroblock. + /// + /// The free part of the current page. + /// Call with the number of tokens written before the next call. + public Span GetMacroBlockSpan() + { + if (this.pageCount == 0 || this.pageSize - this.position < MaxTokensPerMacroBlock) + { + // Start the next page. The tail of a full page is not used, so each page records its length. + if (this.pageCount > 0) + { + this.pageLengths.Add(this.position); + } + + if (this.pageCount == this.pages.Count) + { + // Each token is written before it is read, so the page needs no clear. + this.pages.Add(this.memoryAllocator.Allocate(this.pageSize)); + } + + this.pageCount++; + this.position = 0; + } + + return this.pages[this.pageCount - 1].Memory.Span[this.position..]; + } + + /// + /// Adds the tokens written to the span from to the buffer. + /// + /// The number of tokens written. + public void Advance(int count) => this.position += count; + + /// + /// Writes all tokens in order with their final probabilities. + /// + /// The bit writer. + /// The final probabilities in the flat [type][band][context][proba] order. + public void Emit(Vp8BitWriter bitWriter, ReadOnlySpan probas) + { + for (int i = 0; i < this.pageCount; i++) + { + bitWriter.PutTokens(this.GetPageTokens(i), probas); + } + } + + /// + /// Calculates the cost (in 1/256 bit units) of all tokens with the given probabilities. + /// + /// The probabilities in the flat [type][band][context][proba] order. + /// The cost of all tokens. + public long EstimateSize(ReadOnlySpan probas) + { + long size = 0; + for (int i = 0; i < this.pageCount; i++) + { + foreach (ushort token in this.GetPageTokens(i)) + { + int bit = token >> 15; + byte proba = (token & Vp8Residual.FixedProbaBit) != 0 ? (byte)token : probas[token & 0x3fff]; + size += LossyUtils.Vp8BitCost(bit, proba); + } + } + + return size; + } + + /// + public void Dispose() + { + foreach (IMemoryOwner page in this.pages) + { + page.Dispose(); + } + + this.pages.Clear(); + this.Clear(); + } + + /// + /// Gets the tokens of one page in use. + /// + /// The page index. + /// The tokens of the page. + private ReadOnlySpan GetPageTokens(int index) + { + int length = index < this.pageCount - 1 ? this.pageLengths[index] : this.position; + return this.pages[index].Memory.Span[..length]; + } +} diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8TopSamples.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8TopSamples.cs deleted file mode 100644 index 5b87d7914b..0000000000 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8TopSamples.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.ImageSharp.Formats.Webp.Lossy; - -internal class Vp8TopSamples -{ - public byte[] Y { get; } = new byte[16]; - - public byte[] U { get; } = new byte[8]; - - public byte[] V { get; } = new byte[8]; -} diff --git a/src/ImageSharp/Formats/Webp/Lossy/WebpLossyDecoder.cs b/src/ImageSharp/Formats/Webp/Lossy/WebpLossyDecoder.cs index 0018e3478a..f11018cb79 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/WebpLossyDecoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/WebpLossyDecoder.cs @@ -6,6 +6,7 @@ using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; using SixLabors.ImageSharp.ColorProfiles; using SixLabors.ImageSharp.Formats.Webp.BitReader; using SixLabors.ImageSharp.Formats.Webp.ColorConverters; @@ -72,7 +73,8 @@ public bool TryReadHeaders(WebpImageInfo info, SegmentIntegrityHandling segmentI { decoder = null; - // libwebp rejects a first partition that cannot start the bit reader. + // RFC 6386, section 7.2, keeps the bool decoder value less than the range at all times. The range starts at 255, so a first partition + // that starts with 0xFF is not valid. if (!this.bitReader.IsStartValid) { segmentIntegrityHandling.ThrowOrIgnoreImageDataError(imageExists, "The VP8 first partition starts with a value that is not valid."); @@ -86,14 +88,12 @@ public bool TryReadHeaders(WebpImageInfo info, SegmentIntegrityHandling segmentI { Width = info.Width, Height = info.Height, - XScale = info.XScale, - YScale = info.YScale, ColorSpace = colorSpace, ClampType = clampType }; // Paragraph 9.3: Parse the segment header. - Vp8Proba proba = new(); + Vp8Probabilities proba = new(); Vp8SegmentHeader vp8SegmentHeader = this.ParseSegmentHeader(proba); Vp8Decoder vp8Decoder = new( @@ -124,7 +124,8 @@ public bool TryReadHeaders(WebpImageInfo info, SegmentIntegrityHandling segmentI // Paragraph 13.4: The method parses the probabilities. this.ParseProbabilities(vp8Decoder); - // libwebp rejects frame headers that end before their last field. The bit reader keeps the end-of-data state, so one check covers all headers. + // RFC 6386, section 19.2, defines the fields of the frame header. Data that ends before the last field is not a valid frame header. + // The bit reader keeps the end-of-data state, so one check covers all headers. if (this.bitReader.Eof) { segmentIntegrityHandling.ThrowOrIgnoreImageDataError(imageExists, "The VP8 frame header ends before its last field."); @@ -152,9 +153,10 @@ public bool TryReadHeaders(WebpImageInfo info, SegmentIntegrityHandling segmentI /// The ALPH chunk data, or when the image has no ALPH chunk. /// The selected source ICC converter, if available. /// The image data integrity mode. It controls damaged or truncated image data. - public void Decode( + /// The number of rows from the top that the method wrote. Damaged data in the ignore mode can stop the decode before the last row. + public int Decode( Vp8Decoder decoder, - Buffer2D pixels, + Buffer2DRegion pixels, WebpImageInfo info, IMemoryOwner alphaData, ColorProfileConverter colorProfileConverter, @@ -163,16 +165,13 @@ public void Decode( { int width = (int)info.Width; decoder.AllocateBuffers(this.memoryAllocator); - Vp8Io io = InitializeVp8Io(decoder); - - // Select the native YCbCr converter once from the embedded source profile. - WebpColorConverterBase colorConverter = WebpColorConverterBase.GetYCbCrConverter(colorProfileConverter); - int decodedRows = this.ParseFrame(decoder, io, colorConverter, segmentIntegrityHandling); + InitializeMacroBlockRange(decoder); // As in libwebp, only ALPH data adds alpha. A VP8X alpha flag without an ALPH chunk gives opaque pixels. - if (alphaData is not null) - { - using AlphaDecoder alphaDecoder = new( + // The alpha plane is decoded first, so that each color row can join its alpha row when it is written. + using AlphaDecoder alphaDecoder = alphaData is null + ? null + : new AlphaDecoder( width, (int)info.Height, alphaData, @@ -180,56 +179,15 @@ public void Decode( this.memoryAllocator, this.configuration, segmentIntegrityHandling); - alphaDecoder.Decode(); - this.DecodePixelValues( - width, - decodedRows, - decoder.Pixels.Memory.Span, - pixels, - alphaDecoder.Alpha.Memory.Span, - colorConverter, - colorProfileConverter); - } - else - { - this.DecodePixelValues(width, decodedRows, decoder.Pixels.Memory.Span, pixels, ReadOnlySpan.Empty, colorConverter, colorProfileConverter); - } - } - /// - /// Converts the decoded rows to the pixel buffer. - /// - /// The pixel format. - /// The width of the image. - /// The number of rows to convert. The rows after them keep their fill value. - /// The decoded rows. - /// The pixel buffer to write to. - /// The decoded alpha rows, or empty when the image has no alpha. - /// The YCbCr converter. - /// The selected source ICC converter, if available. - private void DecodePixelValues( - int width, - int height, - Span pixelData, - Buffer2D decodedPixels, - ReadOnlySpan alpha, - WebpColorConverterBase colorConverter, - ColorProfileConverter colorProfileConverter) - where TPixel : unmanaged, IPixel - { - using IMemoryOwner vectorOwner = colorProfileConverter is null ? null : this.memoryAllocator.Allocate(width); - using IMemoryOwner rgbOwner = colorProfileConverter is null ? null : this.memoryAllocator.Allocate(width); - Span vectors = vectorOwner is null ? Span.Empty : vectorOwner.Memory.Span; - Span rgb = rgbOwner is null ? Span.Empty : rgbOwner.Memory.Span; + alphaDecoder?.Decode(); - int widthMul3 = width * 3; - for (int y = 0; y < height; y++) - { - Span row = pixelData.Slice(y * widthMul3, widthMul3); - Span decodedPixelRow = decodedPixels.DangerousGetRowSpan(y); - ReadOnlySpan alphaRow = alpha.IsEmpty ? ReadOnlySpan.Empty : alpha.Slice(y * width, width); - colorConverter.ConvertYuvRow(this.configuration, row, alphaRow, colorProfileConverter, vectors, rgb, decodedPixelRow); - } + WebpColorConverterBase colorConverter = WebpColorConverterBase.GetConverter(WebpColorType.Yuv); + using YuvToRgbConverter writer = + new(this.configuration, this.memoryAllocator, pixels, width, alphaDecoder?.Alpha, colorConverter, colorProfileConverter); + + this.ParseFrame(decoder, writer, segmentIntegrityHandling); + return writer.RowsWritten; } /// @@ -239,13 +197,19 @@ private void DecodePixelValues( /// As in libwebp, the decode stops at the first macroblock row whose data ends early. The method keeps the rows before it. /// /// The decoder. - /// The output description. - /// The YCbCr converter. + /// The writer of the destination rows. /// The image data integrity mode. It controls data that ends early. - /// The number of complete pixel rows. - private int ParseFrame(Vp8Decoder dec, Vp8Io io, WebpColorConverterBase colorConverter, SegmentIntegrityHandling segmentIntegrityHandling) + private void ParseFrame( + Vp8Decoder dec, + YuvToRgbConverter writer, + SegmentIntegrityHandling segmentIntegrityHandling) + where TPixel : unmanaged, IPixel { - int decodedRows = 0; + // The per-column state is in pooled buffers that live for the whole frame, so the spans are taken once. + Span macroBlockData = dec.MacroBlockData.GetSpan(); + Span macroBlockInfo = dec.MacroBlockInfo.GetSpan(); + Span filterInfo = dec.FilterInfo.GetSpan(); + Span intraT = dec.IntraT.GetSpan(); for (dec.MbY = 0; dec.MbY < dec.BottomRightMbY; ++dec.MbY) { // Parse bitstream for this row. @@ -255,25 +219,28 @@ private int ParseFrame(Vp8Decoder dec, Vp8Io io, WebpColorConverterBase colorCon // Parse intra mode mode row. for (int mbX = 0; mbX < dec.MbWidth; ++mbX) { - this.ParseIntraMode(dec, mbX); + ParseIntraMode(dec, ref macroBlockData[mbX], intraT.Slice(4 * mbX, 4), this.bitReader); } - // libwebp stops when the first partition ends before the intra modes of the row are complete. + // RFC 6386, section 9.11, puts the prediction data of all macroblocks in the first partition. When the partition ends before the + // intra modes of the row are complete, the data is truncated. As in libwebp, the decode stops here. if (this.bitReader.Eof) { segmentIntegrityHandling.ThrowOrIgnoreImageDataError("The VP8 first partition ends before the last macroblock row."); - return decodedRows; + return; } while (dec.MbX < dec.MbWidth) { - this.DecodeMacroBlock(dec, bitreader); + int mbX = dec.MbX; + DecodeMacroBlock(dec, bitreader, ref macroBlockInfo[mbX], ref macroBlockData[mbX], ref filterInfo[mbX]); - // libwebp stops when a token partition ends before the macroblock is complete. + // RFC 6386, section 9.5, puts the DCT tokens of each macroblock row in one token partition. When that partition ends before the + // macroblock is complete, the data is truncated. As in libwebp, the decode stops here. if (bitreader.Eof) { segmentIntegrityHandling.ThrowOrIgnoreImageDataError("The VP8 token partition ends before the last macroblock."); - return decodedRows; + return; } ++dec.MbX; @@ -283,25 +250,33 @@ private int ParseFrame(Vp8Decoder dec, Vp8Io io, WebpColorConverterBase colorCon InitScanline(dec); // Reconstruct, filter and emit the row. - // A row that emits no output returns a smaller count, so keep the larger value. - decodedRows = Math.Max(decodedRows, this.ProcessRow(dec, io, colorConverter)); + ReconstructRow(dec); + FinishRow(dec, writer); } - - return decodedRows; } - private void ParseIntraMode(Vp8Decoder dec, int mbX) + /// + /// Reads the segment, the skip flag and the luma and chroma prediction modes of one macroblock from the first partition. + /// The modes go to the macroblock data. The 4x4 modes also update the top and left mode contexts. + /// + /// The decoder. + /// The macroblock data of the column. + /// The 4 top intra modes of the column. + /// The reader of the first partition. + private static void ParseIntraMode(Vp8Decoder dec, ref Vp8MacroBlockData block, Span top, Vp8BitReader br) { - Vp8MacroBlockData block = dec.MacroBlockData[mbX]; - Span top = dec.IntraT.AsSpan(4 * mbX, 4); - byte[] left = dec.IntraL; + // The arithmetic state stays in locals for the macroblock, so the JIT can keep it in registers. A field of the reader stays in memory, and + // each bit then waits for a store and a load. + br.LoadState(out ulong value, out int bits, out uint range); + Span left = dec.IntraL; if (dec.SegmentHeader.UpdateMap) { // Hardcoded tree parsing. - block.Segment = this.bitReader.GetBit((int)dec.Probabilities.Segments[0]) == 0 - ? (byte)this.bitReader.GetBit((int)dec.Probabilities.Segments[1]) - : (byte)(this.bitReader.GetBit((int)dec.Probabilities.Segments[2]) + 2); + uint[] segments = dec.Probabilities.Segments; + block.Segment = Vp8BitReader.GetBit(br, ref value, ref bits, ref range, (int)segments[0]) == 0 + ? (byte)Vp8BitReader.GetBit(br, ref value, ref bits, ref range, (int)segments[1]) + : (byte)(Vp8BitReader.GetBit(br, ref value, ref bits, ref range, (int)segments[2]) + 2); } else { @@ -311,26 +286,21 @@ private void ParseIntraMode(Vp8Decoder dec, int mbX) if (dec.UseSkipProbability) { - block.Skip = this.bitReader.GetBit(dec.SkipProbability) == 1; + block.Skip = Vp8BitReader.GetBit(br, ref value, ref bits, ref range, dec.SkipProbability) == 1; } - block.IsI4x4 = this.bitReader.GetBit(145) == 0; + block.IsI4x4 = Vp8BitReader.GetBit(br, ref value, ref bits, ref range, 145) == 0; if (!block.IsI4x4) { // Hardcoded 16x16 intra-mode decision tree. int yMode; - if (this.bitReader.GetBit(156) != 0) + if (Vp8BitReader.GetBit(br, ref value, ref bits, ref range, 156) != 0) { - if (this.bitReader.GetBit(128) != 0) - { - yMode = (int)IntraPredictionMode.TrueMotion; - } - else - { - yMode = (int)IntraPredictionMode.HPrediction; - } + yMode = Vp8BitReader.GetBit(br, ref value, ref bits, ref range, 128) != 0 + ? (int)IntraPredictionMode.TrueMotion + : (int)IntraPredictionMode.HPrediction; } - else if (this.bitReader.GetBit(163) != 0) + else if (Vp8BitReader.GetBit(br, ref value, ref bits, ref range, 163) != 0) { yMode = (int)IntraPredictionMode.VPrediction; } @@ -340,87 +310,76 @@ private void ParseIntraMode(Vp8Decoder dec, int mbX) } block.Modes[0] = (byte)yMode; - for (int i = 0; i < left.Length; i++) - { - left[i] = (byte)yMode; - top[i] = (byte)yMode; - } + + // The 4 left and the 4 top contexts get the mode. One 4-byte store writes each of them. + uint modes4 = (uint)yMode * 0x01010101u; + Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(left), modes4); + Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(top), modes4); } else { - Span modes = block.Modes.AsSpan(); + // The probabilities of the top and left modes are 9 bytes at ((top * 10) + left) * 9. The modes are less than 10, so each read is in range. + ref byte probabilities = ref MemoryMarshal.GetReference(WebpLookupTables.ModesProba); + ref sbyte tree = ref MemoryMarshal.GetReference(WebpConstants.YModesIntra4); + ref byte modes = ref block.Modes[0]; for (int y = 0; y < 4; y++) { int yMode = left[y]; for (int x = 0; x < 4; x++) { - byte[] prob = WebpLookupTables.ModesProba[top[x], yMode]; - int i = WebpConstants.YModesIntra4[this.bitReader.GetBit(prob[0])]; + ref byte prob = ref Unsafe.Add(ref probabilities, (uint)(((top[x] * WebpConstants.NumBModes) + yMode) * 9)); + int i = Unsafe.Add(ref tree, (uint)Vp8BitReader.GetBit(br, ref value, ref bits, ref range, prob)); while (i > 0) { - i = WebpConstants.YModesIntra4[(2 * i) + this.bitReader.GetBit(prob[i])]; + i = Unsafe.Add(ref tree, (uint)((2 * i) + Vp8BitReader.GetBit(br, ref value, ref bits, ref range, Unsafe.Add(ref prob, (uint)i)))); } yMode = -i; top[x] = (byte)yMode; } - top.CopyTo(modes); - modes = modes[4..]; + // The 4 top modes are the modes of this block row. One 4-byte copy stores them. + Unsafe.WriteUnaligned(ref Unsafe.Add(ref modes, (uint)(4 * y)), Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(top))); left[y] = (byte)yMode; } } // Hardcoded UVMode decision tree. - if (this.bitReader.GetBit(142) == 0) + if (Vp8BitReader.GetBit(br, ref value, ref bits, ref range, 142) == 0) { - // Hardcoded UVMode decision tree. block.UvMode = 0; } - else if (this.bitReader.GetBit(114) == 0) + else if (Vp8BitReader.GetBit(br, ref value, ref bits, ref range, 114) == 0) { - // Hardcoded UVMode decision tree. block.UvMode = 2; } - else if (this.bitReader.GetBit(183) != 0) - { - // Hardcoded UVMode decision tree. - block.UvMode = 1; - } else { - // Hardcoded UVMode decision tree. - block.UvMode = 3; + block.UvMode = Vp8BitReader.GetBit(br, ref value, ref bits, ref range, 183) != 0 ? (byte)1 : (byte)3; } + + br.StoreState(value, bits, range); } + /// + /// Prepares the decoder for the next macroblock row. It clears the left non-zero context and the left intra modes, and sets the column to 0. + /// + /// The decoder. private static void InitScanline(Vp8Decoder dec) { - Vp8MacroBlock left = dec.LeftMacroBlock; - left.NoneZeroAcDcCoeffs = 0; - left.NoneZeroDcCoeffs = 0; - for (int i = 0; i < dec.IntraL.Length; i++) - { - dec.IntraL[i] = 0; - } + dec.LeftMacroBlock = default; + // The 4 left intra modes are one 4-byte store. + Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(dec.IntraL), 0U); dec.MbX = 0; } /// - /// Reconstructs, filters and emits the current macroblock row. + /// Reconstructs the current macroblock row. For each macroblock, it predicts the samples, adds the inverse transform of the residuals, + /// and copies the result to the Y, U and V caches. Samples outside the image use the fixed border values 127 above and 129 to the left. /// /// The decoder. - /// The output description. - /// The YCbCr converter. - /// The number of complete pixel rows after this macroblock row. - private int ProcessRow(Vp8Decoder dec, Vp8Io io, WebpColorConverterBase colorConverter) - { - this.ReconstructRow(dec); - return FinishRow(dec, io, colorConverter); - } - - private void ReconstructRow(Vp8Decoder dec) + private static void ReconstructRow(Vp8Decoder dec) { int mby = dec.MbY; const int yOff = (WebpConstants.Bps * 1) + 8; @@ -431,19 +390,24 @@ private void ReconstructRow(Vp8Decoder dec) Span yDst = yuv[yOff..]; Span uDst = yuv[uOff..]; Span vDst = yuv[vOff..]; + ref byte yRef = ref MemoryMarshal.GetReference(yDst); + ref byte uRef = ref MemoryMarshal.GetReference(uDst); + ref byte vRef = ref MemoryMarshal.GetReference(vDst); - // Initialize left-most block. - int end = 16 * WebpConstants.Bps; - for (int i = 0; i < end; i += WebpConstants.Bps) + // Initialize left-most block. The left samples are the column before each block, so the refs start one sample before the blocks and + // step down one row at a time. + ref byte yLeft = ref Unsafe.Subtract(ref yRef, (nuint)1); + for (nuint i = 0; i < 16; i++) { - yuv[i - 1 + yOff] = 129; + Unsafe.Add(ref yLeft, i * WebpConstants.Bps) = 129; } - end = 8 * WebpConstants.Bps; - for (int i = 0; i < end; i += WebpConstants.Bps) + ref byte uLeft = ref Unsafe.Subtract(ref uRef, (nuint)1); + ref byte vLeft = ref Unsafe.Subtract(ref vRef, (nuint)1); + for (nuint i = 0; i < 8; i++) { - yuv[i - 1 + uOff] = 129; - yuv[i - 1 + vOff] = 129; + Unsafe.Add(ref uLeft, i * WebpConstants.Bps) = 129; + Unsafe.Add(ref vLeft, i * WebpConstants.Bps) = 129; } // Init top-left sample on left column too. @@ -455,64 +419,66 @@ private void ReconstructRow(Vp8Decoder dec) { // We only need to do this init once at block (0,0). // Afterward, it remains valid for the whole topmost row. - Span tmp = yuv.Slice(yOff - WebpConstants.Bps - 1, 16 + 4 + 1); - for (int i = 0; i < tmp.Length; i++) - { - tmp[i] = 127; - } - - tmp = yuv.Slice(uOff - WebpConstants.Bps - 1, 8 + 1); - for (int i = 0; i < tmp.Length; i++) - { - tmp[i] = 127; - } - - tmp = yuv.Slice(vOff - WebpConstants.Bps - 1, 8 + 1); - for (int i = 0; i < tmp.Length; i++) - { - tmp[i] = 127; - } + // The top rows are the top-left sample, the 16 top samples and, for luma, the 4 top-right samples. + yuv.Slice(yOff - WebpConstants.Bps - 1, 16 + 4 + 1).Fill(127); + yuv.Slice(uOff - WebpConstants.Bps - 1, 8 + 1).Fill(127); + yuv.Slice(vOff - WebpConstants.Bps - 1, 8 + 1).Fill(127); } - Span scratch = stackalloc int[16]; - Span scratchBytes = stackalloc byte[4]; + InlineArray16 scratchBuffer = default; + Span scratch = scratchBuffer; + + // The coefficients, the per-column state and the caches are the same for each macroblock of the row. + Span rowCoefficients = dec.Coefficients.GetSpan(); + Span macroBlockData = dec.MacroBlockData.GetSpan(); + ref byte topSamples = ref MemoryMarshal.GetReference(dec.YuvTopSamples.GetSpan()); + ref byte cacheYRef = ref MemoryMarshal.GetReference(dec.CacheY.Memory.Span); + ref byte cacheURef = ref MemoryMarshal.GetReference(dec.CacheU.Memory.Span); + ref byte cacheVRef = ref MemoryMarshal.GetReference(dec.CacheV.Memory.Span); + nuint cacheYStride = (uint)dec.CacheYStride; + nuint cacheUvStride = (uint)dec.CacheUvStride; // Reconstruct one row. for (int mbx = 0; mbx < dec.MbWidth; mbx++) { - Vp8MacroBlockData block = dec.MacroBlockData[mbx]; + ref Vp8MacroBlockData block = ref macroBlockData[mbx]; // Rotate in the left samples from previously decoded block. We move four // pixels at a time for alignment reason, and because of in-loop filter. if (mbx > 0) { - for (int i = -1; i < 16; i++) + // Each row moves its last 4 samples to the 4 samples before the row, with one 4-byte read and write. The row before the block is the + // top row, so it moves too. The row refs start at that top row and step down, so all offsets are unsigned. + ref byte yRow = ref Unsafe.Subtract(ref yRef, (nuint)WebpConstants.Bps); + for (int i = 0; i < 17; i++) { - int srcIdx = (i * WebpConstants.Bps) + 12 + yOff; - int dstIdx = (i * WebpConstants.Bps) - 4 + yOff; - yuv.Slice(srcIdx, 4).CopyTo(yuv[dstIdx..]); + Unsafe.WriteUnaligned(ref Unsafe.Subtract(ref yRow, (nuint)4), Unsafe.ReadUnaligned(ref Unsafe.Add(ref yRow, (nuint)12))); + yRow = ref Unsafe.Add(ref yRow, (nuint)WebpConstants.Bps); } - for (int i = -1; i < 8; i++) + ref byte uRow = ref Unsafe.Subtract(ref uRef, (nuint)WebpConstants.Bps); + ref byte vRow = ref Unsafe.Subtract(ref vRef, (nuint)WebpConstants.Bps); + for (int i = 0; i < 9; i++) { - int srcIdx = (i * WebpConstants.Bps) + 4 + uOff; - int dstIdx = (i * WebpConstants.Bps) - 4 + uOff; - yuv.Slice(srcIdx, 4).CopyTo(yuv[dstIdx..]); - srcIdx = (i * WebpConstants.Bps) + 4 + vOff; - dstIdx = (i * WebpConstants.Bps) - 4 + vOff; - yuv.Slice(srcIdx, 4).CopyTo(yuv[dstIdx..]); + Unsafe.WriteUnaligned(ref Unsafe.Subtract(ref uRow, (nuint)4), Unsafe.ReadUnaligned(ref Unsafe.Add(ref uRow, (nuint)4))); + Unsafe.WriteUnaligned(ref Unsafe.Subtract(ref vRow, (nuint)4), Unsafe.ReadUnaligned(ref Unsafe.Add(ref vRow, (nuint)4))); + uRow = ref Unsafe.Add(ref uRow, (nuint)WebpConstants.Bps); + vRow = ref Unsafe.Add(ref vRow, (nuint)WebpConstants.Bps); } } - // Bring top samples into the cache. - Vp8TopSamples topYuv = dec.YuvTopSamples[mbx]; - short[] coeffs = block.Coeffs; + // Bring top samples into the cache. The top samples of a column are 16 Y, 8 U and 8 V samples at fixed offsets. + ref byte topY = ref Unsafe.Add(ref topSamples, (uint)(mbx * Vp8Decoder.TopSamplesPerMacroBlock)); + ref byte topU = ref Unsafe.Add(ref topY, (nuint)Vp8Decoder.TopSamplesUOffset); + ref byte topV = ref Unsafe.Add(ref topY, (nuint)Vp8Decoder.TopSamplesVOffset); + Span coeffs = rowCoefficients.Slice(mbx * Vp8Decoder.CoefficientsPerMacroBlock, Vp8Decoder.CoefficientsPerMacroBlock); uint bits = block.NonZeroY; if (mby > 0) { - topYuv.Y.CopyTo(yuv[(yOff - WebpConstants.Bps)..]); - topYuv.U.CopyTo(yuv[(uOff - WebpConstants.Bps)..]); - topYuv.V.CopyTo(yuv[(vOff - WebpConstants.Bps)..]); + // The top samples are 16 luma and 2 x 8 chroma bytes. Fixed-size loads and stores copy them without a call to Memmove. + Unsafe.WriteUnaligned(ref Unsafe.Subtract(ref yRef, (nuint)WebpConstants.Bps), Unsafe.ReadUnaligned>(ref topY)); + Unsafe.WriteUnaligned(ref Unsafe.Subtract(ref uRef, (nuint)WebpConstants.Bps), Unsafe.ReadUnaligned(ref topU)); + Unsafe.WriteUnaligned(ref Unsafe.Subtract(ref vRef, (nuint)WebpConstants.Bps), Unsafe.ReadUnaligned(ref topV)); } // Predict and add residuals. @@ -523,16 +489,15 @@ private void ReconstructRow(Vp8Decoder dec) { if (mbx >= dec.MbWidth - 1) { - // On rightmost border. - byte topYuv15 = topYuv.Y[15]; - topRight[0] = topYuv15; - topRight[1] = topYuv15; - topRight[2] = topYuv15; - topRight[3] = topYuv15; + // On rightmost border. The 4 top-right samples repeat the last top sample, with one 4-byte store. + Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(topRight), 0x01010101U * Unsafe.Add(ref topY, (nuint)15)); } else { - dec.YuvTopSamples[mbx + 1].Y.AsSpan(0, 4).CopyTo(topRight); + // The 4 top-right samples are the first 4 top Y samples of the next column, with one 4-byte copy. + Unsafe.WriteUnaligned( + ref MemoryMarshal.GetReference(topRight), + Unsafe.ReadUnaligned(ref Unsafe.Add(ref topY, (nuint)Vp8Decoder.TopSamplesPerMacroBlock))); } } @@ -545,41 +510,42 @@ private void ReconstructRow(Vp8Decoder dec) { int offset = yOff + WebpConstants.Scan[n]; Span dst = yuv[offset..]; + ref byte blockRef = ref MemoryMarshal.GetReference(dst); switch (block.Modes[n]) { case 0: - LossyUtils.DC4(dst, yuv, offset); + LossyUtils.DC4(ref blockRef); break; case 1: - LossyUtils.TM4(dst, yuv, offset); + LossyUtils.TM4(ref blockRef); break; case 2: - LossyUtils.VE4(dst, yuv, offset, scratchBytes); + LossyUtils.VE4(ref blockRef); break; case 3: - LossyUtils.HE4(dst, yuv, offset); + LossyUtils.HE4(ref blockRef); break; case 4: - LossyUtils.RD4(dst, yuv, offset); + LossyUtils.RD4(ref blockRef); break; case 5: - LossyUtils.VR4(dst, yuv, offset); + LossyUtils.VR4(ref blockRef); break; case 6: - LossyUtils.LD4(dst, yuv, offset); + LossyUtils.LD4(ref blockRef); break; case 7: - LossyUtils.VL4(dst, yuv, offset); + LossyUtils.VL4(ref blockRef); break; case 8: - LossyUtils.HD4(dst, yuv, offset); + LossyUtils.HD4(ref blockRef); break; case 9: - LossyUtils.HU4(dst, yuv, offset); + LossyUtils.HU4(ref blockRef); break; } - DoTransform(bits, coeffs.AsSpan(n * 16), dst, scratch); + DoTransform(bits, coeffs[(n * 16)..], dst, scratch); } } else @@ -588,25 +554,25 @@ private void ReconstructRow(Vp8Decoder dec) switch (CheckMode(mbx, mby, block.Modes[0])) { case 0: - LossyUtils.DC16(yDst, yuv, yOff); + LossyUtils.DC16(ref yRef); break; case 1: - LossyUtils.TM16(yDst, yuv, yOff); + LossyUtils.TM16(ref yRef); break; case 2: - LossyUtils.VE16(yDst, yuv, yOff); + LossyUtils.VE16(ref yRef); break; case 3: - LossyUtils.HE16(yDst, yuv, yOff); + LossyUtils.HE16(ref yRef); break; case 4: - LossyUtils.DC16NoTop(yDst, yuv, yOff); + LossyUtils.DC16NoTop(ref yRef); break; case 5: - LossyUtils.DC16NoLeft(yDst, yuv, yOff); + LossyUtils.DC16NoLeft(ref yRef); break; case 6: - LossyUtils.DC16NoTopLeft(yDst); + LossyUtils.DC16NoTopLeft(ref yRef); break; } @@ -614,7 +580,7 @@ private void ReconstructRow(Vp8Decoder dec) { for (int n = 0; n < 16; ++n, bits <<= 2) { - DoTransform(bits, coeffs.AsSpan(n * 16), yDst[WebpConstants.Scan[n]..], scratch); + DoTransform(bits, coeffs[(n * 16)..], yDst[WebpConstants.Scan[n]..], scratch); } } } @@ -624,108 +590,139 @@ private void ReconstructRow(Vp8Decoder dec) switch (CheckMode(mbx, mby, block.UvMode)) { case 0: - LossyUtils.DC8uv(uDst, yuv, uOff); - LossyUtils.DC8uv(vDst, yuv, vOff); + LossyUtils.DC8uv(ref uRef); + LossyUtils.DC8uv(ref vRef); break; case 1: - LossyUtils.TM8uv(uDst, yuv, uOff); - LossyUtils.TM8uv(vDst, yuv, vOff); + LossyUtils.TM8uv(ref uRef); + LossyUtils.TM8uv(ref vRef); break; case 2: - LossyUtils.VE8uv(uDst, yuv, uOff); - LossyUtils.VE8uv(vDst, yuv, vOff); + LossyUtils.VE8uv(ref uRef); + LossyUtils.VE8uv(ref vRef); break; case 3: - LossyUtils.HE8uv(uDst, yuv, uOff); - LossyUtils.HE8uv(vDst, yuv, vOff); + LossyUtils.HE8uv(ref uRef); + LossyUtils.HE8uv(ref vRef); break; case 4: - LossyUtils.DC8uvNoTop(uDst, yuv, uOff); - LossyUtils.DC8uvNoTop(vDst, yuv, vOff); + LossyUtils.DC8uvNoTop(ref uRef); + LossyUtils.DC8uvNoTop(ref vRef); break; case 5: - LossyUtils.DC8uvNoLeft(uDst, yuv, uOff); - LossyUtils.DC8uvNoLeft(vDst, yuv, vOff); + LossyUtils.DC8uvNoLeft(ref uRef); + LossyUtils.DC8uvNoLeft(ref vRef); break; case 6: - LossyUtils.DC8uvNoTopLeft(uDst); - LossyUtils.DC8uvNoTopLeft(vDst); + LossyUtils.DC8uvNoTopLeft(ref uRef); + LossyUtils.DC8uvNoTopLeft(ref vRef); break; } - DoUVTransform(bitsUv, coeffs.AsSpan(16 * 16), uDst, scratch); - DoUVTransform(bitsUv >> 8, coeffs.AsSpan(20 * 16), vDst, scratch); + DoUVTransform(bitsUv, coeffs[(16 * 16)..], uDst, scratch); + DoUVTransform(bitsUv >> 8, coeffs[(20 * 16)..], vDst, scratch); // Stash away top samples for next block. if (mby < dec.MbHeight - 1) { - yDst.Slice(15 * WebpConstants.Bps, 16).CopyTo(topYuv.Y); - uDst.Slice(7 * WebpConstants.Bps, 8).CopyTo(topYuv.U); - vDst.Slice(7 * WebpConstants.Bps, 8).CopyTo(topYuv.V); + Unsafe.WriteUnaligned(ref topY, Unsafe.ReadUnaligned>(ref Unsafe.Add(ref yRef, (nuint)(15 * WebpConstants.Bps)))); + Unsafe.WriteUnaligned(ref topU, Unsafe.ReadUnaligned(ref Unsafe.Add(ref uRef, (nuint)(7 * WebpConstants.Bps)))); + Unsafe.WriteUnaligned(ref topV, Unsafe.ReadUnaligned(ref Unsafe.Add(ref vRef, (nuint)(7 * WebpConstants.Bps)))); } - // Transfer reconstructed samples from yuv_buffer cache to final destination. - Span yOut = dec.CacheY.Memory.Span[(dec.CacheYOffset + (mbx * 16))..]; - Span uOut = dec.CacheU.Memory.Span[(dec.CacheUvOffset + (mbx * 8))..]; - Span vOut = dec.CacheV.Memory.Span[(dec.CacheUvOffset + (mbx * 8))..]; + // Copy the reconstructed samples to the caches. The macroblock is 16 rows of 16 luma bytes and 8 rows of 8 bytes for each chroma + // plane, so each row is one fixed-size load and store. The cache rows are CacheYStride = 16 * MbWidth and CacheUvStride = 8 * MbWidth + // bytes wide, so each row of the macroblock fits in its cache row. + ref byte ySrc = ref yRef; + ref byte yOut = ref Unsafe.Add(ref cacheYRef, (uint)(dec.CacheYOffset + (mbx * 16))); for (int j = 0; j < 16; j++) { - yDst.Slice(j * WebpConstants.Bps, Math.Min(16, yOut.Length)).CopyTo(yOut[(j * dec.CacheYStride)..]); + Unsafe.WriteUnaligned(ref yOut, Unsafe.ReadUnaligned>(ref ySrc)); + ySrc = ref Unsafe.Add(ref ySrc, (nuint)WebpConstants.Bps); + yOut = ref Unsafe.Add(ref yOut, cacheYStride); } + ref byte uSrc = ref uRef; + ref byte vSrc = ref vRef; + nuint uvOffset = (uint)(dec.CacheUvOffset + (mbx * 8)); + ref byte uOut = ref Unsafe.Add(ref cacheURef, uvOffset); + ref byte vOut = ref Unsafe.Add(ref cacheVRef, uvOffset); for (int j = 0; j < 8; j++) { - int jUvStride = j * dec.CacheUvStride; - uDst.Slice(j * WebpConstants.Bps, Math.Min(8, uOut.Length)).CopyTo(uOut[jUvStride..]); - vDst.Slice(j * WebpConstants.Bps, Math.Min(8, vOut.Length)).CopyTo(vOut[jUvStride..]); + Unsafe.WriteUnaligned(ref uOut, Unsafe.ReadUnaligned(ref uSrc)); + Unsafe.WriteUnaligned(ref vOut, Unsafe.ReadUnaligned(ref vSrc)); + uSrc = ref Unsafe.Add(ref uSrc, (nuint)WebpConstants.Bps); + vSrc = ref Unsafe.Add(ref vSrc, (nuint)WebpConstants.Bps); + uOut = ref Unsafe.Add(ref uOut, cacheUvStride); + vOut = ref Unsafe.Add(ref vOut, cacheUvStride); } } } + /// + /// Applies the loop filter to the macroblocks of the current row that are in the filter range. + /// + /// The decoder. private static void FilterRow(Vp8Decoder dec) { + // The filter strengths and the caches are the same for each macroblock of the row, so the method takes them once. int mby = dec.MbY; + Span filterInfo = dec.FilterInfo.GetSpan(); + ref byte cacheY = ref MemoryMarshal.GetReference(dec.CacheY.Memory.Span); + ref byte cacheU = ref MemoryMarshal.GetReference(dec.CacheU.Memory.Span); + ref byte cacheV = ref MemoryMarshal.GetReference(dec.CacheV.Memory.Span); for (int mbx = dec.TopLeftMbX; mbx < dec.BottomRightMbX; ++mbx) { - DoFilter(dec, mbx, mby); + DoFilter(dec, filterInfo[mbx], mbx, mby, ref cacheY, ref cacheU, ref cacheV); } } - private static void DoFilter(Vp8Decoder dec, int mbx, int mby) + /// + /// Applies the loop filter to one macroblock in the caches. It filters the left and top macroblock edges, except at the image border, + /// and the inner 4x4 block edges when the macroblock uses inner filtering. The simple filter changes only the luma samples. + /// + /// The decoder. + /// The filter strength of the macroblock. + /// The macroblock column. + /// The macroblock row. + /// The first sample of the luma cache. + /// The first sample of the U cache. + /// The first sample of the V cache. + private static void DoFilter(Vp8Decoder dec, Vp8FilterInfo filterInfo, int mbx, int mby, ref byte cacheY, ref byte cacheU, ref byte cacheV) { - int yBps = dec.CacheYStride; - Vp8FilterInfo filterInfo = dec.FilterInfo[mbx]; - int iLevel = filterInfo.InnerLevel; int limit = filterInfo.Limit; - if (limit == 0) { return; } + // The filters get the first sample of the macroblock in each cache. The cache offsets keep the rows above the macroblock row, and the + // macroblock columns before it, in the caches, so each filter steps from that sample with unsigned offsets. + int iLevel = filterInfo.InnerLevel; + nuint yBps = (uint)dec.CacheYStride; + ref byte y = ref Unsafe.Add(ref cacheY, (uint)(dec.CacheYOffset + (mbx * 16))); switch (dec.Filter) { case LoopFilter.Simple: { - int offset = dec.CacheYOffset + (mbx * 16); if (mbx > 0) { - LossyUtils.SimpleHFilter16(dec.CacheY.Memory.Span, offset, yBps, limit + 4); + LossyUtils.SimpleHFilter16(ref y, yBps, limit + 4); } if (filterInfo.UseInnerFiltering) { - LossyUtils.SimpleHFilter16i(dec.CacheY.Memory.Span, offset, yBps, limit); + LossyUtils.SimpleHFilter16i(ref y, yBps, limit); } if (mby > 0) { - LossyUtils.SimpleVFilter16(dec.CacheY.Memory.Span, offset, yBps, limit + 4); + LossyUtils.SimpleVFilter16(ref y, yBps, limit + 4); } if (filterInfo.UseInnerFiltering) { - LossyUtils.SimpleVFilter16i(dec.CacheY.Memory.Span, offset, yBps, limit); + LossyUtils.SimpleVFilter16i(ref y, yBps, limit); } break; @@ -733,32 +730,33 @@ private static void DoFilter(Vp8Decoder dec, int mbx, int mby) case LoopFilter.Complex: { - int uvBps = dec.CacheUvStride; - int yOffset = dec.CacheYOffset + (mbx * 16); - int uvOffset = dec.CacheUvOffset + (mbx * 8); + nuint uvBps = (uint)dec.CacheUvStride; + nuint uvOffset = (uint)(dec.CacheUvOffset + (mbx * 8)); + ref byte u = ref Unsafe.Add(ref cacheU, uvOffset); + ref byte v = ref Unsafe.Add(ref cacheV, uvOffset); int hevThresh = filterInfo.HighEdgeVarianceThreshold; if (mbx > 0) { - LossyUtils.HFilter16(dec.CacheY.Memory.Span, yOffset, yBps, limit + 4, iLevel, hevThresh); - LossyUtils.HFilter8(dec.CacheU.Memory.Span, dec.CacheV.Memory.Span, uvOffset, uvBps, limit + 4, iLevel, hevThresh); + LossyUtils.HFilter16(ref y, yBps, limit + 4, iLevel, hevThresh); + LossyUtils.HFilter8(ref u, ref v, uvBps, limit + 4, iLevel, hevThresh); } if (filterInfo.UseInnerFiltering) { - LossyUtils.HFilter16i(dec.CacheY.Memory.Span, yOffset, yBps, limit, iLevel, hevThresh); - LossyUtils.HFilter8i(dec.CacheU.Memory.Span, dec.CacheV.Memory.Span, uvOffset, uvBps, limit, iLevel, hevThresh); + LossyUtils.HFilter16i(ref y, yBps, limit, iLevel, hevThresh); + LossyUtils.HFilter8i(ref u, ref v, uvBps, limit, iLevel, hevThresh); } if (mby > 0) { - LossyUtils.VFilter16(dec.CacheY.Memory.Span, yOffset, yBps, limit + 4, iLevel, hevThresh); - LossyUtils.VFilter8(dec.CacheU.Memory.Span, dec.CacheV.Memory.Span, uvOffset, uvBps, limit + 4, iLevel, hevThresh); + LossyUtils.VFilter16(ref y, yBps, limit + 4, iLevel, hevThresh); + LossyUtils.VFilter8(ref u, ref v, uvBps, limit + 4, iLevel, hevThresh); } if (filterInfo.UseInnerFiltering) { - LossyUtils.VFilter16i(dec.CacheY.Memory.Span, yOffset, yBps, limit, iLevel, hevThresh); - LossyUtils.VFilter8i(dec.CacheU.Memory.Span, dec.CacheV.Memory.Span, uvOffset, uvBps, limit, iLevel, hevThresh); + LossyUtils.VFilter16i(ref y, yBps, limit, iLevel, hevThresh); + LossyUtils.VFilter8i(ref u, ref v, uvBps, limit, iLevel, hevThresh); } break; @@ -770,10 +768,9 @@ private static void DoFilter(Vp8Decoder dec, int mbx, int mby) /// Filters the current macroblock row and emits the rows that are complete. /// /// The decoder. - /// The output description. - /// The YCbCr converter. - /// The number of complete pixel rows after this macroblock row. - private static int FinishRow(Vp8Decoder dec, Vp8Io io, WebpColorConverterBase colorConverter) + /// The writer of the destination rows. + private static void FinishRow(Vp8Decoder dec, YuvToRgbConverter writer) + where TPixel : unmanaged, IPixel { int extraYRows = WebpConstants.FilterExtraRows[(int)dec.Filter]; int ySize = extraYRows * dec.CacheYStride; @@ -791,20 +788,22 @@ private static int FinishRow(Vp8Decoder dec, Vp8Io io, WebpColorConverterBase co FilterRow(dec); } + // A row after the first starts with the extra rows above it, which the filter of this row can change. The first row starts at the + // offset of the cache, after the space of the extra rows. int yStart = mby * 16; int yEnd = (mby + 1) * 16; + Span y = yDst; + Span u = uDst; + Span v = vDst; if (!isFirstRow) { yStart -= extraYRows; - io.Y = yDst; - io.U = uDst; - io.V = vDst; } else { - io.Y = dec.CacheY.Memory.Span[dec.CacheYOffset..]; - io.U = dec.CacheU.Memory.Span[dec.CacheUvOffset..]; - io.V = dec.CacheV.Memory.Span[dec.CacheUvOffset..]; + y = yDst[dec.CacheYOffset..]; + u = uDst[dec.CacheUvOffset..]; + v = vDst[dec.CacheUvOffset..]; } if (!isLastRow) @@ -812,17 +811,16 @@ private static int FinishRow(Vp8Decoder dec, Vp8Io io, WebpColorConverterBase co yEnd -= extraYRows; } - if (yEnd > io.Height) + // The last macroblock row can reach below the picture. + int height = (int)dec.PictureHeader.Height; + if (yEnd > height) { - yEnd = io.Height; // make sure we don't overflow on last row. + yEnd = height; } if (yStart < yEnd) { - io.MbY = yStart; - io.MbW = io.Width; - io.MbH = yEnd - yStart; - EmitRgb(dec, io, colorConverter); + EmitRgb(dec, y, u, v, yStart, yEnd, writer); } // Rotate top samples if needed. @@ -832,84 +830,91 @@ private static int FinishRow(Vp8Decoder dec, Vp8Io io, WebpColorConverterBase co uDst.Slice(8 * dec.CacheUvStride, uvSize).CopyTo(dec.CacheU.Memory.Span); vDst.Slice(8 * dec.CacheUvStride, uvSize).CopyTo(dec.CacheV.Memory.Span); } - - // EmitRgb leaves the last row unfinished until the next call, because the upsampler needs the chroma - // of the next row. Only the call for the last macroblock row finishes all rows. - return yEnd < io.Height ? yEnd - 1 : yEnd; } - private static int EmitRgb(Vp8Decoder dec, Vp8Io io, WebpColorConverterBase colorConverter) + /// + /// Upsamples the luma rows of the current macroblock row and writes each finished row to the destination. + /// + /// + /// The upsampler needs the chroma of the next row. Thus each call finishes the last row of the previous call, and leaves + /// its own last row for the next call. Only the call for the last macroblock row finishes all rows. + /// + /// The pixel format. + /// The decoder. + /// The luma samples, from row . The rows have a stride of . + /// The U samples of the same rows. The rows have a stride of . + /// The V samples of the same rows, with the stride of . + /// The first picture row of the samples. + /// The picture row after the last row of the samples. + /// The writer of the destination rows. + private static void EmitRgb( + Vp8Decoder dec, + Span curY, + Span curU, + Span curV, + int yStart, + int yEnd, + YuvToRgbConverter writer) + where TPixel : unmanaged, IPixel { - Span buf = dec.Pixels.Memory.Span; - int numLinesOut = io.MbH; // a priori guess. - Span curY = io.Y; - Span curU = io.U; - Span curV = io.V; Span tmpYBuffer = dec.TmpYBuffer.Memory.Span; Span tmpUBuffer = dec.TmpUBuffer.Memory.Span; Span tmpVBuffer = dec.TmpVBuffer.Memory.Span; Span topU = tmpUBuffer; Span topV = tmpVBuffer; - const int bpp = 3; - int bufferStride = bpp * io.Width; - int dstStartIdx = io.MbY * bufferStride; - Span dst = buf[dstStartIdx..]; - int yEnd = io.MbY + io.MbH; - int mbw = io.MbW; - int uvw = (mbw + 1) >> 1; // >> 1 is bit-hack for / 2 - int y = io.MbY; - Span uvBuffer = dec.UpsamplingBuffer; + int width = (int)dec.PictureHeader.Width; + int uvw = (width + 1) >> 1; + int yStride = dec.CacheYStride; + int uvStride = dec.CacheUvStride; + int y = yStart; if (y == 0) { // First line is special cased. We mirror the u/v samples at boundary. - colorConverter.UpSample(curY, default, curU, curV, curU, curV, dst, default, mbw, uvBuffer); + writer.WriteRows(0, curY, default, curU, curV, curU, curV); } else { // We can finish the left-over line from previous call. - colorConverter.UpSample(tmpYBuffer, curY, topU, topV, curU, curV, buf[(dstStartIdx - bufferStride)..], dst, mbw, uvBuffer); - numLinesOut++; + writer.WriteRows(y - 1, tmpYBuffer, curY, topU, topV, curU, curV); } // Loop over each output pairs of row. - int bufferStride2 = 2 * bufferStride; - int ioStride2 = 2 * io.YStride; + int yStride2 = 2 * yStride; for (; y + 2 < yEnd; y += 2) { topU = curU; topV = curV; - curU = curU[io.UvStride..]; - curV = curV[io.UvStride..]; - colorConverter.UpSample(curY[io.YStride..], curY[ioStride2..], topU, topV, curU, curV, dst[bufferStride..], dst[bufferStride2..], mbw, uvBuffer); - curY = curY[ioStride2..]; - dst = dst[bufferStride2..]; + curU = curU[uvStride..]; + curV = curV[uvStride..]; + writer.WriteRows(y + 1, curY[yStride..], curY[yStride2..], topU, topV, curU, curV); + curY = curY[yStride2..]; } // Move to last row. - curY = curY[io.YStride..]; - if (yEnd < io.Height) + curY = curY[yStride..]; + if (yEnd < (int)dec.PictureHeader.Height) { // Save the unfinished samples for next call (as we're not done yet). - curY[..mbw].CopyTo(tmpYBuffer); + curY[..width].CopyTo(tmpYBuffer); curU[..uvw].CopyTo(tmpUBuffer); curV[..uvw].CopyTo(tmpVBuffer); - - // The upsampler leaves a row unfinished behind (except for the very last row). - numLinesOut--; } - else + else if ((yEnd & 1) == 0) { // Process the very last row of even-sized picture. - if ((yEnd & 1) == 0) - { - colorConverter.UpSample(curY, default, curU, curV, curU, curV, dst[bufferStride..], default, mbw, uvBuffer); - } + writer.WriteRows(y + 1, curY, default, curU, curV, curU, curV); } - - return numLinesOut; } + /// + /// Adds the inverse transform of one 4x4 luma block to the predicted samples. The top 2 bits of select the transform: + /// 3 is the full transform, 2 is the transform of the first 3 coefficients in zigzag order, 1 is the DC-only transform, and 0 adds nothing. + /// + /// The non-zero code of the block in the top 2 bits. + /// The 16 dequantized coefficients. + /// The predicted samples. The row stride is . + /// A scratch buffer of 16 values for the full transform. private static void DoTransform(uint bits, Span src, Span dst, Span scratch) { switch (bits >> 30) @@ -926,6 +931,14 @@ private static void DoTransform(uint bits, Span src, Span dst, Span } } + /// + /// Adds the inverse transform of the four 4x4 blocks of one 8x8 chroma block to the predicted samples. When only DC coefficients are not zero, + /// it uses the DC-only transform. When all coefficients are zero, it adds nothing. + /// + /// The non-zero codes of the four blocks in the low 8 bits, 2 bits for each block. + /// The 64 dequantized coefficients of the four blocks. + /// The predicted samples. The row stride is . + /// A scratch buffer of 16 values for the full transform. private static void DoUVTransform(uint bits, Span src, Span dst, Span scratch) { // any non-zero coeff at all? @@ -943,16 +956,28 @@ private static void DoUVTransform(uint bits, Span src, Span dst, Sp } } - private void DecodeMacroBlock(Vp8Decoder dec, Vp8BitReader bitreader) + /// + /// Reads the residuals of the current macroblock and stores its loop filter strength. A skipped macroblock has no residuals, + /// so the method clears its non-zero flags. + /// + /// The decoder. + /// The bit reader of the token partition of the current row. + /// The non-zero context of the current macroblock column. + /// The macroblock data of the current macroblock. + /// The filter strength of the current macroblock column. The method sets it when the loop filter is on. + private static void DecodeMacroBlock( + Vp8Decoder dec, + Vp8BitReader bitreader, + ref Vp8MacroBlock macroBlock, + ref Vp8MacroBlockData blockData, + ref Vp8FilterInfo filterInfo) { - Vp8MacroBlock left = dec.LeftMacroBlock; - Vp8MacroBlock macroBlock = dec.CurrentMacroBlock; - Vp8MacroBlockData blockData = dec.CurrentBlockData; + ref Vp8MacroBlock left = ref dec.LeftMacroBlock; bool skip = dec.UseSkipProbability && blockData.Skip; if (!skip) { - skip = this.ParseResiduals(dec, bitreader, macroBlock); + skip = ParseResiduals(dec, bitreader, ref macroBlock, ref blockData); } else { @@ -969,45 +994,54 @@ private void DecodeMacroBlock(Vp8Decoder dec, Vp8BitReader bitreader) // Store filter info. if (dec.Filter != LoopFilter.None) { - Vp8FilterInfo precomputedFilterInfo = dec.FilterStrength[blockData.Segment, blockData.IsI4x4 ? 1 : 0]; - dec.FilterInfo[dec.MbX] = (Vp8FilterInfo)precomputedFilterInfo.DeepClone(); - dec.FilterInfo[dec.MbX].UseInnerFiltering |= !skip; + Vp8FilterInfo strength = dec.FilterStrength[blockData.Segment, blockData.IsI4x4 ? 1 : 0]; + strength.UseInnerFiltering |= !skip; + filterInfo = strength; } } - private bool ParseResiduals(Vp8Decoder dec, Vp8BitReader br, Vp8MacroBlock mb) + /// + /// Reads and dequantizes the coefficients of the current macroblock. For a 16x16 prediction, it first reads the Y2 block and applies the inverse + /// Walsh-Hadamard transform to get the luma DC coefficients. The method updates the top and left non-zero contexts and the non-zero codes + /// of the macroblock data. + /// + /// The decoder. + /// The bit reader of the token partition. + /// The non-zero context of the current macroblock column. + /// The macroblock data of the current macroblock. + /// if all coefficients are zero; otherwise . + private static bool ParseResiduals(Vp8Decoder dec, Vp8BitReader br, ref Vp8MacroBlock mb, ref Vp8MacroBlockData block) { uint nonZeroY = 0; uint nonZeroUv = 0; int first; int dstOffset = 0; - Vp8MacroBlockData block = dec.CurrentBlockData; - Vp8QuantMatrix q = dec.DeQuantMatrices[block.Segment]; - Vp8BandProbas[][] bands = dec.Probabilities.BandsPtr; - Vp8BandProbas[] acProba; - Vp8MacroBlock leftMb = dec.LeftMacroBlock; - short[] dst = block.Coeffs; - for (int i = 0; i < dst.Length; i++) - { - dst[i] = 0; - } + Vp8QuantizationMatrix q = dec.DeQuantMatrices[block.Segment]; + ref byte bands = ref MemoryMarshal.GetArrayDataReference(dec.Probabilities.Coefficients); + int acType; + ref Vp8MacroBlock leftMb = ref dec.LeftMacroBlock; + Span dst = dec.Coefficients.GetSpan().Slice(dec.MbX * Vp8Decoder.CoefficientsPerMacroBlock, Vp8Decoder.CoefficientsPerMacroBlock); + dst.Clear(); if (block.IsI4x4) { first = 0; - acProba = bands[3]; + acType = 3; } else { // Parse DC - Span dc = stackalloc short[16]; + // GetCoeffs writes only the nonzero coefficients, so the DC block starts at zero. + InlineArray16 dcBuffer = default; + Span dc = dcBuffer; int ctx = (int)(mb.NoneZeroDcCoeffs + leftMb.NoneZeroDcCoeffs); - int nz = GetCoeffs(br, bands[1], ctx, q.Y2Mat, 0, dc); + int nz = GetCoeffs(br, ref Unsafe.Add(ref bands, (nuint)(1 * Vp8Probabilities.TypeStride)), ctx, q.Y2Mat, 0, dc); mb.NoneZeroDcCoeffs = leftMb.NoneZeroDcCoeffs = (uint)(nz > 0 ? 1 : 0); if (nz > 1) { // More than just the DC -> perform the full transform. - LossyUtils.TransformWht(dc, dst, stackalloc int[16]); + InlineArray16 scratch = default; + LossyUtils.TransformWht(dc, dst, scratch); } else { @@ -1020,7 +1054,7 @@ private bool ParseResiduals(Vp8Decoder dec, Vp8BitReader br, Vp8MacroBlock mb) } first = 1; - acProba = bands[0]; + acType = 0; } byte tnz = (byte)(mb.NoneZeroAcDcCoeffs & 0x0f); @@ -1033,7 +1067,7 @@ private bool ParseResiduals(Vp8Decoder dec, Vp8BitReader br, Vp8MacroBlock mb) for (int x = 0; x < 4; x++) { int ctx = l + (tnz & 1); - int nz = GetCoeffs(br, acProba, ctx, q.Y1Mat, first, dst.AsSpan(dstOffset)); + int nz = GetCoeffs(br, ref Unsafe.Add(ref bands, (uint)(acType * Vp8Probabilities.TypeStride)), ctx, q.Y1Mat, first, dst[dstOffset..]); l = nz > first ? 1 : 0; tnz = (byte)((tnz >> 1) | (l << 7)); nzCoeffs = NzCodeBits(nzCoeffs, nz, dst[dstOffset] != 0 ? 1 : 0); @@ -1060,7 +1094,7 @@ private bool ParseResiduals(Vp8Decoder dec, Vp8BitReader br, Vp8MacroBlock mb) for (int x = 0; x < 2; x++) { int ctx = l + (tnz & 1); - int nz = GetCoeffs(br, bands[2], ctx, q.UvMat, 0, dst.AsSpan(dstOffset)); + int nz = GetCoeffs(br, ref Unsafe.Add(ref bands, (nuint)(2 * Vp8Probabilities.TypeStride)), ctx, q.UvMat, 0, dst[dstOffset..]); l = nz > 0 ? 1 : 0; tnz = (byte)((tnz >> 1) | (l << 3)); nzCoeffs = NzCodeBits(nzCoeffs, nz, dst[dstOffset] != 0 ? 1 : 0); @@ -1086,103 +1120,120 @@ private bool ParseResiduals(Vp8Decoder dec, Vp8BitReader br, Vp8MacroBlock mb) return (nonZeroY | nonZeroUv) == 0; } - private static int GetCoeffs(Vp8BitReader br, Vp8BandProbas[] prob, int ctx, int[] dq, int n, Span coeffs) + /// + /// Reads the tokens of one 4x4 block and stores the dequantized coefficients. See RFC 6386, section 13. + /// + /// + /// The arithmetic state of the bit reader stays in locals for the block. The probabilities of token position n and context c are at + /// n * PositionStride + c * ContextStride from . + /// + /// The bit reader of the token partition. + /// The first probability of the block type. + /// The context of the first token. + /// The dequantization factors of the DC and the AC coefficients. + /// The first token position. + /// The 16 coefficients of the block, in raster order. The caller clears them. + /// The position of the last non-zero coefficient plus one. + private static int GetCoeffs(Vp8BitReader br, ref byte probabilities, int ctx, int[] dq, int n, Span coeffs) { - // Returns the position of the last non-zero coeff plus one. - Vp8ProbaArray p = prob[n].Probabilities[ctx]; + br.LoadState(out ulong value, out int bits, out uint range); + ref byte p = ref Unsafe.Add(ref probabilities, (uint)((n * Vp8Probabilities.PositionStride) + (ctx * Vp8Probabilities.ContextStride))); for (; n < 16; ++n) { - if (br.GetBit(p.Probabilities[0]) == 0) + if (Vp8BitReader.GetBit(br, ref value, ref bits, ref range, p) == 0) { - // Previous coeff was last non-zero coeff. - return n; + // The previous coefficient was the last non-zero coefficient. + break; } - // Sequence of zero coeffs. - while (br.GetBit(p.Probabilities[1]) == 0) + // A run of zero coefficients. A zero token gives context 0 to the next token. + while (Vp8BitReader.GetBit(br, ref value, ref bits, ref range, Unsafe.Add(ref p, (nuint)1)) == 0) { - p = prob[++n].Probabilities[0]; + p = ref Unsafe.Add(ref probabilities, (uint)(++n * Vp8Probabilities.PositionStride)); if (n == 16) { + br.StoreState(value, bits, range); return 16; } } - // Non zero coeffs. + // A non-zero coefficient. A value of 1 gives context 1 to the next token, and a larger value context 2. int v; - if (br.GetBit(p.Probabilities[2]) == 0) + ref byte next = ref Unsafe.Add(ref probabilities, (uint)((n + 1) * Vp8Probabilities.PositionStride)); + if (Vp8BitReader.GetBit(br, ref value, ref bits, ref range, Unsafe.Add(ref p, (nuint)2)) == 0) { v = 1; - p = prob[n + 1].Probabilities[1]; + p = ref Unsafe.Add(ref next, (nuint)(1 * Vp8Probabilities.ContextStride)); } else { - v = GetLargeValue(br, p.Probabilities); - p = prob[n + 1].Probabilities[2]; + v = GetLargeValue(br, ref value, ref bits, ref range, ref p); + p = ref Unsafe.Add(ref next, (nuint)(2 * Vp8Probabilities.ContextStride)); } int idx = n > 0 ? 1 : 0; - coeffs[WebpConstants.Zigzag[n]] = (short)(br.GetSigned(v) * dq[idx]); + coeffs[WebpConstants.Zigzag[n]] = (short)(Vp8BitReader.GetSigned(br, ref value, ref bits, ref range, v) * dq[idx]); } - return 16; + br.StoreState(value, bits, range); + return n; } - private static int GetLargeValue(Vp8BitReader br, byte[] p) + /// + /// Reads the magnitude of a coefficient that is larger than 1. See RFC 6386, section 13.2. + /// + /// The bit reader of the token partition. + /// The value window. + /// The number of valid bits below the 8-bit comparison window. + /// The range minus 1. + /// The first probability of the token. + /// The magnitude. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int GetLargeValue(Vp8BitReader br, ref ulong value, ref int bits, ref uint range, ref byte p) { - // See section 13 - 2: http://tools.ietf.org/html/rfc6386#section-13.2 int v; - if (br.GetBit(p[3]) == 0) + if (Vp8BitReader.GetBit(br, ref value, ref bits, ref range, Unsafe.Add(ref p, (nuint)3)) == 0) { - if (br.GetBit(p[4]) == 0) + if (Vp8BitReader.GetBit(br, ref value, ref bits, ref range, Unsafe.Add(ref p, (nuint)4)) == 0) { v = 2; } else { - v = 3 + br.GetBit(p[5]); + v = 3 + Vp8BitReader.GetBit(br, ref value, ref bits, ref range, Unsafe.Add(ref p, (nuint)5)); } } - else if (br.GetBit(p[6]) == 0) + else if (Vp8BitReader.GetBit(br, ref value, ref bits, ref range, Unsafe.Add(ref p, (nuint)6)) == 0) { - if (br.GetBit(p[7]) == 0) + if (Vp8BitReader.GetBit(br, ref value, ref bits, ref range, Unsafe.Add(ref p, (nuint)7)) == 0) { - v = 5 + br.GetBit(159); + v = 5 + Vp8BitReader.GetBit(br, ref value, ref bits, ref range, 159); } else { - v = 7 + (2 * br.GetBit(165)); - v += br.GetBit(145); + v = 7 + (2 * Vp8BitReader.GetBit(br, ref value, ref bits, ref range, 165)); + v += Vp8BitReader.GetBit(br, ref value, ref bits, ref range, 145); } } else { - int bit1 = br.GetBit(p[8]); - int bit0 = br.GetBit(p[9 + bit1]); + int bit1 = Vp8BitReader.GetBit(br, ref value, ref bits, ref range, Unsafe.Add(ref p, (nuint)8)); + int bit0 = Vp8BitReader.GetBit(br, ref value, ref bits, ref range, Unsafe.Add(ref p, (uint)(9 + bit1))); // Two bits give a category from 0 to 3, so the switch below sets the table in each case. int cat = (2 * bit1) + bit0; - v = 0; - byte[] tab = null; - switch (cat) + ReadOnlySpan tab = cat switch { - case 0: - tab = WebpConstants.Cat3; - break; - case 1: - tab = WebpConstants.Cat4; - break; - case 2: - tab = WebpConstants.Cat5; - break; - case 3: - tab = WebpConstants.Cat6; - break; - } + 0 => WebpConstants.Cat3, + 1 => WebpConstants.Cat4, + 2 => WebpConstants.Cat5, + _ => WebpConstants.Cat6, + }; + v = 0; for (int i = 0; i < tab.Length; i++) { - v += v + br.GetBit(tab[i]); + v += v + Vp8BitReader.GetBit(br, ref value, ref bits, ref range, tab[i]); } v += 3 + (8 << cat); @@ -1191,7 +1242,12 @@ private static int GetLargeValue(Vp8BitReader br, byte[] p) return v; } - private Vp8SegmentHeader ParseSegmentHeader(Vp8Proba proba) + /// + /// Reads the segment header from the first partition. See RFC 6386, section 9.3. + /// + /// The probabilities. The method stores the segment tree probabilities in them when the segment map changes. + /// The segment header. + private Vp8SegmentHeader ParseSegmentHeader(Vp8Probabilities proba) { Vp8SegmentHeader vp8SegmentHeader = new() { @@ -1236,6 +1292,11 @@ private Vp8SegmentHeader ParseSegmentHeader(Vp8Proba proba) return vp8SegmentHeader; } + /// + /// Reads the loop filter header from the first partition. See RFC 6386, section 9.4. A filter level of 0 turns the loop filter off. + /// The method also sets the cache offsets for the extra rows that the selected filter needs. + /// + /// The decoder. private void ParseFilterHeader(Vp8Decoder dec) { Vp8FilterHeader vp8FilterHeader = dec.FilterHeader; @@ -1295,7 +1356,7 @@ private bool ParsePartitions(Vp8Decoder dec, SegmentIntegrityHandling segmentInt dec.NumPartsMinusOne = (1 << (int)this.bitReader.ReadValue(2)) - 1; int lastPart = dec.NumPartsMinusOne; - // Each partition except the last one has a 3-byte size. libwebp rejects data that cannot hold them. + // RFC 6386, section 9.5, stores a 3-byte size for each partition except the last one. Data that cannot hold these sizes is not valid. int lastPartMul3 = lastPart * 3; if (sizeLeft < lastPartMul3) { @@ -1321,7 +1382,7 @@ private bool ParsePartitions(Vp8Decoder dec, SegmentIntegrityHandling segmentInt dec.Vp8BitReaders[lastPart] = new Vp8BitReader(this.bitReader.Data, (uint)sizeLeft, partStart); - // libwebp rejects a partition that starts with a value larger than the range. + // RFC 6386, section 7.2, keeps the bool decoder value less than the range at all times. A partition that starts with 0xFF is not valid. for (int p = 0; p <= lastPart; ++p) { if (!dec.Vp8BitReaders[p].IsStartValid) @@ -1331,8 +1392,8 @@ private bool ParsePartitions(Vp8Decoder dec, SegmentIntegrityHandling segmentInt } } - // libwebp rejects data in which the last partition is empty. The macroblock loop keeps the rows that - // the other partitions can decode. + // RFC 6386, section 9.5, gives the remainder of the data to the last partition. As in libwebp, an empty last partition is an error. + // The macroblock loop keeps the rows that the other partitions can decode. if (sizeLeft == 0) { segmentIntegrityHandling.ThrowOrIgnoreImageDataError("The VP8 data ends before the last token partition."); @@ -1341,6 +1402,11 @@ private bool ParsePartitions(Vp8Decoder dec, SegmentIntegrityHandling segmentInt return true; } + /// + /// Reads the quantizer indices from the first partition and calculates the dequantization factors of each segment. See RFC 6386, section 9.6. + /// Without segments, all segments share the factors of segment 0. + /// + /// The decoder. private void ParseDequantizationIndices(Vp8Decoder decoder) { Vp8SegmentHeader vp8SegmentHeader = decoder.SegmentHeader; @@ -1378,7 +1444,7 @@ private void ParseDequantizationIndices(Vp8Decoder decoder) q = baseQ0; } - Vp8QuantMatrix m = decoder.DeQuantMatrices[i]; + Vp8QuantizationMatrix m = decoder.DeQuantMatrices[i]; m.Y1Mat[0] = WebpLookupTables.DcTable[Clip(q + dqy1Dc, 127)]; m.Y1Mat[1] = WebpLookupTables.AcTable[Clip(q + 0, 127)]; m.Y2Mat[0] = WebpLookupTables.DcTable[Clip(q + dqy2Dc, 127)] * 2; @@ -1393,16 +1459,21 @@ private void ParseDequantizationIndices(Vp8Decoder decoder) m.UvMat[0] = WebpLookupTables.DcTable[Clip(q + dquvDc, 117)]; m.UvMat[1] = WebpLookupTables.AcTable[Clip(q + dquvAc, 127)]; - - // For dithering strength evaluation. - m.UvQuant = q + dquvAc; } } + /// + /// Reads the coefficient probability updates and the skip probability from the first partition. See RFC 6386, section 13.4. + /// The method expands the probabilities of each band to all token positions of that band. + /// + /// The decoder. private void ParseProbabilities(Vp8Decoder dec) { - Vp8Proba proba = dec.Probabilities; + Vp8Probabilities proba = dec.Probabilities; + // NumBands * PositionStride is 8 * 33 = 264 bytes. The default value of an inline array is zero. + InlineArray264 bandStorage = default; + Span bands = bandStorage; for (int t = 0; t < WebpConstants.NumTypes; ++t) { for (int b = 0; b < WebpConstants.NumBands; ++b) @@ -1412,16 +1483,19 @@ private void ParseProbabilities(Vp8Decoder dec) for (int p = 0; p < WebpConstants.NumProbas; ++p) { byte prob = WebpLookupTables.CoeffsUpdateProba[t, b, c, p]; - proba.Bands[t, b].Probabilities[c].Probabilities[p] = (byte)(this.bitReader.GetBit(prob) != 0 - ? this.bitReader.ReadValue(8) - : WebpLookupTables.DefaultCoeffsProba[t, b, c, p]); + bands[(b * Vp8Probabilities.PositionStride) + (c * Vp8Probabilities.ContextStride) + p] = (byte)(this.bitReader.GetBit(prob) != 0 + ? this.bitReader.ReadValue(8) + : WebpLookupTables.DefaultCoeffsProba[t, b, c, p]); } } } - for (int b = 0; b < 16 + 1; ++b) + // Each token position gets the probabilities of its band. + Span type = proba.Coefficients.AsSpan(t * Vp8Probabilities.TypeStride, Vp8Probabilities.TypeStride); + for (int n = 0; n < Vp8Probabilities.NumPositions; ++n) { - proba.BandsPtr[t][b] = proba.Bands[t, WebpConstants.Vp8EncBands[b]]; + bands.Slice(WebpConstants.Vp8EncBands[n] * Vp8Probabilities.PositionStride, Vp8Probabilities.PositionStride) + .CopyTo(type[(n * Vp8Probabilities.PositionStride)..]); } } @@ -1432,23 +1506,15 @@ private void ParseProbabilities(Vp8Decoder dec) } } - private static Vp8Io InitializeVp8Io(Vp8Decoder dec) + /// + /// Prepares the decoder for the macroblock loop. The method sets the range of macroblocks to filter and to decode. + /// + /// The decoder. + private static void InitializeMacroBlockRange(Vp8Decoder dec) { Vp8PictureHeader pictureHeader = dec.PictureHeader; - Vp8Io io = default; - io.Width = (int)pictureHeader.Width; - io.Height = (int)pictureHeader.Height; - io.UseScaling = false; - io.ScaledWidth = io.Width; - io.ScaledHeight = io.ScaledHeight; - io.MbW = io.Width; - io.MbH = io.Height; - uint strideLength = (pictureHeader.Width + 15) >> 4; - io.YStride = (int)(16 * strideLength); - io.UvStride = (int)(8 * strideLength); - - int intraPredModeSize = 4 * dec.MbWidth; - dec.IntraT = new byte[intraPredModeSize]; + int width = (int)pictureHeader.Width; + int height = (int)pictureHeader.Height; int extraPixels = WebpConstants.FilterExtraRows[(int)dec.Filter]; if (dec.Filter == LoopFilter.Complex) @@ -1476,8 +1542,8 @@ private static Vp8Io InitializeVp8Io(Vp8Decoder dec) } // We need some 'extra' pixels on the right/bottom. - dec.BottomRightMbY = (io.Height + 15 + extraPixels) >> 4; - dec.BottomRightMbX = (io.Width + 15 + extraPixels) >> 4; + dec.BottomRightMbY = (height + 15 + extraPixels) >> 4; + dec.BottomRightMbX = (width + 15 + extraPixels) >> 4; if (dec.BottomRightMbX > dec.MbWidth) { dec.BottomRightMbX = dec.MbWidth; @@ -1487,10 +1553,16 @@ private static Vp8Io InitializeVp8Io(Vp8Decoder dec) { dec.BottomRightMbY = dec.MbHeight; } - - return io; } + /// + /// Appends the 2-bit non-zero code of one block. The code selects the inverse transform. In zigzag order, the code is 3 when the last + /// non-zero coefficient is at position 3 or later, and 2 when it is at position 1 or 2. Otherwise the code is 1 for a non-zero DC and 0 for none. + /// + /// The codes of the previous blocks. + /// The position of the last non-zero coefficient plus one. + /// 1 if the DC coefficient is not zero; otherwise 0. + /// The codes shifted left by 2, with the new code in the low 2 bits. [MethodImpl(InliningOptions.ShortMethod)] private static uint NzCodeBits(uint nzCoeffs, int nz, int dcNz) { @@ -1505,6 +1577,15 @@ private static uint NzCodeBits(uint nzCoeffs, int nz, int dcNz) return nzCoeffs; } + /// + /// Replaces the DC prediction mode at the image border. The DC prediction then uses only the edges that exist. + /// + /// The macroblock column. + /// The macroblock row. + /// The prediction mode. + /// + /// For the DC mode: 6 without top and left samples, 5 without left samples, 4 without top samples, or 0. For other modes: . + /// [MethodImpl(InliningOptions.ShortMethod)] private static int CheckMode(int mbx, int mby, int mode) { @@ -1526,6 +1607,12 @@ private static int CheckMode(int mbx, int mby, int mode) return mode; } + /// + /// Clamps a value to the [0, ] interval. + /// + /// The value. + /// The maximum value. + /// The clamped value. [MethodImpl(InliningOptions.ShortMethod)] private static int Clip(int value, int max) => Math.Clamp(value, 0, max); } diff --git a/src/ImageSharp/Formats/Webp/Lossy/YuvToRgbConverter{TPixel}.cs b/src/ImageSharp/Formats/Webp/Lossy/YuvToRgbConverter{TPixel}.cs new file mode 100644 index 0000000000..7f58aef254 --- /dev/null +++ b/src/ImageSharp/Formats/Webp/Lossy/YuvToRgbConverter{TPixel}.cs @@ -0,0 +1,215 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. +#nullable disable + +using System.Buffers; +using System.Numerics; +using SixLabors.ImageSharp.ColorProfiles; +using SixLabors.ImageSharp.Formats.Webp.ColorConverters; +using SixLabors.ImageSharp.Memory; +using SixLabors.ImageSharp.PixelFormats; + +namespace SixLabors.ImageSharp.Formats.Webp.Lossy; + +/// +/// Writes the reconstructed Y, U, V rows of the lossy decoder to the destination pixels. +/// +/// +/// As in the JPEG decoder, the color converter makes one call for each row and does all color math, here including the +/// chroma interpolation. This type packs the converted planes into the destination pixel format. +/// +/// The pixel format. +internal sealed class YuvToRgbConverter : IDisposable + where TPixel : unmanaged, IPixel +{ + /// + /// The pixel conversion configuration. + /// + private readonly Configuration configuration; + + /// + /// The destination pixels. + /// + private readonly Buffer2DRegion pixels; + + /// + /// The number of rows from the top that can take the padded pack. The pack writes up to three pixels past the row, into the start of the next + /// buffer row. That is safe only when the area has the full width of its buffer, and when the next buffer row is a later row of the area or the + /// pack gets no padded row. Thus the last row of an area that ends above the bottom of its buffer uses the proxy row. + /// + private readonly int paddedRows; + + /// + /// The image width. + /// + private readonly int width; + + /// + /// The decoded alpha plane, one row for each image row, or null when the image has no alpha. The caller owns it. + /// + private readonly Buffer2D alpha; + + /// + /// The YCbCr converter. + /// + private readonly WebpColorConverterBase colorConverter; + + /// + /// The selected source ICC converter, or null. + /// + private readonly ColorProfileConverter colorProfileConverter; + + /// + /// The row scratch: three rows of one byte for each pixel. + /// + private readonly IMemoryOwner rows; + + /// + /// The destination row scratch with 3 pixels of padding, because the plane packing can write up to three pixels past the row. + /// + private readonly IMemoryOwner paddedProxyPixelRow; + + /// + /// The row scratch of the ICC path, or null when no ICC converter is selected. + /// + private readonly IMemoryOwner vectors; + + /// + /// Initializes a new instance of the class. + /// + /// The pixel conversion configuration. + /// The allocator for the row scratch. + /// The destination pixels. + /// The image width. + /// The decoded alpha plane, or null when the image has no alpha. + /// The YCbCr converter. + /// The selected source ICC converter, or null. + public YuvToRgbConverter( + Configuration configuration, + MemoryAllocator memoryAllocator, + Buffer2DRegion pixels, + int width, + Buffer2D alpha, + WebpColorConverterBase colorConverter, + ColorProfileConverter colorProfileConverter) + { + this.configuration = configuration; + this.pixels = pixels; + bool fullWidth = pixels.Bounds.X == 0 && pixels.Width == pixels.Buffer.Width; + this.paddedRows = !fullWidth ? 0 : pixels.Bounds.Bottom == pixels.Buffer.Height ? pixels.Height : pixels.Height - 1; + this.width = width; + this.alpha = alpha; + this.colorConverter = colorConverter; + this.colorProfileConverter = colorProfileConverter; + + // Three rows of one byte for each pixel: the R, G, B planes, or the full-resolution U and V rows of the ICC path. + this.rows = memoryAllocator.Allocate(3 * width); + + // PackFromRgbPlanes can write up to three pixels past the row, as in the JPEG decoder. + this.paddedProxyPixelRow = memoryAllocator.Allocate(width + 3); + if (colorProfileConverter is not null) + { + this.vectors = memoryAllocator.Allocate(width); + } + } + + /// + /// Gets the number of destination rows from the top that the writer wrote. The decoder writes the rows in order, so these rows have no gap. + /// + public int RowsWritten { get; private set; } + + /// + /// Writes the one or two output rows between two chroma rows. + /// + /// The index of the first output row. + /// The luma of the first output row. + /// The luma of the second output row, or empty for a single output row. + /// The preceding U chroma row. + /// The preceding V chroma row. + /// The current U chroma row. + /// The current V chroma row. + public void WriteRows( + int y, + ReadOnlySpan topY, + ReadOnlySpan bottomY, + ReadOnlySpan topU, + ReadOnlySpan topV, + ReadOnlySpan curU, + ReadOnlySpan curV) + { + // The first output row is nearer to the preceding chroma row, and the second output row to the current one. + int w = this.width; + this.WriteRow(y, topY[..w], topU, topV, curU, curV); + this.RowsWritten = y + 1; + if (!bottomY.IsEmpty) + { + this.WriteRow(y + 1, bottomY[..w], curU, curV, topU, topV); + this.RowsWritten = y + 2; + } + } + + /// + /// Converts one output row to its destination row. + /// + /// The row index. + /// The luma samples. + /// The U chroma row nearer to the output row. + /// The V chroma row nearer to the output row. + /// The other U chroma row. + /// The other V chroma row. + private void WriteRow(int y, ReadOnlySpan luma, ReadOnlySpan nearU, ReadOnlySpan nearV, ReadOnlySpan farU, ReadOnlySpan farV) + { + int w = this.width; + ReadOnlySpan alphaRow = this.alpha is null ? ReadOnlySpan.Empty : this.alpha.DangerousGetRowSpan(y); + Span rowBuffer = this.rows.Memory.Span; + + if (this.colorProfileConverter is not null) + { + // The ICC path reads full-resolution chroma, so the chroma rows are interpolated first. The operator gives the + // source profile components, and the ICC transform gives straight RGBA vectors. The vectors are straight, so + // TPixel applies its own alpha representation. + Span u = rowBuffer[..w]; + Span v = rowBuffer.Slice(w, w); + ChromaUpsampler.Upsample(nearU, farU, u); + ChromaUpsampler.Upsample(nearV, farV, v); + Span vectorRow = this.vectors.Memory.Span[..w]; + this.colorConverter.ConvertToRgb(luma, u, v, alphaRow, this.colorProfileConverter, vectorRow); + PixelOperations.Instance.FromUnassociatedScaledVector4Destructive(this.configuration, vectorRow, this.pixels.DangerousGetRowSpan(y)[..w]); + return; + } + + // One converter call interpolates the chroma and converts the row to RGB planes. + Span red = rowBuffer[..w]; + Span green = rowBuffer.Slice(w, w); + Span blue = rowBuffer.Slice(2 * w, w); + this.colorConverter.ConvertToRgb(luma, nearU, nearV, farU, farV, red, green, blue); + + if (!alphaRow.IsEmpty) + { + PixelOperations.Instance.PackFromRgbaPlanes(this.configuration, red, green, blue, alphaRow, this.pixels.DangerousGetRowSpan(y)[..w]); + return; + } + + // PackFromRgbPlanes expects the destination to be padded, so try to get padded span containing extra elements from the next row. + // If we can't get such a padded row because we are on a MemoryGroup boundary or at the last row, + // pack pixels to a temporary, padded proxy buffer, then copy the relevant values to the destination row. + if (y < this.paddedRows && this.pixels.Buffer.DangerousTryGetPaddedRowSpan(this.pixels.Bounds.Y + y, 3, out Span destination)) + { + PixelOperations.Instance.PackFromRgbPlanes(red, green, blue, destination); + } + else + { + Span proxyRow = this.paddedProxyPixelRow.Memory.Span; + PixelOperations.Instance.PackFromRgbPlanes(red, green, blue, proxyRow); + proxyRow[..w].CopyTo(this.pixels.DangerousGetRowSpan(y)); + } + } + + /// + public void Dispose() + { + this.rows.Dispose(); + this.paddedProxyPixelRow.Dispose(); + this.vectors?.Dispose(); + } +} diff --git a/src/ImageSharp/Formats/Webp/RiffHelper.cs b/src/ImageSharp/Formats/Webp/RiffHelper.cs index 468bfdfc9a..6a09811fe8 100644 --- a/src/ImageSharp/Formats/Webp/RiffHelper.cs +++ b/src/ImageSharp/Formats/Webp/RiffHelper.cs @@ -2,11 +2,15 @@ // Licensed under the Six Labors Split License. using System.Buffers.Binary; +using System.Runtime.InteropServices; using System.Text; using SixLabors.ImageSharp.Formats.Webp.Chunks; namespace SixLabors.ImageSharp.Formats.Webp; +/// +/// Writes RIFF files and chunks to a stream. +/// internal static class RiffHelper { /// @@ -14,6 +18,12 @@ internal static class RiffHelper /// private const uint RiffFourCc = 0x52_49_46_46; + /// + /// Writes a RIFF file chunk. The payload is the form type followed by the content that writes. + /// + /// The destination stream. + /// The four ASCII characters of the form type. + /// The method that writes the content after the form type. public static void WriteRiffFile(Stream stream, string formType, Action func) => WriteChunk(stream, RiffFourCc, s => { @@ -21,6 +31,12 @@ public static void WriteRiffFile(Stream stream, string formType, Action func(s); }); + /// + /// Writes a RIFF chunk with the payload that writes. The chunk size and padding come after the payload. + /// + /// The destination stream. + /// The chunk identifier. The most significant byte is the first byte in the stream. + /// The method that writes the payload. public static void WriteChunk(Stream stream, uint fourCc, Action func) { long sizePosition = BeginWriteChunk(stream, fourCc); @@ -28,6 +44,12 @@ public static void WriteChunk(Stream stream, uint fourCc, Action func) EndWriteChunk(stream, sizePosition); } + /// + /// Writes a RIFF chunk with the given payload. A payload of odd size gets one padding byte. + /// + /// The destination stream. + /// The chunk identifier. The most significant byte is the first byte in the stream. + /// The chunk payload. public static void WriteChunk(Stream stream, uint fourCc, ReadOnlySpan data) { Span buffer = stackalloc byte[4]; @@ -47,15 +69,26 @@ public static void WriteChunk(Stream stream, uint fourCc, ReadOnlySpan dat } } - public static unsafe void WriteChunk(Stream stream, uint fourCc, in TStruct chunk) + /// + /// Writes a RIFF chunk whose payload is the in-memory bytes of . + /// + /// The type of the payload. Its memory layout is the payload layout. + /// The destination stream. + /// The chunk identifier. The most significant byte is the first byte in the stream. + /// The chunk payload. + public static void WriteChunk(Stream stream, uint fourCc, in TStruct chunk) where TStruct : unmanaged { - fixed (TStruct* ptr = &chunk) - { - WriteChunk(stream, fourCc, new Span(ptr, sizeof(TStruct))); - } + // The span views the bytes of the struct in place. No copy occurs. + WriteChunk(stream, fourCc, MemoryMarshal.AsBytes(new ReadOnlySpan(in chunk))); } + /// + /// Starts a RIFF chunk. writes its size after the payload. + /// + /// The destination stream. + /// The chunk identifier. The most significant byte is the first byte in the stream. + /// The stream position of the chunk-size field. public static long BeginWriteChunk(Stream stream, uint fourCc) { Span buffer = stackalloc byte[4]; @@ -81,6 +114,13 @@ public static long BeginWriteChunk(Stream stream, ReadOnlySpan fourCc) return sizePosition; } + /// + /// Ends a RIFF chunk. The payload ends at the current stream position. The method writes one padding byte after a payload of odd size. + /// Then it writes the payload size to the chunk-size field. The stream position moves to the end of the padded chunk. + /// A payload larger than bytes causes an exception. + /// + /// The destination stream. + /// The stream position of the chunk-size field, from . public static void EndWriteChunk(Stream stream, long sizePosition) { Span buffer = stackalloc byte[4]; @@ -110,6 +150,12 @@ public static void EndWriteChunk(Stream stream, long sizePosition) stream.Position = position; } + /// + /// Starts a RIFF file and writes its form type. writes the file size after the content. + /// + /// The destination stream. + /// The four ASCII characters of the form type. + /// The stream position of the RIFF size field. public static long BeginWriteRiffFile(Stream stream, string formType) { long sizePosition = BeginWriteChunk(stream, RiffFourCc); @@ -117,6 +163,14 @@ public static long BeginWriteRiffFile(Stream stream, string formType) return sizePosition; } + /// + /// Ends a WebP RIFF file. The file ends at the current stream position. The method writes the RIFF size and can rewrite the VP8X chunk. + /// A file size larger than the WebP limit of 2^32 - 10 bytes causes an exception. + /// + /// The destination stream. + /// The VP8X chunk to write when is . + /// Whether to rewrite the VP8X chunk that follows the RIFF header. + /// The stream position of the start of the RIFF file, before the RIFF identifier. public static void EndWriteRiffFile(Stream stream, in WebpVp8X vp8x, bool updateVp8x, long sizePosition) { // The WebP Container Specification, section "RIFF Header", limits the File Size field to 2^32 - 10. diff --git a/src/ImageSharp/Formats/Webp/WebpAnimationDecoder.cs b/src/ImageSharp/Formats/Webp/WebpAnimationDecoder.cs index b2b392c0f5..0fa2a8fdc4 100644 --- a/src/ImageSharp/Formats/Webp/WebpAnimationDecoder.cs +++ b/src/ImageSharp/Formats/Webp/WebpAnimationDecoder.cs @@ -120,7 +120,8 @@ public ImageInfo Identify( ? Color.Transparent : features.AnimationBackgroundColor; - Span buffer = stackalloc byte[4]; + InlineArray4 bufferStorage = default; + Span buffer = bufferStorage; uint frameCount = 0; while (frameCount < this.maxFrames && this.TryReadToNextFrame(stream, buffer, metadata, containerEnd)) { @@ -180,7 +181,8 @@ public Image Decode( this.webpMetadata.BackgroundColor = backgroundColor; TPixel backgroundPixel = backgroundColor.ToPixel(); - Span buffer = stackalloc byte[4]; + InlineArray4 bufferStorage = default; + Span buffer = bufferStorage; uint frameCount = 0; try { @@ -314,7 +316,8 @@ private bool TryReadFrame( // The frame payload holds an optional ALPH chunk and then a VP8 or VP8L chunk. Nested chunks must fit inside this ANMF payload. Bytes in the next // frame cannot complete this frame. A stream that ends before the image chunk header also misses the image chunk. long frameEnd = stream.Position + frameData.DataSize - WebpFrameData.HeaderSize; - Span buffer = stackalloc byte[4]; + InlineArray4 bufferStorage = default; + Span buffer = bufferStorage; WebpChunkType chunkType; byte alphaChunkHeader = 0; while (true) @@ -420,10 +423,18 @@ private bool TryReadFrame( SetFrameMetadata(currentFrame.Metadata, frameData); } + // A frame that does not blend replaces its area of the canvas, so it decodes straight into that area, as the APNG decoder does. A frame that + // blends needs its own pixels first. Rectangle interest = frameData.Bounds; - bool blend = imageExists && frameData.BlendingMethod == FrameBlendMode.Over; - using Buffer2D pixelData = this.DecodeImageFrameData(frameData, frameInfo, colorProfileConverter); - DrawDecodedImageFrameOnCanvas(pixelData, currentFrame, interest, blend); + if (imageExists && frameData.BlendingMethod == FrameBlendMode.Over) + { + using Buffer2D pixelData = this.DecodeImageFrameData(frameData, frameInfo, colorProfileConverter); + BlendDecodedImageFrameOnCanvas(pixelData, currentFrame, interest); + } + else + { + frameInfo.Decode(currentFrame.PixelBuffer.GetRegion(interest), this.alphaData, colorProfileConverter, this.segmentIntegrityHandling); + } prevFrameData = frameData; @@ -461,66 +472,52 @@ private static void SetFrameMetadata(ImageFrameMetadata meta, WebpFrameData fram private Buffer2D DecodeImageFrameData(WebpFrameData frameData, WebpImageInfo webpInfo, ColorProfileConverter? colorProfileConverter) where TPixel : unmanaged, IPixel { - ImageFrame decodedFrame = new(this.configuration, (int)frameData.Width, (int)frameData.Height); + // WebpImageInfo.Decode writes each row, so the buffer is not clean. + Buffer2D decodeBuffer = this.memoryAllocator.Allocate2D( + (int)frameData.Width, + (int)frameData.Height, + this.configuration.PreferContiguousImageBuffers); try { - Buffer2D decodeBuffer = decodedFrame.PixelBuffer; - webpInfo.Decode(decodeBuffer, this.alphaData, colorProfileConverter, this.segmentIntegrityHandling); + webpInfo.Decode(decodeBuffer.GetRegion(), this.alphaData, colorProfileConverter, this.segmentIntegrityHandling); return decodeBuffer; } catch { - decodedFrame?.Dispose(); + decodeBuffer.Dispose(); throw; } } /// - /// Draws the decoded image on canvas. The decoded image can be smaller the canvas. + /// Blends the decoded image over its area of the canvas. The decoded image can be smaller than the canvas. /// /// The type of the pixel. /// The decoded image. /// The image frame to draw into. /// The area of the frame. - /// Whether to blend the decoded frame data onto the target frame. - private static void DrawDecodedImageFrameOnCanvas( - Buffer2D decodedImageFrame, - ImageFrame imageFrame, - Rectangle restoreArea, - bool blend) + private static void BlendDecodedImageFrameOnCanvas(Buffer2D decodedImageFrame, ImageFrame imageFrame, Rectangle restoreArea) where TPixel : unmanaged, IPixel { // Trim the destination frame to match the restore area. The source frame is already trimmed. + // The destination frame has already been prepopulated with the pixel data from the previous frame + // so blending will leave the desired result which takes into consideration restoration to the + // background color within the restore area. Buffer2DRegion imageFramePixels = imageFrame.PixelBuffer.GetRegion(restoreArea); - if (blend) - { - // The destination frame has already been prepopulated with the pixel data from the previous frame - // so blending will leave the desired result which takes into consideration restoration to the - // background color within the restore area. - PixelBlender blender = PixelBlenders.NormalSrcOver; - - // By using a dedicated vector span we can avoid per-row pool allocations in PixelBlender.Blend - // We need 3 Vector4 values per pixel to store the background, foreground, and result pixels for blending. - using IMemoryOwner workingBufferOwner = imageFrame.Configuration.MemoryAllocator.Allocate(restoreArea.Width * 3); - Span workingBuffer = workingBufferOwner.GetSpan(); + PixelBlender blender = PixelBlenders.NormalSrcOver; - for (int y = 0; y < restoreArea.Height; y++) - { - Span framePixelRow = imageFramePixels.DangerousGetRowSpan(y); - Span decodedPixelRow = decodedImageFrame.DangerousGetRowSpan(y)[..restoreArea.Width]; - - blender.Blend(imageFrame.Configuration, framePixelRow, framePixelRow, decodedPixelRow, 1f, workingBuffer); - } - - return; - } + // By using a dedicated vector span we can avoid per-row pool allocations in PixelBlender.Blend + // We need 3 Vector4 values per pixel to store the background, foreground, and result pixels for blending. + using IMemoryOwner workingBufferOwner = imageFrame.Configuration.MemoryAllocator.Allocate(restoreArea.Width * 3); + Span workingBuffer = workingBufferOwner.GetSpan(); for (int y = 0; y < restoreArea.Height; y++) { Span framePixelRow = imageFramePixels.DangerousGetRowSpan(y); Span decodedPixelRow = decodedImageFrame.DangerousGetRowSpan(y)[..restoreArea.Width]; - decodedPixelRow.CopyTo(framePixelRow); + + blender.Blend(imageFrame.Configuration, framePixelRow, framePixelRow, decodedPixelRow, 1f, workingBuffer); } } diff --git a/src/ImageSharp/Formats/Webp/WebpChunkParsingUtils.cs b/src/ImageSharp/Formats/Webp/WebpChunkParsingUtils.cs index ba894b01de..216f940b03 100644 --- a/src/ImageSharp/Formats/Webp/WebpChunkParsingUtils.cs +++ b/src/ImageSharp/Formats/Webp/WebpChunkParsingUtils.cs @@ -16,6 +16,9 @@ namespace SixLabors.ImageSharp.Formats.Webp; +/// +/// Reads and validates the RIFF chunks of a WebP stream: the image headers, the alpha data and the metadata profiles. +/// internal static class WebpChunkParsingUtils { /// @@ -144,20 +147,17 @@ public static uint ReadUInt24LittleEndian(BufferedReadStream stream, Span /// /// Thrown if the data is not a valid unsigned 24 bit integer. /// - public static unsafe void WriteUInt24LittleEndian(Stream stream, uint data) + public static void WriteUInt24LittleEndian(Stream stream, uint data) { if (data >= 1 << 24) { throw new InvalidDataException($"Invalid data, {data} is not a unsigned 24 bit integer."); } - uint* ptr = &data; - byte* b = (byte*)ptr; - - // Write the data in little endian. - stream.WriteByte(b[0]); - stream.WriteByte(b[1]); - stream.WriteByte(b[2]); + // Write the data in little endian: the low byte first. + stream.WriteByte((byte)data); + stream.WriteByte((byte)(data >> 8)); + stream.WriteByte((byte)(data >> 16)); } /// @@ -411,11 +411,12 @@ private static bool TryReadVp8Header( stream.Read(buffer, 0, 4); uint tmp = BinaryPrimitives.ReadUInt16LittleEndian(buffer); + + // The low 14 bits of each 16-bit field are the size. The top 2 bits are the upscale factor, which a decoder does not apply. + // See RFC 6386, section 9.2. uint width = tmp & 0x3fff; - sbyte xScale = (sbyte)(tmp >> 6); tmp = BinaryPrimitives.ReadUInt16LittleEndian(buffer[2..]); uint height = tmp & 0x3fff; - sbyte yScale = (sbyte)(tmp >> 6); if (width == 0 || height == 0) { segmentIntegrityHandling.ThrowOrIgnoreImageDataError(imageExists, "width or height can not be zero"); @@ -449,8 +450,6 @@ private static bool TryReadVp8Header( DataSize = dataSize, Width = width, Height = height, - XScale = xScale, - YScale = yScale, // The decoder can parse the Vp8 header while it processes the Vp8X header. BitsPerPixel = features?.Alpha == true ? WebpBitsPerPixel.Bit32 : WebpBitsPerPixel.Bit24, @@ -779,6 +778,12 @@ private static long GetChunkEnd(BufferedReadStream stream, uint payloadLength, l return stream.Position + (long)Math.Min(paddedLength, (ulong)available); } + /// + /// Gets the value of an EXIF resolution tag. + /// + /// The EXIF profile. + /// The resolution tag to read. + /// The resolution value, or 0 if the profile does not contain the tag. private static double GetExifResolutionValue(ExifProfile exifProfile, ExifTag tag) { if (exifProfile.TryGetValue(tag, out IExifValue? resolution)) diff --git a/src/ImageSharp/Formats/Webp/WebpCommonUtils.cs b/src/ImageSharp/Formats/Webp/WebpCommonUtils.cs index a2e6ebb344..b74f41f208 100644 --- a/src/ImageSharp/Formats/Webp/WebpCommonUtils.cs +++ b/src/ImageSharp/Formats/Webp/WebpCommonUtils.cs @@ -2,8 +2,6 @@ // Licensed under the Six Labors Split License. using System.Runtime.InteropServices; -using System.Runtime.Intrinsics; -using SixLabors.ImageSharp.Common.Helpers; using SixLabors.ImageSharp.PixelFormats; namespace SixLabors.ImageSharp.Formats.Webp; @@ -14,179 +12,15 @@ namespace SixLabors.ImageSharp.Formats.Webp; internal static class WebpCommonUtils { /// - /// Checks if the pixel row is not opaque. + /// Gets a value indicating whether a row has a pixel with an alpha value other than 255. /// /// The row to check. - /// Returns true if alpha has non-0xff values. - public static unsafe bool CheckNonOpaque(ReadOnlySpan row) + /// if an alpha value is not 255. Else . + public static bool CheckNonOpaque(ReadOnlySpan row) { - if (Vector256.IsHardwareAccelerated) - { - ReadOnlySpan rowBytes = MemoryMarshal.AsBytes(row); - int i = 0; - int length = (row.Length * 4) - 3; - fixed (byte* src = rowBytes) - { - Vector256 alphaMaskVector256 = Vector256.Create( - 0, - 0, - 0, - 255, - 0, - 0, - 0, - 255, - 0, - 0, - 0, - 255, - 0, - 0, - 0, - 255, - 0, - 0, - 0, - 255, - 0, - 0, - 0, - 255, - 0, - 0, - 0, - 255, - 0, - 0, - 0, - 255); - - Vector256 all0x80Vector256 = Vector256.Create((byte)0x80).AsByte(); - - for (; i + 128 <= length; i += 128) - { - Vector256 a0 = Vector256.Load(src + i).AsByte(); - Vector256 a1 = Vector256.Load(src + i + 32).AsByte(); - Vector256 a2 = Vector256.Load(src + i + 64).AsByte(); - Vector256 a3 = Vector256.Load(src + i + 96).AsByte(); - Vector256 b0 = (a0 & alphaMaskVector256).AsInt32(); - Vector256 b1 = (a1 & alphaMaskVector256).AsInt32(); - Vector256 b2 = (a2 & alphaMaskVector256).AsInt32(); - Vector256 b3 = (a3 & alphaMaskVector256).AsInt32(); - Vector256 c0 = Vector256_.PackSignedSaturate(b0, b1).AsInt16(); - Vector256 c1 = Vector256_.PackSignedSaturate(b2, b3).AsInt16(); - Vector256 d = Vector256_.PackSignedSaturate(c0, c1).AsByte(); - Vector256 bits = Vector256.Equals(d, all0x80Vector256); - uint mask = bits.ExtractMostSignificantBits(); - if (mask != 0xFFFF_FFFF) - { - return true; - } - } - - for (; i + 64 <= length; i += 64) - { - if (IsNoneOpaque64BytesVector128(src, i)) - { - return true; - } - } - - for (; i + 32 <= length; i += 32) - { - if (IsNonOpaque32BytesVector128(src, i)) - { - return true; - } - } - - for (; i <= length; i += 4) - { - if (src[i + 3] != 0xFF) - { - return true; - } - } - } - } - else if (Vector128.IsHardwareAccelerated) - { - ReadOnlySpan rowBytes = MemoryMarshal.AsBytes(row); - int i = 0; - int length = (row.Length * 4) - 3; - fixed (byte* src = rowBytes) - { - for (; i + 64 <= length; i += 64) - { - if (IsNoneOpaque64BytesVector128(src, i)) - { - return true; - } - } - - for (; i + 32 <= length; i += 32) - { - if (IsNonOpaque32BytesVector128(src, i)) - { - return true; - } - } - - for (; i <= length; i += 4) - { - if (src[i + 3] != 0xFF) - { - return true; - } - } - } - } - else - { - for (int x = 0; x < row.Length; x++) - { - if (row[x].A != 0xFF) - { - return true; - } - } - } - - return false; - } - - private static unsafe bool IsNoneOpaque64BytesVector128(byte* src, int i) - { - Vector128 alphaMask = Vector128.Create(0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255); - - Vector128 a0 = Vector128.Load(src + i).AsByte(); - Vector128 a1 = Vector128.Load(src + i + 16).AsByte(); - Vector128 a2 = Vector128.Load(src + i + 32).AsByte(); - Vector128 a3 = Vector128.Load(src + i + 48).AsByte(); - Vector128 b0 = (a0 & alphaMask).AsInt32(); - Vector128 b1 = (a1 & alphaMask).AsInt32(); - Vector128 b2 = (a2 & alphaMask).AsInt32(); - Vector128 b3 = (a3 & alphaMask).AsInt32(); - Vector128 c0 = Vector128.NarrowWithSaturation(b0, b1).AsInt16(); - Vector128 c1 = Vector128.NarrowWithSaturation(b2, b3).AsInt16(); - Vector128 d = Vector128.NarrowWithSaturation(c0, c1).AsByte(); - Vector128 bits = Vector128.Equals(d, Vector128.Create((byte)0x80).AsByte()); - uint mask = bits.ExtractMostSignificantBits(); - return mask != 0xFFFF; - } - - private static unsafe bool IsNonOpaque32BytesVector128(byte* src, int i) - { - Vector128 alphaMask = Vector128.Create(0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255); - - Vector128 a0 = Vector128.Load(src + i).AsByte(); - Vector128 a1 = Vector128.Load(src + i + 16).AsByte(); - Vector128 b0 = (a0 & alphaMask).AsInt32(); - Vector128 b1 = (a1 & alphaMask).AsInt32(); - Vector128 c = Vector128.NarrowWithSaturation(b0, b1).AsInt16(); - Vector128 d = Vector128.NarrowWithSaturation(c, c).AsByte(); - Vector128 bits = Vector128.Equals(d, Vector128.Create((byte)0x80).AsByte()); - uint mask = bits.ExtractMostSignificantBits(); - return mask != 0xFFFF; + // Each Bgra32 pixel read as one little-endian uint has alpha in bits 24..31. The AND of all pixels keeps + // all eight alpha bits set only when every alpha value is 255. An empty row gives all bits set, so it is opaque. + const uint alphaMask = 0xFF00_0000; + return (SimdUtils.Reduce(MemoryMarshal.Cast(row)) & alphaMask) != alphaMask; } } diff --git a/src/ImageSharp/Formats/Webp/WebpConstants.cs b/src/ImageSharp/Formats/Webp/WebpConstants.cs index e8e2ea7d20..5027bb7c3f 100644 --- a/src/ImageSharp/Formats/Webp/WebpConstants.cs +++ b/src/ImageSharp/Formats/Webp/WebpConstants.cs @@ -142,34 +142,93 @@ internal static class WebpConstants /// public const int MaxDimension = 16383; + /// + /// The maximum length of a VP8L prefix code. Code length codes 0 to 15 give the length directly. See the WebP Lossless Bitstream Specification, + /// section 6.2.1: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// public const int MaxAllowedCodeLength = HuffmanTableBuilder.MaximumCodeLength; + /// + /// The code length that code length code 16 repeats when no non-zero code length comes before it. See the WebP Lossless Bitstream Specification, + /// section 6.2.1: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// public const int DefaultCodeLength = 8; + /// + /// The number of prefix codes in each VP8L prefix code group. See the WebP Lossless Bitstream Specification, section 6.2.2: + /// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// public const int HuffmanCodesPerMetaCode = 5; + /// + /// The opaque black ARGB value. Predictor mode 0 of the VP8L predictor transform predicts this value. See the WebP Lossless Bitstream Specification, + /// section 4.1: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// public const uint ArgbBlack = 0xff000000; + /// + /// The number of rows that the VP8L decoder transforms in one batch. + /// public const int NumArgbCacheRows = 16; + /// + /// The number of literal codes of one 8-bit channel in a VP8L prefix code. See the WebP Lossless Bitstream Specification, section 6.2.1: + /// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// public const int NumLiteralCodes = 256; + /// + /// The number of LZ77 length prefix codes in the green alphabet of a VP8L prefix code group. See the WebP Lossless Bitstream Specification, + /// section 5.2.2: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// public const int NumLengthCodes = 24; + /// + /// The number of LZ77 distance prefix codes in a VP8L prefix code group. See the WebP Lossless Bitstream Specification, section 5.2.2: + /// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// public const int NumDistanceCodes = 40; + /// + /// The number of code length codes of a VP8L normal code length code. See the WebP Lossless Bitstream Specification, section 6.2.1: + /// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// public const int CodeLengthCodes = 19; + /// + /// The number of index bits of the root lookup table of the VP8L code length code. + /// public const int LengthTableBits = 7; + /// + /// The number of code length codes that give a code length directly. These are the codes 0 to 15. See the WebP Lossless Bitstream Specification, + /// section 6.2.1: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// public const uint CodeLengthLiterals = 16; + /// + /// The code length code that repeats the previous non-zero code length. See the WebP Lossless Bitstream Specification, section 6.2.1: + /// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// public const int CodeLengthRepeatCode = 16; + /// + /// The number of extra bits of the code length codes 16, 17 and 18. See the WebP Lossless Bitstream Specification, section 6.2.1: + /// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// public static readonly int[] CodeLengthExtraBits = [2, 3, 7]; + /// + /// The smallest repeat count of the code length codes 16, 17 and 18. The decoder adds the value of the extra bits to it. + /// See the WebP Lossless Bitstream Specification, section 6.2.1: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// public static readonly int[] CodeLengthRepeatOffsets = [3, 3, 11]; + /// + /// The alphabet size of each of the five prefix codes in a VP8L prefix code group: green with lengths, red, blue, alpha and distance. + /// The green size does not include the color cache. See the WebP Lossless Bitstream Specification, section 6.2.1: + /// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// public static readonly int[] AlphabetSize = [ NumLiteralCodes + NumLengthCodes, @@ -177,50 +236,116 @@ internal static class WebpConstants NumDistanceCodes ]; + /// + /// The number of macroblock segments in a VP8 frame. See RFC 6386, section 9.3: https://www.rfc-editor.org/rfc/rfc6386#section-9.3. + /// public const int NumMbSegments = 4; + /// + /// The maximum number of DCT token partitions in a VP8 frame. See RFC 6386, section 9.5: https://www.rfc-editor.org/rfc/rfc6386#section-9.5. + /// public const int MaxNumPartitions = 8; + /// + /// The number of block types of the VP8 DCT token probabilities. See RFC 6386, section 13.3: https://www.rfc-editor.org/rfc/rfc6386#section-13.3. + /// public const int NumTypes = 4; + /// + /// The number of coefficient bands of the VP8 DCT token probabilities. See RFC 6386, section 13.3: https://www.rfc-editor.org/rfc/rfc6386#section-13.3. + /// public const int NumBands = 8; + /// + /// The number of probabilities of the VP8 DCT token tree. It is one less than the 12 tokens. See RFC 6386, section 13.3: + /// https://www.rfc-editor.org/rfc/rfc6386#section-13.3. + /// public const int NumProbas = 11; + /// + /// The number of 16x16 luma intra modes and of chroma intra modes. See RFC 6386, sections 11.2 and 11.4: + /// https://www.rfc-editor.org/rfc/rfc6386#section-11.2. + /// public const int NumPredModes = 4; + /// + /// The number of 4x4 luma intra modes. See RFC 6386, section 11.2: https://www.rfc-editor.org/rfc/rfc6386#section-11.2. + /// public const int NumBModes = 10; + /// + /// The number of contexts of the VP8 DCT token probabilities. See RFC 6386, section 13.3: https://www.rfc-editor.org/rfc/rfc6386#section-13.3. + /// public const int NumCtx = 3; + /// + /// The largest coefficient level that has its own entry in the level cost tables of the encoder. Larger levels use the cost of this level. + /// public const int MaxVariableLevel = 67; + /// + /// The largest number of non-zero AC levels for which the encoder treats a 16x16 luma area as flat. + /// public const int FlatnessLimitI16 = 0; + /// + /// The largest number of non-zero AC levels for which the encoder treats a chroma area as flat. + /// public const int FlatnessLimitIUv = 2; + /// + /// The largest number of non-zero AC levels for which the encoder treats a 4x4 luma block as flat. + /// public const int FlatnessLimitI4 = 3; + /// + /// The rate penalty for each block that the encoder adds to a mode other than mode 0 on a flat area. + /// public const int FlatnessPenality = 140; - // This is the common stride for enc/dec. + /// + /// The row stride in bytes of the work buffers of the VP8 encoder and decoder. + /// public const int Bps = 32; - // gamma-compensates loss of resolution during chroma subsampling. + /// + /// The gamma exponent of the linear-light chroma downsampling of the encoder. It compensates for the loss of resolution in chroma subsampling. + /// public const double Gamma = 0.80d; + /// + /// The number of fixed-point bits of the linear-light values of the chroma downsampling. + /// public const int GammaFix = 12; // Fixed-point precision for linear values. + /// + /// The largest linear-light value of the chroma downsampling. It is the largest value with bits. + /// public const int GammaScale = (1 << GammaFix) - 1; + /// + /// The number of fractional bits of the interpolation in the linear-to-gamma table. + /// public const int GammaTabFix = 7; // Fixed-point fractional bits precision. + /// + /// The number of intervals of the linear-to-gamma table. The table has one more entry than this value. + /// public const int GammaTabSize = 1 << (GammaFix - GammaTabFix); + /// + /// The fixed-point value of 1 with fractional bits. + /// public const int GammaTabScale = 1 << GammaTabFix; + /// + /// The rounding term that the encoder adds before it removes the fractional bits. It is half of . + /// public const int GammaTabRounder = GammaTabScale >> 1; + /// + /// The number of fractional bits of the reciprocal alpha sums of the chroma downsampling. + /// public const int AlphaFix = 19; /// @@ -253,12 +378,24 @@ internal static class WebpConstants /// public const double SnsToDq = 0.9; + /// + /// The largest chroma AC quantizer delta that the encoder derives from the chroma susceptibility. + /// public const int QuantEncMaxDqUv = 6; + /// + /// The smallest chroma AC quantizer delta that the encoder derives from the chroma susceptibility. + /// public const int QuantEncMinDqUv = -4; + /// + /// The number of fractional bits of the fixed-point reciprocal quantizer steps of the encoder. + /// public const int QFix = 17; + /// + /// The number of edge step entries for each sharpness in the loop filter level table of the encoder. Larger steps use the last entry. + /// public const int MaxDelzaSize = 64; /// @@ -272,8 +409,16 @@ internal static class WebpConstants /// public const int Vp8MaxPartition0Size = 1 << 19; + /// + /// The cost of each chroma intra mode in 1/256 bits. The costs come from the fixed key frame mode probabilities of RFC 6386, section 11.4: + /// https://www.rfc-editor.org/rfc/rfc6386#section-11.4. + /// public static readonly short[] Vp8FixedCostsUv = [302, 984, 439, 642]; + /// + /// The cost of each 16x16 luma intra mode in 1/256 bits. The costs come from the fixed key frame mode probabilities of RFC 6386, section 11.2: + /// https://www.rfc-editor.org/rfc/rfc6386#section-11.2. + /// public static readonly short[] Vp8FixedCostsI16 = [663, 919, 872, 919]; /// @@ -288,13 +433,18 @@ internal static class WebpConstants /// public static readonly byte[] FilterExtraRows = [0, 2, 8]; - // Paragraph 9.9 - public static readonly int[] Vp8EncBands = - [ - 0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0 - ]; + /// + /// Gets the band of each coefficient position, plus one entry for the position after the last coefficient. See RFC 6386, section 13.3. + /// + /// + /// The data comes from the static data of the assembly, so a read is one load from a fixed address and the property allocates nothing. + /// + public static ReadOnlySpan Vp8EncBands => [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0]; - public static readonly short[] Scan = + /// + /// Gets the offset of each of the 16 luma 4x4 blocks in a work buffer with a stride of , in raster order. + /// + public static ReadOnlySpan Scan => [ 0 + (0 * Bps), 4 + (0 * Bps), 8 + (0 * Bps), 12 + (0 * Bps), 0 + (4 * Bps), 4 + (4 * Bps), 8 + (4 * Bps), 12 + (4 * Bps), @@ -302,14 +452,40 @@ internal static class WebpConstants 0 + (12 * Bps), 4 + (12 * Bps), 8 + (12 * Bps), 12 + (12 * Bps) ]; - // Residual decoding (Paragraph 13.2 / 13.3) - public static readonly byte[] Cat3 = [173, 148, 140]; - public static readonly byte[] Cat4 = [176, 155, 140, 135]; - public static readonly byte[] Cat5 = [180, 157, 141, 134, 130]; - public static readonly byte[] Cat6 = [254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129]; - public static readonly byte[] Zigzag = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; + /// + /// Gets the probabilities of the extra bits of the DCT_CAT3 token. See RFC 6386, section 13.2. + /// + public static ReadOnlySpan Cat3 => [173, 148, 140]; - public static readonly sbyte[] YModesIntra4 = + /// + /// Gets the probabilities of the extra bits of the DCT_CAT4 token. See RFC 6386, section 13.2. + /// + public static ReadOnlySpan Cat4 => [176, 155, 140, 135]; + + /// + /// Gets the probabilities of the extra bits of the DCT_CAT5 token. See RFC 6386, section 13.2. + /// + public static ReadOnlySpan Cat5 => [180, 157, 141, 134, 130]; + + /// + /// Gets the probabilities of the extra bits of the DCT_CAT6 token. See RFC 6386, section 13.2. + /// + public static ReadOnlySpan Cat6 => [254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129]; + + /// + /// Gets the raster position of each coefficient in token order. See RFC 6386, section 13. + /// + public static ReadOnlySpan Zigzag => [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; + + /// + /// Gets the coding tree of the 4x4 luma intra modes. It has the shape of the subblock mode tree of RFC 6386, section 11.2: + /// https://www.rfc-editor.org/rfc/rfc6386#section-11.2. + /// + /// + /// A positive entry i is the next node. Its two children are at 2 * i and 2 * i + 1, and its probability has index i. A zero or negative entry is a + /// leaf that holds the negated mode. + /// + public static ReadOnlySpan YModesIntra4 => [ -0, 1, -1, 2, diff --git a/src/ImageSharp/Formats/Webp/WebpDecoderCore.cs b/src/ImageSharp/Formats/Webp/WebpDecoderCore.cs index ef0df10b62..4f3b178248 100644 --- a/src/ImageSharp/Formats/Webp/WebpDecoderCore.cs +++ b/src/ImageSharp/Formats/Webp/WebpDecoderCore.cs @@ -53,6 +53,9 @@ internal sealed class WebpDecoderCore : ImageDecoderCore, IDisposable /// private readonly BackgroundColorHandling backgroundColorHandling; + /// + /// The ICC profile of the containing format, or to use the ICC profile of the WebP image. + /// private readonly IccProfile? sourceIccProfile; /// @@ -93,7 +96,8 @@ protected override Image Decode(BufferedReadStream stream, Cance { // The containing format's profile takes precedence. ICCP parsing already skips a second profile while consuming its chunk. ImageMetadata metadata = new() { IccProfile = this.sourceIccProfile }; - Span buffer = stackalloc byte[4]; + InlineArray4 bufferStorage = default; + Span buffer = bufferStorage; this.ReadImageHeader(stream, buffer); @@ -101,7 +105,7 @@ protected override Image Decode(BufferedReadStream stream, Cance { ColorProfileConverter? colorProfileConverter = WebpColorConverterBase.CreateIccConverter(this.configuration, metadata.IccProfile); - if (this.webImageInfo.Features is { Animation: true }) + if (this.webImageInfo.Features?.Animation == true) { using WebpAnimationDecoder animationDecoder = new( this.memoryAllocator, @@ -128,8 +132,15 @@ protected override Image Decode(BufferedReadStream stream, Cance _ = this.webImageInfo.TryReadImageHeaders(this.memoryAllocator, this.configuration, this.Options.SegmentIntegrityHandling, false); // ReadVp8Info read the metadata chunks after the image chunk too, so the metadata is complete here. - image = new Image(this.configuration, (int)this.webImageInfo.Width, (int)this.webImageInfo.Height, metadata); - this.webImageInfo.Decode(image.GetRootFramePixelBuffer(), this.alphaData, colorProfileConverter, this.Options.SegmentIntegrityHandling); + // WebpImageInfo.Decode writes each row, so the buffer is not clean. A clean allocation of a 1920 x 1080 Rgba32 image clears 8 MB that the + // decode then writes again. + Buffer2D pixels = this.memoryAllocator.Allocate2D( + (int)this.webImageInfo.Width, + (int)this.webImageInfo.Height, + this.configuration.PreferContiguousImageBuffers); + + image = new Image(this.configuration, pixels, metadata); + this.webImageInfo.Decode(pixels.GetRegion(), this.alphaData, colorProfileConverter, this.Options.SegmentIntegrityHandling); return image; } } @@ -143,12 +154,13 @@ protected override Image Decode(BufferedReadStream stream, Cance /// protected override ImageInfo Identify(BufferedReadStream stream, CancellationToken cancellationToken) { - this.ReadImageHeader(stream, stackalloc byte[4]); + InlineArray4 buffer = default; + this.ReadImageHeader(stream, buffer); ImageMetadata metadata = new(); using (this.webImageInfo = this.ReadVp8Info(stream, metadata, true)) { - if (this.webImageInfo.Features is { Animation: true }) + if (this.webImageInfo.Features?.Animation == true) { using WebpAnimationDecoder animationDecoder = new( this.memoryAllocator, @@ -200,7 +212,7 @@ private void ReadImageHeader(BufferedReadStream stream, Span buffer) // Read file size. // The size of the file in bytes starting at offset 8. - // The file size in the header is the total size of the chunks that follow plus 4 bytes for the ‘WEBP’ FourCC. + // The file size in the header is the total size of the chunks that follow plus 4 bytes for the 'WEBP' FourCC. if (stream.Read(buffer) != 4) { WebpThrowHelper.ThrowInvalidImageContentException("Not enough data to read the RIFF size."); @@ -237,7 +249,8 @@ private WebpImageInfo ReadVp8Info(BufferedReadStream stream, ImageMetadata metad { WebpMetadata webpMetadata = metadata.GetFormatMetadata(WebpFormat.Instance); - Span buffer = stackalloc byte[4]; + InlineArray4 bufferStorage = default; + Span buffer = bufferStorage; WebpChunkType chunkType = WebpChunkParsingUtils.ReadChunkType(stream, buffer); WebpFeatures features = new(); if (chunkType is WebpChunkType.Vp8 or WebpChunkType.Vp8L) diff --git a/src/ImageSharp/Formats/Webp/WebpEncoderCore.cs b/src/ImageSharp/Formats/Webp/WebpEncoderCore.cs index 2653c8fd19..f953ceea83 100644 --- a/src/ImageSharp/Formats/Webp/WebpEncoderCore.cs +++ b/src/ImageSharp/Formats/Webp/WebpEncoderCore.cs @@ -55,8 +55,8 @@ internal sealed class WebpEncoderCore private readonly int filterStrength; /// - /// Flag indicating whether to preserve the exact RGB values under transparent area. Otherwise, discard this invisible - /// RGB information for better compression. + /// The mode for the RGB values of transparent pixels. sets all components + /// of each source pixel with zero alpha to zero before the encode. /// private readonly TransparentColorMode transparentColorMode; @@ -165,10 +165,12 @@ public void Encode(Image image, Stream stream, CancellationToken ushort repeatCount = this.repeatCount ?? webpMetadata.RepeatCount; // Borrow the same row scratch for every frame and both compression paths. Direct sRGB packing needs no scratch. - using IMemoryOwner? vectorBuffer = converter is null ? null : this.memoryAllocator.Allocate(image.Width); - using IMemoryOwner? rgbBuffer = converter is null ? null : this.memoryAllocator.Allocate(image.Width); + // The clear of transparent pixels also uses the vector row, as in the other encoders. + bool clearTransparentPixels = EncodingUtilities.ShouldReplaceTransparentPixels(this.transparentColorMode); + using IMemoryOwner? vectorBuffer = + converter is null && !clearTransparentPixels ? null : this.memoryAllocator.Allocate(image.Width); + Span vectors = vectorBuffer is null ? default : vectorBuffer.GetSpan(); - Span rgb = rgbBuffer is null ? default : rgbBuffer.GetSpan(); if (lossless) { @@ -194,7 +196,7 @@ public void Encode(Image image, Stream stream, CancellationToken cancellationToken.ThrowIfCancellationRequested(); - hasAlpha |= encoder.Encode(previousFrame, previousFrame.Bounds, frameMetadata, stream, hasAnimation, converter, vectors, rgb); + hasAlpha |= encoder.Encode(previousFrame, previousFrame.Bounds, frameMetadata, stream, hasAnimation, converter, vectors); if (hasAnimation) { @@ -229,19 +231,9 @@ public void Encode(Image image, Stream stream, CancellationToken blend, ClampingMode.Even); - using Vp8LEncoder animatedEncoder = new( - this.memoryAllocator, - this.configuration, - bounds.Width, - bounds.Height, - this.quality, - this.skipMetadata, - this.method, - this.transparentColorMode, - this.nearLossless, - this.nearLosslessQuality); - - hasAlpha |= animatedEncoder.Encode(encodingFrame, bounds, frameMetadata, stream, hasAnimation, converter, vectors, rgb); + // The root encoder has buffers for the whole canvas, and the bounds of a frame are inside the canvas. Each encode derives + // all transforms, palettes and references again, so the frames reuse the root encoder and its buffers. + hasAlpha |= encoder.Encode(encodingFrame, bounds, frameMetadata, stream, hasAnimation, converter, vectors); previousFrame = currentFrame; previousDisposal = frameMetadata.DisposalMode; @@ -263,7 +255,8 @@ public void Encode(Image image, Stream stream, CancellationToken this.entropyPasses, this.filterStrength, this.spatialNoiseShaping, - this.alphaCompression); + this.alphaCompression, + this.transparentColorMode); long initialPosition = stream.Position; bool hasAlpha = false; @@ -278,7 +271,7 @@ public void Encode(Image image, Stream stream, CancellationToken WebpFrameMetadata frameMetadata = previousFrame.Metadata.GetWebpMetadata(); FrameDisposalMode previousDisposal = frameMetadata.DisposalMode; - hasAlpha |= encoder.EncodeAnimation(previousFrame, stream, previousFrame.Bounds, frameMetadata, outputIccProfile, converter, vectors, rgb); + hasAlpha |= encoder.EncodeAnimation(previousFrame, stream, previousFrame.Bounds, frameMetadata, outputIccProfile, converter, vectors); // Encode additional frames // This frame is reused to store de-duplicated pixel buffers. @@ -309,20 +302,9 @@ public void Encode(Image image, Stream stream, CancellationToken blend, ClampingMode.Even); - using Vp8Encoder animatedEncoder = new( - this.memoryAllocator, - this.configuration, - bounds.Width, - bounds.Height, - this.quality, - this.skipMetadata, - this.method, - this.entropyPasses, - this.filterStrength, - this.spatialNoiseShaping, - this.alphaCompression); - - hasAlpha |= animatedEncoder.EncodeAnimation(encodingFrame, stream, bounds, frameMetadata, outputIccProfile, converter, vectors, rgb); + // The frame bounds are inside the image, so the buffers of the image-size encoder hold every frame. + // Each frame starts from the state of a new encoder, so the output is the same as with an encoder for each frame. + hasAlpha |= encoder.EncodeAnimation(encodingFrame, stream, bounds, frameMetadata, outputIccProfile, converter, vectors); previousFrame = currentFrame; previousDisposal = frameMetadata.DisposalMode; @@ -333,7 +315,7 @@ public void Encode(Image image, Stream stream, CancellationToken else { cancellationToken.ThrowIfCancellationRequested(); - encoder.EncodeStatic(stream, image, outputIccProfile, converter, vectors, rgb); + encoder.EncodeStatic(stream, image, outputIccProfile, converter, vectors); encoder.EncodeFooter(image, in vp8x, hasAlpha, stream, initialPosition); } } diff --git a/src/ImageSharp/Formats/Webp/WebpImageInfo.cs b/src/ImageSharp/Formats/Webp/WebpImageInfo.cs index 9c08b6f950..3053a48b97 100644 --- a/src/ImageSharp/Formats/Webp/WebpImageInfo.cs +++ b/src/ImageSharp/Formats/Webp/WebpImageInfo.cs @@ -11,6 +11,9 @@ namespace SixLabors.ImageSharp.Formats.Webp; +/// +/// The information about a VP8 or VP8L image, and the decoders of its data. +/// internal class WebpImageInfo : IDisposable { /// @@ -48,16 +51,6 @@ internal class WebpImageInfo : IDisposable /// public uint Height { get; set; } - /// - /// Gets or sets the horizontal scale. - /// - public sbyte XScale { get; set; } - - /// - /// Gets or sets the vertical scale. - /// - public sbyte YScale { get; set; } - /// /// Gets or sets the bits per pixel. /// @@ -129,24 +122,30 @@ public bool TryReadImageHeaders( /// Decodes the pixels of the image. The caller reads the headers with before it calls this method. /// /// The pixel format. - /// The pixel buffer to write to. It has the size of the image. + /// + /// The pixels to write to: a whole image, or the area of an animation frame on its canvas. The area has the size of the image. Its content can be + /// undefined, because the method writes each row. + /// /// The ALPH chunk data of a lossy image, or when there is no ALPH chunk. /// The selected source ICC converter, if available. /// The image data integrity mode. It controls damaged or truncated image data. public void Decode( - Buffer2D pixels, + Buffer2DRegion pixels, IMemoryOwner? alphaData, ColorProfileConverter? colorProfileConverter, SegmentIntegrityHandling segmentIntegrityHandling) where TPixel : unmanaged, IPixel { - if (this.IsLossless) + int rows = this.IsLossless + ? this.losslessDecoder!.Decode(this.vp8LDecoder!, pixels, (int)this.Width, colorProfileConverter, segmentIntegrityHandling) + : this.lossyDecoder!.Decode(this.vp8Decoder!, pixels, this, alphaData, colorProfileConverter, segmentIntegrityHandling); + + // Damaged data in the ignore mode can stop the decode before the last row. As in the JPEG decoder, only these rows get 0, the transparent fill of + // the other codecs. A complete decode writes every row, so the buffer needs no clean allocation. + for (int y = rows; y < pixels.Height; y++) { - this.losslessDecoder!.Decode(this.vp8LDecoder!, pixels, (int)this.Width, colorProfileConverter, segmentIntegrityHandling); - return; + pixels.DangerousGetRowSpan(y).Clear(); } - - this.lossyDecoder!.Decode(this.vp8Decoder!, pixels, this, alphaData, colorProfileConverter, segmentIntegrityHandling); } /// diff --git a/src/ImageSharp/Formats/Webp/WebpLookupTables.cs b/src/ImageSharp/Formats/Webp/WebpLookupTables.cs index 4c45329bc8..ae1ace5afe 100644 --- a/src/ImageSharp/Formats/Webp/WebpLookupTables.cs +++ b/src/ImageSharp/Formats/Webp/WebpLookupTables.cs @@ -6,19 +6,149 @@ namespace SixLabors.ImageSharp.Formats.Webp; #pragma warning disable SA1201 // Elements should appear in the correct order +/// +/// Lookup tables of the VP8 and VP8L encoders and decoders. +/// internal static class WebpLookupTables { - public static readonly byte[,][] ModesProba = new byte[10, 10][]; + /// + /// Gets the probabilities of the 4x4 luma mode tree for each pair of top and left modes. See RFC 6386, section 11.5: + /// https://www.rfc-editor.org/rfc/rfc6386#section-11.5. + /// + /// + /// The 9 probabilities of top mode t and left mode l start at ((t * 10) + l) * 9. The data comes from the static data of the assembly, so a read + /// is one load from a fixed address, without the two indirections of a jagged two-dimensional array. + /// + public static ReadOnlySpan ModesProba => + [ + 231, 120, 48, 89, 115, 113, 120, 152, 112, + 152, 179, 64, 126, 170, 118, 46, 70, 95, + 175, 69, 143, 80, 85, 82, 72, 155, 103, + 56, 58, 10, 171, 218, 189, 17, 13, 152, + 114, 26, 17, 163, 44, 195, 21, 10, 173, + 121, 24, 80, 195, 26, 62, 44, 64, 85, + 144, 71, 10, 38, 171, 213, 144, 34, 26, + 170, 46, 55, 19, 136, 160, 33, 206, 71, + 63, 20, 8, 114, 114, 208, 12, 9, 226, + 81, 40, 11, 96, 182, 84, 29, 16, 36, + 134, 183, 89, 137, 98, 101, 106, 165, 148, + 72, 187, 100, 130, 157, 111, 32, 75, 80, + 66, 102, 167, 99, 74, 62, 40, 234, 128, + 41, 53, 9, 178, 241, 141, 26, 8, 107, + 74, 43, 26, 146, 73, 166, 49, 23, 157, + 65, 38, 105, 160, 51, 52, 31, 115, 128, + 104, 79, 12, 27, 217, 255, 87, 17, 7, + 87, 68, 71, 44, 114, 51, 15, 186, 23, + 47, 41, 14, 110, 182, 183, 21, 17, 194, + 66, 45, 25, 102, 197, 189, 23, 18, 22, + 88, 88, 147, 150, 42, 46, 45, 196, 205, + 43, 97, 183, 117, 85, 38, 35, 179, 61, + 39, 53, 200, 87, 26, 21, 43, 232, 171, + 56, 34, 51, 104, 114, 102, 29, 93, 77, + 39, 28, 85, 171, 58, 165, 90, 98, 64, + 34, 22, 116, 206, 23, 34, 43, 166, 73, + 107, 54, 32, 26, 51, 1, 81, 43, 31, + 68, 25, 106, 22, 64, 171, 36, 225, 114, + 34, 19, 21, 102, 132, 188, 16, 76, 124, + 62, 18, 78, 95, 85, 57, 50, 48, 51, + 193, 101, 35, 159, 215, 111, 89, 46, 111, + 60, 148, 31, 172, 219, 228, 21, 18, 111, + 112, 113, 77, 85, 179, 255, 38, 120, 114, + 40, 42, 1, 196, 245, 209, 10, 25, 109, + 88, 43, 29, 140, 166, 213, 37, 43, 154, + 61, 63, 30, 155, 67, 45, 68, 1, 209, + 100, 80, 8, 43, 154, 1, 51, 26, 71, + 142, 78, 78, 16, 255, 128, 34, 197, 171, + 41, 40, 5, 102, 211, 183, 4, 1, 221, + 51, 50, 17, 168, 209, 192, 23, 25, 82, + 138, 31, 36, 171, 27, 166, 38, 44, 229, + 67, 87, 58, 169, 82, 115, 26, 59, 179, + 63, 59, 90, 180, 59, 166, 93, 73, 154, + 40, 40, 21, 116, 143, 209, 34, 39, 175, + 47, 15, 16, 183, 34, 223, 49, 45, 183, + 46, 17, 33, 183, 6, 98, 15, 32, 183, + 57, 46, 22, 24, 128, 1, 54, 17, 37, + 65, 32, 73, 115, 28, 128, 23, 128, 205, + 40, 3, 9, 115, 51, 192, 18, 6, 223, + 87, 37, 9, 115, 59, 77, 64, 21, 47, + 104, 55, 44, 218, 9, 54, 53, 130, 226, + 64, 90, 70, 205, 40, 41, 23, 26, 57, + 54, 57, 112, 184, 5, 41, 38, 166, 213, + 30, 34, 26, 133, 152, 116, 10, 32, 134, + 39, 19, 53, 221, 26, 114, 32, 73, 255, + 31, 9, 65, 234, 2, 15, 1, 118, 73, + 75, 32, 12, 51, 192, 255, 160, 43, 51, + 88, 31, 35, 67, 102, 85, 55, 186, 85, + 56, 21, 23, 111, 59, 205, 45, 37, 192, + 55, 38, 70, 124, 73, 102, 1, 34, 98, + 125, 98, 42, 88, 104, 85, 117, 175, 82, + 95, 84, 53, 89, 128, 100, 113, 101, 45, + 75, 79, 123, 47, 51, 128, 81, 171, 1, + 57, 17, 5, 71, 102, 57, 53, 41, 49, + 38, 33, 13, 121, 57, 73, 26, 1, 85, + 41, 10, 67, 138, 77, 110, 90, 47, 114, + 115, 21, 2, 10, 102, 255, 166, 23, 6, + 101, 29, 16, 10, 85, 128, 101, 196, 26, + 57, 18, 10, 102, 102, 213, 34, 20, 43, + 117, 20, 15, 36, 163, 128, 68, 1, 26, + 102, 61, 71, 37, 34, 53, 31, 243, 192, + 69, 60, 71, 38, 73, 119, 28, 222, 37, + 68, 45, 128, 34, 1, 47, 11, 245, 171, + 62, 17, 19, 70, 146, 85, 55, 62, 70, + 37, 43, 37, 154, 100, 163, 85, 160, 1, + 63, 9, 92, 136, 28, 64, 32, 201, 85, + 75, 15, 9, 9, 64, 255, 184, 119, 16, + 86, 6, 28, 5, 64, 255, 25, 248, 1, + 56, 8, 17, 132, 137, 255, 55, 116, 128, + 58, 15, 20, 82, 135, 57, 26, 121, 40, + 164, 50, 31, 137, 154, 133, 25, 35, 218, + 51, 103, 44, 131, 131, 123, 31, 6, 158, + 86, 40, 64, 135, 148, 224, 45, 183, 128, + 22, 26, 17, 131, 240, 154, 14, 1, 209, + 45, 16, 21, 91, 64, 222, 7, 1, 197, + 56, 21, 39, 155, 60, 138, 23, 102, 213, + 83, 12, 13, 54, 192, 255, 68, 47, 28, + 85, 26, 85, 85, 128, 128, 32, 146, 171, + 18, 11, 7, 63, 144, 171, 4, 4, 246, + 35, 27, 10, 146, 174, 171, 12, 26, 128, + 190, 80, 35, 99, 180, 80, 126, 54, 45, + 85, 126, 47, 87, 176, 51, 41, 20, 32, + 101, 75, 128, 139, 118, 146, 116, 128, 85, + 56, 41, 15, 176, 236, 85, 37, 9, 62, + 71, 30, 17, 119, 118, 255, 17, 18, 138, + 101, 38, 60, 138, 55, 70, 43, 26, 142, + 146, 36, 19, 30, 171, 255, 97, 27, 20, + 138, 45, 61, 62, 219, 1, 81, 188, 64, + 32, 41, 20, 117, 151, 142, 20, 21, 163, + 112, 19, 12, 61, 195, 128, 48, 4, 24 + ]; + /// + /// The linear-light value of each gamma-encoded byte, from 0 to . The static constructor sets entry v to + /// ((v / 255)^Gamma) * GammaScale, rounded. The chroma downsampling of the encoder uses it. + /// public static readonly ushort[] GammaToLinearTab = new ushort[256]; + /// + /// The gamma-encoded value, from 0 to 255, of each linear-light value v * , for v from 0 to + /// . The chroma downsampling of the encoder interpolates between the entries. + /// public static readonly int[] LinearToGammaTab = new int[WebpConstants.GammaTabSize + 1]; + /// + /// The cost of each 4x4 luma intra mode in 1/256 bits, for each pair of top and left modes. The index is [top, left]. The costs come from the + /// fixed key frame probabilities of RFC 6386, section 11.5: https://www.rfc-editor.org/rfc/rfc6386#section-11.5. + /// public static readonly short[,][] Vp8FixedCostsI4 = new short[10, 10][]; - // Compute susceptibility based on DCT-coeff histograms: - // the higher, the "easier" the macroblock is to compress. - public static readonly int[] Vp8DspScan = + /// + /// Gets the offset of each 4x4 block in a work buffer with a stride of : the 16 luma blocks, then the 4 U + /// blocks and the 4 V blocks. The analysis reads the blocks in this order to collect the histograms of the DCT coefficients. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// + public static ReadOnlySpan Vp8DspScan => [ // Luma @@ -31,7 +161,13 @@ internal static class WebpLookupTables 8 + (0 * WebpConstants.Bps), 12 + (0 * WebpConstants.Bps), 8 + (4 * WebpConstants.Bps), 12 + (4 * WebpConstants.Bps) // V ]; - public static readonly short[] Vp8Scan = + /// + /// Gets the offset of each of the 16 luma 4x4 blocks in a work buffer with a stride of , in raster order. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// + public static ReadOnlySpan Vp8Scan => [ // Luma @@ -41,27 +177,57 @@ internal static class WebpLookupTables 0 + (12 * WebpConstants.Bps), 4 + (12 * WebpConstants.Bps), 8 + (12 * WebpConstants.Bps), 12 + (12 * WebpConstants.Bps) ]; - public static readonly short[] Vp8ScanUv = + /// + /// Gets the offset of each of the 4 U and 4 V 4x4 blocks in a work buffer with a stride of . + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// + public static ReadOnlySpan Vp8ScanUv => [ 0 + (0 * WebpConstants.Bps), 4 + (0 * WebpConstants.Bps), 0 + (4 * WebpConstants.Bps), 4 + (4 * WebpConstants.Bps), // U 8 + (0 * WebpConstants.Bps), 12 + (0 * WebpConstants.Bps), 8 + (4 * WebpConstants.Bps), 12 + (4 * WebpConstants.Bps) // V ]; + /// + /// Gets the absolute value of . + /// + /// The value, from -255 to 255. + /// The absolute value. [MethodImpl(InliningOptions.ShortMethod)] public static byte Abs0(int x) => Abs0Table[x + 255]; + /// + /// Clamps to the signed byte range [-128, 127]. + /// + /// The value, from -1020 to 1020. + /// The clamped value. [MethodImpl(InliningOptions.ShortMethod)] public static sbyte Sclip1(int x) => Sclip1Table[x + 1020]; + /// + /// Clamps to the range [-16, 15]. + /// + /// The value, from -112 to 112. + /// The clamped value. [MethodImpl(InliningOptions.ShortMethod)] public static sbyte Sclip2(int x) => Sclip2Table[x + 112]; + /// + /// Clamps to the byte range [0, 255]. + /// + /// The value, from -255 to 510. + /// The clamped value. [MethodImpl(InliningOptions.ShortMethod)] public static byte Clip1(int x) => Clip1Table[x + 255]; - // fixed costs for coding levels, deduce from the coding tree. - // This is only the part that doesn't depend on the probability state. - public static readonly short[] Vp8LevelFixedCosts = + /// + /// Gets the fixed cost of coding each level, from the coding tree. It is the part of the cost that does not depend on the probability state. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// + public static ReadOnlySpan Vp8LevelFixedCosts => [ 0, 256, 256, 256, 256, 432, 618, 630, 731, 640, 640, 828, 901, 948, 1021, 1101, 1174, 1221, 1294, 1042, 1085, 1115, 1158, 1202, 1245, 1275, 1318, 1337, 1380, 1410, 1453, 1497, 1540, 1570, 1613, 1280, 1295, @@ -186,8 +352,10 @@ internal static class WebpLookupTables 7729, 7735, 7744, 7750, 7761 ]; - // This table gives, for a given sharpness, the filtering strength to be - // used (at least) in order to filter a given edge step delta. + /// + /// The smallest loop filter level that smooths an edge step, for each sharpness from 0 to 7 and each step below + /// . The index is [sharpness, step]. The encoder uses it to select the filter level. + /// public static readonly byte[,] LevelsFromDelta = { { @@ -240,7 +408,13 @@ internal static class WebpLookupTables } }; - // This uses C#'s compiler optimization to refer to assembly's static data directly. + /// + /// Gets the number of bits that the VP8 bool encoder shifts out to renormalize the range. The index is the range minus 1. See RFC 6386, + /// section 7.2: https://www.rfc-editor.org/rfc/rfc6386#section-7.2. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// public static ReadOnlySpan Norm => [ @@ -256,7 +430,13 @@ internal static class WebpLookupTables 0 ]; - // This uses C#'s compiler optimization to refer to assembly's static data directly. + /// + /// Gets the range minus 1 after the renormalization shift of the VP8 bool encoder. The index is the range minus 1 before the shift. See RFC 6386, + /// section 7.2: https://www.rfc-editor.org/rfc/rfc6386#section-7.2. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// public static ReadOnlySpan NewRange => [ @@ -272,7 +452,13 @@ internal static class WebpLookupTables 241, 243, 245, 247, 249, 251, 253, 127 ]; - public static readonly ushort[] Vp8EntropyCost = + /// + /// Gets the cost of coding a zero bit with each probability from 0 to 255, in 1/256 bits. A one bit with probability p costs the value at 255 - p. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// + public static ReadOnlySpan Vp8EntropyCost => [ 1792, 1792, 1792, 1536, 1536, 1408, 1366, 1280, 1280, 1216, 1178, 1152, 1110, 1076, 1061, 1024, 1024, 992, 968, 951, @@ -302,6 +488,11 @@ internal static class WebpLookupTables 10, 9, 7, 6, 4, 3 ]; + /// + /// The DCT token tree path of each coefficient level from 1 to . Entry level - 1 holds a pattern and + /// the bits. Bit k of the pattern is set when the path uses the tree probability k + 2. Bit k of the bits is the bit at that node. + /// See RFC 6386, section 13.2: https://www.rfc-editor.org/rfc/rfc6386#section-13.2. + /// public static readonly ushort[][] Vp8LevelCodes = [ [0x001, 0x000], [0x007, 0x001], [0x00f, 0x005], @@ -324,9 +515,12 @@ internal static class WebpLookupTables ]; /// - /// Lookup table for small values of log2(int). + /// Gets log2(v) for the small values of v. /// - public static readonly float[] Log2Table = + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// + public static ReadOnlySpan Log2Table => [ 0.0000000000000000f, 0.0000000000000000f, 1.0000000000000000f, 1.5849625007211560f, @@ -458,7 +652,13 @@ internal static class WebpLookupTables 7.9886846867721654f, 7.9943534368588577f ]; - public static readonly float[] SLog2Table = + /// + /// Gets v * log2(v) for the small values of v. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// + public static ReadOnlySpan SLog2Table => [ 0.00000000f, 0.00000000f, 2.00000000f, 4.75488750f, 8.00000000f, 11.60964047f, 15.50977500f, 19.65148445f, @@ -526,7 +726,15 @@ internal static class WebpLookupTables 2010.27454072f, 2019.69737440f, 2029.12591044f, 2038.56012640f ]; - public static readonly uint[] PlaneToCodeLut = + /// + /// Gets the plane code minus one of each small two-dimensional distance. The index is yOffset * 16 + 8 - xOffset. See the WebP Lossless + /// Bitstream Specification, section 5.2.2 "LZ77 Backward Reference": + /// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// + public static ReadOnlySpan PlaneToCodeLut => [ 96, 73, 55, 39, 23, 13, 5, 1, 255, 255, 255, 255, 255, 255, 255, 255, 101, 78, 58, 42, 26, 16, 8, 2, 0, 3, 9, 17, 27, 43, 59, 79, @@ -538,7 +746,12 @@ internal static class WebpLookupTables 119, 116, 111, 106, 97, 88, 84, 74, 72, 75, 85, 89, 98, 107, 112, 117 ]; - // 31 ^ clz(i) + /// + /// Gets the integer part of log2(i) for each byte value i. Entry 0 is 0. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// public static ReadOnlySpan LogTable8Bit => [ 0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, @@ -559,8 +772,12 @@ internal static class WebpLookupTables 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 ]; - // Paragraph 14.1 - // This uses C#'s compiler optimization to refer to assembly's static data directly. + /// + /// Gets the DC quantizer step of each quantizer index. See RFC 6386, section 14.1: https://www.rfc-editor.org/rfc/rfc6386#section-14.1. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// public static ReadOnlySpan DcTable => [ 4, 5, 6, 7, 8, 9, 10, 10, @@ -581,8 +798,13 @@ internal static class WebpLookupTables 138, 140, 143, 145, 148, 151, 154, 157 ]; - // Paragraph 14.1 - public static readonly ushort[] AcTable = + /// + /// Gets the AC quantizer step of each quantizer index. See RFC 6386, section 14.1. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// + public static ReadOnlySpan AcTable => [ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, @@ -602,7 +824,13 @@ internal static class WebpLookupTables 249, 254, 259, 264, 269, 274, 279, 284 ]; - public static readonly ushort[] AcTable2 = + /// + /// Gets the AC quantizer step of the Y2 block for each quantizer index. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// + public static ReadOnlySpan AcTable2 => [ 8, 8, 9, 10, 12, 13, 15, 17, 18, 20, 21, 23, 24, 26, 27, 29, @@ -622,7 +850,10 @@ internal static class WebpLookupTables 385, 393, 401, 409, 416, 424, 432, 440 ]; - // Paragraph 13 + /// + /// The probability that the frame header updates each DCT token probability. The index is [block type, band, context, tree node]. + /// See RFC 6386, section 13.4: https://www.rfc-editor.org/rfc/rfc6386#section-13.4. + /// public static readonly byte[,,,] CoeffsUpdateProba = { { @@ -795,7 +1026,10 @@ internal static class WebpLookupTables } }; - // Paragraph 13.5: Default Token Probability Table. + /// + /// The default DCT token probabilities. The index is [block type, band, context, tree node]. + /// See RFC 6386, section 13.5: https://www.rfc-editor.org/rfc/rfc6386#section-13.5. + /// public static readonly byte[,,,] DefaultCoeffsProba = { { @@ -968,6 +1202,10 @@ internal static class WebpLookupTables } }; + /// + /// The prefix code and the number of extra bits of each LZ77 distance or length value below 512. The index is the value. Entry 0 is not used. + /// See the WebP Lossless Bitstream Specification, section 5.2.2: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// public static readonly (int Code, int ExtraBits)[] PrefixEncodeCode = [ (0, 0), (0, 0), (1, 0), (2, 0), (3, 0), (4, 1), (4, 1), (5, 1), @@ -1036,7 +1274,13 @@ public static readonly (int Code, int ExtraBits)[] PrefixEncodeCode = (17, 7), (17, 7), (17, 7), (17, 7), (17, 7), (17, 7), (17, 7), (17, 7) ]; - // This uses C#'s compiler optimization to refer to assembly's static data directly. + /// + /// Gets the value of the extra bits of each LZ77 distance or length value below 512. The index is the value. Entry 0 is not used. + /// See the WebP Lossless Bitstream Specification, section 5.2.2: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// public static ReadOnlySpan PrefixEncodeExtraBitsValue => [ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 2, 3, @@ -1074,14 +1318,23 @@ public static readonly (int Code, int ExtraBits)[] PrefixEncodeCode = 118, 119, 120, 121, 122, 123, 124, 125, 126 ]; - // Following table is (1 << AlphaFix) / a. The (v * InvAlpha[a]) >> AlphaFix - // formula is then equal to v / a in most (99.6%) cases. Note that this table - // and constant are adjusted very tightly to fit 32b arithmetic. - // In particular, they use the fact that the operands for 'v / a' are actually - // derived as v = (a0.p0 + a1.p1 + a2.p2 + a3.p3) and a = a0 + a1 + a2 + a3 - // with ai in [0..255] and pi in [0..1< + /// Gets the inverse of each alpha sum, for the division of the gamma-corrected chroma sums. + /// + /// + /// + /// Entry a is (1 << AlphaFix) / a. Thus (v * InvAlpha[a]) >> AlphaFix is equal to v / a in 99.6% of the cases. + /// + /// + /// The table and the constant fit 32-bit arithmetic only because of the range of the operands. The value is v = a0 * p0 + a1 * p1 + a2 * p2 + a3 * p3, + /// and the sum is a = a0 + a1 + a2 + a3, with each ai in [0, 255] and each pi in [0, 1 << GammaFix). The products do not overflow when + /// GammaFix + AlphaFix is 31 or less. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// + /// + public static ReadOnlySpan InvAlpha => [ 0, /* alpha = 0 */ 524288, 262144, 174762, 131072, 104857, 87381, 74898, 65536, @@ -1214,6 +1467,9 @@ public static readonly (int Code, int ExtraBits)[] PrefixEncodeCode = 515, 515, 514, 514 ]; + /// + /// Initializes static members of the class. It computes the gamma tables and sets the 4x4 mode costs. + /// static WebpLookupTables() { double scale = (double)(1 << WebpConstants.GammaTabFix) / WebpConstants.GammaScale; @@ -1228,11 +1484,15 @@ static WebpLookupTables() LinearToGammaTab[v] = (int)((255.0d * Math.Pow(scale * v, 1.0d / WebpConstants.Gamma)) + .5); } - InitializeModesProbabilities(); InitializeFixedCostsI4(); } - // This uses C#'s compiler optimization to refer to assembly's static data directly. + /// + /// Gets the absolute value of each value from -255 to 255. The index is the value plus 255. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// private static ReadOnlySpan Abs0Table => [ 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, @@ -1268,7 +1528,12 @@ static WebpLookupTables() 0xff ]; - // This uses C#'s compiler optimization to refer to assembly's static data directly. + /// + /// Gets each value from -255 to 510, clamped to [0, 255]. The index is the value plus 255. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// private static ReadOnlySpan Clip1Table => [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -1319,7 +1584,12 @@ static WebpLookupTables() 0xff ]; - // This uses C#'s compiler optimization to refer to assembly's static data directly. + /// + /// Gets each value from -1020 to 1020, clamped to [-128, 127]. The index is the value plus 1020. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// private static ReadOnlySpan Sclip1Table => [ -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, @@ -1431,7 +1701,12 @@ static WebpLookupTables() 127, 127, 127, 127, 127, 127, 127, 127, 127 ]; - // This uses C#'s compiler optimization to refer to assembly's static data directly. + /// + /// Gets each value from -112 to 112, clamped to [-16, 15]. The index is the value plus 112. + /// + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// private static ReadOnlySpan Sclip2Table => [ -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, @@ -1446,111 +1721,9 @@ static WebpLookupTables() 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 ]; - private static void InitializeModesProbabilities() - { - // Paragraph 11.5 - ModesProba[0, 0] = [231, 120, 48, 89, 115, 113, 120, 152, 112]; - ModesProba[0, 1] = [152, 179, 64, 126, 170, 118, 46, 70, 95]; - ModesProba[0, 2] = [175, 69, 143, 80, 85, 82, 72, 155, 103]; - ModesProba[0, 3] = [56, 58, 10, 171, 218, 189, 17, 13, 152]; - ModesProba[0, 4] = [114, 26, 17, 163, 44, 195, 21, 10, 173]; - ModesProba[0, 5] = [121, 24, 80, 195, 26, 62, 44, 64, 85]; - ModesProba[0, 6] = [144, 71, 10, 38, 171, 213, 144, 34, 26]; - ModesProba[0, 7] = [170, 46, 55, 19, 136, 160, 33, 206, 71]; - ModesProba[0, 8] = [63, 20, 8, 114, 114, 208, 12, 9, 226]; - ModesProba[0, 9] = [81, 40, 11, 96, 182, 84, 29, 16, 36]; - ModesProba[1, 0] = [134, 183, 89, 137, 98, 101, 106, 165, 148]; - ModesProba[1, 1] = [72, 187, 100, 130, 157, 111, 32, 75, 80]; - ModesProba[1, 2] = [66, 102, 167, 99, 74, 62, 40, 234, 128]; - ModesProba[1, 3] = [41, 53, 9, 178, 241, 141, 26, 8, 107]; - ModesProba[1, 4] = [74, 43, 26, 146, 73, 166, 49, 23, 157]; - ModesProba[1, 5] = [65, 38, 105, 160, 51, 52, 31, 115, 128]; - ModesProba[1, 6] = [104, 79, 12, 27, 217, 255, 87, 17, 7]; - ModesProba[1, 7] = [87, 68, 71, 44, 114, 51, 15, 186, 23]; - ModesProba[1, 8] = [47, 41, 14, 110, 182, 183, 21, 17, 194]; - ModesProba[1, 9] = [66, 45, 25, 102, 197, 189, 23, 18, 22]; - ModesProba[2, 0] = [88, 88, 147, 150, 42, 46, 45, 196, 205]; - ModesProba[2, 1] = [43, 97, 183, 117, 85, 38, 35, 179, 61]; - ModesProba[2, 2] = [39, 53, 200, 87, 26, 21, 43, 232, 171]; - ModesProba[2, 3] = [56, 34, 51, 104, 114, 102, 29, 93, 77]; - ModesProba[2, 4] = [39, 28, 85, 171, 58, 165, 90, 98, 64]; - ModesProba[2, 5] = [34, 22, 116, 206, 23, 34, 43, 166, 73]; - ModesProba[2, 6] = [107, 54, 32, 26, 51, 1, 81, 43, 31]; - ModesProba[2, 7] = [68, 25, 106, 22, 64, 171, 36, 225, 114]; - ModesProba[2, 8] = [34, 19, 21, 102, 132, 188, 16, 76, 124]; - ModesProba[2, 9] = [62, 18, 78, 95, 85, 57, 50, 48, 51]; - ModesProba[3, 0] = [193, 101, 35, 159, 215, 111, 89, 46, 111]; - ModesProba[3, 1] = [60, 148, 31, 172, 219, 228, 21, 18, 111]; - ModesProba[3, 2] = [112, 113, 77, 85, 179, 255, 38, 120, 114]; - ModesProba[3, 3] = [40, 42, 1, 196, 245, 209, 10, 25, 109]; - ModesProba[3, 4] = [88, 43, 29, 140, 166, 213, 37, 43, 154]; - ModesProba[3, 5] = [61, 63, 30, 155, 67, 45, 68, 1, 209]; - ModesProba[3, 6] = [100, 80, 8, 43, 154, 1, 51, 26, 71]; - ModesProba[3, 7] = [142, 78, 78, 16, 255, 128, 34, 197, 171]; - ModesProba[3, 8] = [41, 40, 5, 102, 211, 183, 4, 1, 221]; - ModesProba[3, 9] = [51, 50, 17, 168, 209, 192, 23, 25, 82]; - ModesProba[4, 0] = [138, 31, 36, 171, 27, 166, 38, 44, 229]; - ModesProba[4, 1] = [67, 87, 58, 169, 82, 115, 26, 59, 179]; - ModesProba[4, 2] = [63, 59, 90, 180, 59, 166, 93, 73, 154]; - ModesProba[4, 3] = [40, 40, 21, 116, 143, 209, 34, 39, 175]; - ModesProba[4, 4] = [47, 15, 16, 183, 34, 223, 49, 45, 183]; - ModesProba[4, 5] = [46, 17, 33, 183, 6, 98, 15, 32, 183]; - ModesProba[4, 6] = [57, 46, 22, 24, 128, 1, 54, 17, 37]; - ModesProba[4, 7] = [65, 32, 73, 115, 28, 128, 23, 128, 205]; - ModesProba[4, 8] = [40, 3, 9, 115, 51, 192, 18, 6, 223]; - ModesProba[4, 9] = [87, 37, 9, 115, 59, 77, 64, 21, 47]; - ModesProba[5, 0] = [104, 55, 44, 218, 9, 54, 53, 130, 226]; - ModesProba[5, 1] = [64, 90, 70, 205, 40, 41, 23, 26, 57]; - ModesProba[5, 2] = [54, 57, 112, 184, 5, 41, 38, 166, 213]; - ModesProba[5, 3] = [30, 34, 26, 133, 152, 116, 10, 32, 134]; - ModesProba[5, 4] = [39, 19, 53, 221, 26, 114, 32, 73, 255]; - ModesProba[5, 5] = [31, 9, 65, 234, 2, 15, 1, 118, 73]; - ModesProba[5, 6] = [75, 32, 12, 51, 192, 255, 160, 43, 51]; - ModesProba[5, 7] = [88, 31, 35, 67, 102, 85, 55, 186, 85]; - ModesProba[5, 8] = [56, 21, 23, 111, 59, 205, 45, 37, 192]; - ModesProba[5, 9] = [55, 38, 70, 124, 73, 102, 1, 34, 98]; - ModesProba[6, 0] = [125, 98, 42, 88, 104, 85, 117, 175, 82]; - ModesProba[6, 1] = [95, 84, 53, 89, 128, 100, 113, 101, 45]; - ModesProba[6, 2] = [75, 79, 123, 47, 51, 128, 81, 171, 1]; - ModesProba[6, 3] = [57, 17, 5, 71, 102, 57, 53, 41, 49]; - ModesProba[6, 4] = [38, 33, 13, 121, 57, 73, 26, 1, 85]; - ModesProba[6, 5] = [41, 10, 67, 138, 77, 110, 90, 47, 114]; - ModesProba[6, 6] = [115, 21, 2, 10, 102, 255, 166, 23, 6]; - ModesProba[6, 7] = [101, 29, 16, 10, 85, 128, 101, 196, 26]; - ModesProba[6, 8] = [57, 18, 10, 102, 102, 213, 34, 20, 43]; - ModesProba[6, 9] = [117, 20, 15, 36, 163, 128, 68, 1, 26]; - ModesProba[7, 0] = [102, 61, 71, 37, 34, 53, 31, 243, 192]; - ModesProba[7, 1] = [69, 60, 71, 38, 73, 119, 28, 222, 37]; - ModesProba[7, 2] = [68, 45, 128, 34, 1, 47, 11, 245, 171]; - ModesProba[7, 3] = [62, 17, 19, 70, 146, 85, 55, 62, 70]; - ModesProba[7, 4] = [37, 43, 37, 154, 100, 163, 85, 160, 1]; - ModesProba[7, 5] = [63, 9, 92, 136, 28, 64, 32, 201, 85]; - ModesProba[7, 6] = [75, 15, 9, 9, 64, 255, 184, 119, 16]; - ModesProba[7, 7] = [86, 6, 28, 5, 64, 255, 25, 248, 1]; - ModesProba[7, 8] = [56, 8, 17, 132, 137, 255, 55, 116, 128]; - ModesProba[7, 9] = [58, 15, 20, 82, 135, 57, 26, 121, 40]; - ModesProba[8, 0] = [164, 50, 31, 137, 154, 133, 25, 35, 218]; - ModesProba[8, 1] = [51, 103, 44, 131, 131, 123, 31, 6, 158]; - ModesProba[8, 2] = [86, 40, 64, 135, 148, 224, 45, 183, 128]; - ModesProba[8, 3] = [22, 26, 17, 131, 240, 154, 14, 1, 209]; - ModesProba[8, 4] = [45, 16, 21, 91, 64, 222, 7, 1, 197]; - ModesProba[8, 5] = [56, 21, 39, 155, 60, 138, 23, 102, 213]; - ModesProba[8, 6] = [83, 12, 13, 54, 192, 255, 68, 47, 28]; - ModesProba[8, 7] = [85, 26, 85, 85, 128, 128, 32, 146, 171]; - ModesProba[8, 8] = [18, 11, 7, 63, 144, 171, 4, 4, 246]; - ModesProba[8, 9] = [35, 27, 10, 146, 174, 171, 12, 26, 128]; - ModesProba[9, 0] = [190, 80, 35, 99, 180, 80, 126, 54, 45]; - ModesProba[9, 1] = [85, 126, 47, 87, 176, 51, 41, 20, 32]; - ModesProba[9, 2] = [101, 75, 128, 139, 118, 146, 116, 128, 85]; - ModesProba[9, 3] = [56, 41, 15, 176, 236, 85, 37, 9, 62]; - ModesProba[9, 4] = [71, 30, 17, 119, 118, 255, 17, 18, 138]; - ModesProba[9, 5] = [101, 38, 60, 138, 55, 70, 43, 26, 142]; - ModesProba[9, 6] = [146, 36, 19, 30, 171, 255, 97, 27, 20]; - ModesProba[9, 7] = [138, 45, 61, 62, 219, 1, 81, 188, 64]; - ModesProba[9, 8] = [32, 41, 20, 117, 151, 142, 20, 21, 163]; - ModesProba[9, 9] = [112, 19, 12, 61, 195, 128, 48, 4, 24]; - } - + /// + /// Sets the cost arrays of . + /// private static void InitializeFixedCostsI4() { Vp8FixedCostsI4[0, 0] = [40, 1151, 1723, 1874, 2103, 2019, 1628, 1777, 2226, 2137]; diff --git a/src/ImageSharp/PixelFormats/PixelBlenders/PorterDuffFunctions.cs b/src/ImageSharp/PixelFormats/PixelBlenders/PorterDuffFunctions.cs index da2d56066d..6665c82bd6 100644 --- a/src/ImageSharp/PixelFormats/PixelBlenders/PorterDuffFunctions.cs +++ b/src/ImageSharp/PixelFormats/PixelBlenders/PorterDuffFunctions.cs @@ -22,7 +22,15 @@ namespace SixLabors.ImageSharp.PixelFormats.PixelBlenders; /// internal static partial class PorterDuffFunctions { + /// + /// The control that takes lanes 3 and 7 (the W lanes) from the second operand. + /// All other lanes come from the first operand. + /// private const int BlendAlphaControl = 0b_10_00_10_00; + + /// + /// The shuffle control that copies element 3 (W) of each four-lane group into all four lanes of that group. + /// private const int ShuffleAlphaControl = 0b_11_11_11_11; /// @@ -808,8 +816,12 @@ public static Vector4 Over(Vector4 destination, Vector4 source, Vector4 blend) // calculate final alpha Vector4 alpha = dstW + sW; - // calculate final color - Vector4 color = (destination * dstW) + (source * srcW) + (blend * blendW); + // calculate final color. Use the same fused operations as the wider paths, so a result at an exact midpoint + // rounds the same way at every vector width. + Vector128 color128 = (destination * dstW).AsVector128(); + color128 = Vector128.MultiplyAddEstimate(source.AsVector128(), srcW.AsVector128(), color128); + color128 = Vector128.MultiplyAddEstimate(blend.AsVector128(), blendW.AsVector128(), color128); + Vector4 color = color128.AsVector4(); // unpremultiply color = Numerics.UnPremultiply(color.AsVector128(), alpha.AsVector128()).AsVector4(); @@ -896,8 +908,9 @@ public static Vector4 Atop(Vector4 destination, Vector4 source, Vector4 blend) // calculate final alpha Vector4 alpha = dW; - // calculate final color - Vector4 color = (destination * dstW) + (blend * blendW); + // calculate final color. Use the same fused operation as the wider paths, so a result at an exact midpoint + // rounds the same way at every vector width. + Vector4 color = Vector128.MultiplyAddEstimate(destination.AsVector128(), dstW.AsVector128(), (blend * blendW).AsVector128()).AsVector4(); // unpremultiply color = Numerics.UnPremultiply(color.AsVector128(), alpha.AsVector128()).AsVector4(); @@ -1081,8 +1094,9 @@ public static Vector4 Xor(Vector4 destination, Vector4 source) Vector4 srcW = Vector4.One - dW; Vector4 dstW = Vector4.One - sW; - Vector4 alpha = (sW * srcW) + (dW * dstW); - Vector4 color = (sW * source * srcW) + (dW * destination * dstW); + // Use the same fused operations as the wider paths, so a result at an exact midpoint rounds the same way at every vector width. + Vector4 alpha = Vector128.MultiplyAddEstimate(sW.AsVector128(), srcW.AsVector128(), (dW * dstW).AsVector128()).AsVector4(); + Vector4 color = Vector128.MultiplyAddEstimate((sW * source).AsVector128(), srcW.AsVector128(), (dW * destination * dstW).AsVector128()).AsVector4(); // unpremultiply color = Numerics.UnPremultiply(color.AsVector128(), alpha.AsVector128()).AsVector4(); @@ -1190,15 +1204,37 @@ public static Vector512 Plus(Vector512 destination, Vector512 + /// Returns the result of the "Clear" compositing equation. The result is transparent black. + /// + /// The backdrop vector. The result does not use it. + /// The source vector. The result does not use it. + /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector4 Clear(Vector4 backdrop, Vector4 source) => Vector4.Zero; + /// + /// Returns the result of the "Clear" compositing equation for two packed vectors. The result is transparent black. + /// + /// The backdrop vectors. The result does not use them. + /// The source vectors. The result does not use them. + /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector256 Clear(Vector256 backdrop, Vector256 source) => Vector256.Zero; + /// + /// Returns the result of the "Clear" compositing equation for four packed vectors. The result is transparent black. + /// + /// The backdrop vectors. The result does not use them. + /// The source vectors. The result does not use them. + /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector512 Clear(Vector512 backdrop, Vector512 source) => Vector512.Zero; + /// + /// Creates a SIMD lane mask selecting the alpha component of each packed vector. + /// + /// The alpha-component mask. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector512 AlphaMask512() => Vector512.Create(0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1).AsSingle(); diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/Abgr32.cs b/src/ImageSharp/PixelFormats/PixelImplementations/Abgr32.cs index 20c3e1ba03..ec8ad24dd7 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/Abgr32.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/Abgr32.cs @@ -5,6 +5,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Common.Helpers; namespace SixLabors.ImageSharp.PixelFormats; @@ -47,11 +48,6 @@ public partial struct Abgr32 : IPixel, IPackedVector /// private static readonly Vector4 MaxBytes = Vector128.Create(255f).AsVector4(); - /// - /// The half vector value. - /// - private static readonly Vector4 Half = Vector128.Create(.5f).AsVector4(); - /// /// Initializes a new instance of the struct. /// @@ -351,6 +347,7 @@ public static Abgr32 FromRgba64(Rgba64 source) /// The y-component /// The z-component /// The w-component + /// The color. The x, y, z and w values map to red, green, blue and alpha in the range 0 to 1. Values outside the range are clamped. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Abgr32 Pack(float x, float y, float z, float w) => Pack(new Vector4(x, y, z, w)); @@ -358,6 +355,7 @@ public static Abgr32 FromRgba64(Rgba64 source) /// Packs a into a uint. /// /// The vector containing the values to pack. + /// The color. X, Y and Z map to red, green and blue in the range 0 to 1. Values outside the range are clamped. Alpha is 255. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Abgr32 Pack(Vector3 vector) => Pack(new Vector4(vector, 1)); @@ -365,14 +363,15 @@ public static Abgr32 FromRgba64(Rgba64 source) /// Packs a into a color. /// /// The vector containing the values to pack. + /// The color. X, Y, Z and W map to red, green, blue and alpha in the range 0 to 1. Values outside the range are clamped. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Abgr32 Pack(Vector4 vector) { vector *= MaxBytes; - vector += Half; vector = ColorNumerics.ClampToFinite(vector, Vector4.Zero, MaxBytes); - Vector128 result = Vector128.ConvertToInt32(vector.AsVector128()).AsByte(); + // Round to the nearest integer, with ties to even, as the bulk byte packer does. + Vector128 result = Vector128_.ConvertToInt32RoundToEven(vector.AsVector128()).AsByte(); return new Abgr32(result.GetElement(0), result.GetElement(4), result.GetElement(8), result.GetElement(12)); } } diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/Abgr32P.cs b/src/ImageSharp/PixelFormats/PixelImplementations/Abgr32P.cs index 24827161ec..56b4bf7684 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/Abgr32P.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/Abgr32P.cs @@ -4,7 +4,6 @@ using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Runtime.Intrinsics; namespace SixLabors.ImageSharp.PixelFormats; @@ -18,9 +17,6 @@ namespace SixLabors.ImageSharp.PixelFormats; [StructLayout(LayoutKind.Sequential)] public partial struct Abgr32P : IPixel, IPackedVector { - private static readonly Vector4 Half = new(0.5F); - private static readonly Vector4 MaxBytes = new(byte.MaxValue); - /// /// Gets or sets the alpha component. /// @@ -290,16 +286,4 @@ public static Abgr32P FromAssociatedScaledVector4(Vector4 source) /// public override readonly string ToString() => $"Abgr32P({this.R}, {this.G}, {this.B}, {this.A})"; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static Abgr32P Pack(Vector4 vector) - { - vector *= MaxBytes; - vector += Half; - vector = ColorNumerics.ClampToFinite(vector, Vector4.Zero, MaxBytes); - - // Each converted component occupies one 32-bit lane. Reinterpreting those lanes as bytes exposes their low bytes at offsets 0, 4, 8, and 12. - Vector128 result = Vector128.ConvertToInt32(vector.AsVector128()).AsByte(); - return new Abgr32P(result.GetElement(0), result.GetElement(4), result.GetElement(8), result.GetElement(12)); - } } diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/Argb32.cs b/src/ImageSharp/PixelFormats/PixelImplementations/Argb32.cs index 5f7d4b1ce2..b85ff07252 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/Argb32.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/Argb32.cs @@ -5,6 +5,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Common.Helpers; namespace SixLabors.ImageSharp.PixelFormats; @@ -42,8 +43,10 @@ public partial struct Argb32 : IPixel, IPackedVector /// public byte B; + /// + /// The maximum byte value. + /// private static readonly Vector4 MaxBytes = Vector128.Create(255f).AsVector4(); - private static readonly Vector4 Half = Vector128.Create(.5f).AsVector4(); /// /// Initializes a new instance of the struct. @@ -341,14 +344,15 @@ public static Argb32 FromRgba64(Rgba64 source) /// Packs a into a color. /// /// The vector containing the values to pack. + /// The color. X, Y, Z and W map to red, green, blue and alpha in the range 0 to 1. Values outside the range are clamped. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Argb32 Pack(Vector4 vector) { vector *= MaxBytes; - vector += Half; vector = ColorNumerics.ClampToFinite(vector, Vector4.Zero, MaxBytes); - Vector128 result = Vector128.ConvertToInt32(vector.AsVector128()).AsByte(); + // Round to the nearest integer, with ties to even, as the bulk byte packer does. + Vector128 result = Vector128_.ConvertToInt32RoundToEven(vector.AsVector128()).AsByte(); return new Argb32(result.GetElement(0), result.GetElement(4), result.GetElement(8), result.GetElement(12)); } } diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/Argb32P.cs b/src/ImageSharp/PixelFormats/PixelImplementations/Argb32P.cs index b93287dcef..75519de986 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/Argb32P.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/Argb32P.cs @@ -4,7 +4,6 @@ using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Runtime.Intrinsics; namespace SixLabors.ImageSharp.PixelFormats; @@ -18,9 +17,6 @@ namespace SixLabors.ImageSharp.PixelFormats; [StructLayout(LayoutKind.Sequential)] public partial struct Argb32P : IPixel, IPackedVector { - private static readonly Vector4 Half = new(0.5F); - private static readonly Vector4 MaxBytes = new(byte.MaxValue); - /// /// Gets or sets the alpha component. /// @@ -290,16 +286,4 @@ public static Argb32P FromAssociatedScaledVector4(Vector4 source) /// public override readonly string ToString() => $"Argb32P({this.R}, {this.G}, {this.B}, {this.A})"; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static Argb32P Pack(Vector4 vector) - { - vector *= MaxBytes; - vector += Half; - vector = ColorNumerics.ClampToFinite(vector, Vector4.Zero, MaxBytes); - - // Each converted component occupies one 32-bit lane. Reinterpreting those lanes as bytes exposes their low bytes at offsets 0, 4, 8, and 12. - Vector128 result = Vector128.ConvertToInt32(vector.AsVector128()).AsByte(); - return new Argb32P(result.GetElement(0), result.GetElement(4), result.GetElement(8), result.GetElement(12)); - } } diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/Bgr24.cs b/src/ImageSharp/PixelFormats/PixelImplementations/Bgr24.cs index c3386c4848..5b95cf5978 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/Bgr24.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/Bgr24.cs @@ -5,6 +5,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Common.Helpers; namespace SixLabors.ImageSharp.PixelFormats; @@ -36,8 +37,10 @@ public partial struct Bgr24 : IPixel [FieldOffset(2)] public byte R; + /// + /// The maximum byte value. + /// private static readonly Vector4 MaxBytes = Vector128.Create(255f).AsVector4(); - private static readonly Vector4 Half = Vector128.Create(.5f).AsVector4(); /// /// Initializes a new instance of the struct. @@ -155,10 +158,10 @@ public static Bgr24 FromAssociatedScaledVector4(Vector4 source) public static Bgr24 FromVector4(Vector4 source) { source *= MaxBytes; - source += Half; source = ColorNumerics.ClampToFinite(source, Vector4.Zero, MaxBytes); - Vector128 result = Vector128.ConvertToInt32(source.AsVector128()).AsByte(); + // Round to the nearest integer, with ties to even, as the bulk byte packer does. + Vector128 result = Vector128_.ConvertToInt32RoundToEven(source.AsVector128()).AsByte(); return new Bgr24(result.GetElement(0), result.GetElement(4), result.GetElement(8)); } diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/Bgra32.cs b/src/ImageSharp/PixelFormats/PixelImplementations/Bgra32.cs index 72d1183cc6..2bd681dd4b 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/Bgra32.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/Bgra32.cs @@ -5,6 +5,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Common.Helpers; namespace SixLabors.ImageSharp.PixelFormats; @@ -39,8 +40,10 @@ public partial struct Bgra32 : IPixel, IPackedVector /// public byte A; + /// + /// The maximum byte value. + /// private static readonly Vector4 MaxBytes = Vector128.Create(255f).AsVector4(); - private static readonly Vector4 Half = Vector128.Create(.5f).AsVector4(); /// /// Initializes a new instance of the struct. @@ -331,14 +334,15 @@ public static Bgra32 FromRgba64(Rgba64 source) /// Packs a into a color. /// /// The vector containing the values to pack. + /// The color. X, Y, Z and W map to red, green, blue and alpha in the range 0 to 1. Values outside the range are clamped. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Bgra32 Pack(Vector4 vector) { vector *= MaxBytes; - vector += Half; vector = ColorNumerics.ClampToFinite(vector, Vector4.Zero, MaxBytes); - Vector128 result = Vector128.ConvertToInt32(vector.AsVector128()).AsByte(); + // Round to the nearest integer, with ties to even, as the bulk byte packer does. + Vector128 result = Vector128_.ConvertToInt32RoundToEven(vector.AsVector128()).AsByte(); return new Bgra32(result.GetElement(0), result.GetElement(4), result.GetElement(8), result.GetElement(12)); } } diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/Bgra32P.cs b/src/ImageSharp/PixelFormats/PixelImplementations/Bgra32P.cs index 31e0d536b4..41d057b51b 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/Bgra32P.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/Bgra32P.cs @@ -4,7 +4,6 @@ using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Runtime.Intrinsics; namespace SixLabors.ImageSharp.PixelFormats; @@ -18,9 +17,6 @@ namespace SixLabors.ImageSharp.PixelFormats; [StructLayout(LayoutKind.Sequential)] public partial struct Bgra32P : IPixel, IPackedVector { - private static readonly Vector4 Half = new(0.5F); - private static readonly Vector4 MaxBytes = new(byte.MaxValue); - /// /// Gets or sets the associated blue component. /// @@ -290,16 +286,4 @@ public static Bgra32P FromAssociatedScaledVector4(Vector4 source) /// public override readonly string ToString() => $"Bgra32P({this.R}, {this.G}, {this.B}, {this.A})"; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static Bgra32P Pack(Vector4 vector) - { - vector *= MaxBytes; - vector += Half; - vector = ColorNumerics.ClampToFinite(vector, Vector4.Zero, MaxBytes); - - // Each converted component occupies one 32-bit lane. Reinterpreting those lanes as bytes exposes their low bytes at offsets 0, 4, 8, and 12. - Vector128 result = Vector128.ConvertToInt32(vector.AsVector128()).AsByte(); - return new Bgra32P(result.GetElement(0), result.GetElement(4), result.GetElement(8), result.GetElement(12)); - } } diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/L8.cs b/src/ImageSharp/PixelFormats/PixelImplementations/L8.cs index 4ac7fa101f..cfb5401021 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/L8.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/L8.cs @@ -4,6 +4,7 @@ using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Common.Helpers; namespace SixLabors.ImageSharp.PixelFormats; @@ -15,8 +16,10 @@ namespace SixLabors.ImageSharp.PixelFormats; /// public partial struct L8 : IPixel, IPackedVector { + /// + /// The maximum byte value. + /// private static readonly Vector4 MaxBytes = Vector128.Create(255f).AsVector4(); - private static readonly Vector4 Half = Vector128.Create(.5f).AsVector4(); /// /// Initializes a new instance of the struct. @@ -204,14 +207,20 @@ public static L8 FromAssociatedScaledVector4(Vector4 source) /// public override readonly int GetHashCode() => this.PackedValue.GetHashCode(); + /// + /// Packs the X, Y and Z components of a into an 8-bit BT.709 luminance value. + /// Each component scales from [0, 1] to [0, 255], clamps, and rounds to the nearest integer, with ties to even, before the luminance calculation. + /// + /// The vector containing the values to pack. The W component is ignored. + /// The luminance value. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static byte Pack(Vector4 vector) { vector *= MaxBytes; - vector += Half; vector = ColorNumerics.ClampToFinite(vector, Vector4.Zero, MaxBytes); - Vector128 result = Vector128.ConvertToInt32(vector.AsVector128()).AsByte(); + // Round to the nearest integer, with ties to even, as the bulk byte packer does. + Vector128 result = Vector128_.ConvertToInt32RoundToEven(vector.AsVector128()).AsByte(); return ColorNumerics.Get8BitBT709Luminance(result.GetElement(0), result.GetElement(4), result.GetElement(8)); } } diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/La16.cs b/src/ImageSharp/PixelFormats/PixelImplementations/La16.cs index 53ba57d9c0..4d33402440 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/La16.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/La16.cs @@ -5,6 +5,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Common.Helpers; namespace SixLabors.ImageSharp.PixelFormats; @@ -22,11 +23,6 @@ public partial struct La16 : IPixel, IPackedVector /// private static readonly Vector4 MaxBytes = Vector128.Create(255f).AsVector4(); - /// - /// The half vector value. - /// - private static readonly Vector4 Half = Vector128.Create(.5f).AsVector4(); - /// /// Gets or sets the luminance component. /// @@ -243,14 +239,20 @@ public static La16 FromRgba64(Rgba64 source) /// public override readonly int GetHashCode() => this.PackedValue.GetHashCode(); + /// + /// Packs a into a color. The X, Y and Z components give the 8-bit BT.709 luminance. The W component gives alpha. + /// Each component scales from [0, 1] to [0, 255], clamps, and rounds to the nearest integer, with ties to even, before the luminance calculation. + /// + /// The vector containing the values to pack. + /// The packed color. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static La16 Pack(Vector4 vector) { vector *= MaxBytes; - vector += Half; vector = ColorNumerics.ClampToFinite(vector, Vector4.Zero, MaxBytes); - Vector128 result = Vector128.ConvertToInt32(vector.AsVector128()).AsByte(); + // Round to the nearest integer, with ties to even, as the bulk byte packer does. + Vector128 result = Vector128_.ConvertToInt32RoundToEven(vector.AsVector128()).AsByte(); byte l = ColorNumerics.Get8BitBT709Luminance(result.GetElement(0), result.GetElement(4), result.GetElement(8)); byte a = result.GetElement(12); diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/PixelOperations/Rgba32.PixelOperations.cs b/src/ImageSharp/PixelFormats/PixelImplementations/PixelOperations/Rgba32.PixelOperations.cs index b25ea96fff..12481dca5b 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/PixelOperations/Rgba32.PixelOperations.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/PixelOperations/Rgba32.PixelOperations.cs @@ -57,5 +57,20 @@ internal override void PackFromRgbPlanes( SimdUtils.PackFromRgbPlanes(redChannel, greenChannel, blueChannel, destination); } + + /// + internal override void PackFromRgbaPlanes( + Configuration configuration, + ReadOnlySpan redChannel, + ReadOnlySpan greenChannel, + ReadOnlySpan blueChannel, + ReadOnlySpan alphaChannel, + Span destination) + { + int count = redChannel.Length; + GuardPackFromRgbaPlanes(greenChannel, blueChannel, alphaChannel, destination, count); + + SimdUtils.PackFromRgbaPlanes(redChannel, greenChannel, blueChannel, alphaChannel, destination); + } } } diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/Rgb24.cs b/src/ImageSharp/PixelFormats/PixelImplementations/Rgb24.cs index ce75c224a4..8225f645ad 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/Rgb24.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/Rgb24.cs @@ -6,6 +6,7 @@ using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using SixLabors.ImageSharp.ColorProfiles; +using SixLabors.ImageSharp.Common.Helpers; namespace SixLabors.ImageSharp.PixelFormats; @@ -37,8 +38,10 @@ public partial struct Rgb24 : IPixel [FieldOffset(2)] public byte B; + /// + /// The maximum byte value. + /// private static readonly Vector4 MaxBytes = Vector128.Create(255f).AsVector4(); - private static readonly Vector4 Half = Vector128.Create(.5f).AsVector4(); /// /// Initializes a new instance of the struct. @@ -166,10 +169,10 @@ public static Rgb24 FromAssociatedScaledVector4(Vector4 source) public static Rgb24 FromVector4(Vector4 source) { source *= MaxBytes; - source += Half; source = ColorNumerics.ClampToFinite(source, Vector4.Zero, MaxBytes); - Vector128 result = Vector128.ConvertToInt32(source.AsVector128()).AsByte(); + // Round to the nearest integer, with ties to even, as the bulk byte packer does. + Vector128 result = Vector128_.ConvertToInt32RoundToEven(source.AsVector128()).AsByte(); return new Rgb24(result.GetElement(0), result.GetElement(4), result.GetElement(8)); } diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/Rgba32.cs b/src/ImageSharp/PixelFormats/PixelImplementations/Rgba32.cs index ebe784a0ca..0c47ed13b0 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/Rgba32.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/Rgba32.cs @@ -7,6 +7,7 @@ using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using SixLabors.ImageSharp.ColorProfiles; +using SixLabors.ImageSharp.Common.Helpers; namespace SixLabors.ImageSharp.PixelFormats; @@ -44,8 +45,10 @@ public partial struct Rgba32 : IPixel, IPackedVector /// public byte A; + /// + /// The maximum byte value. + /// private static readonly Vector4 MaxBytes = Vector128.Create(255f).AsVector4(); - private static readonly Vector4 Half = Vector128.Create(.5f).AsVector4(); /// /// Initializes a new instance of the struct. @@ -423,14 +426,15 @@ public readonly string ToHex() /// Packs a into a color. /// /// The vector containing the values to pack. + /// The color. X, Y, Z and W map to red, green, blue and alpha in the range 0 to 1. Values outside the range are clamped. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Rgba32 Pack(Vector4 vector) { vector *= MaxBytes; - vector += Half; vector = ColorNumerics.ClampToFinite(vector, Vector4.Zero, MaxBytes); - Vector128 result = Vector128.ConvertToInt32(vector.AsVector128()).AsByte(); + // Round to the nearest integer, with ties to even, as the bulk byte packer does. + Vector128 result = Vector128_.ConvertToInt32RoundToEven(vector.AsVector128()).AsByte(); return new Rgba32(result.GetElement(0), result.GetElement(4), result.GetElement(8), result.GetElement(12)); } } diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/Rgba32P.cs b/src/ImageSharp/PixelFormats/PixelImplementations/Rgba32P.cs index 300911e33a..5562dbaeec 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/Rgba32P.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/Rgba32P.cs @@ -4,7 +4,6 @@ using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Runtime.Intrinsics; namespace SixLabors.ImageSharp.PixelFormats; @@ -18,9 +17,6 @@ namespace SixLabors.ImageSharp.PixelFormats; [StructLayout(LayoutKind.Sequential)] public partial struct Rgba32P : IPixel, IPackedVector { - private static readonly Vector4 Half = new(0.5F); - private static readonly Vector4 MaxBytes = new(byte.MaxValue); - /// /// Gets or sets the associated red component. /// @@ -290,16 +286,4 @@ public static Rgba32P FromAssociatedScaledVector4(Vector4 source) /// public override readonly string ToString() => $"Rgba32P({this.R}, {this.G}, {this.B}, {this.A})"; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static Rgba32P Pack(Vector4 vector) - { - vector *= MaxBytes; - vector += Half; - vector = ColorNumerics.ClampToFinite(vector, Vector4.Zero, MaxBytes); - - // Each converted component occupies one 32-bit lane. Reinterpreting those lanes as bytes exposes their low bytes at offsets 0, 4, 8, and 12. - Vector128 result = Vector128.ConvertToInt32(vector.AsVector128()).AsByte(); - return new Rgba32P(result.GetElement(0), result.GetElement(4), result.GetElement(8), result.GetElement(12)); - } } diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/RgbaVector.cs b/src/ImageSharp/PixelFormats/PixelImplementations/RgbaVector.cs index 6430ef9268..1812934eff 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/RgbaVector.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/RgbaVector.cs @@ -42,9 +42,15 @@ public partial struct RgbaVector : IPixel /// public float A; + /// + /// The maximum byte value. + /// private const float MaxBytes = byte.MaxValue; + + /// + /// The maximum byte value in each component. uses it to scale the components to bytes. + /// private static readonly Vector4 Max = new(MaxBytes); - private static readonly Vector4 Half = new(0.5F); /// /// Initializes a new instance of the struct. @@ -241,8 +247,8 @@ public static RgbaVector FromAssociatedScaledVector4(Vector4 source) public readonly string ToHex() { // Hex is RRGGBBAA - Vector4 vector = this.ToVector4() * Max; - vector += Half; + // Round to the nearest integer, with ties to even, as the byte packers do. + Vector4 vector = Vector4.Round(this.ToVector4() * Max); uint hexOrder = (uint)((byte)vector.W | ((byte)vector.Z << 8) | ((byte)vector.Y << 16) | ((byte)vector.X << 24)); return hexOrder.ToString("X8", CultureInfo.InvariantCulture); } diff --git a/src/ImageSharp/PixelFormats/PixelOperations{TPixel}.cs b/src/ImageSharp/PixelFormats/PixelOperations{TPixel}.cs index 4f34189d19..c83c16caba 100644 --- a/src/ImageSharp/PixelFormats/PixelOperations{TPixel}.cs +++ b/src/ImageSharp/PixelFormats/PixelOperations{TPixel}.cs @@ -677,6 +677,46 @@ internal virtual void PackFromRgbPlanes( } } + /// + /// Bulk operation that packs 4 separate RGBA channels to . + /// The destination must contain at least as many pixels as each source channel. + /// + /// The to configure internal operations. + /// The red values. + /// The green values. + /// The blue values. + /// The straight alpha values. + /// The destination pixels. + internal virtual void PackFromRgbaPlanes( + Configuration configuration, + ReadOnlySpan redChannel, + ReadOnlySpan greenChannel, + ReadOnlySpan blueChannel, + ReadOnlySpan alphaChannel, + Span destination) + { + int count = redChannel.Length; + GuardPackFromRgbaPlanes(greenChannel, blueChannel, alphaChannel, destination, count); + + // Pack each block of 64 pixels to straight Rgba32 with SIMD, then convert the block through the bulk FromRgba32 path. + // The 256-byte block is on the stack, so the method needs no row allocation. + InlineArray64 blockBuffer = default; + Span block = blockBuffer; + for (int offset = 0; offset < count; offset += block.Length) + { + int length = Math.Min(block.Length, count - offset); + Span pixels = block[..length]; + SimdUtils.PackFromRgbaPlanes( + redChannel.Slice(offset, length), + greenChannel.Slice(offset, length), + blueChannel.Slice(offset, length), + alphaChannel.Slice(offset, length), + pixels); + + this.FromRgba32(configuration, pixels, destination.Slice(offset, length)); + } + } + /// /// Bulk operation that unpacks pixels from /// into 3 separate RGB channels. @@ -729,6 +769,13 @@ internal static void GuardUnpackIntoRgbPlanes( Guard.IsTrue(source.Length <= redChannel.Length, nameof(source), "'source' span should not be bigger than the destination channels!"); } + /// + /// Throws when the green or blue plane length is not , or when the destination is shorter. + /// + /// The green values. + /// The blue values. + /// The destination pixels. + /// The length of the red plane. [MethodImpl(InliningOptions.ShortMethod)] internal static void GuardPackFromRgbPlanes(ReadOnlySpan greenChannel, ReadOnlySpan blueChannel, Span destination, int count) { @@ -737,6 +784,26 @@ internal static void GuardPackFromRgbPlanes(ReadOnlySpan greenChannel, Rea Guard.IsTrue(destination.Length >= count, nameof(destination), "'destination' span should not be shorter than the source channels!"); } + /// + /// Throws when the green, blue or alpha plane length is not , or when the destination is shorter. + /// + /// The green values. + /// The blue values. + /// The alpha values. + /// The destination pixels. + /// The length of the red plane. + [MethodImpl(InliningOptions.ShortMethod)] + internal static void GuardPackFromRgbaPlanes( + ReadOnlySpan greenChannel, + ReadOnlySpan blueChannel, + ReadOnlySpan alphaChannel, + Span destination, + int count) + { + GuardPackFromRgbPlanes(greenChannel, blueChannel, destination, count); + Guard.IsTrue(alphaChannel.Length == count, nameof(alphaChannel), "Channels must be of same size!"); + } + /// /// Converts associated source pixels to an unassociated destination format. /// diff --git a/src/ImageSharp/PixelFormats/Rgba32CompatiblePixelOperations{TPixel}.cs b/src/ImageSharp/PixelFormats/Rgba32CompatiblePixelOperations{TPixel}.cs index 8b919d0c92..cd134d8214 100644 --- a/src/ImageSharp/PixelFormats/Rgba32CompatiblePixelOperations{TPixel}.cs +++ b/src/ImageSharp/PixelFormats/Rgba32CompatiblePixelOperations{TPixel}.cs @@ -325,10 +325,13 @@ public static void UnassociateBytes(ReadOnlySpan source, Span des Unsafe.Add(ref destinationBase, (uint)i) = Numerics.UnPremultiply(Vector128.ConvertToSingle(integers0), byte.MaxValue).AsVector4(); + Unsafe.Add(ref destinationBase, (uint)i + 1u) = Numerics.UnPremultiply(Vector128.ConvertToSingle(integers1), byte.MaxValue).AsVector4(); + Unsafe.Add(ref destinationBase, (uint)i + 2u) = Numerics.UnPremultiply(Vector128.ConvertToSingle(integers2), byte.MaxValue).AsVector4(); + Unsafe.Add(ref destinationBase, (uint)i + 3u) = Numerics.UnPremultiply(Vector128.ConvertToSingle(integers3), byte.MaxValue).AsVector4(); } @@ -369,15 +372,16 @@ public static Vector4 ReassociateToByte(Vector4 source) /// Converts a floating-point byte magnitude to a byte. /// /// The byte magnitude. - /// The rounded and clamped byte. + /// The clamped byte, rounded to the nearest integer with ties to even. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte ConvertToByte(float value) => (byte)ColorNumerics.ClampToFinite(value + .5F, 0, byte.MaxValue); + public static byte ConvertToByte(float value) => (byte)MathF.Round(ColorNumerics.ClampToFinite(value, 0, byte.MaxValue)); /// /// Converts unassociated scaled RGBA pixels to associated byte magnitudes, with the alpha byte that the destination stores. /// /// - /// The components are bounded to [0, 1] first. NaN becomes zero. The alpha byte is floor(alpha * 255 + 0.5). + /// The components are bounded to [0, 1] first. NaN becomes zero. + /// The alpha byte is alpha * 255, rounded to the nearest integer with ties to even, as the byte packer rounds. /// RGB is multiplied by that alpha byte, so the result is associated and in byte units in one step. /// private readonly struct AssociateToByteOperator : PixelFormats.PixelOperations.IAlphaOperator @@ -388,7 +392,7 @@ public static Vector128 Apply(Vector128 source) { source = ColorNumerics.ClampToFinite(source, Vector128.Zero, Vector128.One); Vector128 alpha = Vector128_.ShuffleNative(source, 0b_11_11_11_11); - Vector128 storedAlpha = Vector128.Floor((alpha * Vector128.Create((float)byte.MaxValue)) + Vector128.Create(.5F)); + Vector128 storedAlpha = Vector128.Round(alpha * Vector128.Create((float)byte.MaxValue)); // RGB is associated with the quantized alpha byte. The alpha lane stores that byte. Vector128 alphaMask = Vector128.Create(0, 0, 0, -1).AsSingle(); @@ -401,7 +405,7 @@ public static Vector256 Apply(Vector256 source) { source = ColorNumerics.ClampToFinite(source, Vector256.Zero, Vector256.One); Vector256 alpha = Vector256_.ShuffleNative(source, 0b_11_11_11_11); - Vector256 storedAlpha = Vector256.Floor((alpha * Vector256.Create((float)byte.MaxValue)) + Vector256.Create(.5F)); + Vector256 storedAlpha = Vector256.Round(alpha * Vector256.Create((float)byte.MaxValue)); // Each four-lane group uses its own alpha byte, as in the 128-bit form. Vector256 alphaMask = Vector256.Create(0, 0, 0, -1, 0, 0, 0, -1).AsSingle(); @@ -414,7 +418,7 @@ public static Vector512 Apply(Vector512 source) { source = ColorNumerics.ClampToFinite(source, Vector512.Zero, Vector512.One); Vector512 alpha = Vector512_.ShuffleNative(source, 0b_11_11_11_11); - Vector512 storedAlpha = Vector512.Floor((alpha * Vector512.Create((float)byte.MaxValue)) + Vector512.Create(.5F)); + Vector512 storedAlpha = Vector512.Round(alpha * Vector512.Create((float)byte.MaxValue)); // Each four-lane group uses its own alpha byte, as in the 128-bit form. Vector512 alphaMask = Vector512.Create(0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1).AsSingle(); @@ -444,7 +448,7 @@ public static Vector128 Apply(Vector128 source) Vector128 alpha = Vector128_.ShuffleNative(source, 0b_11_11_11_11); alpha = ColorNumerics.ClampToFinite(alpha, zero, Vector128.Create(float.MaxValue)); Vector128 byteAlpha = alpha * byteMax; - Vector128 storedAlpha = Vector128.Floor(ColorNumerics.ClampToFinite(byteAlpha + Vector128.Create(.5F), zero, byteMax)); + Vector128 storedAlpha = Vector128.Round(ColorNumerics.ClampToFinite(byteAlpha, zero, byteMax)); Vector128 result = (source / alpha) * storedAlpha; Vector128 alphaMask = Vector128.Create(0, 0, 0, -1).AsSingle(); @@ -465,7 +469,7 @@ public static Vector256 Apply(Vector256 source) Vector256 alpha = Vector256_.ShuffleNative(source, 0b_11_11_11_11); alpha = ColorNumerics.ClampToFinite(alpha, zero, Vector256.Create(float.MaxValue)); Vector256 byteAlpha = alpha * byteMax; - Vector256 storedAlpha = Vector256.Floor(ColorNumerics.ClampToFinite(byteAlpha + Vector256.Create(.5F), zero, byteMax)); + Vector256 storedAlpha = Vector256.Round(ColorNumerics.ClampToFinite(byteAlpha, zero, byteMax)); Vector256 result = (source / alpha) * storedAlpha; Vector256 alphaMask = Vector256.Create(0, 0, 0, -1, 0, 0, 0, -1).AsSingle(); @@ -486,7 +490,7 @@ public static Vector512 Apply(Vector512 source) Vector512 alpha = Vector512_.ShuffleNative(source, 0b_11_11_11_11); alpha = ColorNumerics.ClampToFinite(alpha, zero, Vector512.Create(float.MaxValue)); Vector512 byteAlpha = alpha * byteMax; - Vector512 storedAlpha = Vector512.Floor(ColorNumerics.ClampToFinite(byteAlpha + Vector512.Create(.5F), zero, byteMax)); + Vector512 storedAlpha = Vector512.Round(ColorNumerics.ClampToFinite(byteAlpha, zero, byteMax)); Vector512 result = (source / alpha) * storedAlpha; Vector512 alphaMask = Vector512.Create(0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1).AsSingle(); diff --git a/src/ImageSharp/PixelFormats/Utils/PixelConverter.Rgba32Sources.cs b/src/ImageSharp/PixelFormats/Utils/PixelConverter.Rgba32Sources.cs index 1a9a6e6bbb..99450eec7f 100644 --- a/src/ImageSharp/PixelFormats/Utils/PixelConverter.Rgba32Sources.cs +++ b/src/ImageSharp/PixelFormats/Utils/PixelConverter.Rgba32Sources.cs @@ -52,7 +52,7 @@ public interface IRgba32SourceOperator /// Pixels 4 to 7. /// Pixels 8 to 11. /// Pixels 12 to 15. - static abstract void Load128( + static abstract void Load( ref byte row, nuint x, out Vector128 pixels0, @@ -69,7 +69,7 @@ static abstract void Load128( /// Pixels 8 to 15. /// Pixels 16 to 23. /// Pixels 24 to 31. - static abstract void Load256( + static abstract void Load( ref byte row, nuint x, out Vector256 pixels0, @@ -86,7 +86,7 @@ static abstract void Load256( /// Pixels 16 to 31. /// Pixels 32 to 47. /// Pixels 48 to 63. - static abstract void Load512( + static abstract void Load( ref byte row, nuint x, out Vector512 pixels0, @@ -223,7 +223,7 @@ private static uint LuminanceToRgba32(uint luminance, uint alpha) /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load128( + public static void Load( ref byte row, nuint x, out Vector128 pixels0, @@ -238,12 +238,15 @@ public static void Load128( pixels0 = Vector128.ShuffleNative( luminance, Vector128.Create((byte)0, 0, 0, 0x80, 1, 1, 1, 0x80, 2, 2, 2, 0x80, 3, 3, 3, 0x80)) | opaque; + pixels1 = Vector128.ShuffleNative( luminance, Vector128.Create((byte)4, 4, 4, 0x80, 5, 5, 5, 0x80, 6, 6, 6, 0x80, 7, 7, 7, 0x80)) | opaque; + pixels2 = Vector128.ShuffleNative( luminance, Vector128.Create((byte)8, 8, 8, 0x80, 9, 9, 9, 0x80, 10, 10, 10, 0x80, 11, 11, 11, 0x80)) | opaque; + pixels3 = Vector128.ShuffleNative( luminance, Vector128.Create((byte)12, 12, 12, 0x80, 13, 13, 13, 0x80, 14, 14, 14, 0x80, 15, 15, 15, 0x80)) | opaque; @@ -251,7 +254,7 @@ public static void Load128( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load256( + public static void Load( ref byte row, nuint x, out Vector256 pixels0, @@ -271,7 +274,7 @@ public static void Load256( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load512( + public static void Load( ref byte row, nuint x, out Vector512 pixels0, @@ -313,7 +316,7 @@ public static uint Load(ref byte row, nuint x) /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load128( + public static void Load( ref byte row, nuint x, out Vector128 pixels0, @@ -336,7 +339,7 @@ public static void Load128( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load256( + public static void Load( ref byte row, nuint x, out Vector256 pixels0, @@ -357,7 +360,7 @@ public static void Load256( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load512( + public static void Load( ref byte row, nuint x, out Vector512 pixels0, @@ -397,7 +400,7 @@ public static uint Load(ref byte row, nuint x) /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load128( + public static void Load( ref byte row, nuint x, out Vector128 pixels0, @@ -418,7 +421,7 @@ public static void Load128( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load256( + public static void Load( ref byte row, nuint x, out Vector256 pixels0, @@ -439,7 +442,7 @@ public static void Load256( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load512( + public static void Load( ref byte row, nuint x, out Vector512 pixels0, @@ -482,7 +485,7 @@ public static uint Load(ref byte row, nuint x) /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load128( + public static void Load( ref byte row, nuint x, out Vector128 pixels0, @@ -499,7 +502,7 @@ public static void Load128( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load256( + public static void Load( ref byte row, nuint x, out Vector256 pixels0, @@ -516,7 +519,7 @@ public static void Load256( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load512( + public static void Load( ref byte row, nuint x, out Vector512 pixels0, @@ -593,7 +596,7 @@ public static uint Load(ref byte row, nuint x) /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load128( + public static void Load( ref byte row, nuint x, out Vector128 pixels0, @@ -621,7 +624,7 @@ public static void Load128( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load256( + public static void Load( ref byte row, nuint x, out Vector256 pixels0, @@ -649,7 +652,7 @@ public static void Load256( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load512( + public static void Load( ref byte row, nuint x, out Vector512 pixels0, @@ -702,7 +705,7 @@ public static uint Load(ref byte row, nuint x) /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load128( + public static void Load( ref byte row, nuint x, out Vector128 pixels0, @@ -720,7 +723,7 @@ public static void Load128( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load256( + public static void Load( ref byte row, nuint x, out Vector256 pixels0, @@ -738,7 +741,7 @@ public static void Load256( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load512( + public static void Load( ref byte row, nuint x, out Vector512 pixels0, @@ -788,7 +791,7 @@ public static void To4Bytes(ReadOnlySpan source, Span dest { for (; x + 64 <= length; x += 64) { - TSource.Load512( + TSource.Load( ref sourceBase, x, out Vector512 pixels0, @@ -808,7 +811,7 @@ public static void To4Bytes(ReadOnlySpan source, Span dest { for (; x + 32 <= length; x += 32) { - TSource.Load256( + TSource.Load( ref sourceBase, x, out Vector256 pixels0, @@ -828,7 +831,7 @@ public static void To4Bytes(ReadOnlySpan source, Span dest { for (; x + 16 <= length; x += 16) { - TSource.Load128( + TSource.Load( ref sourceBase, x, out Vector128 pixels0, @@ -873,7 +876,7 @@ public static void To3Bytes(ReadOnlySpan source, Span dest { for (; x + 64 <= length; x += 64) { - TSource.Load512( + TSource.Load( ref sourceBase, x, out Vector512 pixels0, @@ -901,7 +904,7 @@ public static void To3Bytes(ReadOnlySpan source, Span dest { for (; x + 32 <= length; x += 32) { - TSource.Load256( + TSource.Load( ref sourceBase, x, out Vector256 pixels0, @@ -929,7 +932,7 @@ public static void To3Bytes(ReadOnlySpan source, Span dest { for (; x + 16 <= length; x += 16) { - TSource.Load128( + TSource.Load( ref sourceBase, x, out Vector128 pixels0, diff --git a/src/ImageSharp/PixelFormats/Utils/PixelConverter.Rgba64Sources.cs b/src/ImageSharp/PixelFormats/Utils/PixelConverter.Rgba64Sources.cs index c19c448f43..142facf4d0 100644 --- a/src/ImageSharp/PixelFormats/Utils/PixelConverter.Rgba64Sources.cs +++ b/src/ImageSharp/PixelFormats/Utils/PixelConverter.Rgba64Sources.cs @@ -52,7 +52,7 @@ public interface IRgba64SourceOperator /// Pixels 2 and 3. /// Pixels 4 and 5. /// Pixels 6 and 7. - static abstract void Load128( + static abstract void Load( ref byte row, nuint x, out Vector128 pixels0, @@ -69,7 +69,7 @@ static abstract void Load128( /// Pixels 4 to 7. /// Pixels 8 to 11. /// Pixels 12 to 15. - static abstract void Load256( + static abstract void Load( ref byte row, nuint x, out Vector256 pixels0, @@ -86,7 +86,7 @@ static abstract void Load256( /// Pixels 8 to 15. /// Pixels 16 to 23. /// Pixels 24 to 31. - static abstract void Load512( + static abstract void Load( ref byte row, nuint x, out Vector512 pixels0, @@ -227,7 +227,7 @@ public static ulong Load(ref byte row, nuint x) /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load128( + public static void Load( ref byte row, nuint x, out Vector128 pixels0, @@ -248,7 +248,7 @@ public static void Load128( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load256( + public static void Load( ref byte row, nuint x, out Vector256 pixels0, @@ -269,7 +269,7 @@ public static void Load256( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load512( + public static void Load( ref byte row, nuint x, out Vector512 pixels0, @@ -314,7 +314,7 @@ public static ulong Load(ref byte row, nuint x) /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load128( + public static void Load( ref byte row, nuint x, out Vector128 pixels0, @@ -334,7 +334,7 @@ public static void Load128( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load256( + public static void Load( ref byte row, nuint x, out Vector256 pixels0, @@ -354,7 +354,7 @@ public static void Load256( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load512( + public static void Load( ref byte row, nuint x, out Vector512 pixels0, @@ -398,7 +398,7 @@ public static ulong Load(ref byte row, nuint x) /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load128( + public static void Load( ref byte row, nuint x, out Vector128 pixels0, @@ -426,7 +426,7 @@ public static void Load128( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load256( + public static void Load( ref byte row, nuint x, out Vector256 pixels0, @@ -454,7 +454,7 @@ public static void Load256( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load512( + public static void Load( ref byte row, nuint x, out Vector512 pixels0, @@ -499,7 +499,7 @@ public static void Load512( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load128( + public static void Load( ref byte row, nuint x, out Vector128 pixels0, @@ -516,7 +516,7 @@ public static void Load128( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load256( + public static void Load( ref byte row, nuint x, out Vector256 pixels0, @@ -533,7 +533,7 @@ public static void Load256( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Load512( + public static void Load( ref byte row, nuint x, out Vector512 pixels0, @@ -577,7 +577,7 @@ public static void ToRgba64(ReadOnlySpan source, Span destination) { for (; x + 32 <= length; x += 32) { - TSource.Load512( + TSource.Load( ref sourceBase, x, out Vector512 pixels0, @@ -597,7 +597,7 @@ public static void ToRgba64(ReadOnlySpan source, Span destination) { for (; x + 16 <= length; x += 16) { - TSource.Load256( + TSource.Load( ref sourceBase, x, out Vector256 pixels0, @@ -617,7 +617,7 @@ public static void ToRgba64(ReadOnlySpan source, Span destination) { for (; x + 8 <= length; x += 8) { - TSource.Load128( + TSource.Load( ref sourceBase, x, out Vector128 pixels0, @@ -659,7 +659,7 @@ public static void ToRgb48(ReadOnlySpan source, Span destination) { for (; x + 32 <= length; x += 32) { - TSource.Load512( + TSource.Load( ref sourceBase, x, out Vector512 pixels0, @@ -687,7 +687,7 @@ public static void ToRgb48(ReadOnlySpan source, Span destination) { for (; x + 16 <= length; x += 16) { - TSource.Load256( + TSource.Load( ref sourceBase, x, out Vector256 pixels0, @@ -715,7 +715,7 @@ public static void ToRgb48(ReadOnlySpan source, Span destination) { for (; x + 8 <= length; x += 8) { - TSource.Load128( + TSource.Load( ref sourceBase, x, out Vector128 pixels0, diff --git a/tests/ImageSharp.Tests/Common/SimdUtilsTests.cs b/tests/ImageSharp.Tests/Common/SimdUtilsTests.cs index cf885fe4d1..e6412784bc 100644 --- a/tests/ImageSharp.Tests/Common/SimdUtilsTests.cs +++ b/tests/ImageSharp.Tests/Common/SimdUtilsTests.cs @@ -224,7 +224,7 @@ public void BulkConvertNormalizedFloatToByteClampOverflows(int count) } [Fact] - public void BulkConvertNormalizedFloatToByteRoundsMidpointsAwayFromZero() + public void BulkConvertNormalizedFloatToByteRoundsMidpointsToEven() { float[] midpointValues = [.. Enumerable.Range(0, byte.MaxValue).Select(x => (x + 0.5F) / byte.MaxValue)]; float[] source = new float[1024]; @@ -235,7 +235,9 @@ public void BulkConvertNormalizedFloatToByteRoundsMidpointsAwayFromZero() { int value = i % midpointValues.Length; source[i] = midpointValues[value]; - expected[i] = (byte)(value + 1); + + // Each source is the midpoint value + 0.5 after the scale by 255. A midpoint rounds to the even byte. + expected[i] = (byte)Math.Round(value + 0.5D, MidpointRounding.ToEven); } SimdUtils.NormalizedFloatToByteSaturate(source, actual); @@ -244,7 +246,7 @@ public void BulkConvertNormalizedFloatToByteRoundsMidpointsAwayFromZero() } [Fact] - public void BulkConvertFloatToByteRoundsMidpointsAwayFromZeroAndClampsOverflows() + public void BulkConvertFloatToByteRoundsMidpointsToEvenAndClampsOverflows() { float[] source = new float[1027]; byte[] expected = new byte[source.Length]; @@ -254,7 +256,8 @@ public void BulkConvertFloatToByteRoundsMidpointsAwayFromZeroAndClampsOverflows( { float value = (i % 258) - .5F; source[i] = value; - expected[i] = (byte)Math.Min(byte.MaxValue, Math.Max(0, value + .5F)); + // Each value is an exact midpoint. It rounds to the even integer, then clamps to the byte range. + expected[i] = (byte)Math.Clamp(Math.Round(value, MidpointRounding.ToEven), 0, byte.MaxValue); } SimdUtils.FloatToByteSaturate(source, actual); diff --git a/tests/ImageSharp.Tests/Common/Vector128UtilitiesTests.cs b/tests/ImageSharp.Tests/Common/Vector128UtilitiesTests.cs new file mode 100644 index 0000000000..07af268bd6 --- /dev/null +++ b/tests/ImageSharp.Tests/Common/Vector128UtilitiesTests.cs @@ -0,0 +1,71 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Common.Helpers; +using SixLabors.ImageSharp.Tests.TestUtilities; + +namespace SixLabors.ImageSharp.Tests.Common; + +public class Vector128UtilitiesTests +{ + /// + /// Gets the values that the shift tests move: all bits set, the lowest bit, the lowest and highest bits, and a mixed pattern. + /// + private static ReadOnlySpan ShiftValues => [ulong.MaxValue, 1, 0x8000000000000001, 0x123456789ABCDEF0]; + + /// + /// Verifies that each 32-bit lane shifts left by its own count, for every count from 0 to 31. The runs cover the AVX2 path, the + /// SSE4.1 path without AVX2, and the scalar path without hardware intrinsics. + /// + [Fact] + public void ShiftLeftLogicalVariableUInt32MatchesScalarShift() + { + static void RunTest() + { + foreach (ulong pattern in ShiftValues) + { + uint value = (uint)pattern; + for (uint count = 0; count < 32; count += 4) + { + Vector128 counts = Vector128.Create(count, count + 1, count + 2, count + 3); + Vector128 shifted = Vector128_.ShiftLeftLogicalVariable(Vector128.Create(value), counts); + for (int lane = 0; lane < 4; lane++) + { + Assert.Equal(value << (int)counts.GetElement(lane), shifted.GetElement(lane)); + } + } + } + } + + FeatureTestRunner.RunWithHwIntrinsicsFeature( + RunTest, + HwIntrinsics.AllowAll | HwIntrinsics.DisableAVX2 | HwIntrinsics.DisableHWIntrinsic); + } + + /// + /// Verifies that each 64-bit lane shifts left by its own count, for every count from 0 to 63. The runs cover the AVX2 path, the + /// SSE2 path without AVX2, and the scalar path without hardware intrinsics. + /// + [Fact] + public void ShiftLeftLogicalVariableUInt64MatchesScalarShift() + { + static void RunTest() + { + foreach (ulong value in ShiftValues) + { + for (ulong count = 0; count < 64; count += 2) + { + Vector128 counts = Vector128.Create(count, 63 - count); + Vector128 shifted = Vector128_.ShiftLeftLogicalVariable(Vector128.Create(value), counts); + Assert.Equal(value << (int)count, shifted.GetElement(0)); + Assert.Equal(value << (int)(63 - count), shifted.GetElement(1)); + } + } + } + + FeatureTestRunner.RunWithHwIntrinsicsFeature( + RunTest, + HwIntrinsics.AllowAll | HwIntrinsics.DisableAVX2 | HwIntrinsics.DisableHWIntrinsic); + } +} diff --git a/tests/ImageSharp.Tests/Formats/Jxl/JxlHybridUintTests.cs b/tests/ImageSharp.Tests/Formats/Jxl/JxlHybridUintTests.cs new file mode 100644 index 0000000000..1c24024764 --- /dev/null +++ b/tests/ImageSharp.Tests/Formats/Jxl/JxlHybridUintTests.cs @@ -0,0 +1,194 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Formats; +using SixLabors.ImageSharp.Formats.Jxl; +using SixLabors.ImageSharp.Formats.Jxl.Components.Decoder; +using SixLabors.ImageSharp.Formats.Jxl.Components.Entropy; +using SixLabors.ImageSharp.IO; + +namespace SixLabors.ImageSharp.Tests.Formats.Jxl; + +[Trait("Format", "Jxl")] +public class JxlHybridUintTests +{ + /// + /// Verifies that the scalar overload and each vector overload of the 4/2/0 split give, for each value, the result of the general split + /// with the configuration 4/2/0 that a stream header declares. + /// + [Fact] + public void Encode420VectorLanesMatchScalar() + { + JxlHybridUint configuration = Read420Configuration(); + uint[] lanes = GetSplitValues(); + uint[] tokens = new uint[16]; + uint[] bitCounts = new uint[16]; + uint[] extras = new uint[16]; + for (int i = 0; i < lanes.Length; i += 16) + { + JxlHybridUint.Encode420(Vector512.Create(lanes.AsSpan(i, 16)), out Vector512 token, out Vector512 bits, out Vector512 extra); + token.CopyTo(tokens); + bits.CopyTo(bitCounts); + extra.CopyTo(extras); + AssertLanes(configuration, lanes.AsSpan(i, 16), tokens, bitCounts, extras); + } + + for (int i = 0; i < lanes.Length; i += 8) + { + JxlHybridUint.Encode420(Vector256.Create(lanes.AsSpan(i, 8)), out Vector256 token, out Vector256 bits, out Vector256 extra); + token.CopyTo(tokens); + bits.CopyTo(bitCounts); + extra.CopyTo(extras); + AssertLanes(configuration, lanes.AsSpan(i, 8), tokens, bitCounts, extras); + } + + for (int i = 0; i < lanes.Length; i += 4) + { + JxlHybridUint.Encode420(Vector128.Create(lanes.AsSpan(i, 4)), out Vector128 token, out Vector128 bits, out Vector128 extra); + token.CopyTo(tokens); + bits.CopyTo(bitCounts); + extra.CopyTo(extras); + AssertLanes(configuration, lanes.AsSpan(i, 4), tokens, bitCounts, extras); + } + } + + /// + /// Verifies that each vector overload of the 0/0/0 split gives, for each value, the result of the general split with the + /// configuration 0/0/0. + /// + [Fact] + public void Encode000VectorLanesMatchZeroConfiguration() + { + uint[] lanes = GetSplitValues(); + uint[] tokens = new uint[16]; + uint[] bitCounts = new uint[16]; + uint[] extras = new uint[16]; + for (int i = 0; i < lanes.Length; i += 16) + { + JxlHybridUint.Encode000(Vector512.Create(lanes.AsSpan(i, 16)), out Vector512 token, out Vector512 bits, out Vector512 extra); + token.CopyTo(tokens); + bits.CopyTo(bitCounts); + extra.CopyTo(extras); + AssertZeroLanes(lanes.AsSpan(i, 16), tokens, bitCounts, extras); + } + + for (int i = 0; i < lanes.Length; i += 8) + { + JxlHybridUint.Encode000(Vector256.Create(lanes.AsSpan(i, 8)), out Vector256 token, out Vector256 bits, out Vector256 extra); + token.CopyTo(tokens); + bits.CopyTo(bitCounts); + extra.CopyTo(extras); + AssertZeroLanes(lanes.AsSpan(i, 8), tokens, bitCounts, extras); + } + + for (int i = 0; i < lanes.Length; i += 4) + { + JxlHybridUint.Encode000(Vector128.Create(lanes.AsSpan(i, 4)), out Vector128 token, out Vector128 bits, out Vector128 extra); + token.CopyTo(tokens); + bits.CopyTo(bitCounts); + extra.CopyTo(extras); + AssertZeroLanes(lanes.AsSpan(i, 4), tokens, bitCounts, extras); + } + } + + /// + /// Gets the values of the split tests: all values below 2^17, and for each leading bit from 17 to 31 the values around its power of + /// two, with each of the four two-bit patterns below the leading one, and with all low bits set. The values from 2^24 test the clear + /// of the low bits before the float conversion. The largest value fills the last vector of sixteen lanes. + /// + /// The values, a multiple of sixteen. + private static uint[] GetSplitValues() + { + List values = []; + for (uint value = 0; value < 1U << 17; value++) + { + values.Add(value); + } + + for (int exponent = 17; exponent < 32; exponent++) + { + uint power = 1U << exponent; + for (uint pattern = 0; pattern < 4; pattern++) + { + uint top = power | (pattern << (exponent - 2)); + values.Add(top); + values.Add(top + 1); + values.Add(top | ((1U << (exponent - 2)) - 1)); + } + + values.Add(power - 1); + } + + while (values.Count % 16 != 0) + { + values.Add(uint.MaxValue); + } + + return [.. values]; + } + + /// + /// Compares the lanes of one vector 0/0/0 split with the general split of each value. + /// + /// The values of the lanes. + /// The vector tokens, at least one for each value. + /// The vector bit counts, at least one for each value. + /// The vector extra bits, at least one for each value. + private static void AssertZeroLanes(ReadOnlySpan values, ReadOnlySpan tokens, ReadOnlySpan bitCounts, ReadOnlySpan extraBits) + { + for (int lane = 0; lane < values.Length; lane++) + { + JxlHybridUint.Zero.Encode(values[lane], out uint token, out int bitCount, out uint extra); + Assert.Equal(token, tokens[lane]); + Assert.Equal((uint)bitCount, bitCounts[lane]); + Assert.Equal(extra, extraBits[lane]); + } + } + + /// + /// Reads the configuration 4/2/0 of a prefix-coded stream from its header bits, as the decoder reads it. + /// + /// The configuration. + private static JxlHybridUint Read420Configuration() + { + // The codestream signature, then the configuration least-significant bit first: a split exponent of 4 in 4 bits, 2 leading + // token bits in 3 bits and 0 trailing token bits in 2 bits. The zero bytes after them pad the stream. + byte[] data = [0xFF, 0x0A, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + using MemoryStream stream = new(data, false); + using BufferedReadStream buffered = new(Configuration.Default, stream); + JxlBitReader reader = new(new JxlCodestreamReader(buffered, SegmentIntegrityHandling.Strict)); + Assert.Equal(0x0AFFU, reader.ReadBits(16)); + JxlHybridUint configuration = JxlHybridUint.Read(ref reader, 15); + Assert.True(configuration.Is420); + return configuration; + } + + /// + /// Compares the lanes of one vector split, and the scalar split of each value, with the general split of each value. + /// + /// The configuration 4/2/0 of the general split. + /// The values of the lanes. + /// The vector tokens, at least one for each value. + /// The vector bit counts, at least one for each value. + /// The vector extra bits, at least one for each value. + private static void AssertLanes( + JxlHybridUint configuration, + ReadOnlySpan values, + ReadOnlySpan tokens, + ReadOnlySpan bitCounts, + ReadOnlySpan extraBits) + { + for (int lane = 0; lane < values.Length; lane++) + { + configuration.Encode(values[lane], out uint token, out int bitCount, out uint extra); + JxlHybridUint.Encode420(values[lane], out uint scalarToken, out int scalarBitCount, out uint scalarExtra); + Assert.Equal(token, scalarToken); + Assert.Equal(bitCount, scalarBitCount); + Assert.Equal(extra, scalarExtra); + Assert.Equal(token, tokens[lane]); + Assert.Equal((uint)bitCount, bitCounts[lane]); + Assert.Equal(extra, extraBits[lane]); + } + } +} diff --git a/tests/ImageSharp.Tests/Formats/WebP/LosslessUtilsTests.cs b/tests/ImageSharp.Tests/Formats/WebP/LosslessUtilsTests.cs index 0d915aa368..bb7039f369 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/LosslessUtilsTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/LosslessUtilsTests.cs @@ -50,8 +50,8 @@ private static void RunFindMatchLengthTest() ReadOnlySpan right = [0x01020304, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0x01000010]; // The final words differ in one byte. A byte-based SIMD scan must report complete uint values. - Assert.Equal(16, LosslessUtils.VectorMismatch(left, right, left.Length)); - Assert.Equal(9, LosslessUtils.VectorMismatch(left, right, 9)); + Assert.Equal(16, LosslessUtils.FindMatchLength(left, right, 0, left.Length)); + Assert.Equal(9, LosslessUtils.FindMatchLength(left, right, 0, 9)); // A candidate can extend the previous best only when the values at that position match. Assert.Equal(16, LosslessUtils.FindMatchLength(left, right, 15, left.Length)); @@ -79,6 +79,7 @@ private static void RunCombinedShannonEntropyTest() 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 1, 2, 4, 6, 4 ]; + const float expected = 884.7585f; float actual = LosslessUtils.CombinedShannonEntropy(x, y); @@ -213,20 +214,13 @@ private static void RunPredictor11Test() // arrange uint[] topData = [4278258949, 4278258949]; const uint left = 4294839812; - short[] scratch = new short[8]; const uint expectedResult = 4294839812; // act - unsafe - { - fixed (uint* top = &topData[1]) - { - uint actual = LosslessUtils.Predictor11(left, top, scratch); - - // assert - Assert.Equal(expectedResult, actual); - } - } + uint actual = LosslessUtils.Predict(11, left, ref topData[1]); + + // assert + Assert.Equal(expectedResult, actual); } private static void RunPredictor12Test() @@ -237,16 +231,10 @@ private static void RunPredictor12Test() const uint expectedResult = 4294779388; // act - unsafe - { - fixed (uint* top = &topData[1]) - { - uint actual = LosslessUtils.Predictor12(left, top); - - // assert - Assert.Equal(expectedResult, actual); - } - } + uint actual = LosslessUtils.Predict(12, left, ref topData[1]); + + // assert + Assert.Equal(expectedResult, actual); } private static void RunPredictor13Test() @@ -258,22 +246,10 @@ private static void RunPredictor13Test() uint[] topData1 = [4294933015, 4278219803]; const uint left1 = 4278236686; const uint expectedResult1 = 4278231571; - uint actual0 = 0; - uint actual1 = 0; // act - unsafe - { - fixed (uint* top = &topData0[1]) - { - actual0 = LosslessUtils.Predictor13(left0, top); - } - - fixed (uint* top = &topData1[1]) - { - actual1 = LosslessUtils.Predictor13(left1, top); - } - } + uint actual0 = LosslessUtils.Predict(13, left0, ref topData0[1]); + uint actual1 = LosslessUtils.Predict(13, left1, ref topData1[1]); // assert Assert.Equal(expectedResult0, actual0); @@ -286,6 +262,7 @@ public void BundleColorMap_WithXbitsZero_Works() // arrange byte[] row = [238, 238, 238, 238, 238, 238, 240, 237, 240, 235, 223, 223, 218, 220, 226, 219, 220, 204, 218, 211, 218, 221, 254, 255 ]; + int xBits = 0; uint[] actual = new uint[row.Length]; uint[] expected = @@ -319,6 +296,7 @@ public void BundleColorMap_WithXbitsNoneZero_Works() 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 ]; + int xBits = 2; uint[] actual = new uint[row.Length]; uint[] expected = diff --git a/tests/ImageSharp.Tests/Formats/WebP/PredictorEncoderTests.cs b/tests/ImageSharp.Tests/Formats/WebP/PredictorEncoderTests.cs index 16990c3577..f868482a47 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/PredictorEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/PredictorEncoderTests.cs @@ -2,6 +2,7 @@ // Licensed under the Six Labors Split License. using SixLabors.ImageSharp.Formats.Webp.Lossless; +using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Tests.TestUtilities; @@ -87,10 +88,20 @@ private static void RunColorSpaceTransformTestWithPeakImage() int transformWidth = LosslessUtils.SubSampleSize(image.Width, colorTransformBits); int transformHeight = LosslessUtils.SubSampleSize(image.Height, colorTransformBits); uint[] transformData = new uint[transformWidth * transformHeight]; - int[] scratch = new int[256]; + int[] histograms = new int[3 * 256]; // act - PredictorEncoder.ColorSpaceTransform(image.Width, image.Height, colorTransformBits, 75, bgra, transformData, scratch); + using Buffer2D bgraPlane = Buffer2D.WrapMemory(bgra, image.Width, image.Height); + using Buffer2D transformPlane = Buffer2D.WrapMemory(transformData, transformWidth, transformHeight); + PredictorEncoder.ColorSpaceTransform( + Configuration.Default.MemoryAllocator, + image.Width, + image.Height, + colorTransformBits, + 75, + bgraPlane, + transformPlane, + histograms); // assert Assert.Equal(expectedData, transformData); @@ -117,10 +128,20 @@ private static void RunColorSpaceTransformTestWithBikeImage() int transformWidth = LosslessUtils.SubSampleSize(image.Width, colorTransformBits); int transformHeight = LosslessUtils.SubSampleSize(image.Height, colorTransformBits); uint[] transformData = new uint[transformWidth * transformHeight]; - int[] scratch = new int[256]; + int[] histograms = new int[3 * 256]; // act - PredictorEncoder.ColorSpaceTransform(image.Width, image.Height, colorTransformBits, 75, bgra, transformData, scratch); + using Buffer2D bgraPlane = Buffer2D.WrapMemory(bgra, image.Width, image.Height); + using Buffer2D transformPlane = Buffer2D.WrapMemory(transformData, transformWidth, transformHeight); + PredictorEncoder.ColorSpaceTransform( + Configuration.Default.MemoryAllocator, + image.Width, + image.Height, + colorTransformBits, + 75, + bgraPlane, + transformPlane, + histograms); // assert Assert.Equal(expectedData, transformData); diff --git a/tests/ImageSharp.Tests/Formats/WebP/Vp8BitWriterTests.cs b/tests/ImageSharp.Tests/Formats/WebP/Vp8BitWriterTests.cs index 4bd5eeae0a..53568f2e72 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/Vp8BitWriterTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/Vp8BitWriterTests.cs @@ -1,6 +1,9 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Webp; using SixLabors.ImageSharp.Formats.Webp.BitWriter; using SixLabors.ImageSharp.Formats.Webp.Lossy; @@ -14,13 +17,13 @@ public class Vp8BitWriterTests public void BitWriterResize_WithinCapacity_DoesNotReallocate() { using Vp8Encoder encoder = CreateEncoder(); - Vp8BitWriter writer = new(4096, encoder); - byte[] buffer = writer.Buffer; + using Vp8BitWriter writer = new(Configuration.Default.MemoryAllocator, 4096, encoder); + ref byte buffer = ref MemoryMarshal.GetReference(writer.Buffer); writer.BitWriterResize(1); writer.BitWriterResize(4096); - Assert.Same(buffer, writer.Buffer); + Assert.True(Unsafe.AreSame(ref buffer, ref MemoryMarshal.GetReference(writer.Buffer))); Assert.Equal(4096, writer.Buffer.Length); } @@ -29,20 +32,20 @@ public void BitWriterResize_GrowsBufferGeometrically() { const int targetBytes = 256 * 1024; using Vp8Encoder encoder = CreateEncoder(); - Vp8BitWriter writer = new(1024, encoder); + using Vp8BitWriter writer = new(Configuration.Default.MemoryAllocator, 1024, encoder); Random random = new(42); - byte[] buffer = writer.Buffer; + int capacity = writer.Buffer.Length; int reallocations = 0; - // Emit pseudo-random modes until the partition holds at least targetBytes, counting how often - // the backing buffer is replaced. + // Emit pseudo-random modes until the partition holds at least targetBytes. The buffer is not pinned, so its address + // can move. A reallocation is the only change of the capacity, so count the capacity changes. while (writer.NumBytes < targetBytes) { writer.PutUvMode(random.Next(4)); - if (!ReferenceEquals(buffer, writer.Buffer)) + if (writer.Buffer.Length != capacity) { reallocations++; - buffer = writer.Buffer; + capacity = writer.Buffer.Length; } } @@ -67,5 +70,6 @@ private static Vp8Encoder CreateEncoder() 1, 60, 50, - false); + false, + TransparentColorMode.Clear); } diff --git a/tests/ImageSharp.Tests/Formats/WebP/Vp8EncodingTests.cs b/tests/ImageSharp.Tests/Formats/WebP/Vp8EncodingTests.cs index f787a38649..29a16f44bc 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/Vp8EncodingTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/Vp8EncodingTests.cs @@ -29,13 +29,15 @@ private static void RunFTransform2Test() 129, 129, 129, 129, 129, 129, 129, 129, 129, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129 ]; + short[] actualOutput1 = new short[16]; short[] actualOutput2 = new short[16]; short[] expectedOutput1 = [182, 4, 1, 1, 6, 7, -1, -4, 5, 0, -2, 1, 2, 1, 1, 1]; short[] expectedOutput2 = [192, -34, 10, 1, -11, 8, 10, -7, 6, 3, -8, 4, 5, -3, -2, 6]; + int[] scratch = new int[16]; // act - Vp8Encoding.FTransform2(src, reference, actualOutput1, actualOutput2, new int[16]); + Vp8Encoding.FTransform2(ref src[0], ref reference[0], ref actualOutput1[0], ref actualOutput2[0], ref scratch[0]); // assert Assert.True(expectedOutput1.SequenceEqual(actualOutput1)); @@ -55,6 +57,7 @@ private static void RunFTransformTest() 148, 151, 160, 159, 157, 157, 148, 133, 96, 90, 103, 107, 104, 104, 101, 100, 102, 102, 121, 117, 170, 170, 169, 171, 171, 179, 173, 175 ]; + byte[] reference = [ 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 129, 129, 129, 129, @@ -65,11 +68,13 @@ private static void RunFTransformTest() 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129 ]; + short[] actualOutput = new short[16]; short[] expectedOutput = [182, 4, 1, 1, 6, 7, -1, -4, 5, 0, -2, 1, 2, 1, 1, 1]; + int[] scratch = new int[16]; // act - Vp8Encoding.FTransform(src, reference, actualOutput, new int[16]); + Vp8Encoding.FTransform(ref src[0], ref reference[0], ref actualOutput[0], ref scratch[0]); // assert Assert.True(expectedOutput.SequenceEqual(actualOutput)); @@ -88,8 +93,10 @@ private static void RunOneInverseTransformTest() 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129 ]; + short[] input = [1, 216, -48, 0, 96, -24, -48, 24, 0, -24, 24, 0, 0, 0, 0, 0, 38, -240, -72, -24, 0, -24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; + byte[] dst = new byte[128]; byte[] expected = [ @@ -99,10 +106,11 @@ private static void RunOneInverseTransformTest() 0, 0, 0, 152, 128, 87, 83, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; + int[] scratch = new int[16]; // act - Vp8Encoding.ITransformOne(reference, input, dst, scratch); + Vp8Encoding.ITransformOne(ref reference[0], ref input[0], ref dst[0], ref scratch[0]); // assert Assert.True(dst.SequenceEqual(expected)); @@ -121,8 +129,10 @@ private static void RunTwoInverseTransformTest() 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129 ]; + short[] input = [1, 216, -48, 0, 96, -24, -48, 24, 0, -24, 24, 0, 0, 0, 0, 0, 38, -240, -72, -24, 0, -24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; + byte[] dst = new byte[128]; byte[] expected = [ @@ -132,10 +142,11 @@ private static void RunTwoInverseTransformTest() 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 152, 128, 87, 83, 88, 132, 152, 159, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; + int[] scratch = new int[16]; // act - Vp8Encoding.ITransformTwo(reference, input, dst, scratch); + Vp8Encoding.ITransformTwo(ref reference[0], ref input[0], ref dst[0], ref scratch[0]); // assert Assert.True(dst.SequenceEqual(expected)); diff --git a/tests/ImageSharp.Tests/Formats/WebP/Vp8LHistogramTests.cs b/tests/ImageSharp.Tests/Formats/WebP/Vp8LHistogramTests.cs index 8d8bcb57c3..22f7fd67f9 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/Vp8LHistogramTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/Vp8LHistogramTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +using SixLabors.ImageSharp.Formats.Webp; using SixLabors.ImageSharp.Formats.Webp.Lossless; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.Tests.TestUtilities; @@ -61,19 +62,29 @@ private static void RunAddVectorTest() 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 6, 0, 2, 0, 2, 0, 2, 0, 0, 0, 8, 0, 2, 0, 38, 0, 4 ]; - uint[] expectedLiterals = new uint[1305]; + uint[] expectedLiterals = new uint[WebpConstants.NumLiteralCodes + WebpConstants.NumLengthCodes + (1 << 3)]; // All remaining values are expected to be zero. literals.AsSpan().CopyTo(expectedLiterals); MemoryAllocator memoryAllocator = Configuration.Default.MemoryAllocator; - using Vp8LBackwardRefs backwardRefs = new(memoryAllocator, pixelData.Length); + using Vp8LBackwardReferences backwardRefs = new(memoryAllocator, pixelData.Length); + Span tokens = backwardRefs.BeginWrite(); + int tokenCount = 0; for (int i = 0; i < pixelData.Length; i++) { - backwardRefs.Add(PixOrCopy.CreateLiteral(pixelData[i])); + if (tokenCount == tokens.Length) + { + tokens = backwardRefs.NextBlock(); + tokenCount = 0; + } + + tokens[tokenCount++] = PixelOrCopy.CreateLiteral(pixelData[i]); } + backwardRefs.EndWrite(tokenCount); + using OwnedVp8LHistogram histogram0 = OwnedVp8LHistogram.Create(memoryAllocator, backwardRefs, 3); using OwnedVp8LHistogram histogram1 = OwnedVp8LHistogram.Create(memoryAllocator, backwardRefs, 3); for (int i = 0; i < 5; i++) diff --git a/tests/ImageSharp.Tests/Formats/WebP/QuantEncTests.cs b/tests/ImageSharp.Tests/Formats/WebP/Vp8QuantizationTests.cs similarity index 94% rename from tests/ImageSharp.Tests/Formats/WebP/QuantEncTests.cs rename to tests/ImageSharp.Tests/Formats/WebP/Vp8QuantizationTests.cs index 1ca07bc0ac..28313afae3 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/QuantEncTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/Vp8QuantizationTests.cs @@ -7,7 +7,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Webp; [Trait("Format", "Webp")] -public class QuantEncTests +public class Vp8QuantizationTests { private static unsafe void RunQuantizeBlockTest() { @@ -18,6 +18,7 @@ private static unsafe void RunQuantizeBlockTest() ushort[] iq = [3120, 3542, 3542, 3542, 3542, 3542, 3542, 3542, 3542, 3542, 3542, 3542, 3542, 3542, 3542, 3542]; uint[] bias = [49152, 55296, 55296, 55296, 55296, 55296, 55296, 55296, 55296, 55296, 55296, 55296, 55296, 55296, 55296, 55296 ]; + uint[] zthresh = [26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21]; short[] expectedOutput = [9, 21, 7, -5, 4, -23, 24, 0, -5, 4, 2, -2, -3, -1, 3, 2]; int expectedResult = 1; @@ -31,7 +32,7 @@ private static unsafe void RunQuantizeBlockTest() } // act - int actualResult = QuantEnc.QuantizeBlock(input, output, ref vp8Matrix); + int actualResult = Vp8Quantization.QuantizeBlock(ref input[0], ref output[0], ref vp8Matrix); // assert Assert.True(output.SequenceEqual(expectedOutput)); @@ -58,7 +59,7 @@ private static void RunQuantizeBlockWithSharpeningTest() vp8Matrix.Expand(0); // act - int actualResult = QuantEnc.QuantizeBlock(input, output, ref vp8Matrix); + int actualResult = Vp8Quantization.QuantizeBlock(ref input[0], ref output[0], ref vp8Matrix); // assert Assert.Equal(expectedOutput, output); diff --git a/tests/ImageSharp.Tests/Formats/WebP/Vp8ResidualTests.cs b/tests/ImageSharp.Tests/Formats/WebP/Vp8ResidualTests.cs index 2a0821108a..9de330c626 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/Vp8ResidualTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/Vp8ResidualTests.cs @@ -11,229 +11,74 @@ namespace SixLabors.ImageSharp.Tests.Formats.Webp; [Trait("Format", "Webp")] public class Vp8ResidualTests { - private static void WriteVp8Residual(string filename, Vp8Residual residual) - { - using FileStream stream = File.Open(filename, FileMode.Create); - using BinaryWriter writer = new(stream, Encoding.UTF8, false); - - writer.Write(residual.First); - writer.Write(residual.Last); - writer.Write(residual.CoeffType); - - for (int i = 0; i < residual.Coeffs.Length; i++) - { - writer.Write(residual.Coeffs[i]); - } - - for (int i = 0; i < residual.Prob.Length; i++) - { - for (int j = 0; j < residual.Prob[i].Probabilities.Length; j++) - { - writer.Write(residual.Prob[i].Probabilities[j].Probabilities); - } - } - - for (int i = 0; i < residual.Costs.Length; i++) - { - Vp8Costs costs = residual.Costs[i]; - Vp8CostArray[] costsArray = costs.Costs; - for (int j = 0; j < costsArray.Length; j++) - { - for (int k = 0; k < costsArray[j].Costs.Length; k++) - { - writer.Write(costsArray[j].Costs[k]); - } - } - } - - for (int i = 0; i < residual.Stats.Length; i++) - { - for (int j = 0; j < residual.Stats[i].Stats.Length; j++) - { - for (int k = 0; k < residual.Stats[i].Stats[j].Stats.Length; k++) - { - writer.Write(residual.Stats[i].Stats[j].Stats[k]); - } - } - } - - writer.Flush(); - } - - private static Vp8Residual ReadVp8Residual(string fileName) + /// + /// Reads a residual dump. The dump holds first, last and coefficient type (3 x int32), 16 coefficients (int16), + /// the probabilities of 8 bands x 3 contexts x 11 probabilities (byte), the level costs of 16 positions x 3 contexts + /// x 68 levels (uint16), and the statistics of 8 bands x 3 contexts x 11 probabilities (uint32). + /// The level costs of the dump are the band tables repeated for each position. + /// + private static Vp8Residual ReadVp8Residual(string fileName, out short[] coeffs) { using FileStream stream = File.Open(fileName, FileMode.Open); using BinaryReader reader = new(stream, Encoding.UTF8, false); - Vp8Residual residual = new() - { - First = reader.ReadInt32(), - Last = reader.ReadInt32(), - CoeffType = reader.ReadInt32() - }; + int first = reader.ReadInt32(); + _ = reader.ReadInt32(); // last: GetResidualCost sets it from the coefficients. + int coeffType = reader.ReadInt32(); - for (int i = 0; i < residual.Coeffs.Length; i++) + coeffs = new short[16]; + for (int i = 0; i < coeffs.Length; i++) { - residual.Coeffs[i] = reader.ReadInt16(); + coeffs[i] = reader.ReadInt16(); } - Vp8BandProbas[] bandProbas = new Vp8BandProbas[8]; - for (int i = 0; i < bandProbas.Length; i++) + Vp8EncoderProbabilities proba = new(); + int probaOffset = coeffType * Vp8EncoderProbabilities.ProbasPerType; + for (int i = 0; i < Vp8EncoderProbabilities.ProbasPerType; i++) { - bandProbas[i] = new Vp8BandProbas(); - for (int j = 0; j < bandProbas[i].Probabilities.Length; j++) - { - for (int k = 0; k < 11; k++) - { - bandProbas[i].Probabilities[j].Probabilities[k] = reader.ReadByte(); - } - } + proba.Coeffs[probaOffset + i] = reader.ReadByte(); } - residual.Prob = bandProbas; - - residual.Costs = new Vp8Costs[16]; - for (int i = 0; i < residual.Costs.Length; i++) + int costOffset = coeffType * Vp8EncoderProbabilities.CostsPerType; + for (int n = 0; n < 16; n++) { - residual.Costs[i] = new Vp8Costs(); - Vp8CostArray[] costsArray = residual.Costs[i].Costs; - for (int j = 0; j < costsArray.Length; j++) + int band = WebpConstants.Vp8EncBands[n]; + for (int ctx = 0; ctx < WebpConstants.NumCtx; ctx++) { - for (int k = 0; k < costsArray[j].Costs.Length; k++) + int tableOffset = costOffset + (((band * WebpConstants.NumCtx) + ctx) * Vp8EncoderProbabilities.CostsPerContext); + for (int k = 0; k < Vp8EncoderProbabilities.CostsPerContext; k++) { - costsArray[j].Costs[k] = reader.ReadUInt16(); - } - } - } - - residual.Stats = new Vp8Stats[8]; - for (int i = 0; i < residual.Stats.Length; i++) - { - residual.Stats[i] = new Vp8Stats(); - for (int j = 0; j < residual.Stats[i].Stats.Length; j++) - { - for (int k = 0; k < residual.Stats[i].Stats[j].Stats.Length; k++) - { - residual.Stats[i].Stats[j].Stats[k] = reader.ReadUInt32(); + proba.LevelCost[tableOffset + k] = reader.ReadUInt16(); } } } + Vp8Residual residual = new(); + residual.Init(first, coeffType, proba); return residual; } - [Fact] - public void Vp8Residual_Serialization_Works() - { - // arrange - Vp8Residual expected = new(); - Vp8EncProba encProb = new(); - Random rand = new(439); - CreateRandomProbas(encProb, rand); - CreateCosts(encProb, rand); - expected.Init(1, 0, encProb); - for (int i = 0; i < expected.Coeffs.Length; i++) - { - expected.Coeffs[i] = (byte)rand.Next(255); - } - - // act - string fileName = "Vp8SerializationTest.bin"; - WriteVp8Residual(fileName, expected); - Vp8Residual actual = ReadVp8Residual(fileName); - File.Delete(fileName); - - // assert - Assert.Equal(expected.CoeffType, actual.CoeffType); - Assert.Equal(expected.Coeffs, actual.Coeffs); - Assert.Equal(expected.Costs.Length, actual.Costs.Length); - Assert.Equal(expected.First, actual.First); - Assert.Equal(expected.Last, actual.Last); - Assert.Equal(expected.Stats.Length, actual.Stats.Length); - for (int i = 0; i < expected.Stats.Length; i++) - { - Vp8StatsArray[] expectedStats = expected.Stats[i].Stats; - Vp8StatsArray[] actualStats = actual.Stats[i].Stats; - Assert.Equal(expectedStats.Length, actualStats.Length); - for (int j = 0; j < expectedStats.Length; j++) - { - Assert.Equal(expectedStats[j].Stats, actualStats[j].Stats); - } - } - - Assert.Equal(expected.Prob.Length, actual.Prob.Length); - for (int i = 0; i < expected.Prob.Length; i++) - { - Vp8ProbaArray[] expectedProbabilities = expected.Prob[i].Probabilities; - Vp8ProbaArray[] actualProbabilities = actual.Prob[i].Probabilities; - Assert.Equal(expectedProbabilities.Length, actualProbabilities.Length); - for (int j = 0; j < expectedProbabilities.Length; j++) - { - Assert.Equal(expectedProbabilities[j].Probabilities, actualProbabilities[j].Probabilities); - } - } - - for (int i = 0; i < expected.Costs.Length; i++) - { - Vp8CostArray[] expectedCosts = expected.Costs[i].Costs; - Vp8CostArray[] actualCosts = actual.Costs[i].Costs; - Assert.Equal(expectedCosts.Length, actualCosts.Length); - for (int j = 0; j < expectedCosts.Length; j++) - { - Assert.Equal(expectedCosts[j].Costs, actualCosts[j].Costs); - } - } - } - - [Fact] - public void GetResidualCost_Works() + private static void RunGetResidualCostTest() { // arrange int ctx0 = 0; int expected = 20911; - Vp8Residual residual = ReadVp8Residual(Path.Combine("TestDataWebp", "Vp8Residual.bin")); + Vp8Residual residual = ReadVp8Residual(Path.Combine("TestDataWebp", "Vp8Residual.bin"), out short[] coeffs); // act - int actual = residual.GetResidualCost(ctx0); + int actual = residual.GetResidualCost(ctx0, ref coeffs[0]); // assert Assert.Equal(expected, actual); + Assert.Equal(15, residual.Last); } - private static void CreateRandomProbas(Vp8EncProba probas, Random rand) - { - for (int t = 0; t < WebpConstants.NumTypes; ++t) - { - for (int b = 0; b < WebpConstants.NumBands; ++b) - { - for (int c = 0; c < WebpConstants.NumCtx; ++c) - { - for (int p = 0; p < WebpConstants.NumProbas; ++p) - { - probas.Coeffs[t][b].Probabilities[c].Probabilities[p] = (byte)rand.Next(255); - } - } - } - } - } + [Fact] + public void GetResidualCost_Works() => FeatureTestRunner.RunWithHwIntrinsicsFeature(RunGetResidualCostTest, HwIntrinsics.AllowAll); - private static void CreateCosts(Vp8EncProba probas, Random rand) - { - for (int i = 0; i < probas.RemappedCosts.Length; i++) - { - for (int j = 0; j < probas.RemappedCosts[i].Length; j++) - { - for (int k = 0; k < probas.RemappedCosts[i][j].Costs.Length; k++) - { - ushort[] costs = probas.RemappedCosts[i][j].Costs[k].Costs; - for (int m = 0; m < costs.Length; m++) - { - costs[m] = (byte)rand.Next(255); - } - } - } - } - } + [Fact] + public void GetResidualCost_WithoutHwIntrinsics_Works() + => FeatureTestRunner.RunWithHwIntrinsicsFeature(RunGetResidualCostTest, HwIntrinsics.DisableHWIntrinsic); private static void RunSetCoeffsTest() { diff --git a/tests/ImageSharp.Tests/Formats/WebP/WebpDecoderTests.cs b/tests/ImageSharp.Tests/Formats/WebP/WebpDecoderTests.cs index 1310b972f6..0a59e5ae87 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/WebpDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/WebpDecoderTests.cs @@ -3,6 +3,7 @@ using System.Buffers.Binary; using System.Runtime.Intrinsics.X86; +using Microsoft.DotNet.RemoteExecutor; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.Formats.Webp; @@ -187,6 +188,16 @@ public void WebpDecoder_CanDecode_Lossy_WithAlpha(TestImageProvider(TestImageProvider provider) + where TPixel : unmanaged, IPixel + { + using Image image = provider.GetImage(WebpDecoder.Instance); + image.CompareToOriginal(provider, ImageComparer.Exact, ReferenceDecoder); + } + /// /// Compares lossy decoding with uncompressed alpha against the reference decoder across hardware configurations. /// @@ -290,6 +301,35 @@ public void WebpDecoder_CanDecode_Lossless_WithCrossColorTransform(TestI image.CompareToOriginal(provider, ReferenceDecoder); } + // The decoded pixels are in pooled buffers of whole rows. A small buffer capacity makes many buffers, so backward references and color cache fills + // cross buffer boundaries. + [Theory] + [WithFile(Lossless.Earth, PixelTypes.Rgba32)] + [WithFile(Lossless.BikeThreeTransforms, PixelTypes.Rgba32)] + [WithFile(Lossless.ThreeTransforms1, PixelTypes.Rgba32)] + [WithFile(Lossless.TwoTransforms4, PixelTypes.Rgba32)] + [WithFile(Lossless.Alpha, PixelTypes.Rgba32)] + public void WebpDecoder_CanDecode_Lossless_WithLimitedAllocatorBufferCapacity(TestImageProvider provider) + { + static void RunTest(string providerDump, string nonContiguousBuffersStr) + { + TestImageProvider provider = BasicSerializer.Deserialize>(providerDump); + + provider.LimitAllocatorBufferCapacity().InPixelsSqrt(100); + + using Image image = provider.GetImage(WebpDecoder.Instance); + image.DebugSave(provider, testOutputDetails: nonContiguousBuffersStr); + image.CompareToOriginal(provider, ReferenceDecoder); + } + + string providerDump = BasicSerializer.Serialize(provider); + RemoteExecutor.Invoke( + RunTest, + providerDump, + "Disco") + .Dispose(); + } + [Theory] [WithFile(Lossless.TwoTransforms1, PixelTypes.Rgba32)] [WithFile(Lossless.TwoTransforms2, PixelTypes.Rgba32)] @@ -415,6 +455,7 @@ public void Decode_AnimatedLossy_IgnoreBackgroundColor_Works(TestImagePr { BackgroundColorHandling = BackgroundColorHandling.Ignore }; + using Image image = provider.GetImage(WebpDecoder.Instance, options); image.DebugSave(provider); image.CompareToOriginal(provider, ReferenceDecoder); diff --git a/tests/ImageSharp.Tests/Formats/WebP/WebpEncoderTests.cs b/tests/ImageSharp.Tests/Formats/WebP/WebpEncoderTests.cs index 86763169e3..248e3ade1d 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/WebpEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/WebpEncoderTests.cs @@ -373,6 +373,57 @@ public void Encode_Lossless_WithPalette_Works(TestImageProvider image.VerifyEncoder(provider, "webp", string.Empty, encoder); } + [Theory] + [WithFile(TestImages.Bmp.Car, PixelTypes.Rgba32, WebpFileFormatType.Lossless, WebpEncodingMethod.Default, 75, false)] + [WithFile(TestImages.Bmp.Car, PixelTypes.Rgba32, WebpFileFormatType.Lossless, WebpEncodingMethod.BestQuality, 100, false)] + [WithFile(TestImages.Bmp.Car, PixelTypes.Rgba32, WebpFileFormatType.Lossless, WebpEncodingMethod.Default, 75, true)] + [WithFile(TestImages.Webp.Flag, PixelTypes.Rgba32, WebpFileFormatType.Lossless, WebpEncodingMethod.BestQuality, 100, false)] + [WithFile(Lossless.ThreeTransforms1, PixelTypes.Rgba32, WebpFileFormatType.Lossless, WebpEncodingMethod.Default, 75, false)] + [WithFile(Lossless.TwoTransforms4, PixelTypes.Rgba32, WebpFileFormatType.Lossless, WebpEncodingMethod.BestQuality, 100, false)] + [WithFile(Lossy.Alpha1, PixelTypes.Rgba32, WebpFileFormatType.Lossy, WebpEncodingMethod.Default, 75, false)] + [WithFile(TestImages.Bmp.Car, PixelTypes.Rgba32, WebpFileFormatType.Lossy, WebpEncodingMethod.BestQuality, 75, false)] + public void Encode_WorksWithDiscontiguousBuffers( + TestImageProvider provider, + WebpFileFormatType fileFormat, + WebpEncodingMethod method, + int quality, + bool nearLossless) + where TPixel : unmanaged, IPixel + { + // The encoder reads its pixel planes by flat position. The output must not depend on where the allocator splits a plane into + // buffers, so an encode with small buffers must give the same bytes as an encode with one buffer for each plane. + WebpEncoder encoder = new() + { + FileFormat = fileFormat, + Method = method, + Quality = quality, + NearLossless = nearLossless, + NearLosslessQuality = nearLossless ? 60 : 100 + }; + + using MemoryStream contiguous = new(); + using (Image image = provider.GetImage()) + { + image.SaveAsWebp(contiguous, encoder); + } + + // 100 x 100 bytes holds a few rows of these images in each buffer, so each plane has many buffer ends. + provider.LimitAllocatorBufferCapacity().InBytesSqrt(100); + using MemoryStream discontiguous = new(); + using Image source = provider.GetImage(); + source.SaveAsWebp(discontiguous, encoder); + + Assert.Equal(contiguous.ToArray(), discontiguous.ToArray()); + + // A lossless encode without the near-lossless step must decode to the source pixels. + if (fileFormat == WebpFileFormatType.Lossless && !nearLossless) + { + discontiguous.Position = 0; + using Image decoded = Image.Load(discontiguous); + ImageComparer.Exact.VerifySimilarity(source, decoded); + } + } + [Theory] [WithFile(TestImages.Bmp.Car, PixelTypes.Rgba32, 100)] [WithFile(TestImages.Bmp.Car, PixelTypes.Rgba32, 80)] @@ -693,8 +744,46 @@ public void WebpDecoder_CanDecode_Issue2801(TestImageProvider pr Quality = 100 }; + // The default transparent color mode is Clear, so the encoded image has zero RGB in each pixel with zero alpha. + // The reference is the source with the same pixels cleared. using Image image = provider.GetImage(); - image.VerifyEncoder(provider, "webp", string.Empty, encoder, ImageComparer.TolerantPercentage(0.0994F)); + using Image expected = image.Clone(); + EncodingUtilities.ReplaceTransparentPixels(expected.Frames.RootFrame); + + using MemoryStream stream = new(); + image.Save(stream, encoder); + stream.Position = 0; + using Image actual = Image.Load(stream); + + ImageComparer.TolerantPercentage(0.0994F).VerifySimilarity(expected, actual); + } + + [Theory] + [WithFile(Lossy.Issue2801, PixelTypes.Rgba32)] + public void Encode_Lossy_WithClearTransparentColor_EncodesClearedPixels(TestImageProvider provider) + where TPixel : unmanaged, IPixel + { + using Image source = provider.GetImage(); + using Image unchanged = source.Clone(); + + // Clear a copy through the existing pixel API. Encoding it with Preserve defines the expected Clear output. + using Image expected = source.Clone(); + EncodingUtilities.ReplaceTransparentPixels(expected.Frames.RootFrame); + + using MemoryStream reference = new(); + expected.Save(reference, new WebpEncoder { FileFormat = WebpFileFormatType.Lossy, TransparentColorMode = TransparentColorMode.Preserve }); + reference.Position = 0; + using Image expectedPixels = Image.Load(reference); + + using MemoryStream encoded = new(); + source.Save(encoded, new WebpEncoder { FileFormat = WebpFileFormatType.Lossy, TransparentColorMode = TransparentColorMode.Clear }); + encoded.Position = 0; + using Image actual = Image.Load(encoded); + + ImageComparer.Exact.VerifySimilarity(expectedPixels, actual); + + // The encoder clears a staged copy of each row. The source pixels do not change. + ImageComparer.Exact.VerifySimilarity(unchanged, source); } public static void RunEncodeLossy_WithPeakImage() diff --git a/tests/ImageSharp.Tests/Formats/WebP/YuvConversionTests.cs b/tests/ImageSharp.Tests/Formats/WebP/YuvConversionTests.cs index 4f2bf05639..f4d692c087 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/YuvConversionTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/YuvConversionTests.cs @@ -1,8 +1,9 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +using System.Buffers; using SixLabors.ImageSharp.Formats.Webp; -using SixLabors.ImageSharp.Formats.Webp.ColorConverters; +using SixLabors.ImageSharp.Formats.Webp.Lossy; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Tests.TestUtilities; @@ -128,6 +129,7 @@ private static void AssertRgbToYuv(string providerDump) 115, 117, 123, 90, 71, 76, 79, 62, 51, 51, 47, 59, 79, 75, 74, 81, 100, 97, 98, 98, 100, 100, 100, 100 ]; + byte[] expectedU = [ 90, 90, 59, 63, 36, 38, 23, 20, 34, 35, 47, 48, 70, 82, 104, 121, 121, 90, 90, 61, 69, 37, 42, 22, @@ -145,6 +147,7 @@ private static void AssertRgbToYuv(string providerDump) 232, 237, 223, 222, 211, 208, 185, 173, 172, 121, 120, 164, 166, 193, 194, 217, 219, 232, 235, 224, 220, 212, 207, 188, 172, 172 ]; + byte[] expectedV = [ 240, 240, 201, 206, 172, 174, 136, 136, 92, 90, 55, 50, 37, 30, 26, 23, 23, 240, 240, 204, 213, 173, @@ -163,8 +166,13 @@ private static void AssertRgbToYuv(string providerDump) ]; // act - WebpColorConverterBase converter = WebpColorConverterBase.GetConverter(WebpColorType.Yuv); - converter.ConvertFromRgb(image.Frames.RootFrame.PixelBuffer.GetRegion(), config, memoryAllocator, null, [], [], y, u, v); + // The converter writes plane rows. The planes wrap the buffers with tight rows, so the buffers hold the samples in scan order. + int uvHeight = (image.Height + 1) >> 1; + using Buffer2D yPlane = Buffer2D.WrapMemory(yBuffer.Memory[..pixels], image.Width, image.Height); + using Buffer2D uPlane = Buffer2D.WrapMemory(uBuffer.Memory[..(uvWidth * uvHeight)], uvWidth, uvHeight); + using Buffer2D vPlane = Buffer2D.WrapMemory(vBuffer.Memory[..(uvWidth * uvHeight)], uvWidth, uvHeight); + RgbToYuvConverter converter = new(config, memoryAllocator, null, false); + using Buffer2D alpha = converter.Convert(image.Frames.RootFrame.PixelBuffer.GetRegion(), [], yPlane, uPlane, vPlane); // assert Assert.True(expectedY.AsSpan().SequenceEqual(y)); @@ -251,6 +259,7 @@ private static void AssertRgbToYuvWithAlpha(string providerDump) 116, 103, 180, 63, 140, 152, 75, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 93, 171, 53, 131, 118, 66, 78, 155, 103, 90, 167, 50, 128, 140, 63, 75 ]; + byte[] expectedU = [ 128, 128, 128, 128, 128, 128, 128, 139, 240, 139, 240, 139, 240, 139, 240, 139, 128, 128, 128, 128, @@ -267,6 +276,7 @@ private static void AssertRgbToYuvWithAlpha(string providerDump) 240, 240, 240, 137, 110, 162, 110, 140, 158, 104, 159, 137, 240, 240, 240, 240, 240, 240, 240, 109, 150, 108, 140, 161, 80, 157, 162, 128 ]; + byte[] expectedV = [ 128, 128, 128, 128, 128, 128, 128, 189, 110, 189, 110, 189, 110, 189, 110, 189, 128, 128, 128, 128, @@ -285,8 +295,13 @@ private static void AssertRgbToYuvWithAlpha(string providerDump) ]; // act - WebpColorConverterBase converter = WebpColorConverterBase.GetConverter(WebpColorType.Yuv); - converter.ConvertFromRgb(image.Frames.RootFrame.PixelBuffer.GetRegion(), config, memoryAllocator, null, [], [], y, u, v); + // The converter writes plane rows. The planes wrap the buffers with tight rows, so the buffers hold the samples in scan order. + int uvHeight = (image.Height + 1) >> 1; + using Buffer2D yPlane = Buffer2D.WrapMemory(yBuffer.Memory[..pixels], image.Width, image.Height); + using Buffer2D uPlane = Buffer2D.WrapMemory(uBuffer.Memory[..(uvWidth * uvHeight)], uvWidth, uvHeight); + using Buffer2D vPlane = Buffer2D.WrapMemory(vBuffer.Memory[..(uvWidth * uvHeight)], uvWidth, uvHeight); + RgbToYuvConverter converter = new(config, memoryAllocator, null, false); + using Buffer2D alpha = converter.Convert(image.Frames.RootFrame.PixelBuffer.GetRegion(), [], yPlane, uPlane, vPlane); // assert Assert.True(expectedY.AsSpan().SequenceEqual(y)); diff --git a/tests/ImageSharp.Tests/PixelFormats/AssociatedAlphaPixelTests.cs b/tests/ImageSharp.Tests/PixelFormats/AssociatedAlphaPixelTests.cs index 19033df3ed..4785460373 100644 --- a/tests/ImageSharp.Tests/PixelFormats/AssociatedAlphaPixelTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/AssociatedAlphaPixelTests.cs @@ -1015,7 +1015,8 @@ public void Rgba32PToRgba32ScalarRoundTripPreservesEveryLosslesslyRoundTrippable for (int associated = 0; associated <= alpha; associated++) { // This integer expression is the exact nearest 8-bit unassociated value for associated * 255 / alpha. - byte unassociated = alpha == 0 ? (byte)0 : (byte)(((associated * byte.MaxValue) + (alpha / 2)) / alpha); + // A midpoint rounds to the even value, as the byte packers do. + byte unassociated = alpha == 0 ? (byte)0 : (byte)DivideRoundToEven(associated * byte.MaxValue, alpha); Rgba32P source = new((byte)associated, 0, 0, (byte)alpha); Rgba32 expectedUnassociated = new(unassociated, 0, 0, (byte)alpha); @@ -1040,7 +1041,7 @@ public void ColorFromRgba32PPreservesEveryLosslesslyRoundTrippableAssociatedComp { for (int associated = 0; associated <= alpha; associated++) { - byte unassociated = alpha == 0 ? (byte)0 : (byte)(((associated * byte.MaxValue) + (alpha / 2)) / alpha); + byte unassociated = alpha == 0 ? (byte)0 : (byte)DivideRoundToEven(associated * byte.MaxValue, alpha); Rgba32P source = new((byte)associated, 0, 0, (byte)alpha); Color color = Color.FromPixel(source); sourcePixels[index++] = source; @@ -1081,8 +1082,8 @@ public void NormalizedByte4PToRgba32ScalarRoundTripPreservesEveryLosslesslyRound { for (int associated = 0; associated <= alpha; associated++) { - byte unassociated = alpha == 0 ? (byte)0 : (byte)(((associated * byte.MaxValue) + (alpha / 2)) / alpha); - byte unassociatedAlpha = (byte)(((alpha * byte.MaxValue) + 127) / 254); + byte unassociated = alpha == 0 ? (byte)0 : (byte)DivideRoundToEven(associated * byte.MaxValue, alpha); + byte unassociatedAlpha = (byte)DivideRoundToEven(alpha * byte.MaxValue, 254); NormalizedByte4P source = CreateNormalizedByte4P(associated, 0, 0, alpha); Rgba32 actualUnassociated = source.ToRgba32(); @@ -1106,8 +1107,8 @@ public void ColorFromNormalizedByte4PPreservesEveryLosslesslyRoundTrippableAssoc { for (int associated = 0; associated <= alpha; associated++) { - byte unassociated = alpha == 0 ? (byte)0 : (byte)(((associated * byte.MaxValue) + (alpha / 2)) / alpha); - byte unassociatedAlpha = (byte)(((alpha * byte.MaxValue) + 127) / 254); + byte unassociated = alpha == 0 ? (byte)0 : (byte)DivideRoundToEven(associated * byte.MaxValue, alpha); + byte unassociatedAlpha = (byte)DivideRoundToEven(alpha * byte.MaxValue, 254); NormalizedByte4P source = CreateNormalizedByte4P(associated, 0, 0, alpha); Color color = Color.FromPixel(source); sourcePixels[index++] = source; @@ -1140,8 +1141,8 @@ public void NormalizedByte4PToBgra32RoundTripPreservesEveryLosslesslyRoundTrippa { for (int associated = 0; associated <= alpha; associated++) { - byte unassociated = alpha == 0 ? (byte)0 : (byte)(((associated * byte.MaxValue) + (alpha / 2)) / alpha); - byte unassociatedAlpha = (byte)(((alpha * byte.MaxValue) + 127) / 254); + byte unassociated = alpha == 0 ? (byte)0 : (byte)DivideRoundToEven(associated * byte.MaxValue, alpha); + byte unassociatedAlpha = (byte)DivideRoundToEven(alpha * byte.MaxValue, 254); source[index] = CreateNormalizedByte4P(associated, 0, 0, alpha); expectedUnassociated[index++] = new Bgra32(unassociated, 0, 0, unassociatedAlpha); @@ -1186,7 +1187,8 @@ private static void AssertUnsignedByteBulkRoundTrip(Func(Func + /// Divides two nonnegative integers and rounds the quotient to the nearest integer. A midpoint rounds to the even integer, + /// as the byte packers do. The integer arithmetic keeps the expected value independent of the floating-point implementation. + /// + /// The nonnegative numerator. + /// The positive denominator. + /// The rounded quotient. + private static int DivideRoundToEven(int numerator, int denominator) + { + int quotient = numerator / denominator; + int twiceRemainder = 2 * (numerator % denominator); + + return twiceRemainder > denominator || (twiceRemainder == denominator && (quotient & 1) == 1) ? quotient + 1 : quotient; + } + private static NormalizedByte4P CreateNormalizedByte4P(int red, int green, int blue, int alpha) { uint packed = (byte)(red - 127) diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelBlenderTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelBlenderTests.cs index 242d04d282..e3b5d093f9 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelBlenderTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelBlenderTests.cs @@ -404,18 +404,19 @@ public void PlusMatchesAcrossAlphaRepresentations() } [Fact] - public void AssociatedHardLightDestAtopRoundsExactMidpointAwayFromZero() => + public void AssociatedHardLightDestAtopRoundsExactMidpointToEven() => FeatureTestRunner.RunWithHwIntrinsicsFeature( - RunAssociatedHardLightDestAtopRoundsExactMidpointAwayFromZero, + RunAssociatedHardLightDestAtopRoundsExactMidpointToEven, HwIntrinsics.AllowAll | HwIntrinsics.DisableAVX512F | HwIntrinsics.DisableAVX | HwIntrinsics.DisableHWIntrinsic); - private static void RunAssociatedHardLightDestAtopRoundsExactMidpointAwayFromZero() + private static void RunAssociatedHardLightDestAtopRoundsExactMidpointToEven() { Rgba32P background = Rgba32P.FromRgba32(new Rgba32(220, 80, 40, 160)); Rgba32P source = Rgba32P.FromRgba32(new Rgba32(20, 180, 120, 96)); PixelBlender blender = PixelBlenders.GetPixelBlender(PixelColorBlendingMode.HardLight, PixelAlphaCompositionMode.DestAtop); - Assert.Equal(new Rgba32P(30, 33, 16, 60), blender.Blend(background, source, .625F)); + // The green component is the exact midpoint 32.5. It rounds to the even byte, as the byte packers do. + Assert.Equal(new Rgba32P(30, 32, 16, 60), blender.Blend(background, source, .625F)); } [Fact] diff --git a/tests/Images/External/ReferenceOutput/BmpEncoderTests/Encode_8BitColor_WithHexadecatreeQuantizer_rgb32.bmp b/tests/Images/External/ReferenceOutput/BmpEncoderTests/Encode_8BitColor_WithHexadecatreeQuantizer_rgb32.bmp index 7f79c6f3a5..c25a479137 100644 --- a/tests/Images/External/ReferenceOutput/BmpEncoderTests/Encode_8BitColor_WithHexadecatreeQuantizer_rgb32.bmp +++ b/tests/Images/External/ReferenceOutput/BmpEncoderTests/Encode_8BitColor_WithHexadecatreeQuantizer_rgb32.bmp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:fff91e78a87c2b2db661609dd70af2d7a74e6a0de18924ab2b6272e12c60977d +oid sha256:197be32add21f8dfa0231e838429d6b72c0a90f67fc1db01ce2eb60c0067fb3f size 9270 diff --git a/tests/Images/External/ReferenceOutput/BmpEncoderTests/Encode_8BitColor_WithWuQuantizer_rgb32.bmp b/tests/Images/External/ReferenceOutput/BmpEncoderTests/Encode_8BitColor_WithWuQuantizer_rgb32.bmp index f7eb06c558..0cebc523a6 100644 --- a/tests/Images/External/ReferenceOutput/BmpEncoderTests/Encode_8BitColor_WithWuQuantizer_rgb32.bmp +++ b/tests/Images/External/ReferenceOutput/BmpEncoderTests/Encode_8BitColor_WithWuQuantizer_rgb32.bmp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:e063e97cd8a000de6830adcc3961a7dc41785d40cd4d83af10ca38d96e071362 +oid sha256:1696c47564e730e88781eba226ab44968b4e9ad3185df0fa4a889afe3b7c2f4d size 9270 diff --git a/tests/Images/External/ReferenceOutput/BokehBlurTest/BokehBlurFilterProcessor_TestPattern200x100_R16_C1_G3.png b/tests/Images/External/ReferenceOutput/BokehBlurTest/BokehBlurFilterProcessor_TestPattern200x100_R16_C1_G3.png index 1526be25b6..62ae9ac783 100644 --- a/tests/Images/External/ReferenceOutput/BokehBlurTest/BokehBlurFilterProcessor_TestPattern200x100_R16_C1_G3.png +++ b/tests/Images/External/ReferenceOutput/BokehBlurTest/BokehBlurFilterProcessor_TestPattern200x100_R16_C1_G3.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:87514c6e9c2f011d5eaca49e3d265340f6e447a2c5308fa14bf43608d13ad24c -size 40519 +oid sha256:9251ece216a488137bf94c7bf935dc97ce0c0ba3775ca3f2833ad3ab3ad2c4b0 +size 40514 diff --git a/tests/Images/External/ReferenceOutput/BokehBlurTest/BokehBlurFilterProcessor_TestPattern200x100_R16_C2_G3.png b/tests/Images/External/ReferenceOutput/BokehBlurTest/BokehBlurFilterProcessor_TestPattern200x100_R16_C2_G3.png index aa164ce765..ba5064ce32 100644 --- a/tests/Images/External/ReferenceOutput/BokehBlurTest/BokehBlurFilterProcessor_TestPattern200x100_R16_C2_G3.png +++ b/tests/Images/External/ReferenceOutput/BokehBlurTest/BokehBlurFilterProcessor_TestPattern200x100_R16_C2_G3.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a4aeefe11720585529be8d5e2a44c2ce9400ac6247d82179787629267fe78fb2 -size 44615 +oid sha256:8658fe4afe1b822fd97f401f7d111bf223fe63747269172cac44714df3afb8f1 +size 44610 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/ApplyDiffusionFilterInBox_Rgba32_CalliphoraPartial.png b/tests/Images/External/ReferenceOutput/DitherTests/ApplyDiffusionFilterInBox_Rgba32_CalliphoraPartial.png index de42d1bfc2..b7bebb47b9 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/ApplyDiffusionFilterInBox_Rgba32_CalliphoraPartial.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/ApplyDiffusionFilterInBox_Rgba32_CalliphoraPartial.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:681b0e36298cb702683fb9ffb2a82f7dfd9080b268db19a03f413809f69d0e07 -size 273269 +oid sha256:12c71872de72e92221b41e3045958c9a48084952a66a64588f4f0ad5743d921e +size 324601 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_ShouldNotDependOnSinglePixelType_Bgra32_filter0.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_ShouldNotDependOnSinglePixelType_Bgra32_filter0.png index d8ececb4cd..264170d3ef 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_ShouldNotDependOnSinglePixelType_Bgra32_filter0.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_ShouldNotDependOnSinglePixelType_Bgra32_filter0.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f7c19df70d24948e1a36299705bb030715cf0d01b453d390989d472c0999d46a -size 728 +oid sha256:8fff0a076dbd51a1bf8c67361a15428351a7da4b7405619f915694664e6062f9 +size 847 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_ShouldNotDependOnSinglePixelType_Rgb24_filter0.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_ShouldNotDependOnSinglePixelType_Rgb24_filter0.png index d8ececb4cd..264170d3ef 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_ShouldNotDependOnSinglePixelType_Rgb24_filter0.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_ShouldNotDependOnSinglePixelType_Rgb24_filter0.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f7c19df70d24948e1a36299705bb030715cf0d01b453d390989d472c0999d46a -size 728 +oid sha256:8fff0a076dbd51a1bf8c67361a15428351a7da4b7405619f915694664e6062f9 +size 847 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_ShouldNotDependOnSinglePixelType_Rgba32_filter0.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_ShouldNotDependOnSinglePixelType_Rgba32_filter0.png index d8ececb4cd..264170d3ef 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_ShouldNotDependOnSinglePixelType_Rgba32_filter0.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_ShouldNotDependOnSinglePixelType_Rgba32_filter0.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f7c19df70d24948e1a36299705bb030715cf0d01b453d390989d472c0999d46a -size 728 +oid sha256:8fff0a076dbd51a1bf8c67361a15428351a7da4b7405619f915694664e6062f9 +size 847 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Atkinson.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Atkinson.png index 1656b2e9cb..ccacfd14bf 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Atkinson.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Atkinson.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:38597c6144d61960d25c74d7a465b1cdf69b7c0804a6dec68128a6c953258313 -size 52688 +oid sha256:fd018b15420b96ec213111d75fa42c6fd2e4c48f88cdc465cc85c44d5fc6239c +size 91835 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Burks.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Burks.png index c6016ae358..fcc5a5d6ef 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Burks.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Burks.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:5f9191c71eea1f73aa4c55397ca26f240615c9c4a7fff9a05e6f2e046b5e4d8b -size 62323 +oid sha256:1097fa95ce2bf181f6db18c6bb05c183e253bd44802a2b6690dfae0c7ee54549 +size 108823 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_FloydSteinberg.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_FloydSteinberg.png index 40243937d3..c8c9c87eb8 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_FloydSteinberg.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_FloydSteinberg.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b63810145832db459bb7a6b37a028a7b778f6b6b4e6eae00e50e6e21c5a06086 -size 62199 +oid sha256:94348c53786bcbf676c912ce5a2f60d182815c2384003ceefe16eee5f8033673 +size 107903 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_JarvisJudiceNinke.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_JarvisJudiceNinke.png index 83f9e067db..35131b4b27 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_JarvisJudiceNinke.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_JarvisJudiceNinke.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a67c14ef99a943706f050ff1ea0ef101429292d52bc14ed4610f8338736ff87e -size 56800 +oid sha256:42d02314c101f9cd9a7932863ae104fa6d5572566a636f99e1a5ac3f560eddb6 +size 99982 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Sierra2.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Sierra2.png index 22e4f4b6d6..d6028b89cc 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Sierra2.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Sierra2.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:623dd82d372ba517b0d3357d06cffaf105d407a9090cbcbc6a76ae944ab33d67 -size 59468 +oid sha256:c7e8d64b0ef4947d241f1d1bf744ff467ae066ff870661be2d68d6aab20b2b60 +size 107943 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Sierra3.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Sierra3.png index 838863c158..612b5c010b 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Sierra3.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Sierra3.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:8edceef8e12c4f3d194523437045c5cf4e80c7bb95ff75f38c1f38a21872e3d0 -size 59376 +oid sha256:b5d43df0e189be6dc830d6a13fd933aaac6fa656bfd1d8e8def074acf7c44d62 +size 102465 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_SierraLite.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_SierraLite.png index 60513e1992..a1df02c915 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_SierraLite.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_SierraLite.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b1d7019e8cb170ae67496f8250446c4f6b6217378658408c3d51a95c49a4c3bc -size 63287 +oid sha256:cb1741fbb03038b4491128a2d4c88f9baef7a877f33f1f428582b6ceec8b6d40 +size 110663 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_StevensonArce.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_StevensonArce.png index 0d1b34d8ce..da1be18b67 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_StevensonArce.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_StevensonArce.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d7c03ede7ab3bd4e57e6a63e53e2e8c771e938fdc7d5dfe5c9339a2c9907c9cf -size 55550 +oid sha256:7642a9e632b02e9d3f2dd2dbe20645c147c086014c7c3e8a730309491b966ef1 +size 96710 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Stucki.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Stucki.png index f8c998ecbd..279eb8d47c 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Stucki.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_Bike_Stucki.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:79b690b91223d1fe7ddf1b8826b4474b89644822bc8aa9adee3cf819bc095b4c -size 60979 +oid sha256:23b2ca27d31243baf362bde4ee93ef130bfc5a2d4e463aa6afbabb8e63deb492 +size 100019 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Atkinson.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Atkinson.png index 70acb3f32e..fe8a02a78e 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Atkinson.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Atkinson.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:e44c49a8f2ab1280c38e6ba71da29a93803b2aa4cf117e1e919909521b0373e6 -size 57636 +oid sha256:0a45c56944f6c45e33ebc3dad4bdf8a919cd342be1f36f2e846dbf093123faca +size 94982 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Burks.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Burks.png index af35177491..f54e48c912 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Burks.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Burks.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:359a44bb957481c85d5acd65559b43ffc0acf806d4f4e57d6a791ca65b28295b -size 59839 +oid sha256:49529f991b00ede556fcd10c6b878316562c97b667ba75066781b51545f40368 +size 98165 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_FloydSteinberg.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_FloydSteinberg.png index a14c2cb1f6..0d9614e9d3 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_FloydSteinberg.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_FloydSteinberg.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7fb3743098a8147fd24294d933d93a61ec0155d754f52544650f6589719905be -size 60688 +oid sha256:52555ed8902969e2abf0d9e9b5827b170498ad48ca27b84590d99f9e9798e1a3 +size 99907 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_JarvisJudiceNinke.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_JarvisJudiceNinke.png index 683f59ea1e..4386b22613 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_JarvisJudiceNinke.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_JarvisJudiceNinke.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:41fa7d92a10db450f3b3729ab9e36074224baaefeda21cffd0466e37a111e138 -size 59113 +oid sha256:3ae28a412bbcbf37e172cf84662569b1ffb15bd4d4b88bbd75b5d371d2aeb7b0 +size 96267 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Sierra2.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Sierra2.png index 813289a26d..7d850a92e9 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Sierra2.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Sierra2.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:bebf3b3762b339874891e3d434511e5f2557be90d66d6d7fe827b50334ede6c2 -size 58976 +oid sha256:392512a3a28a1dcc5fd53068d9f634f64515022719771403eb58fd240485dc0b +size 97313 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Sierra3.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Sierra3.png index d4da100376..ca3698e4d8 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Sierra3.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Sierra3.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:fd4358826739db2c22064e8aa90597f8b6403b9d7e2866ec280e743c51d2f41f -size 59203 +oid sha256:cb742c5d191643413a3ed9a241d3c6572e5d83970108d7c31a83dbb8433ddce2 +size 97146 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_SierraLite.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_SierraLite.png index 8d3cf1a564..e8a86371ba 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_SierraLite.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_SierraLite.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6c88740c0553829eaa42ca751b34cc456623a84ccdff4020949a06ef4b4802d1 -size 61137 +oid sha256:fb830830a68c6fd070265aefd988ce552773c456876320ddba2f42a31f13fa18 +size 100196 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_StevensonArce.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_StevensonArce.png index a146f8f668..b18c0458b0 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_StevensonArce.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_StevensonArce.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0a4a404b0767faac952435f768867cf7bf053848e1e3ef121624f136658a107c -size 58386 +oid sha256:cc1ce7fef114678c4d0b93f6e4aeb844bb97058396c19bc68e908434ece676ab +size 96202 diff --git a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Stucki.png b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Stucki.png index fa8eea57a9..f70ac6c726 100644 --- a/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Stucki.png +++ b/tests/Images/External/ReferenceOutput/DitherTests/DiffusionFilter_WorksWithAllErrorDiffusers_CalliphoraPartial_Stucki.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:174ee39c08eb9a174b48b19dc618d043bf6b71eee68ab7127407eb713e164e61 -size 58934 +oid sha256:6fbcdc8048741f5c4ff675590e05dfb65bf721c981561d8b754391eda8be7010 +size 96951 diff --git a/tests/Images/External/ReferenceOutput/Filters/BlackWhiteTest/ApplyBlackWhiteFilter_Rgba32_TestPattern48x48.png b/tests/Images/External/ReferenceOutput/Filters/BlackWhiteTest/ApplyBlackWhiteFilter_Rgba32_TestPattern48x48.png index aa561ace81..6e0d5e8c05 100644 --- a/tests/Images/External/ReferenceOutput/Filters/BlackWhiteTest/ApplyBlackWhiteFilter_Rgba32_TestPattern48x48.png +++ b/tests/Images/External/ReferenceOutput/Filters/BlackWhiteTest/ApplyBlackWhiteFilter_Rgba32_TestPattern48x48.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d76ae5ac1a0aebb9d76b2fa5c6b1fc109e5fcbdc6c41d9681a76ade9c86fab79 -size 748 +oid sha256:2e7a2b536223267e6e8b8b2d256ae445df884f63278e9d6f7278a25a62d282b1 +size 1902 diff --git a/tests/Images/External/ReferenceOutput/Filters/ContrastTest/ApplyContrastFilter_Rgba32_TestPattern48x48_0.5.png b/tests/Images/External/ReferenceOutput/Filters/ContrastTest/ApplyContrastFilter_Rgba32_TestPattern48x48_0.5.png index 5e6834dcac..78f5f8b32e 100644 --- a/tests/Images/External/ReferenceOutput/Filters/ContrastTest/ApplyContrastFilter_Rgba32_TestPattern48x48_0.5.png +++ b/tests/Images/External/ReferenceOutput/Filters/ContrastTest/ApplyContrastFilter_Rgba32_TestPattern48x48_0.5.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:94fd1158d54d50563ec5658b3f278dc51a99f808740e022a4ead7dd69a91b879 -size 2923 +oid sha256:d09c1c829a4ef538621dcd56d3ccb896318eb4e11ca798746674d05901c80615 +size 2466 diff --git a/tests/Images/External/ReferenceOutput/Filters/ContrastTest/ApplyContrastFilter_Rgba32_TestPattern48x48_1.5.png b/tests/Images/External/ReferenceOutput/Filters/ContrastTest/ApplyContrastFilter_Rgba32_TestPattern48x48_1.5.png index 3ad2338c8a..202aa5057a 100644 --- a/tests/Images/External/ReferenceOutput/Filters/ContrastTest/ApplyContrastFilter_Rgba32_TestPattern48x48_1.5.png +++ b/tests/Images/External/ReferenceOutput/Filters/ContrastTest/ApplyContrastFilter_Rgba32_TestPattern48x48_1.5.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a96097f3248bb50244f3aa07753b077066576e0ecb2f96010607a7ebf0bd8af8 -size 2807 +oid sha256:30ab49330746657b5232b6e9df5c8db0ca0ce78a3e5faa4fb8c38902ded27a22 +size 2338 diff --git a/tests/Images/External/ReferenceOutput/Filters/GrayscaleTest/ApplyGrayscaleFilter_Rgba32_TestPattern48x48_Bt601.png b/tests/Images/External/ReferenceOutput/Filters/GrayscaleTest/ApplyGrayscaleFilter_Rgba32_TestPattern48x48_Bt601.png index 9010cad7ec..55a6c14eb8 100644 --- a/tests/Images/External/ReferenceOutput/Filters/GrayscaleTest/ApplyGrayscaleFilter_Rgba32_TestPattern48x48_Bt601.png +++ b/tests/Images/External/ReferenceOutput/Filters/GrayscaleTest/ApplyGrayscaleFilter_Rgba32_TestPattern48x48_Bt601.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ddd12a6a0ba522c738ebd08ce8bbe4a0c4bb41cdf01e55ea08ca8ced509cb4ba -size 2689 +oid sha256:7fc3716b9de56bb80438da1178d73b3b78c758ffe6cc0059bbe80c31d6f158c1 +size 2935 diff --git a/tests/Images/External/ReferenceOutput/Filters/GrayscaleTest/ApplyGrayscaleFilter_Rgba32_TestPattern48x48_Bt709.png b/tests/Images/External/ReferenceOutput/Filters/GrayscaleTest/ApplyGrayscaleFilter_Rgba32_TestPattern48x48_Bt709.png index a88d1613b7..210e77fb36 100644 --- a/tests/Images/External/ReferenceOutput/Filters/GrayscaleTest/ApplyGrayscaleFilter_Rgba32_TestPattern48x48_Bt709.png +++ b/tests/Images/External/ReferenceOutput/Filters/GrayscaleTest/ApplyGrayscaleFilter_Rgba32_TestPattern48x48_Bt709.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:df275704a518359615540bf355464655196ecbb2ea66c69c77feec8e47249068 -size 2658 +oid sha256:c5f7ec2805f0f4d91b2d3c31aae7f673ab1f77014ea2db64021755f485fca6d0 +size 2943 diff --git a/tests/Images/External/ReferenceOutput/Filters/HueTest/ApplyHueFilter_Rgba32_TestPattern48x48_-180.png b/tests/Images/External/ReferenceOutput/Filters/HueTest/ApplyHueFilter_Rgba32_TestPattern48x48_-180.png index ee959e9118..2d48356e09 100644 --- a/tests/Images/External/ReferenceOutput/Filters/HueTest/ApplyHueFilter_Rgba32_TestPattern48x48_-180.png +++ b/tests/Images/External/ReferenceOutput/Filters/HueTest/ApplyHueFilter_Rgba32_TestPattern48x48_-180.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:297694e34588a4d2bdeb4856ca0665f92b8133d53e362d18a853c73e8416c608 -size 2833 +oid sha256:7b35247d66280b2b6a834cbc767d32df9157cfb051e5d58034ccb14ca6b2ae4e +size 2834 diff --git a/tests/Images/External/ReferenceOutput/Filters/HueTest/ApplyHueFilter_Rgba32_TestPattern48x48_180.png b/tests/Images/External/ReferenceOutput/Filters/HueTest/ApplyHueFilter_Rgba32_TestPattern48x48_180.png index ee959e9118..2d48356e09 100644 --- a/tests/Images/External/ReferenceOutput/Filters/HueTest/ApplyHueFilter_Rgba32_TestPattern48x48_180.png +++ b/tests/Images/External/ReferenceOutput/Filters/HueTest/ApplyHueFilter_Rgba32_TestPattern48x48_180.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:297694e34588a4d2bdeb4856ca0665f92b8133d53e362d18a853c73e8416c608 -size 2833 +oid sha256:7b35247d66280b2b6a834cbc767d32df9157cfb051e5d58034ccb14ca6b2ae4e +size 2834 diff --git a/tests/Images/External/ReferenceOutput/Filters/InvertTest/ApplyInvertFilter_Rgba32_TestPattern48x48.png b/tests/Images/External/ReferenceOutput/Filters/InvertTest/ApplyInvertFilter_Rgba32_TestPattern48x48.png index a0cb6ba41b..31efdd07e5 100644 --- a/tests/Images/External/ReferenceOutput/Filters/InvertTest/ApplyInvertFilter_Rgba32_TestPattern48x48.png +++ b/tests/Images/External/ReferenceOutput/Filters/InvertTest/ApplyInvertFilter_Rgba32_TestPattern48x48.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:19b4539af71059a004bcbfaffb81da342e05b65723b7c528556e3516cae36b41 -size 2633 +oid sha256:fbcc0876f1bc477e08dfa4aa60e370c2844cf6bdc3b3c8f01a0432b00e299b3d +size 2595 diff --git a/tests/Images/External/ReferenceOutput/Filters/KodachromeTest/ApplyKodachromeFilter_Rgba32_TestPattern48x48.png b/tests/Images/External/ReferenceOutput/Filters/KodachromeTest/ApplyKodachromeFilter_Rgba32_TestPattern48x48.png index 02d8deb119..82e9c9fb6c 100644 --- a/tests/Images/External/ReferenceOutput/Filters/KodachromeTest/ApplyKodachromeFilter_Rgba32_TestPattern48x48.png +++ b/tests/Images/External/ReferenceOutput/Filters/KodachromeTest/ApplyKodachromeFilter_Rgba32_TestPattern48x48.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:789ff8ee73b3e18c8d96b662002aeab476270c495447961055a60d8b83c5a94e -size 3038 +oid sha256:1138a0dcd3b53b7e0e1ad9897f8e4b6d95f2023041b194d383b47ef4b774acc7 +size 2918 diff --git a/tests/Images/External/ReferenceOutput/Filters/LomographTest/ApplyLomographFilter_Rgba32_TestPattern48x48.png b/tests/Images/External/ReferenceOutput/Filters/LomographTest/ApplyLomographFilter_Rgba32_TestPattern48x48.png index f4d9b4538b..4e8d886b8b 100644 --- a/tests/Images/External/ReferenceOutput/Filters/LomographTest/ApplyLomographFilter_Rgba32_TestPattern48x48.png +++ b/tests/Images/External/ReferenceOutput/Filters/LomographTest/ApplyLomographFilter_Rgba32_TestPattern48x48.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1c11bb97fe2e2d6f8bf4c8a21c9a58702e1cff6bb02bb52412a8f54d4e1d3bbb -size 6428 +oid sha256:35e602b530c1cf7a3ac807676b909a9b4995e4d42275a87722290174a3ae6482 +size 6435 diff --git a/tests/Images/External/ReferenceOutput/Filters/OpacityTest/ApplyAlphaFilter_Rgba32_TestPattern48x48_0.2.png b/tests/Images/External/ReferenceOutput/Filters/OpacityTest/ApplyAlphaFilter_Rgba32_TestPattern48x48_0.2.png index 4e1731515a..51e512d8d8 100644 --- a/tests/Images/External/ReferenceOutput/Filters/OpacityTest/ApplyAlphaFilter_Rgba32_TestPattern48x48_0.2.png +++ b/tests/Images/External/ReferenceOutput/Filters/OpacityTest/ApplyAlphaFilter_Rgba32_TestPattern48x48_0.2.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7089899b93d357320558f3e75fa5c609d18d89eb9965cfcf8bf20e6f6c21b9f0 -size 2528 +oid sha256:4357700229c60fc66a07eb74214266e0aa4255da34e36f38e05b12ee91c9d040 +size 2431 diff --git a/tests/Images/External/ReferenceOutput/Filters/PolaroidTest/ApplyPolaroidFilter_Rgba32_TestPattern48x48.png b/tests/Images/External/ReferenceOutput/Filters/PolaroidTest/ApplyPolaroidFilter_Rgba32_TestPattern48x48.png index db3cde6bb6..9bd541ca26 100644 --- a/tests/Images/External/ReferenceOutput/Filters/PolaroidTest/ApplyPolaroidFilter_Rgba32_TestPattern48x48.png +++ b/tests/Images/External/ReferenceOutput/Filters/PolaroidTest/ApplyPolaroidFilter_Rgba32_TestPattern48x48.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c91c5113e9dd6ee5b95d32b3181d3d777b6e1dbb64339630cc9817e91208f338 -size 7210 +oid sha256:7f210296818e18b21e1ce814c56b1bcb02d6c9708fce3f20352bc23d0989c2c1 +size 7382 diff --git a/tests/Images/External/ReferenceOutput/Filters/SaturateTest/ApplySaturationFilter_Rgba32_TestPattern48x48_0.5.png b/tests/Images/External/ReferenceOutput/Filters/SaturateTest/ApplySaturationFilter_Rgba32_TestPattern48x48_0.5.png index 5fef5f9f6e..e44dab804a 100644 --- a/tests/Images/External/ReferenceOutput/Filters/SaturateTest/ApplySaturationFilter_Rgba32_TestPattern48x48_0.5.png +++ b/tests/Images/External/ReferenceOutput/Filters/SaturateTest/ApplySaturationFilter_Rgba32_TestPattern48x48_0.5.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d4e17b9f746d2e6b7032d41df00d6f3fbda3b1b03eedb33d81e060d8d4dabef5 -size 2955 +oid sha256:ff415a4aa3a11b8dc9afe1997ee51a080e4f29242edf1665f7319ccbd7f9349d +size 2969 diff --git a/tests/Images/External/ReferenceOutput/Filters/SaturateTest/ApplySaturationFilter_Rgba32_TestPattern48x48_1.5.png b/tests/Images/External/ReferenceOutput/Filters/SaturateTest/ApplySaturationFilter_Rgba32_TestPattern48x48_1.5.png index 84eac27006..8d00b901e1 100644 --- a/tests/Images/External/ReferenceOutput/Filters/SaturateTest/ApplySaturationFilter_Rgba32_TestPattern48x48_1.5.png +++ b/tests/Images/External/ReferenceOutput/Filters/SaturateTest/ApplySaturationFilter_Rgba32_TestPattern48x48_1.5.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:4ca8d88eac7513d3418e6d66fb576d598940e860eb600345310228547542862f -size 2806 +oid sha256:7f5aa9a8cbab5c52cce3656e8f1c99193e8cf99f049f0c798d88812e0aa74648 +size 2629 diff --git a/tests/Images/External/ReferenceOutput/Filters/SepiaTest/ApplySepiaFilter_Rgba32_TestPattern48x48.png b/tests/Images/External/ReferenceOutput/Filters/SepiaTest/ApplySepiaFilter_Rgba32_TestPattern48x48.png index 8ed26346e0..f8bba13cfe 100644 --- a/tests/Images/External/ReferenceOutput/Filters/SepiaTest/ApplySepiaFilter_Rgba32_TestPattern48x48.png +++ b/tests/Images/External/ReferenceOutput/Filters/SepiaTest/ApplySepiaFilter_Rgba32_TestPattern48x48.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:998821190abd23ac3c54d70866bc8e056995ac2570b78353c78fbb27626bdb56 -size 2788 +oid sha256:d06bcf0d8550fecb355564fccea2494f67ebdaa5a182e92c39c59a2e152c9c7f +size 2883 diff --git a/tests/Images/External/ReferenceOutput/JpegDecoderTests/JpegDecoder_Decode_Resize_Box_Calliphora_140_140.png b/tests/Images/External/ReferenceOutput/JpegDecoderTests/JpegDecoder_Decode_Resize_Box_Calliphora_140_140.png index 5b72e9e8f0..da4bb651ae 100644 --- a/tests/Images/External/ReferenceOutput/JpegDecoderTests/JpegDecoder_Decode_Resize_Box_Calliphora_140_140.png +++ b/tests/Images/External/ReferenceOutput/JpegDecoderTests/JpegDecoder_Decode_Resize_Box_Calliphora_140_140.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:36c54604eaec0f4b7b32b64269b19ad671e3463f1480858ec8a882327112956d -size 38680 +oid sha256:3ee5e9d36310551602e79c48faf087e2c57a73c7591c0349e4448494997640e7 +size 38677 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/00.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/00.png index 17c8e35c6f..79e53569c4 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/00.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/00.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:4aa1dea5da7a94fddd2259cd86e7171a57cb5cd2198decedd86149778b9aa20a -size 64030 +oid sha256:e2cabe886e508a7406ef61a0b3ade1abacc582b4c35411e9e7b582744f036942 +size 63791 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/08.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/08.png index f2ec385a88..32c9742a82 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/08.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/08.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:16d4159e492162372a16b08fb3a4fdf36908ce759c6a0ad72a0da4bbeb477b72 -size 68619 +oid sha256:0f19354c187157a15e7372271e7502279a8fa57def149e63926421c17faeaf21 +size 71293 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/104.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/104.png index dc57ed717f..3ec5ee64ca 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/104.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/104.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1095bc829b8fab3c5fda66b90cdd751b81439ad80e9fc7d564a5212c75155b2c -size 76100 +oid sha256:efef97c46cc07cb4489bd0acdd8349d5c58a10f0b38302160ae07971a336824a +size 80189 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/112.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/112.png index 0158b28407..9e1ec7ef6c 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/112.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/112.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0212cd29319c0d90c18a5f90716156a888c9925e4a36a6d9bbbe8d67a706db8f -size 66282 +oid sha256:b36a06864c5ebf60473382660b5917f55b8ee508caed21c082daf47047a5143c +size 70645 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/16.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/16.png index 52867f468e..d013663791 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/16.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/16.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:620ea89afc2e41b6199c47b2e4777f5ef9afe139e22bfabca9ec094b0adcbdc2 -size 73862 +oid sha256:c92e775bfa0db3441f851523ef8815fbc74b8544d0a35bc034d7e384f1bd6430 +size 76648 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/24.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/24.png index 26ae147489..c5dfe47c44 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/24.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/24.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d39997f18af5b97ed32ea30c15da879f70906b4f5cf12439ea6ff2d229e40199 -size 75734 +oid sha256:47d5fa1882605912bb341d993b101e555c9ca3b9696f211eeab4b6bc28741f96 +size 78848 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/32.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/32.png index 6cd5074ecf..2a0f9c69ef 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/32.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/32.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:4b459edf763ffff8a8a016c1b7d9e13b7e99f6752e4452b52539d2eb0f7f31be -size 79505 +oid sha256:054ec938254f792de639f46f1bf077b86cbbb9c5c894f370d7b6dae67da6f0c9 +size 82544 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/40.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/40.png index 8b9ea7c239..9f8e6ece46 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/40.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/40.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f1957c82709b22abbaa354ecd679159eeddf135aabb301c266518c23ff4918f9 -size 77588 +oid sha256:996e97ba9bc803686eb78c34ccd75c344f40d96217d7015af6b71ec3e6aabe05 +size 81294 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/48.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/48.png index 4430290427..2c798ff20c 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/48.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/48.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ae33b303bd1feae301cf645ee6596c499ad4eaa9164c52a37fca760169f9f363 -size 80317 +oid sha256:a6753e11727865de695195fa0da84ea0cf28e3f2838c6fc5b47a448c9878f6a6 +size 85069 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/56.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/56.png index 8feae54c6a..c64a190de5 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/56.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/56.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d86360bd43de392a9cf4b671a4cf3cd7ba9f61952a6d0400a5baab7dbb5eeb6d -size 78578 +oid sha256:c22afd0710fb1a960c14e6d87b4484e95b9a880e71227090c973e5f7213d786e +size 81412 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/64.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/64.png index 284ad99233..ef4297f9b6 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/64.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/64.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:60e1694b121d0d3fa17d62f4477de349376aa6c2a98b83f9a4525da9ea471662 -size 75204 +oid sha256:66ad1c25d59bf5e544838077abe104a54f799221d6fa3efbb652537ec86705a7 +size 77141 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/72.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/72.png index d09b77afca..777b0963e9 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/72.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/72.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9348ef330a239bea501f41a3256107fc10a6bb323642118b1fcbe5227b742c88 -size 79048 +oid sha256:4a5ae9099ca6b6965f1295a1211d7a1e9cc1a3873eade11e5c9ec741ae7ab2c8 +size 80101 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/80.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/80.png index d31fd5a808..7f673e2627 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/80.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/80.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:452dd2339b6ad3e35528601c289d88eafcc7e9a6e717f25da2bbf4267b85be97 -size 81553 +oid sha256:a19e0d4785825da38482aaf89f90833bffad68d933f84dbb8f63615065c0d08d +size 84604 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/88.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/88.png index 669dfb8600..d1340172a3 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/88.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/88.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b67e3b57b62f9e1c924de6fbd2699f93a6594812ad8c4cafd6160323547b1a88 -size 86402 +oid sha256:cf6e0b3ddb3537dd69544e6535a318b457b533f3597b25bc1755b43afd9ba5c1 +size 87528 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/96.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/96.png index f9a5aee191..aae8dc63a4 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/96.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_issue_2866.gif/96.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:887e94402f93a491820d3d25d641c5901cf796c1275a2feb9e1c072a6a63ce28 -size 87335 +oid sha256:56a10d642a636956714d061b2a387a7d0d2cd32628147829b048e30155fe20e0 +size 90430 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_leo.gif/00.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_leo.gif/00.png index 961e205f9f..a9abf56119 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_leo.gif/00.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_leo.gif/00.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a6baac5db47ef2ee3ba72c7e8d5e04fc888c5e1460d4d7e348f63b597e1b5ff7 -size 23660 +oid sha256:36bfaa91f3460f3c570c14d67db3543aaae4772af9894e3356483eda652c10c7 +size 22864 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_leo.gif/08.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_leo.gif/08.png index 82cb6168e8..ca596b2777 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_leo.gif/08.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Encode_AnimatedFormatTransform_FromGif_Rgba32_leo.gif/08.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7fad45a0682a70a1fb84eec76d4a80ee054e85df59e6729508f3698d39999e31 -size 29509 +oid sha256:164a9ea64f9b2934d69c91b78b6f5f2bd49da627acb98b37b73a54884edf3291 +size 28882 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Issue2469_Quantized_Encode_Artifacts_Rgba32_issue_2469.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Issue2469_Quantized_Encode_Artifacts_Rgba32_issue_2469.png index c10227c6bd..86aa90a512 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Issue2469_Quantized_Encode_Artifacts_Rgba32_issue_2469.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Issue2469_Quantized_Encode_Artifacts_Rgba32_issue_2469.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b33a960891c6b1e9cc6ac2ddc3cf49d8f49e0c749dfa7a67db49354988b129f6 -size 935007 +oid sha256:1a9f043ecd5a1c977e6e205f567769c2713bfc2140bf2f2473eeb16076d66fe8 +size 1034125 diff --git a/tests/Images/External/ReferenceOutput/PngEncoderTests/Issue2668_Quantized_Encode_Alpha_Rgba32_Issue_2668.png b/tests/Images/External/ReferenceOutput/PngEncoderTests/Issue2668_Quantized_Encode_Alpha_Rgba32_Issue_2668.png index 3e47a66050..ad17378512 100644 --- a/tests/Images/External/ReferenceOutput/PngEncoderTests/Issue2668_Quantized_Encode_Alpha_Rgba32_Issue_2668.png +++ b/tests/Images/External/ReferenceOutput/PngEncoderTests/Issue2668_Quantized_Encode_Alpha_Rgba32_Issue_2668.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:02e5f9b545efe6e92a0d9d8c856db150ff705cb59305b4a5e19d249de462a35b -size 8053 +oid sha256:992eb076d359f0e20bc5823c5f0db631d462b22f4b7db59ed1738b84839e5239 +size 8178 diff --git a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_HexadecatreeQuantizer_ErrorDither_1.png b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_HexadecatreeQuantizer_ErrorDither_1.png index c84edd138f..5df4d57dc2 100644 --- a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_HexadecatreeQuantizer_ErrorDither_1.png +++ b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_HexadecatreeQuantizer_ErrorDither_1.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:997e5281abd8cf3a587984ec1b7e31487ec5ddf16326d025124833d536e4ac27 -size 13910 +oid sha256:2318aac69862183aa3c45e1fa5930932447dab9625603701f879fdc4f3afbdf1 +size 24259 diff --git a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WebSafePaletteQuantizer_ErrorDither_0.75.png b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WebSafePaletteQuantizer_ErrorDither_0.75.png index 77821255bb..6bb5ca6254 100644 --- a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WebSafePaletteQuantizer_ErrorDither_0.75.png +++ b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WebSafePaletteQuantizer_ErrorDither_0.75.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:717fe46156f3d144f31cfce066dd13532ee8721d7d3a7b8c8425c646f411e8a5 -size 11099 +oid sha256:88cdb165c48d4c3a442b8cfd144d5b2895d079fb2d8c11876b3cec1283cedad1 +size 18477 diff --git a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WebSafePaletteQuantizer_ErrorDither_1.png b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WebSafePaletteQuantizer_ErrorDither_1.png index c43b5836ec..a531cdcf53 100644 --- a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WebSafePaletteQuantizer_ErrorDither_1.png +++ b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WebSafePaletteQuantizer_ErrorDither_1.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ae18d22edc011d576d6a1e9545bc52084ca0bed55a6ce19d391d2a5f97b1843c -size 11763 +oid sha256:cb0e8d15a9f3249e24c6f11bff7b55057b208867031382ce364c8298c674fa72 +size 20019 diff --git a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WernerPaletteQuantizer_ErrorDither_0.75.png b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WernerPaletteQuantizer_ErrorDither_0.75.png index 30f75826eb..c57857d593 100644 --- a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WernerPaletteQuantizer_ErrorDither_0.75.png +++ b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WernerPaletteQuantizer_ErrorDither_0.75.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f7838c37c32134f325960312095ed8e1decbb0dd7e14a84e82637258c7ea117e -size 12826 +oid sha256:b2fa66504e88700079a974e0006d6cb6bb9dd6ce93bda550d834a9743912f13c +size 20552 diff --git a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WernerPaletteQuantizer_ErrorDither_1.png b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WernerPaletteQuantizer_ErrorDither_1.png index 5b8c5127c0..5fafb1a0a6 100644 --- a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WernerPaletteQuantizer_ErrorDither_1.png +++ b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WernerPaletteQuantizer_ErrorDither_1.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:aaeee39c61b86d9ce569ca2288f998b8461a3f2169dac23cf2f750dd475d8b81 -size 14145 +oid sha256:b7c0419634ceb503a4ebbfb5066b84738867735e775af584896a8ffd2ed71742 +size 22460 diff --git a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WuQuantizer_ErrorDither_1.png b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WuQuantizer_ErrorDither_1.png index 74cbbd7581..82f61d57f2 100644 --- a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WuQuantizer_ErrorDither_1.png +++ b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantizationWithDitheringScale_david_WuQuantizer_ErrorDither_1.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:234854be2a3f774a58baf79f20e68c7331b6caff486ab4b1e509a96e2a3d70b9 -size 13455 +oid sha256:6b8b01c4bb1ff53014e8058ea35f52e1c3d6ea4f4918846b938934fbae0dbfcd +size 24006 diff --git a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_HexadecatreeQuantizer_ErrorDither.png b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_HexadecatreeQuantizer_ErrorDither.png index b17bce9e3e..91096212e5 100644 --- a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_HexadecatreeQuantizer_ErrorDither.png +++ b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_HexadecatreeQuantizer_ErrorDither.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:822f4ae1d8676e2231a0c938296931be42a74c0a51b4ec63fdf6dcd17d64dc7e -size 83924 +oid sha256:d389645834aba15354e456531d3b3010557971bd1e280eae6cc4fcb7e6f2c9e8 +size 135660 diff --git a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_WebSafePaletteQuantizer_ErrorDither.png b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_WebSafePaletteQuantizer_ErrorDither.png index 40243937d3..c8c9c87eb8 100644 --- a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_WebSafePaletteQuantizer_ErrorDither.png +++ b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_WebSafePaletteQuantizer_ErrorDither.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b63810145832db459bb7a6b37a028a7b778f6b6b4e6eae00e50e6e21c5a06086 -size 62199 +oid sha256:94348c53786bcbf676c912ce5a2f60d182815c2384003ceefe16eee5f8033673 +size 107903 diff --git a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_WernerPaletteQuantizer_ErrorDither.png b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_WernerPaletteQuantizer_ErrorDither.png index 96c66aad72..7185518262 100644 --- a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_WernerPaletteQuantizer_ErrorDither.png +++ b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_WernerPaletteQuantizer_ErrorDither.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:828b082a1892f0200ef84254637b340b1276e1bee44e01c6b715de8838e4818f -size 35301 +oid sha256:aa5a66bdc0e15b06dd7e8abb3df72dbe7fc1bc86df5f08e5dcd2cdf385b8f462 +size 59420 diff --git a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_WuQuantizer_ErrorDither.png b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_WuQuantizer_ErrorDither.png index c342e3a230..bf43a715e5 100644 --- a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_WuQuantizer_ErrorDither.png +++ b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_Bike_WuQuantizer_ErrorDither.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:83c8403f5d0e5457721d992c1e6980134e8a65a1f646163a4f091cf34583ca02 -size 101417 +oid sha256:33464e67f4e7e66c23f37148032dbaef6ac009de42d34d41c1c3b6d819e4836c +size 154908 diff --git a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_HexadecatreeQuantizer_ErrorDither.png b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_HexadecatreeQuantizer_ErrorDither.png index 79711e2ebc..1a1983bc0d 100644 --- a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_HexadecatreeQuantizer_ErrorDither.png +++ b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_HexadecatreeQuantizer_ErrorDither.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:22920fb2379dee7d12fee52f6a39b8e46e1e99f77b91f879c51bb33a981dfdcb -size 98851 +oid sha256:583661c416e613505345e4dc9d01b7c428a012e42e0073188e8faaee43a50f3b +size 148728 diff --git a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_WebSafePaletteQuantizer_ErrorDither.png b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_WebSafePaletteQuantizer_ErrorDither.png index a14c2cb1f6..0d9614e9d3 100644 --- a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_WebSafePaletteQuantizer_ErrorDither.png +++ b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_WebSafePaletteQuantizer_ErrorDither.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7fb3743098a8147fd24294d933d93a61ec0155d754f52544650f6589719905be -size 60688 +oid sha256:52555ed8902969e2abf0d9e9b5827b170498ad48ca27b84590d99f9e9798e1a3 +size 99907 diff --git a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_WernerPaletteQuantizer_ErrorDither.png b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_WernerPaletteQuantizer_ErrorDither.png index 0d548ca79d..6d5af671f5 100644 --- a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_WernerPaletteQuantizer_ErrorDither.png +++ b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_WernerPaletteQuantizer_ErrorDither.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:e2f4f4e2237925403fd0228344f9fce9be96c0f26e3465775763aca775779763 -size 68222 +oid sha256:09a46cef735f549e094fb44fd12956420b75fbd7f19fad9c8aea3980a40f15ee +size 105664 diff --git a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_WuQuantizer_ErrorDither.png b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_WuQuantizer_ErrorDither.png index ef86e7c48d..96e21a7226 100644 --- a/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_WuQuantizer_ErrorDither.png +++ b/tests/Images/External/ReferenceOutput/QuantizerTests/ApplyQuantization_CalliphoraPartial_WuQuantizer_ErrorDither.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0b3c8dc7e653ef1846c7359e9a0f719bee91549846f160abb547cd0aab6a8a59 -size 110711 +oid sha256:ace4014c046881c49c60b6316d8d57898458f1b6ad23fa4f053ed1292212834c +size 170180 diff --git a/tests/Images/External/ReferenceOutput/ResizeTests/Resize_WorksWithAllResamplers_CalliphoraPartial_Box-0.5.png b/tests/Images/External/ReferenceOutput/ResizeTests/Resize_WorksWithAllResamplers_CalliphoraPartial_Box-0.5.png index 413cab719e..2c002bde33 100644 --- a/tests/Images/External/ReferenceOutput/ResizeTests/Resize_WorksWithAllResamplers_CalliphoraPartial_Box-0.5.png +++ b/tests/Images/External/ReferenceOutput/ResizeTests/Resize_WorksWithAllResamplers_CalliphoraPartial_Box-0.5.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:307cee04c98332cd4783caec027e841c4130382996a0fd3d5e50e5cf278c2b30 -size 81225 +oid sha256:963a613c768184e34a8bdb50f7fb1390b6cbfdac8463e0397291ecddf8d02d0a +size 104087 diff --git a/tests/Images/External/ReferenceOutput/ResizeTests/WorkingBufferSizeHintInBytes_IsAppliedCorrectly_TestPattern100x100_50.png b/tests/Images/External/ReferenceOutput/ResizeTests/WorkingBufferSizeHintInBytes_IsAppliedCorrectly_TestPattern100x100_50.png index 8e74e665df..132378ec87 100644 --- a/tests/Images/External/ReferenceOutput/ResizeTests/WorkingBufferSizeHintInBytes_IsAppliedCorrectly_TestPattern100x100_50.png +++ b/tests/Images/External/ReferenceOutput/ResizeTests/WorkingBufferSizeHintInBytes_IsAppliedCorrectly_TestPattern100x100_50.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c35c951bdf36949fee9c834686bc39daac14494768c56e20c6d1b3de30640ef0 -size 1429 +oid sha256:f53c8f2e2e5bf24397c3bde3a066ffdc9b9a767abf9e0f227577e09497b5086d +size 1424 diff --git a/tests/Images/External/ReferenceOutput/ResizeTests/WorkingBufferSizeHintInBytes_IsAppliedCorrectly_TestPattern100x100_60.png b/tests/Images/External/ReferenceOutput/ResizeTests/WorkingBufferSizeHintInBytes_IsAppliedCorrectly_TestPattern100x100_60.png index 8e74e665df..132378ec87 100644 --- a/tests/Images/External/ReferenceOutput/ResizeTests/WorkingBufferSizeHintInBytes_IsAppliedCorrectly_TestPattern100x100_60.png +++ b/tests/Images/External/ReferenceOutput/ResizeTests/WorkingBufferSizeHintInBytes_IsAppliedCorrectly_TestPattern100x100_60.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c35c951bdf36949fee9c834686bc39daac14494768c56e20c6d1b3de30640ef0 -size 1429 +oid sha256:f53c8f2e2e5bf24397c3bde3a066ffdc9b9a767abf9e0f227577e09497b5086d +size 1424 diff --git a/tests/Images/External/ReferenceOutput/ResizeTests/WorkingBufferSizeHintInBytes_IsAppliedCorrectly_TestPattern100x400_110.png b/tests/Images/External/ReferenceOutput/ResizeTests/WorkingBufferSizeHintInBytes_IsAppliedCorrectly_TestPattern100x400_110.png index ad88805d3e..324fc0567a 100644 --- a/tests/Images/External/ReferenceOutput/ResizeTests/WorkingBufferSizeHintInBytes_IsAppliedCorrectly_TestPattern100x400_110.png +++ b/tests/Images/External/ReferenceOutput/ResizeTests/WorkingBufferSizeHintInBytes_IsAppliedCorrectly_TestPattern100x400_110.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:da4bde43ef0945720c64af88642765d9809c3fafc3f74ea766cc73b92c65c5f6 -size 2284 +oid sha256:13c961ada6b5eaa90b3d37565cf9f301a18035b869d71a4f3f0d263ced6933ea +size 3169 diff --git a/tests/Images/External/ReferenceOutput/Transforms/FlipTests/Flip_TestPattern20x37_Horizontal.png b/tests/Images/External/ReferenceOutput/Transforms/FlipTests/Flip_TestPattern20x37_Horizontal.png index 1a2954e4a8..b2e7dbd6fc 100644 --- a/tests/Images/External/ReferenceOutput/Transforms/FlipTests/Flip_TestPattern20x37_Horizontal.png +++ b/tests/Images/External/ReferenceOutput/Transforms/FlipTests/Flip_TestPattern20x37_Horizontal.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:de933ecd5d553ba278d29156d08ff6405fe498a4dae92b1b24c57b65f23e831e -size 1096 +oid sha256:87f96783f33f8bd9505966fa3c346b2da4e4afc43218ad6334c69c5e795f84d1 +size 1126 diff --git a/tests/Images/External/ReferenceOutput/Transforms/FlipTests/Flip_TestPattern20x37_None.png b/tests/Images/External/ReferenceOutput/Transforms/FlipTests/Flip_TestPattern20x37_None.png index 52fe4d8ce4..daf9bfec60 100644 --- a/tests/Images/External/ReferenceOutput/Transforms/FlipTests/Flip_TestPattern20x37_None.png +++ b/tests/Images/External/ReferenceOutput/Transforms/FlipTests/Flip_TestPattern20x37_None.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ea42b20f513e45a81e6979315d4a32411d78339414e4c27968c82bfd66458f7c -size 1097 +oid sha256:74b768538b668bf3599f439254b1af6bfc5c239b41f28f69dfca04fd3f1db917 +size 1114 diff --git a/tests/Images/External/ReferenceOutput/Transforms/FlipTests/Flip_TestPattern20x37_Vertical.png b/tests/Images/External/ReferenceOutput/Transforms/FlipTests/Flip_TestPattern20x37_Vertical.png index d65f126408..74e727e900 100644 --- a/tests/Images/External/ReferenceOutput/Transforms/FlipTests/Flip_TestPattern20x37_Vertical.png +++ b/tests/Images/External/ReferenceOutput/Transforms/FlipTests/Flip_TestPattern20x37_Vertical.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a26b7e67ab4f1f8395bf814ac256c26f9d4d58253fb1de9a92174b4896d1f5cc -size 1093 +oid sha256:3a59a4c9e65db050be8dcdc4cee236ab3d940ef424cb9873aa25ac9e414ec5aa +size 1121 From 9324d85886934eae0e172d1a804bb221aff982a3 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Tue, 1 Dec 2026 13:38:41 +1000 Subject: [PATCH 2/7] Speed up WebP lossy encode with output unchanged - Analysis histogram: Vp8Histogram.BinOperator with one CountBins traversal; zero bins counted with a vector compare and popcount. - Mode trials: exact early-outs with Vp8ModeScore.GetScoreBound in the I4, I16 and UV searches. A mode whose header and distortion already reach the best score skips its spectral distortion and rate. - I4 predictors DC, HE, HD and HU: packed rows stored by ref. - Update shared-infrastructure to the latest main. The encoded bytes are identical to the previous build. --- shared-infrastructure | 2 +- .../Formats/Webp/Lossy/Vp8Encoding.cs | 179 ++++++++--------- .../Formats/Webp/Lossy/Vp8Histogram.cs | 183 +++++++++++++----- .../Formats/Webp/Lossy/Vp8ModeScore.cs | 11 ++ .../Formats/Webp/Lossy/Vp8Quantization.cs | 49 +++-- 5 files changed, 277 insertions(+), 147 deletions(-) diff --git a/shared-infrastructure b/shared-infrastructure index 579946ec6d..1f2a90058b 160000 --- a/shared-infrastructure +++ b/shared-infrastructure @@ -1 +1 @@ -Subproject commit 579946ec6de4350854b17e5213aafd79932cd364 +Subproject commit 1f2a90058b08b0ee01542ffbdd9050ef43e19b04 diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.cs index 42d339a37a..38d281b837 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.cs @@ -892,29 +892,35 @@ public static void EncPredLuma4(Span dst, ReadOnlySpan top, int topO // the left samples L K J I, the top-left sample X, the top samples A B C D and the top-right samples E F G H. // DC, HE, HD and HU have no useful lane layout, so they use the scalar forms. ReadOnlySpan boundary = top.Slice(topOffset - 5, 13); - Dc4(dst[I4DC4..], top, topOffset); + ref byte vectorDst = ref MemoryMarshal.GetReference(dst); + ref byte vectorA = ref MemoryMarshal.GetReference(boundary[5..]); + Dc4(ref Unsafe.Add(ref vectorDst, (nuint)I4DC4), ref vectorA); Tm4(dst[I4TM4..], boundary); Ve4(dst[I4VE4..], boundary); - He4(dst[I4HE4..], top, topOffset); + He4(ref Unsafe.Add(ref vectorDst, (nuint)I4HE4), ref vectorA); Rd4(dst[I4RD4..], boundary); Vr4(dst[I4VR4..], boundary); Ld4(dst[I4LD4..], boundary); Vl4(dst[I4VL4..], boundary); - Hd4(dst[I4HD4..], top, topOffset); - Hu4(dst[I4HU4..], top, topOffset); + Hd4(ref Unsafe.Add(ref vectorDst, (nuint)I4HD4), ref vectorA); + Hu4(ref Unsafe.Add(ref vectorDst, (nuint)I4HU4), ref vectorA); return; } - Dc4(dst[I4DC4..], top, topOffset); + // The ref forms read the 13 boundary samples around A, so one slice checks their range. + ReadOnlySpan samples = top.Slice(topOffset - 5, 13); + ref byte scalarDst = ref MemoryMarshal.GetReference(dst); + ref byte scalarA = ref MemoryMarshal.GetReference(samples[5..]); + Dc4(ref Unsafe.Add(ref scalarDst, (nuint)I4DC4), ref scalarA); Tm4(dst[I4TM4..], top, topOffset); Ve4(dst[I4VE4..], top, topOffset, vals); - He4(dst[I4HE4..], top, topOffset); + He4(ref Unsafe.Add(ref scalarDst, (nuint)I4HE4), ref scalarA); Rd4(dst[I4RD4..], top, topOffset); Vr4(dst[I4VR4..], top, topOffset); Ld4(dst[I4LD4..], top, topOffset); Vl4(dst[I4VL4..], top, topOffset); - Hd4(dst[I4HD4..], top, topOffset); - Hu4(dst[I4HU4..], top, topOffset); + Hd4(ref Unsafe.Add(ref scalarDst, (nuint)I4HD4), ref scalarA); + Hu4(ref Unsafe.Add(ref scalarDst, (nuint)I4HU4), ref scalarA); } /// @@ -1354,19 +1360,18 @@ private static void Vl4(Span dst, ReadOnlySpan boundary) /// /// Writes the 4x4 DC prediction: the rounded mean of the 4 top samples and the 4 left samples. /// - /// The first sample of the block. - /// The boundary samples, in the layout of . - /// The index of the top sample A in . - private static void Dc4(Span dst, ReadOnlySpan top, int topOffset) + /// The first sample of the block. The rows have a stride of . + /// The top sample A. The 5 samples before it are L K J I X, and the 7 after it are B C D E F G H. + private static void Dc4(ref byte dst, ref byte a) { uint dc = 4; - int i; - for (i = 0; i < 4; i++) + for (nuint i = 0; i < 4; i++) { - dc += (uint)(top[topOffset + i] + top[topOffset - 5 + i]); + dc += (uint)(Unsafe.Add(ref a, i) + Unsafe.Subtract(ref a, 5 - i)); } - Fill(dst, (int)(dc >> 3), 4); + uint row = 0x01010101U * (dc >> 3); + StoreRows(ref dst, row, row, row, row); } /// @@ -1414,26 +1419,21 @@ private static void Ve4(Span dst, ReadOnlySpan top, int topOffset, S /// /// Writes the 4x4 horizontal prediction. Each row is the smoothed left sample of that row. /// - /// The first sample of the block. - /// The boundary samples, in the layout of . - /// The index of the top sample A in . - private static void He4(Span dst, ReadOnlySpan top, int topOffset) + /// The first sample of the block. The rows have a stride of . + /// The top sample A. The 5 samples before it are L K J I X. + private static void He4(ref byte dst, ref byte a) { - // horizontal - byte x = top[topOffset - 1]; - byte i = top[topOffset - 2]; - byte j = top[topOffset - 3]; - byte k = top[topOffset - 4]; - byte l = top[topOffset - 5]; - - uint val = 0x01010101U * LossyUtils.Avg3(x, i, j); - BinaryPrimitives.WriteUInt32BigEndian(dst, val); - val = 0x01010101U * LossyUtils.Avg3(i, j, k); - BinaryPrimitives.WriteUInt32BigEndian(dst[(1 * WebpConstants.Bps)..], val); - val = 0x01010101U * LossyUtils.Avg3(j, k, l); - BinaryPrimitives.WriteUInt32BigEndian(dst[(2 * WebpConstants.Bps)..], val); - val = 0x01010101U * LossyUtils.Avg3(k, l, l); - BinaryPrimitives.WriteUInt32BigEndian(dst[(3 * WebpConstants.Bps)..], val); + byte x = Unsafe.Subtract(ref a, (nuint)1); + byte i = Unsafe.Subtract(ref a, (nuint)2); + byte j = Unsafe.Subtract(ref a, (nuint)3); + byte k = Unsafe.Subtract(ref a, (nuint)4); + byte l = Unsafe.Subtract(ref a, (nuint)5); + StoreRows( + ref dst, + 0x01010101U * LossyUtils.Avg3(x, i, j), + 0x01010101U * LossyUtils.Avg3(i, j, k), + 0x01010101U * LossyUtils.Avg3(j, k, l), + 0x01010101U * LossyUtils.Avg3(k, l, l)); } /// @@ -1602,77 +1602,82 @@ private static void Vl4(Span dst, ReadOnlySpan top, int topOffset) /// /// Writes the 4x4 horizontal-down prediction. /// - /// The first sample of the block. - /// The boundary samples, in the layout of . - /// The index of the top sample A in . - private static void Hd4(Span dst, ReadOnlySpan top, int topOffset) + /// The first sample of the block. The rows have a stride of . + /// The top sample A. The 5 samples before it are L K J I X, and the 2 after it are B C. + private static void Hd4(ref byte dst, ref byte a) { - byte x = top[topOffset - 1]; - byte i = top[topOffset - 2]; - byte j = top[topOffset - 3]; - byte k = top[topOffset - 4]; - byte l = top[topOffset - 5]; - byte a = top[topOffset]; - byte b = top[topOffset + 1]; - byte c = top[topOffset + 2]; + byte x = Unsafe.Subtract(ref a, (nuint)1); + byte i = Unsafe.Subtract(ref a, (nuint)2); + byte j = Unsafe.Subtract(ref a, (nuint)3); + byte k = Unsafe.Subtract(ref a, (nuint)4); + byte l = Unsafe.Subtract(ref a, (nuint)5); + byte b = Unsafe.Add(ref a, (nuint)1); + byte c = Unsafe.Add(ref a, (nuint)2); byte ix = LossyUtils.Avg2(i, x); - LossyUtils.Dst(dst, 0, 0, ix); - LossyUtils.Dst(dst, 2, 1, ix); byte ji = LossyUtils.Avg2(j, i); - LossyUtils.Dst(dst, 0, 1, ji); - LossyUtils.Dst(dst, 2, 2, ji); byte kj = LossyUtils.Avg2(k, j); - LossyUtils.Dst(dst, 0, 2, kj); - LossyUtils.Dst(dst, 2, 3, kj); - LossyUtils.Dst(dst, 0, 3, LossyUtils.Avg2(l, k)); - LossyUtils.Dst(dst, 3, 0, LossyUtils.Avg3(a, b, c)); - LossyUtils.Dst(dst, 2, 0, LossyUtils.Avg3(x, a, b)); + byte lk = LossyUtils.Avg2(l, k); + byte abc = LossyUtils.Avg3(a, b, c); + byte xab = LossyUtils.Avg3(x, a, b); byte ixa = LossyUtils.Avg3(i, x, a); - LossyUtils.Dst(dst, 1, 0, ixa); - LossyUtils.Dst(dst, 3, 1, ixa); byte jix = LossyUtils.Avg3(j, i, x); - LossyUtils.Dst(dst, 1, 1, jix); - LossyUtils.Dst(dst, 3, 2, jix); byte kji = LossyUtils.Avg3(k, j, i); - LossyUtils.Dst(dst, 1, 2, kji); - LossyUtils.Dst(dst, 3, 3, kji); - LossyUtils.Dst(dst, 1, 3, LossyUtils.Avg3(l, k, j)); + byte lkj = LossyUtils.Avg3(l, k, j); + + // Each row moves two samples to the right and takes the next pair of values on the left. + StoreRows(ref dst, Pack(ix, ixa, xab, abc), Pack(ji, jix, ix, ixa), Pack(kj, kji, ji, jix), Pack(lk, lkj, kj, kji)); } /// /// Writes the 4x4 horizontal-up prediction. It reads only the left samples. The samples below the left column repeat L. /// - /// The first sample of the block. - /// The boundary samples, in the layout of . - /// The index of the top sample A in . - private static void Hu4(Span dst, ReadOnlySpan top, int topOffset) + /// The first sample of the block. The rows have a stride of . + /// The top sample A. The 5 samples before it are L K J I X. + private static void Hu4(ref byte dst, ref byte a) { - byte i = top[topOffset - 2]; - byte j = top[topOffset - 3]; - byte k = top[topOffset - 4]; - byte l = top[topOffset - 5]; + byte i = Unsafe.Subtract(ref a, (nuint)2); + byte j = Unsafe.Subtract(ref a, (nuint)3); + byte k = Unsafe.Subtract(ref a, (nuint)4); + byte l = Unsafe.Subtract(ref a, (nuint)5); - LossyUtils.Dst(dst, 0, 0, LossyUtils.Avg2(i, j)); + byte ij = LossyUtils.Avg2(i, j); byte jk = LossyUtils.Avg2(j, k); - LossyUtils.Dst(dst, 2, 0, jk); - LossyUtils.Dst(dst, 0, 1, jk); byte kl = LossyUtils.Avg2(k, l); - LossyUtils.Dst(dst, 2, 1, kl); - LossyUtils.Dst(dst, 0, 2, kl); - LossyUtils.Dst(dst, 1, 0, LossyUtils.Avg3(i, j, k)); + byte ijk = LossyUtils.Avg3(i, j, k); byte jkl = LossyUtils.Avg3(j, k, l); - LossyUtils.Dst(dst, 3, 0, jkl); - LossyUtils.Dst(dst, 1, 1, jkl); byte kll = LossyUtils.Avg3(k, l, l); - LossyUtils.Dst(dst, 3, 1, kll); - LossyUtils.Dst(dst, 1, 2, kll); - LossyUtils.Dst(dst, 3, 2, l); - LossyUtils.Dst(dst, 2, 2, l); - LossyUtils.Dst(dst, 0, 3, l); - LossyUtils.Dst(dst, 1, 3, l); - LossyUtils.Dst(dst, 2, 3, l); - LossyUtils.Dst(dst, 3, 3, l); + + // Each row moves two samples to the left, and L fills the rest. + StoreRows(ref dst, Pack(ij, ijk, jk, jkl), Pack(jk, jkl, kl, kll), Pack(kl, kll, l, l), 0x01010101U * l); + } + + /// + /// Packs the 4 samples of one row into a word, the first sample in the low byte, as a little-endian store writes them. + /// + /// The first sample. + /// The second sample. + /// The third sample. + /// The fourth sample. + /// The packed row. + [MethodImpl(InliningOptions.ShortMethod)] + private static uint Pack(byte s0, byte s1, byte s2, byte s3) => s0 | ((uint)s1 << 8) | ((uint)s2 << 16) | ((uint)s3 << 24); + + /// + /// Stores the 4 packed rows of a 4x4 block, one word store for each row. + /// + /// The first sample of the block. The rows have a stride of . + /// The first row. + /// The second row. + /// The third row. + /// The fourth row. + [MethodImpl(InliningOptions.ShortMethod)] + private static void StoreRows(ref byte dst, uint row0, uint row1, uint row2, uint row3) + { + BinaryPrimitives.WriteUInt32LittleEndian(MemoryMarshal.CreateSpan(ref dst, 4), row0); + BinaryPrimitives.WriteUInt32LittleEndian(MemoryMarshal.CreateSpan(ref Unsafe.Add(ref dst, (nuint)WebpConstants.Bps), 4), row1); + BinaryPrimitives.WriteUInt32LittleEndian(MemoryMarshal.CreateSpan(ref Unsafe.Add(ref dst, (nuint)(2 * WebpConstants.Bps)), 4), row2); + BinaryPrimitives.WriteUInt32LittleEndian(MemoryMarshal.CreateSpan(ref Unsafe.Add(ref dst, (nuint)(3 * WebpConstants.Bps)), 4), row3); } /// diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Histogram.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Histogram.cs index 9017211eec..243953e052 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Histogram.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Histogram.cs @@ -1,6 +1,7 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; @@ -99,70 +100,89 @@ ref Unsafe.Add(ref outputRef, (nuint)16), Vp8Encoding.FTransform(ref Unsafe.Add(ref referenceRef, offset), ref Unsafe.Add(ref predRef, offset), ref outputRef, ref scratchRef); } - // Replace each coefficient with its bin. The coefficients of one or two blocks are contiguous, so the widest - // accelerated width takes them all: a 512-bit vector holds two blocks and a 256-bit vector one block. - nuint k = 0; - if (Vector512.IsHardwareAccelerated) - { - for (; k + (uint)Vector512.Count <= coefficients; k += (uint)Vector512.Count) - { - Bin(Vector512.LoadUnsafe(ref outputRef, k)).StoreUnsafe(ref outputRef, k); - } - } + CountBins(ref outputRef, coefficients, ref distribution[0]); + } - if (Vector256.IsHardwareAccelerated) - { - for (; k + (uint)Vector256.Count <= coefficients; k += (uint)Vector256.Count) - { - Bin(Vector256.LoadUnsafe(ref outputRef, k)).StoreUnsafe(ref outputRef, k); - } - } + this.SetHistogramData(distribution); + } - if (Vector128.IsHardwareAccelerated) + /// + /// Adds the bin of each coefficient to the distribution. The widest accelerated width runs first, then the narrower widths and + /// the scalar form take the rest. The coefficients of one or two blocks are contiguous, so a 512-bit vector takes two blocks and + /// a 256-bit vector one block. + /// + /// + /// Most bins are 0. The zero lanes of each vector add to the count of bin 0 with one population count, and only the other lanes + /// add one by one. The counts are the same as with one increment for each coefficient. + /// + /// The first coefficient. It receives the bins. + /// The number of coefficients: 16 or 32. + /// The count of bin 0. The counts of the bins 0 to follow it. + [MethodImpl(InliningOptions.ShortMethod)] + private static void CountBins(ref short coefficients, nuint count, ref int distribution) + { + // The bins are stored over the coefficients, so the non-zero lanes read their bins back as scalars. + nuint i = 0; + int zeros = 0; + if (Vector512.IsHardwareAccelerated) + { + for (; i + (uint)Vector512.Count <= count; i += (uint)Vector512.Count) { - for (; k + (uint)Vector128.Count <= coefficients; k += (uint)Vector128.Count) - { - Bin(Vector128.LoadUnsafe(ref outputRef, k)).StoreUnsafe(ref outputRef, k); - } + Vector512 bins = BinOperator.Bin(Vector512.LoadUnsafe(ref coefficients, i)); + bins.StoreUnsafe(ref coefficients, i); + ulong zeroLanes = BinOperator.GetZeroLanes(bins); + zeros += BitOperations.PopCount(zeroLanes); + CountLanes(~zeroLanes & uint.MaxValue, ref Unsafe.Add(ref coefficients, i), ref distribution); } + } - for (; k < coefficients; k++) + if (Vector256.IsHardwareAccelerated) + { + for (; i + (uint)Vector256.Count <= count; i += (uint)Vector256.Count) { - ref short coefficient = ref Unsafe.Add(ref outputRef, k); - coefficient = (short)ClipMax(Math.Abs(coefficient) >> 3, MaxCoeffThresh); + Vector256 bins = BinOperator.Bin(Vector256.LoadUnsafe(ref coefficients, i)); + bins.StoreUnsafe(ref coefficients, i); + uint zeroLanes = BinOperator.GetZeroLanes(bins); + zeros += BitOperations.PopCount(zeroLanes); + CountLanes(~zeroLanes & ushort.MaxValue, ref Unsafe.Add(ref coefficients, i), ref distribution); } + } - for (nuint i = 0; i < coefficients; i++) + if (Vector128.IsHardwareAccelerated) + { + for (; i + (uint)Vector128.Count <= count; i += (uint)Vector128.Count) { - ++distribution[Unsafe.Add(ref outputRef, i)]; + Vector128 bins = BinOperator.Bin(Vector128.LoadUnsafe(ref coefficients, i)); + bins.StoreUnsafe(ref coefficients, i); + uint zeroLanes = BinOperator.GetZeroLanes(bins); + zeros += BitOperations.PopCount(zeroLanes); + CountLanes(~zeroLanes & byte.MaxValue, ref Unsafe.Add(ref coefficients, i), ref distribution); } } - this.SetHistogramData(distribution); + distribution += zeros; + for (; i < count; i++) + { + Unsafe.Add(ref distribution, (nuint)BinOperator.Bin(Unsafe.Add(ref coefficients, i)))++; + } } /// - /// Gets the bin of each coefficient: min(abs(coefficient) >> 3, MaxCoeffThresh). + /// Adds one to the count of the bin of each selected lane. /// - /// - /// The absolute value is read as unsigned 16-bit. Thus the absolute value of -32768 is 32768, as in the 32-bit - /// scalar arithmetic, and its bin is MaxCoeffThresh. - /// - /// The coefficients, one in each lane. - /// The bins, one in each lane. + /// The mask of the selected lanes: bit i selects lane i. + /// The bin of the first lane. + /// The count of bin 0. [MethodImpl(InliningOptions.ShortMethod)] - private static Vector128 Bin(Vector128 coefficients) - => Vector128.Min(Vector128.Abs(coefficients).AsUInt16() >>> 3, Vector128.Create((ushort)MaxCoeffThresh)).AsInt16(); - - /// - [MethodImpl(InliningOptions.ShortMethod)] - private static Vector256 Bin(Vector256 coefficients) - => Vector256.Min(Vector256.Abs(coefficients).AsUInt16() >>> 3, Vector256.Create((ushort)MaxCoeffThresh)).AsInt16(); - - /// - [MethodImpl(InliningOptions.ShortMethod)] - private static Vector512 Bin(Vector512 coefficients) - => Vector512.Min(Vector512.Abs(coefficients).AsUInt16() >>> 3, Vector512.Create((ushort)MaxCoeffThresh)).AsInt16(); + private static void CountLanes(ulong lanes, ref short bins, ref int distribution) + { + while (lanes != 0) + { + nuint lane = (nuint)BitOperations.TrailingZeroCount(lanes); + Unsafe.Add(ref distribution, (nuint)(ushort)Unsafe.Add(ref bins, lane))++; + lanes &= lanes - 1; + } + } /// /// Raises the maximum value and the last-non-zero index of to those of this @@ -217,4 +237,73 @@ private void SetHistogramData(ReadOnlySpan distribution) /// The smaller of and . [MethodImpl(InliningOptions.ShortMethod)] private static int ClipMax(int v, int max) => v > max ? max : v; + + /// + /// Maps forward transform coefficients to histogram bins: min(abs(coefficient) >> 3, MaxCoeffThresh). + /// + /// + /// Each overload gives the same bins. The absolute value is read as unsigned 16-bit, so the absolute value of -32768 is 32768, as + /// in the 32-bit scalar arithmetic, and its bin is MaxCoeffThresh. + /// + private static class BinOperator + { + /// + /// Gets the bin of one coefficient. + /// + /// The coefficient. + /// The bin. + [MethodImpl(InliningOptions.ShortMethod)] + public static int Bin(short coefficient) => ClipMax(Math.Abs((int)coefficient) >> 3, MaxCoeffThresh); + + /// + /// Gets the bin of each of eight coefficients. + /// + /// The coefficients, one in each lane. + /// The bins, one in each lane. + [MethodImpl(InliningOptions.ShortMethod)] + public static Vector128 Bin(Vector128 coefficients) + => Vector128.Min(Vector128.Abs(coefficients).AsUInt16() >>> 3, Vector128.Create((ushort)MaxCoeffThresh)).AsInt16(); + + /// + /// Gets the bin of each of sixteen coefficients. + /// + /// The coefficients, one in each lane. + /// The bins, one in each lane. + [MethodImpl(InliningOptions.ShortMethod)] + public static Vector256 Bin(Vector256 coefficients) + => Vector256.Min(Vector256.Abs(coefficients).AsUInt16() >>> 3, Vector256.Create((ushort)MaxCoeffThresh)).AsInt16(); + + /// + /// Gets the bin of each of thirty-two coefficients. + /// + /// The coefficients, one in each lane. + /// The bins, one in each lane. + [MethodImpl(InliningOptions.ShortMethod)] + public static Vector512 Bin(Vector512 coefficients) + => Vector512.Min(Vector512.Abs(coefficients).AsUInt16() >>> 3, Vector512.Create((ushort)MaxCoeffThresh)).AsInt16(); + + /// + /// Gets the mask of the lanes with bin 0 among eight bins. + /// + /// The bins. + /// The mask: bit i is set when lane i has bin 0. + [MethodImpl(InliningOptions.ShortMethod)] + public static uint GetZeroLanes(Vector128 bins) => Vector128.Equals(bins, Vector128.Zero).ExtractMostSignificantBits(); + + /// + /// Gets the mask of the lanes with bin 0 among sixteen bins. + /// + /// The bins. + /// The mask: bit i is set when lane i has bin 0. + [MethodImpl(InliningOptions.ShortMethod)] + public static uint GetZeroLanes(Vector256 bins) => Vector256.Equals(bins, Vector256.Zero).ExtractMostSignificantBits(); + + /// + /// Gets the mask of the lanes with bin 0 among thirty-two bins. + /// + /// The bins. + /// The mask: bit i is set when lane i has bin 0. + [MethodImpl(InliningOptions.ShortMethod)] + public static ulong GetZeroLanes(Vector512 bins) => Vector512.Equals(bins, Vector512.Zero).ExtractMostSignificantBits(); + } } diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8ModeScore.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8ModeScore.cs index 61736ff0ca..8a79acac58 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8ModeScore.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8ModeScore.cs @@ -148,4 +148,15 @@ public void AddScore(Vp8ModeScore other) /// /// The weight of the rate and the header bits against the distortion. public void SetRdScore(int lambda) => this.Score = ((this.R + this.H) * lambda) + (RdDistoMult * (this.D + this.SD)); + + /// + /// Gets the lowest score that a candidate with these header bits and this distortion can get. The rate and the spectral + /// distortion are never negative, so the score of is at least this value. A candidate whose bound + /// reaches the best score cannot replace it, and its rate and spectral distortion need not be computed. + /// + /// The header bits. + /// The distortion. + /// The lambda of the score. + /// The lowest possible score. + public static long GetScoreBound(long header, long distortion, int lambda) => (header * lambda) + (RdDistoMult * distortion); } diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Quantization.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Quantization.cs index cdcbb152cb..fa2da3c898 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Quantization.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Quantization.cs @@ -131,24 +131,32 @@ public static void PickBestIntra16(Vp8EncoderIterator it, ref Vp8ModeScore rd, V // Reconstruct. rdCur.Nz = (uint)ReconstructIntra16(it, dqm, rdCur, proba, ref tmpDstRef, mode); - // Measure RD-score. - rdCur.D = LossyUtils.Vp8_Sse16x16(src, tmpDst); - rdCur.SD = Mult8B(tlambda, LossyUtils.Vp8Disto16X16(ref srcSums, ref tmpDstRef, ref weights, ref scratch)); - rdCur.H = WebpConstants.Vp8FixedCostsI16[mode]; - rdCur.R = it.GetCostLuma16(rdCur, proba, res); - + // Measure RD-score. The flatness refinement runs for every mode, because a mode that is not flat ends it for the later modes. + long distortion = LossyUtils.Vp8_Sse16x16(src, tmpDst); + int header = WebpConstants.Vp8FixedCostsI16[mode]; + bool doubled = false; if (isFlat) { // Refine the first impression (which was in pixel space). isFlat = IsFlat(ref MemoryMarshal.GetArrayDataReference(rdCur.YAcLevels), numBlocks, WebpConstants.FlatnessLimitI16); - if (isFlat) - { - // Block is very flat. We put emphasis on the distortion being very low! - rdCur.D *= 2; - rdCur.SD *= 2; - } + doubled = isFlat; } + // Block is very flat. We put emphasis on the distortion being very low! + distortion = doubled ? 2 * distortion : distortion; + + // A mode that cannot reach a lower score than the best mode needs no spectral distortion and no rate. + if (mode > 0 && Vp8ModeScore.GetScoreBound(header, distortion, lambda) >= rdBest.Score) + { + continue; + } + + rdCur.D = distortion; + rdCur.SD = Mult8B(tlambda, LossyUtils.Vp8Disto16X16(ref srcSums, ref tmpDstRef, ref weights, ref scratch)); + rdCur.SD = doubled ? 2 * rdCur.SD : rdCur.SD; + rdCur.H = header; + rdCur.R = it.GetCostLuma16(rdCur, proba, res); + // The search always checks Intra16 first, so it can overwrite *rd directly. rdCur.SetRdScore(lambda); @@ -313,6 +321,16 @@ ref Unsafe.Add(ref levels, (nuint)16), // Compute the distortions of both modes. LossyUtils.Vp8_Sse4x4Pair(ref src, ref pairRecon, out int d0, out int d1); + + // When neither mode of the pair can reach a lower score than the best mode, the pair changes nothing, so it needs no + // spectral sums and no rates. + if (bestMode >= 0 + && Vp8ModeScore.GetScoreBound(modeCosts[pair], d0, lambda) >= rdi4.Score + && Vp8ModeScore.GetScoreBound(modeCosts[pair + 1], d1, lambda) >= rdi4.Score) + { + continue; + } + LossyUtils.TTransformSums2(ref pairRecon, ref weights, ref scratch, out int sum0, out int sum1); int sd0 = Mult8B(tlambda, Math.Abs(srcSum - sum0) >> 5); int sd1 = Mult8B(tlambda, Math.Abs(srcSum - sum1) >> 5); @@ -436,6 +454,13 @@ public static void PickBestUv(Vp8EncoderIterator it, ref Vp8ModeScore rd, Vp8Seg rdUv.D = LossyUtils.Vp8_Sse16x8(src, tmpDst); rdUv.SD = 0; // not calling TDisto here: it tends to flatten areas. rdUv.H = WebpConstants.Vp8FixedCostsUv[mode]; + + // A mode that cannot reach a lower score than the best mode needs no rate. + if (mode > 0 && Vp8ModeScore.GetScoreBound(rdUv.H, rdUv.D, lambda) >= rdBest.Score) + { + continue; + } + rdUv.R = it.GetCostUv(rdUv, proba, res); if (mode > 0 && IsFlat(ref MemoryMarshal.GetArrayDataReference(rdUv.UvLevels), numBlocks, WebpConstants.FlatnessLimitIUv)) { From 6fbecf5fd0e0c11e5e0c13b983ac9f724ab7cb2b Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Tue, 1 Dec 2026 13:55:56 +1000 Subject: [PATCH 3/7] Update the JPEG XL benchmark results --- .../Codecs/Jxl/DecodeJxl.cs | 67 +++--------- .../Codecs/Jxl/EncodeJxl.cs | 101 +++++++----------- 2 files changed, 58 insertions(+), 110 deletions(-) diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jxl/DecodeJxl.cs b/tests/ImageSharp.Benchmarks/Codecs/Jxl/DecodeJxl.cs index d143fbb01b..c3e8fa8fdb 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jxl/DecodeJxl.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jxl/DecodeJxl.cs @@ -102,56 +102,23 @@ private static void ValidatePixels(Image image, JxlReferenceImage re } } - /* Results 05.11.2026 - BenchmarkDotNet v0.15.8, Windows 11 (10.0.26300.9818) + /* Results 01.12.2026 + BenchmarkDotNet v0.15.8, Windows 11 (10.0.26300.10075) AMD RYZEN AI MAX+ 395 w/ Radeon 8060S 3.00GHz, 1 CPU, 32 logical and 16 physical cores - .NET SDK 11.0.100-preview.7.26381.103 - [Host] : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 - Job-RCQXAA : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 - - Arguments=/p:DebugType=portable IterationCount=3 LaunchCount=1 - WarmupCount=3 - - Without NativeMemoryProfiler (21:06:39): - - | Method | TestImage | Mean | Error | StdDev | Ratio | Allocated | Alloc Ratio | - | ---------- | ------------------------- | --------: | -------: | -------: | ----: | --------: | ----------: | - | ImageSharp | Jxl/dice.jxl | 19.28 ms | 2.964 ms | 0.162 ms | 0.64 | 37624 B | 522.56 | - | Libjxl | Jxl/dice.jxl | 29.92 ms | 4.678 ms | 0.256 ms | 1.00 | 72 B | 1.00 | - | | | | | | | | | - | ImageSharp | Jxl/has_permutation.jxl | 17.74 ms | 2.636 ms | 0.145 ms | 0.34 | 27440 B | 356.36 | - | Libjxl | Jxl/has_permutation.jxl | 51.67 ms | 5.092 ms | 0.279 ms | 1.00 | 77 B | 1.00 | - | | | | | | | | | - | ImageSharp | Jxl/issue648_palette0.jxl | 114.89 ms | 2.645 ms | 0.145 ms | 0.88 | 30040 B | 417.22 | - | Libjxl | Jxl/issue648_palette0.jxl | 130.66 ms | 7.784 ms | 0.427 ms | 1.00 | 72 B | 1.00 | - | | | | | | | | | - | ImageSharp | Jxl/progressive_ac.jxl | 49.93 ms | 4.589 ms | 0.252 ms | 0.49 | 26688 B | 370.67 | - | Libjxl | Jxl/progressive_ac.jxl | 100.92 ms | 8.644 ms | 0.474 ms | 1.00 | 72 B | 1.00 | - - With NativeMemoryProfiler (21:11:13): - - | Method | TestImage | Mean | Error | StdDev | Ratio | Allocated native memory | Native memory leak | Allocated | Alloc Ratio | - | ---------- | ------------------------- | --------: | --------: | -------: | ----: | ----------------------: | -----------------: | --------: | ----------: | - | ImageSharp | Jxl/dice.jxl | 20.44 ms | 7.559 ms | 0.414 ms | 0.65 | 5,243,136 B | 5,243,136 B | 37624 B | 522.56 | - | Libjxl | Jxl/dice.jxl | 31.29 ms | 3.379 ms | 0.185 ms | 1.00 | 53,902,572 B | - | 72 B | 1.00 | - | | | | | | | | | | | - | ImageSharp | Jxl/has_permutation.jxl | 18.73 ms | 12.245 ms | 0.671 ms | 0.36 | 356 B | 242 B | 27440 B | 356.36 | - | Libjxl | Jxl/has_permutation.jxl | 51.83 ms | 6.651 ms | 0.365 ms | 1.00 | 49,736,696 B | 33 B | 77 B | 1.00 | - | | | | | | | | | | | - | ImageSharp | Jxl/issue648_palette0.jxl | 119.53 ms | 11.650 ms | 0.639 ms | 0.89 | 1,281,548 B | 1,420 B | 30040 B | 417.22 | - | Libjxl | Jxl/issue648_palette0.jxl | 134.28 ms | 20.583 ms | 1.128 ms | 1.00 | 119,047,387 B | - | 72 B | 1.00 | - | | | | | | | | | | | - | ImageSharp | Jxl/progressive_ac.jxl | 52.61 ms | 12.969 ms | 0.711 ms | 0.51 | 796,806 B | 28 B | 26688 B | 333.60 | - | Libjxl | Jxl/progressive_ac.jxl | 102.91 ms | 15.121 ms | 0.829 ms | 1.00 | 106,975,397 B | - | 80 B | 1.00 | - - libjxl 0.12.0 through JxlNet 0.12.0.5. - Each operation includes decoder/output allocation, complete decode, shared final pixel bounds and disposal. - Output is unassociated sRGB float RGBA in codestream order. Ancillary EXIF/XMP is skipped by every decoder. - Full-image output validation runs before measurement. The existing Config.Short and .NET JIT/thread settings are unchanged. - - Allocated reports new managed allocations. Allocated native memory reports new native allocations. - Reused pooled buffers are not new allocations. These columns do not measure peak working memory. - ImageSharp's native leak values are entirely retained pooled storage. - Every output contains 16 bytes per pixel. Error is half the 99.9% confidence interval; StdDev describes the three measured iterations. + .NET SDK 11.0.100 + [Host] : .NET 10.0.15 (10.0.15, 10.0.1526.53008), X64 RyuJIT x86-64-v4 + Toolchain=InProcessEmitToolchain IterationCount=10 IterationTime=100ms + WarmupCount=10 DOTNET_GCHighMemPercent=0x63 + + | Method | TestImage | Mean | Error | StdDev | Ratio | RatioSD | Allocated | Alloc Ratio | + |------------|---------------------------|----------:|---------:|---------:|------:|--------:|----------:|------------:| + | ImageSharp | Jxl/dice.jxl | 18.97 ms | 0.660 ms | 0.345 ms | 0.56 | 0.02 | 34872 B | 54.49 | + | Libjxl | Jxl/dice.jxl | 34.14 ms | 2.128 ms | 1.408 ms | 1.00 | 0.06 | 640 B | 1.00 | + | ImageSharp | Jxl/has_permutation.jxl | 18.90 ms | 3.150 ms | 2.084 ms | 0.37 | 0.04 | 28180 B | 14.93 | + | Libjxl | Jxl/has_permutation.jxl | 51.57 ms | 1.477 ms | 0.772 ms | 1.00 | 0.02 | 1888 B | 1.00 | + | ImageSharp | Jxl/issue648_palette0.jxl | 113.52 ms | 4.630 ms | 3.062 ms | 0.86 | 0.02 | 30456 B | 4.79 | + | Libjxl | Jxl/issue648_palette0.jxl | 132.60 ms | 2.037 ms | 1.212 ms | 1.00 | 0.01 | 6352 B | 1.00 | + | ImageSharp | Jxl/progressive_ac.jxl | 52.04 ms | 0.407 ms | 0.242 ms | 0.52 | 0.01 | 28928 B | 5.05 | + | Libjxl | Jxl/progressive_ac.jxl | 100.98 ms | 1.961 ms | 1.297 ms | 1.00 | 0.02 | 5728 B | 1.00 | */ } diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jxl/EncodeJxl.cs b/tests/ImageSharp.Benchmarks/Codecs/Jxl/EncodeJxl.cs index 1c7406de9b..35ef1c5d0b 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jxl/EncodeJxl.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jxl/EncodeJxl.cs @@ -248,66 +248,47 @@ private static void Check(JxlEncoderStatus status) } } - /* Results 12.11.2026 - BenchmarkDotNet v0.15.8, Windows 11 (10.0.26300.9818) + /* Results 01.12.2026 + BenchmarkDotNet v0.15.8, Windows 11 (10.0.26300.10075) AMD RYZEN AI MAX+ 395 w/ Radeon 8060S 3.00GHz, 1 CPU, 32 logical and 16 physical cores - .NET SDK 11.0.100-preview.7.26381.103 - [Host] : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 - Job-RCQXAA : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 - - Arguments=/p:DebugType=portable IterationCount=3 LaunchCount=1 - WarmupCount=3 - - | Method | TestImage | Distance | Progressive | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | - |----------- |-------------------------- |--------- |------------ |-----------:|------------:|----------:|------:|--------:|---------:|---------:|---------:|----------:|------------:| - | ImageSharp | Jxl/dice.jxl | 0 | False | 4.416 ms | 0.5669 ms | 0.0311 ms | 0.52 | 0.00 | 7.8125 | 7.8125 | 7.8125 | 10959 B | 40.29 | - | Libjxl | Jxl/dice.jxl | 0 | False | 8.532 ms | 1.2719 ms | 0.0697 ms | 1.00 | 0.01 | - | - | - | 272 B | 1.00 | - | | | | | | | | | | | | | | | - | ImageSharp | Jxl/dice.jxl | 0 | True | 5.396 ms | 0.4826 ms | 0.0265 ms | 0.15 | 0.00 | 15.6250 | 15.6250 | 15.6250 | 21131 B | 28.91 | - | Libjxl | Jxl/dice.jxl | 0 | True | 36.439 ms | 2.0891 ms | 0.1145 ms | 1.00 | 0.00 | - | - | - | 731 B | 1.00 | - | | | | | | | | | | | | | | | - | ImageSharp | Jxl/dice.jxl | 1 | False | 5.157 ms | 1.3154 ms | 0.0721 ms | 0.24 | 0.00 | 15.6250 | 15.6250 | 15.6250 | 8770 B | 21.87 | - | Libjxl | Jxl/dice.jxl | 1 | False | 21.226 ms | 4.2897 ms | 0.2351 ms | 1.00 | 0.01 | - | - | - | 401 B | 1.00 | - | | | | | | | | | | | | | | | - | ImageSharp | Jxl/dice.jxl | 1 | True | 5.184 ms | 1.0561 ms | 0.0579 ms | 0.17 | 0.00 | 15.6250 | 15.6250 | 15.6250 | 8770 B | 21.87 | - | Libjxl | Jxl/dice.jxl | 1 | True | 29.779 ms | 1.8818 ms | 0.1031 ms | 1.00 | 0.00 | - | - | - | 401 B | 1.00 | - | | | | | | | | | | | | | | | - | ImageSharp | Jxl/has_permutation.jxl | 0 | False | 5.908 ms | 0.4359 ms | 0.0239 ms | 0.27 | 0.00 | 7.8125 | 7.8125 | 7.8125 | 11138 B | 27.78 | - | Libjxl | Jxl/has_permutation.jxl | 0 | False | 21.489 ms | 0.5220 ms | 0.0286 ms | 1.00 | 0.00 | - | - | - | 401 B | 1.00 | - | | | | | | | | | | | | | | | - | ImageSharp | Jxl/has_permutation.jxl | 0 | True | 13.321 ms | 0.8920 ms | 0.0489 ms | 0.10 | 0.00 | 31.2500 | 31.2500 | 31.2500 | 10451 B | 4.75 | - | Libjxl | Jxl/has_permutation.jxl | 0 | True | 139.785 ms | 10.9720 ms | 0.6014 ms | 1.00 | 0.01 | - | - | - | 2198 B | 1.00 | - | | | | | | | | | | | | | | | - | ImageSharp | Jxl/has_permutation.jxl | 1 | False | 21.953 ms | 9.0182 ms | 0.4943 ms | 0.29 | 0.01 | 62.5000 | 62.5000 | 62.5000 | 11102 B | 8.42 | - | Libjxl | Jxl/has_permutation.jxl | 1 | False | 75.391 ms | 9.5058 ms | 0.5210 ms | 1.00 | 0.01 | - | - | - | 1318 B | 1.00 | - | | | | | | | | | | | | | | | - | ImageSharp | Jxl/has_permutation.jxl | 1 | True | 30.069 ms | 20.8179 ms | 1.1411 ms | 0.23 | 0.02 | 62.5000 | 62.5000 | 62.5000 | 11135 B | 5.07 | - | Libjxl | Jxl/has_permutation.jxl | 1 | True | 132.523 ms | 163.2294 ms | 8.9472 ms | 1.00 | 0.08 | - | - | - | 2198 B | 1.00 | - | | | | | | | | | | | | | | | - | ImageSharp | Jxl/issue648_palette0.jxl | 0 | False | 15.571 ms | 2.1124 ms | 0.1158 ms | 0.41 | 0.01 | 31.2500 | 31.2500 | 31.2500 | 36222 B | 49.55 | - | Libjxl | Jxl/issue648_palette0.jxl | 0 | False | 37.653 ms | 21.5425 ms | 1.1808 ms | 1.00 | 0.04 | - | - | - | 731 B | 1.00 | - | | | | | | | | | | | | | | | - | ImageSharp | Jxl/issue648_palette0.jxl | 0 | True | 20.627 ms | 1.5929 ms | 0.0873 ms | 0.12 | 0.00 | 62.5000 | 62.5000 | 62.5000 | 12447 B | 5.66 | - | Libjxl | Jxl/issue648_palette0.jxl | 0 | True | 165.912 ms | 10.4955 ms | 0.5753 ms | 1.00 | 0.00 | - | - | - | 2198 B | 1.00 | - | | | | | | | | | | | | | | | - | ImageSharp | Jxl/issue648_palette0.jxl | 1 | False | 21.051 ms | 5.7083 ms | 0.3129 ms | 0.31 | 0.00 | 62.5000 | 62.5000 | 62.5000 | 10894 B | 9.30 | - | Libjxl | Jxl/issue648_palette0.jxl | 1 | False | 67.920 ms | 10.6730 ms | 0.5850 ms | 1.00 | 0.01 | - | - | - | 1171 B | 1.00 | - | | | | | | | | | | | | | | | - | ImageSharp | Jxl/issue648_palette0.jxl | 1 | True | 25.149 ms | 4.0404 ms | 0.2215 ms | 0.24 | 0.00 | 62.5000 | 62.5000 | 62.5000 | 10911 B | 6.11 | - | Libjxl | Jxl/issue648_palette0.jxl | 1 | True | 102.883 ms | 11.9190 ms | 0.6533 ms | 1.00 | 0.01 | - | - | - | 1787 B | 1.00 | - | | | | | | | | | | | | | | | - | ImageSharp | Jxl/progressive_ac.jxl | 0 | False | 29.919 ms | 2.5288 ms | 0.1386 ms | 0.39 | 0.00 | 31.2500 | 31.2500 | 31.2500 | 36222 B | 27.48 | - | Libjxl | Jxl/progressive_ac.jxl | 0 | False | 77.084 ms | 3.6761 ms | 0.2015 ms | 1.00 | 0.00 | - | - | - | 1318 B | 1.00 | - | | | | | | | | | | | | | | | - | ImageSharp | Jxl/progressive_ac.jxl | 0 | True | 40.029 ms | 1.0292 ms | 0.0564 ms | 0.15 | 0.00 | 153.8462 | 153.8462 | 153.8462 | 26330 B | 6.19 | - | Libjxl | Jxl/progressive_ac.jxl | 0 | True | 275.095 ms | 28.2466 ms | 1.5483 ms | 1.00 | 0.01 | - | - | - | 4252 B | 1.00 | - | | | | | | | | | | | | | | | - | ImageSharp | Jxl/progressive_ac.jxl | 1 | False | 41.247 ms | 29.3119 ms | 1.6067 ms | 0.27 | 0.01 | 153.8462 | 153.8462 | 153.8462 | 14381 B | 6.54 | - | Libjxl | Jxl/progressive_ac.jxl | 1 | False | 150.854 ms | 30.4876 ms | 1.6711 ms | 1.00 | 0.01 | - | - | - | 2198 B | 1.00 | - | | | | | | | | | | | | | | | - | ImageSharp | Jxl/progressive_ac.jxl | 1 | True | 53.636 ms | 5.6686 ms | 0.3107 ms | 0.27 | 0.00 | 222.2222 | 222.2222 | 222.2222 | 16764 B | 5.81 | - | Libjxl | Jxl/progressive_ac.jxl | 1 | True | 198.356 ms | 39.6413 ms | 2.1729 ms | 1.00 | 0.01 | - | - | - | 2883 B | 1.00 | - - Allocated reports managed memory only. + .NET SDK 11.0.100 + [Host] : .NET 10.0.15 (10.0.15, 10.0.1526.53008), X64 RyuJIT x86-64-v4 + Toolchain=InProcessEmitToolchain IterationCount=10 IterationTime=100ms + WarmupCount=10 DOTNET_GCHighMemPercent=0x63 + + | Method | TestImage | Distance | Progressive | Mean | Error | StdDev | Ratio | RatioSD | Allocated | Alloc Ratio | + |------------|---------------------------|---------:|-------------|-----------:|----------:|----------:|------:|--------:|----------:|------------:| + | ImageSharp | Jxl/dice.jxl | 0 | False | 2.453 ms | 0.0660 ms | 0.0393 ms | 0.28 | 0.01 | 4632 B | 7.26 | + | Libjxl | Jxl/dice.jxl | 0 | False | 8.778 ms | 0.3061 ms | 0.2025 ms | 1.00 | 0.03 | 638 B | 1.00 | + | ImageSharp | Jxl/dice.jxl | 0 | True | 7.372 ms | 1.8273 ms | 1.2086 ms | 0.19 | 0.03 | 34624 B | 23.27 | + | Libjxl | Jxl/dice.jxl | 0 | True | 38.231 ms | 1.6000 ms | 1.0583 ms | 1.00 | 0.04 | 1488 B | 1.00 | + | ImageSharp | Jxl/dice.jxl | 1 | False | 6.979 ms | 0.3633 ms | 0.1900 ms | 0.32 | 0.01 | 26620 B | 14.79 | + | Libjxl | Jxl/dice.jxl | 1 | False | 22.108 ms | 0.4793 ms | 0.3170 ms | 1.00 | 0.02 | 1800 B | 1.00 | + | ImageSharp | Jxl/dice.jxl | 1 | True | 7.652 ms | 0.3225 ms | 0.2133 ms | 0.26 | 0.01 | 30540 B | 54.15 | + | Libjxl | Jxl/dice.jxl | 1 | True | 29.515 ms | 0.7353 ms | 0.4864 ms | 1.00 | 0.02 | 564 B | 1.00 | + | ImageSharp | Jxl/has_permutation.jxl | 0 | False | 7.582 ms | 0.1406 ms | 0.0930 ms | 0.34 | 0.00 | 5064 B | 3.46 | + | Libjxl | Jxl/has_permutation.jxl | 0 | False | 22.214 ms | 0.3272 ms | 0.1711 ms | 1.00 | 0.01 | 1464 B | 1.00 | + | ImageSharp | Jxl/has_permutation.jxl | 0 | True | 18.082 ms | 0.2158 ms | 0.1427 ms | 0.13 | 0.00 | 102348 B | 21.54 | + | Libjxl | Jxl/has_permutation.jxl | 0 | True | 142.016 ms | 2.6436 ms | 1.3827 ms | 1.00 | 0.01 | 4752 B | 1.00 | + | ImageSharp | Jxl/has_permutation.jxl | 1 | False | 25.245 ms | 0.7375 ms | 0.4389 ms | 0.31 | 0.01 | 55204 B | 25.00 | + | Libjxl | Jxl/has_permutation.jxl | 1 | False | 80.631 ms | 3.0919 ms | 1.8399 ms | 1.00 | 0.03 | 2208 B | 1.00 | + | ImageSharp | Jxl/has_permutation.jxl | 1 | True | 35.729 ms | 2.2813 ms | 1.3575 ms | 0.30 | 0.01 | 55372 B | 9.61 | + | Libjxl | Jxl/has_permutation.jxl | 1 | True | 118.923 ms | 3.0481 ms | 2.0161 ms | 1.00 | 0.02 | 5760 B | 1.00 | + | ImageSharp | Jxl/issue648_palette0.jxl | 0 | False | 9.517 ms | 0.0734 ms | 0.0437 ms | 0.26 | 0.00 | 5227 B | 3.18 | + | Libjxl | Jxl/issue648_palette0.jxl | 0 | False | 37.051 ms | 0.3220 ms | 0.1684 ms | 1.00 | 0.01 | 1644 B | 1.00 | + | ImageSharp | Jxl/issue648_palette0.jxl | 0 | True | 21.698 ms | 0.1411 ms | 0.0840 ms | 0.13 | 0.00 | 90316 B | 14.82 | + | Libjxl | Jxl/issue648_palette0.jxl | 0 | True | 163.783 ms | 3.4502 ms | 2.2821 ms | 1.00 | 0.02 | 6096 B | 1.00 | + | ImageSharp | Jxl/issue648_palette0.jxl | 1 | False | 30.237 ms | 0.6114 ms | 0.4044 ms | 0.44 | 0.01 | 46344 B | 7.54 | + | Libjxl | Jxl/issue648_palette0.jxl | 1 | False | 68.178 ms | 0.9160 ms | 0.4791 ms | 1.00 | 0.01 | 6144 B | 1.00 | + | ImageSharp | Jxl/issue648_palette0.jxl | 1 | True | 36.062 ms | 0.7136 ms | 0.4720 ms | 0.36 | 0.01 | 50940 B | 10.72 | + | Libjxl | Jxl/issue648_palette0.jxl | 1 | True | 98.843 ms | 1.3112 ms | 0.8673 ms | 1.00 | 0.01 | 4752 B | 1.00 | + | ImageSharp | Jxl/progressive_ac.jxl | 0 | False | 18.802 ms | 0.7554 ms | 0.4997 ms | 0.25 | 0.01 | 6120 B | 0.95 | + | Libjxl | Jxl/progressive_ac.jxl | 0 | False | 76.645 ms | 1.3107 ms | 0.6855 ms | 1.00 | 0.01 | 6432 B | 1.00 | + | ImageSharp | Jxl/progressive_ac.jxl | 0 | True | 45.126 ms | 0.3672 ms | 0.1920 ms | 0.17 | 0.00 | 135920 B | 20.98 | + | Libjxl | Jxl/progressive_ac.jxl | 0 | True | 273.467 ms | 4.0114 ms | 2.6533 ms | 1.00 | 0.01 | 6480 B | 1.00 | + | ImageSharp | Jxl/progressive_ac.jxl | 1 | False | 55.916 ms | 1.2281 ms | 0.7308 ms | 0.42 | 0.01 | 66552 B | 9.83 | + | Libjxl | Jxl/progressive_ac.jxl | 1 | False | 134.294 ms | 2.4018 ms | 1.2562 ms | 1.00 | 0.01 | 6768 B | 1.00 | + | ImageSharp | Jxl/progressive_ac.jxl | 1 | True | 79.757 ms | 2.3843 ms | 1.5771 ms | 0.42 | 0.01 | 74664 B | 12.25 | + | Libjxl | Jxl/progressive_ac.jxl | 1 | True | 189.833 ms | 5.6298 ms | 3.7237 ms | 1.00 | 0.03 | 6096 B | 1.00 | */ } From 03dc4743fa1afe0223b5d70105e61271a20d4139 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Tue, 1 Dec 2026 14:32:14 +1000 Subject: [PATCH 4/7] Use the TIFF default YCbCr subsampling for each directory An IFD without the YCbCrSubSampling tag now uses 2, 2, the TIFF 6.0 default, not 1, 1. The value is never null, so the null checks in the parser, the decoder and the YCbCr readers are removed. --- .../Readers/YCbCrPlanarTiffColor{TPixel}.cs | 11 +-- .../Tiff/Readers/YCbCrTiffColor{TPixel}.cs | 11 +-- .../Formats/Tiff/TiffDecoderCore.cs | 1 - .../Formats/Tiff/TiffDecoderOptionsParser.cs | 10 ++- .../Tiff/TiffDecoderStripLayoutTests.cs | 76 +++++++++++++++++++ 5 files changed, 90 insertions(+), 19 deletions(-) diff --git a/src/ImageSharp/Formats/Tiff/Readers/YCbCrPlanarTiffColor{TPixel}.cs b/src/ImageSharp/Formats/Tiff/Readers/YCbCrPlanarTiffColor{TPixel}.cs index 37db2b4974..8181f1209a 100644 --- a/src/ImageSharp/Formats/Tiff/Readers/YCbCrPlanarTiffColor{TPixel}.cs +++ b/src/ImageSharp/Formats/Tiff/Readers/YCbCrPlanarTiffColor{TPixel}.cs @@ -91,18 +91,15 @@ public override void Decode(IMemoryOwner[] data, Buffer2D pixels, Span cbData = data[1].GetSpan(); Span crData = data[2].GetSpan(); - if (this.ycbcrSubSampling != null && !(this.ycbcrSubSampling[0] == 1 && this.ycbcrSubSampling[1] == 1)) + if (!(this.ycbcrSubSampling[0] == 1 && this.ycbcrSubSampling[1] == 1)) { ReverseChromaSubSampling(width, height, this.ycbcrSubSampling[0], this.ycbcrSubSampling[1], cbData, crData); } int offset = 0; - int widthPadding = 0; - if (this.ycbcrSubSampling != null) - { - // Round to the next integer multiple of horizontalSubSampling. - widthPadding = TiffUtilities.PaddingToNextInteger(width, this.ycbcrSubSampling[0]); - } + + // Round to the next integer multiple of horizontalSubSampling. + int widthPadding = TiffUtilities.PaddingToNextInteger(width, this.ycbcrSubSampling[0]); ColorProfileConverter? iccConverter = this.iccConverter; diff --git a/src/ImageSharp/Formats/Tiff/Readers/YCbCrTiffColor{TPixel}.cs b/src/ImageSharp/Formats/Tiff/Readers/YCbCrTiffColor{TPixel}.cs index 05952d1baf..b77437700b 100644 --- a/src/ImageSharp/Formats/Tiff/Readers/YCbCrTiffColor{TPixel}.cs +++ b/src/ImageSharp/Formats/Tiff/Readers/YCbCrTiffColor{TPixel}.cs @@ -92,7 +92,7 @@ public YCbCrTiffColor( public override void Decode(ReadOnlySpan data, Buffer2D pixels, int left, int top, int width, int height) { ReadOnlySpan ycbcrData = data; - if (this.ycbcrSubSampling != null && !(this.ycbcrSubSampling[0] == 1 && this.ycbcrSubSampling[1] == 1)) + if (!(this.ycbcrSubSampling[0] == 1 && this.ycbcrSubSampling[1] == 1)) { // 4 extra rows and columns for possible padding. int paddedWidth = width + 4; @@ -121,12 +121,9 @@ public override void Decode(ReadOnlySpan data, Buffer2D pixels, in private void DecodeYCbCrData(Buffer2D pixels, int left, int top, int width, int height, ReadOnlySpan ycbcrData) { int offset = 0; - int widthPadding = 0; - if (this.ycbcrSubSampling != null) - { - // Round to the next integer multiple of horizontalSubSampling. - widthPadding = TiffUtilities.PaddingToNextInteger(width, this.ycbcrSubSampling[0]); - } + + // Round to the next integer multiple of horizontalSubSampling. + int widthPadding = TiffUtilities.PaddingToNextInteger(width, this.ycbcrSubSampling[0]); ColorProfileConverter? iccConverter = this.iccConverter; ColorConversionOptions? rgbSourceOptions = this.rgbSourceOptions; diff --git a/src/ImageSharp/Formats/Tiff/TiffDecoderCore.cs b/src/ImageSharp/Formats/Tiff/TiffDecoderCore.cs index c5bd4d3ddf..506663bde4 100644 --- a/src/ImageSharp/Formats/Tiff/TiffDecoderCore.cs +++ b/src/ImageSharp/Formats/Tiff/TiffDecoderCore.cs @@ -1236,7 +1236,6 @@ private bool CanReadStripRows() { // Subsampled YCbCr groups can span rows. Read the complete strip before expanding its chroma samples. return this.PhotometricInterpretation != TiffPhotometricInterpretation.YCbCr - || this.YcbcrSubSampling is null || (this.YcbcrSubSampling[0] == 1 && this.YcbcrSubSampling[1] == 1); } diff --git a/src/ImageSharp/Formats/Tiff/TiffDecoderOptionsParser.cs b/src/ImageSharp/Formats/Tiff/TiffDecoderOptionsParser.cs index 5eca5e4f4f..b6c611660f 100644 --- a/src/ImageSharp/Formats/Tiff/TiffDecoderOptionsParser.cs +++ b/src/ImageSharp/Formats/Tiff/TiffDecoderOptionsParser.cs @@ -84,18 +84,20 @@ public static TiffDirectoryStatus VerifyAndParse( } } - ushort[] ycbcrSubSampling = null; + // The default YCbCrSubSampling value is 2, 2. See TIFF 6.0 specification, section 21, YCbCrSubSampling, page 92. libtiff also uses this default + // for each directory without the tag. + ushort[] ycbcrSubSampling = [2, 2]; if (exifProfile.TryGetValue(ExifTag.YCbCrSubsampling, out IExifValue subSamplingValue)) { ycbcrSubSampling = subSamplingValue.Value; } - if (ycbcrSubSampling != null && ycbcrSubSampling.Length != 2) + if (ycbcrSubSampling.Length != 2) { return Damaged("Invalid YCbCrSubsampling, expected 2 values.", out message); } - if (ycbcrSubSampling != null && ycbcrSubSampling[1] > ycbcrSubSampling[0]) + if (ycbcrSubSampling[1] > ycbcrSubSampling[0]) { return Damaged("ChromaSubsampleVert shall always be less than or equal to ChromaSubsampleHoriz.", out message); } @@ -539,7 +541,7 @@ private static TiffDirectoryStatus ParseColorType(this TiffDecoderCore options, { // The TIFF YCbCr readers divide the image width and height by the subsampling factors. TIFF 6.0 allows only the values 1, 2 and 4 (section // 21, YCbCrSubSampling, page 92). Thus a zero factor is not valid. - if (options.YcbcrSubSampling != null && (options.YcbcrSubSampling[0] == 0 || options.YcbcrSubSampling[1] == 0)) + if (options.YcbcrSubSampling[0] == 0 || options.YcbcrSubSampling[1] == 0) { return Damaged("YCbCrSubsampling factors must be greater than zero.", out message); } diff --git a/tests/ImageSharp.Tests/Formats/Tiff/TiffDecoderStripLayoutTests.cs b/tests/ImageSharp.Tests/Formats/Tiff/TiffDecoderStripLayoutTests.cs index 8ff5c65f49..389847dd25 100644 --- a/tests/ImageSharp.Tests/Formats/Tiff/TiffDecoderStripLayoutTests.cs +++ b/tests/ImageSharp.Tests/Formats/Tiff/TiffDecoderStripLayoutTests.cs @@ -35,6 +35,11 @@ public class TiffDecoderStripLayoutTests /// private const ushort TiffCompressionTag = 259; + /// + /// The StripOffsets tag. + /// + private const ushort TiffStripOffsetsTag = 273; + /// /// The RowsPerStrip tag. /// @@ -510,6 +515,26 @@ public void Decode_JpegWithZeroYCbCrSubSampling_DecodesImage() ImageComparer.Exact.VerifySimilarity(expected, actual); } + /// + /// The default YCbCrSubSampling value is 2, 2. See TIFF 6.0 specification, section 21, YCbCrSubSampling, page 92. An IFD without the tag uses the + /// default value, not the value of the IFD before it. + /// + [Fact] + public void Decode_LaterDirectoryWithoutYCbCrSubSampling_UsesDefault() + { + // The first IFD uses 4, 4. The second IFD stores 2, 2 data. Tag 65000 is in the private range, and the decoder does not use it. + byte[] second = TestFile.Create(FlowerYCbCr888Contiguoush2v2).Bytes; + byte[] data = AppendDirectory(TestFile.Create(FlowerYCbCr888Contiguoush4v4).Bytes, second); + SetDirectoryTag(data, 1, TiffYCbCrSubSamplingTag, 65000); + + using Image expected = Image.Load(second); + using Image image = Image.Load(data); + Assert.Equal(2, image.Frames.Count); + + using Image actual = image.Frames.CloneFrame(1); + ImageComparer.Exact.VerifySimilarity(expected, actual); + } + /// /// Creates an image of fixed pseudo-random noise. /// @@ -562,6 +587,57 @@ private static void SetDirectoryTagValue(byte[] data, int directory, ushort tag, } } + /// + /// Appends the first IFD of a little-endian TIFF file to the IFD chain of another little-endian TIFF file. + /// + /// + /// The method copies the second file after the first file. Then it adds the length of the first file to each offset in the copied IFD: the value + /// offsets of entries with more than 4 value bytes, and the StripOffsets values. See for the IFD layout. + /// + /// The file with the first IFD. It has one IFD. + /// The file with the IFD to append. It has one IFD. + /// The file with two IFDs. + private static byte[] AppendDirectory(byte[] first, byte[] second) + { + // The byte sizes of the TIFF field types 1 to 12. See TIFF 6.0 specification, section 2, page 15. + ReadOnlySpan typeSizes = [0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8]; + uint delta = (uint)first.Length; + byte[] data = [.. first, .. second]; + + int firstDirectory = (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(4)); + int firstCount = BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(firstDirectory)); + int secondDirectory = (int)(BinaryPrimitives.ReadUInt32LittleEndian(second.AsSpan(4)) + delta); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(firstDirectory + 2 + (firstCount * 12)), (uint)secondDirectory); + + int count = BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(secondDirectory)); + for (int i = 0; i < count; i++) + { + Span entry = data.AsSpan(secondDirectory + 2 + (i * 12), 12); + ushort tag = BinaryPrimitives.ReadUInt16LittleEndian(entry); + int type = BinaryPrimitives.ReadUInt16LittleEndian(entry[2..]); + uint valueCount = BinaryPrimitives.ReadUInt32LittleEndian(entry[4..]); + Span values = entry[8..]; + if (valueCount * typeSizes[type] > 4) + { + uint valueOffset = BinaryPrimitives.ReadUInt32LittleEndian(values) + delta; + BinaryPrimitives.WriteUInt32LittleEndian(values, valueOffset); + values = data.AsSpan((int)valueOffset, (int)(valueCount * typeSizes[type])); + } + + if (tag == TiffStripOffsetsTag) + { + Assert.Equal(4, type); + for (int j = 0; j < valueCount; j++) + { + Span offset = values.Slice(j * 4, 4); + BinaryPrimitives.WriteUInt32LittleEndian(offset, BinaryPrimitives.ReadUInt32LittleEndian(offset) + delta); + } + } + } + + return data; + } + /// /// Changes the tag of an entry in an IFD of a little-endian TIFF file. The entry keeps its type, count and value. /// From 4e8b652982098689c5dc025ded80fc16bae3ec5e Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Tue, 1 Dec 2026 14:40:07 +1000 Subject: [PATCH 5/7] Add the WebP benchmark results --- .../Codecs/Webp/DecodeWebp.cs | 18 ++++++++++++++++++ .../Codecs/Webp/EncodeWebp.cs | 18 ++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/tests/ImageSharp.Benchmarks/Codecs/Webp/DecodeWebp.cs b/tests/ImageSharp.Benchmarks/Codecs/Webp/DecodeWebp.cs index 65ae71d307..499e35f27e 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Webp/DecodeWebp.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Webp/DecodeWebp.cs @@ -76,4 +76,22 @@ public int WebpImageSharp() using Image image = Image.Load(this.webpStream); return image.Height; } + + /* Results 01.12.2026 + BenchmarkDotNet v0.15.8, Windows 11 (10.0.26300.10075) + AMD RYZEN AI MAX+ 395 w/ Radeon 8060S 3.00GHz, 1 CPU, 32 logical and 16 physical cores + .NET SDK 11.0.100 + [Host] : .NET 10.0.15 (10.0.15, 10.0.1526.53008), X64 RyuJIT x86-64-v4 + Toolchain=InProcessEmitToolchain IterationCount=10 IterationTime=100ms + WarmupCount=10 DOTNET_GCHighMemPercent=0x63 + + | Method | Layout | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | + |-------------------|-------------|----------:|---------:|---------:|------:|--------:|-----:|-----:|-----:|----------:|------------:| + | 'Magick Webp' | Lossless | 105.57 ms | 1.163 ms | 0.769 ms | 1.00 | 0.01 | - | - | - | 17.55 KB | 1.00 | + | 'ImageSharp Webp' | Lossless | 62.39 ms | 1.506 ms | 0.896 ms | 0.59 | 0.01 | - | - | - | 14.43 KB | 0.82 | + | 'Magick Webp' | LossyAlpha | 68.24 ms | 1.338 ms | 0.885 ms | 1.00 | 0.02 | - | - | - | 20.45 KB | 1.00 | + | 'ImageSharp Webp' | LossyAlpha | 32.81 ms | 0.607 ms | 0.402 ms | 0.48 | 0.01 | - | - | - | 14.13 KB | 0.69 | + | 'Magick Webp' | LossyOpaque | 62.05 ms | 1.971 ms | 1.304 ms | 1.00 | 0.03 | - | - | - | 13.47 KB | 1.00 | + | 'ImageSharp Webp' | LossyOpaque | 34.08 ms | 0.528 ms | 0.314 ms | 0.55 | 0.01 | - | - | - | 89.36 KB | 6.63 | + */ } diff --git a/tests/ImageSharp.Benchmarks/Codecs/Webp/EncodeWebp.cs b/tests/ImageSharp.Benchmarks/Codecs/Webp/EncodeWebp.cs index 59430283c1..41ff966eee 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Webp/EncodeWebp.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Webp/EncodeWebp.cs @@ -110,4 +110,22 @@ public void ImageSharpWebp() this.webp.Save(this.outputStream, encoder); } + + /* Results 01.12.2026 + BenchmarkDotNet v0.15.8, Windows 11 (10.0.26300.10075) + AMD RYZEN AI MAX+ 395 w/ Radeon 8060S 3.00GHz, 1 CPU, 32 logical and 16 physical cores + .NET SDK 11.0.100 + [Host] : .NET 10.0.15 (10.0.15, 10.0.1526.53008), X64 RyuJIT x86-64-v4 + Toolchain=InProcessEmitToolchain IterationCount=10 IterationTime=100ms + WarmupCount=10 DOTNET_GCHighMemPercent=0x63 + + | Method | Layout | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | + |-------------------|-------------|-----------:|----------:|---------:|------:|--------:|----------:|----------:|----------:|----------:|------------:| + | 'Magick Webp' | Lossless | 2,175.6 ms | 14.72 ms | 9.73 ms | 1.00 | 0.01 | - | - | - | 14.61 KB | 1.00 | + | 'ImageSharp Webp' | Lossless | 1,288.6 ms | 103.56 ms | 68.50 ms | 0.59 | 0.03 | 1000.0000 | 1000.0000 | 1000.0000 | 183.45 KB | 12.56 | + | 'Magick Webp' | LossyAlpha | 517.9 ms | 39.91 ms | 26.40 ms | 1.00 | 0.07 | - | - | - | 16.61 KB | 1.00 | + | 'ImageSharp Webp' | LossyAlpha | 520.6 ms | 42.81 ms | 25.47 ms | 1.01 | 0.07 | - | - | - | 152.94 KB | 9.21 | + | 'Magick Webp' | LossyOpaque | 207.9 ms | 24.39 ms | 16.13 ms | 1.01 | 0.10 | - | - | - | 19.05 KB | 1.00 | + | 'ImageSharp Webp' | LossyOpaque | 209.8 ms | 6.14 ms | 4.06 ms | 1.01 | 0.08 | - | - | - | 48.63 KB | 2.55 | + */ } From 67f2dc6ee22991c0048f71ad512c0a5fc953f9c9 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Tue, 1 Dec 2026 15:27:18 +1000 Subject: [PATCH 6/7] Speed up the WebP lossy bit writer and follow the libwebp alpha filter The token loop gets the output buffer once for each call, not once for each flushed byte, and both bit writers are sealed. The scalar 4x4 vertical predictor needs no scratch. The alpha encoder selects its filter as libwebp does, records it in the ALPH header, and keeps compressed data of equal size. --- src/ImageSharp/Formats/Webp/AlphaEncoder.cs | 467 ++++++++++++++++-- .../Formats/Webp/BitWriter/BitWriterBase.cs | 30 +- .../Formats/Webp/BitWriter/Vp8BitWriter.cs | 93 ++-- .../Formats/Webp/BitWriter/Vp8LBitWriter.cs | 6 +- .../Formats/Webp/Lossless/Vp8LEncoder.cs | 6 +- .../Formats/Webp/Lossy/Vp8Encoder.cs | 32 +- .../Formats/Webp/Lossy/Vp8EncoderIterator.cs | 2 +- .../Formats/Webp/Lossy/Vp8Encoding.cs | 29 +- .../Formats/WebP/WebpEncoderTests.cs | 73 +++ 9 files changed, 615 insertions(+), 123 deletions(-) diff --git a/src/ImageSharp/Formats/Webp/AlphaEncoder.cs b/src/ImageSharp/Formats/Webp/AlphaEncoder.cs index 7140cdca35..cd19c1b65a 100644 --- a/src/ImageSharp/Formats/Webp/AlphaEncoder.cs +++ b/src/ImageSharp/Formats/Webp/AlphaEncoder.cs @@ -2,9 +2,12 @@ // Licensed under the Six Labors Split License. using System.Buffers; +using System.Numerics; +using System.Numerics.Tensors; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; +using SixLabors.ImageSharp.Formats.Webp.BitWriter; using SixLabors.ImageSharp.Formats.Webp.Lossless; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; @@ -17,9 +20,34 @@ namespace SixLabors.ImageSharp.Formats.Webp; internal static class AlphaEncoder { /// - /// Encodes the alpha channel data. - /// Data is either compressed as lossless webp image or uncompressed. + /// The largest number of alpha values for which the fast filter selection uses no filter. For a plane with few values, + /// no filter compresses better. /// + private const int MinColorsForFilterNone = 16; + + /// + /// The largest number of alpha values for which the fast filter selection tries only the estimated filter at efforts 0 to 3. + /// A plane with more values also tries no filter at each effort. + /// + private const int MaxColorsForFilterNone = 192; + + /// + /// Encodes the alpha plane and writes the ALPH chunk to the stream. + /// + /// + /// + /// The method uses the default alpha settings of libwebp. These are the fast filter selection, the lossless compression when + /// is set, and quality 100. Thus all alpha levels stay. + /// + /// + /// The fast filter selection makes one or two trials. A plane with 16 values or fewer uses no filter. For a plane with more values, + /// selects the filter. At efforts 4 to 6, or for a plane with more than 192 values, no filter is a + /// second trial. Each trial filters the plane and encodes it with the lossless encoder. When the compressed data is larger than the + /// plane, the trial keeps the filtered plane uncompressed. The smallest trial wins. Of trials with equal size, the first trial wins, and no filter + /// comes first. + /// + /// + /// The stream to write the ALPH chunk to. /// The alpha plane with the 8-bit transparency values. It has the image size. /// The image width. /// The image height. @@ -27,12 +55,9 @@ internal static class AlphaEncoder /// The memory manager. /// Whether to skip metadata encoding. /// Indicates, if the data should be compressed with the lossless webp compression. - /// Receives the number of bytes of the compressed data, or 0 when the method returns null. - /// - /// The compressed data, when is set and the compressed data is smaller than the plane. Otherwise null, and the - /// plane stays uncompressed. The caller owns and disposes the data. - /// - public static IMemoryOwner? EncodeAlpha( + /// The effort of the lossy encoder. It sets the filter trials and the method of the lossless encoder. + public static void EncodeAlpha( + Stream stream, Buffer2D alphaData, int width, int height, @@ -40,38 +65,89 @@ internal static class AlphaEncoder MemoryAllocator memoryAllocator, bool skipMetadata, bool compress, - out int size) + WebpEncodingMethod effort) { - size = 0; - if (compress) + if (!compress) { - const WebpEncodingMethod effort = WebpEncodingMethod.Default; - const int quality = 8 * (int)effort; - using Vp8LEncoder lossLessEncoder = new( - memoryAllocator, - configuration, - width, - height, - quality, - skipMetadata, - effort, - TransparentColorMode.Preserve, - false, - 0); + // A filter does not change the size of uncompressed data, so libwebp writes the plane without a filter. + BitWriterBase.WriteAlphaChunk(stream, alphaData, width, height, WebpAlphaFilterType.None); + return; + } - // The transparency information will be stored in the green channel of the ARGB quadruplet. - // The green channel is allowed extra transformation steps in the specification -- unlike the other channels, - // that can improve compression. The values go straight into the encoder's pixel plane, one row at a time, so no other copy is - // necessary. - for (int y = 0; y < height; y++) + // The fast filter selection of libwebp. The trial without a filter runs first, so it wins a tie. + int colorCount = GetColorCount(alphaData, height); + WebpAlphaFilterType estimatedFilter = colorCount <= MinColorsForFilterNone ? WebpAlphaFilterType.None : EstimateBestFilter(alphaData, width, height); + bool tryNoFilter = estimatedFilter == WebpAlphaFilterType.None || effort > WebpEncodingMethod.Level3 || colorCount > MaxColorsForFilterNone; + + // libwebp uses the lossy effort as the lossless method. The quality is 8 times the effort, so efforts 0 to 3 stay below the quality + // of the costly backward reference search. Effort 6 uses quality 100, so the lossless encoder tries all transforms. + uint quality = effort == WebpEncodingMethod.BestQuality ? 100 : 8 * (uint)effort; + + // All trials use one lossless encoder. Each trial fills the whole input plane, and each encode resets the encoder state, + // as for the frames of an animation. + using Vp8LEncoder losslessEncoder = new( + memoryAllocator, + configuration, + width, + height, + quality, + skipMetadata, + effort, + TransparentColorMode.Preserve, + false, + 0); + + int pixelCount = width * height; + IMemoryOwner? bestData = null; + Buffer2D? filtered = null; + try + { + // Each trial has the same 1-byte header, so the trials compare the size of the data after the header. Uncompressed data has the + // size of the plane. The first trial always wins against the initial size. A later trial wins only when it is smaller. + int bestSize = int.MaxValue; + WebpAlphaFilterType bestFilter = WebpAlphaFilterType.None; + Buffer2D bestPlane = alphaData; + if (tryNoFilter) { - DispatchAlphaToGreen(alphaData.DangerousGetRowSpan(y), lossLessEncoder.Bgra.DangerousGetRowSpan(y)); + bestData = EncodeTrial(losslessEncoder, alphaData, width, height, out int size); + bestSize = bestData is null ? pixelCount : size; } - return lossLessEncoder.EncodeAlphaImageData(width, height, out size); - } + if (estimatedFilter != WebpAlphaFilterType.None) + { + // As in libwebp, the filtered plane is a separate buffer. An uncompressed trial writes it. + filtered = memoryAllocator.Allocate2D(width, height); + FilterPlane(alphaData, filtered, height, estimatedFilter); + IMemoryOwner? data = EncodeTrial(losslessEncoder, filtered, width, height, out int size); + int trialSize = data is null ? pixelCount : size; + if (trialSize < bestSize) + { + bestData?.Dispose(); + bestData = data; + bestSize = trialSize; + bestFilter = estimatedFilter; + bestPlane = filtered; + } + else + { + data?.Dispose(); + } + } - return null; + if (bestData is not null) + { + BitWriterBase.WriteAlphaChunk(stream, bestData.GetSpan()[..bestSize], bestFilter); + } + else + { + BitWriterBase.WriteAlphaChunk(stream, bestPlane, width, height, bestFilter); + } + } + finally + { + bestData?.Dispose(); + filtered?.Dispose(); + } } /// @@ -236,4 +312,329 @@ public static void DispatchAlphaToGreen(ReadOnlySpan alpha, Span bgr Unsafe.Add(ref destination, x) = (uint)Unsafe.Add(ref source, x) << 8; } } + + /// + /// Encodes one filter trial: it copies the plane to the green channel of the lossless encoder input and encodes it. + /// + /// The lossless encoder. Its input plane has the image size. + /// The alpha plane of the trial, filtered or not. + /// The image width. + /// The image height. + /// Receives the size of the compressed data in bytes, or 0 when the method returns null. + /// + /// The compressed data, or null when the compressed data is larger than the plane. The caller owns and disposes the data. + /// + private static IMemoryOwner? EncodeTrial(Vp8LEncoder encoder, Buffer2D plane, int width, int height, out int size) + { + // The alpha values go to the green channel of the ARGB pixels. Unlike the other channels, the green channel can use extra transforms + // of the lossless format, and these transforms can improve the compression. The values go straight into the input plane of the encoder, + // one row at a time, so no other copy is necessary. + Buffer2D bgra = encoder.Bgra; + for (int y = 0; y < height; y++) + { + DispatchAlphaToGreen(plane.DangerousGetRowSpan(y), bgra.DangerousGetRowSpan(y)); + } + + return encoder.EncodeAlphaImageData(width, height, out size); + } + + /// + /// Counts the different alpha values in the plane. + /// + /// The alpha plane. Each row has the image width. + /// The image height. + /// The number of different alpha values, from 1 to 256. + private static int GetColorCount(Buffer2D alpha, int height) + { + // One flag for each alpha value. Each value of the plane sets its flag to 1. + InlineArray256 seen = default; + Span flags = seen; + ref byte flagsRef = ref MemoryMarshal.GetReference(flags); + for (int y = 0; y < height; y++) + { + Span row = alpha.DangerousGetRowSpan(y); + ref byte rowRef = ref MemoryMarshal.GetReference(row); + nuint length = (uint)row.Length; + for (nuint x = 0; x < length; x++) + { + nuint value = Unsafe.Add(ref rowRef, x); + Unsafe.Add(ref flagsRef, value) = 1; + } + } + + return flags.Count((byte)1); + } + + /// + /// Estimates the filter that gives the best compression of the alpha plane, as the fast filter selection of libwebp does. + /// + /// + /// The estimate samples every second value of every second row, from row 2 and column 2, and skips the last row and the last column. + /// For each filter, a sample puts the absolute difference between the value and its prediction, divided by 16, in one of 16 bins. + /// Without a filter, the prediction is a running mean of the samples of the row. The score of a filter is the sum of the indices of its + /// used bins. The filter with the lowest score wins. Of equal scores, the first filter wins, in the order None, Horizontal, Vertical, Gradient. + /// + /// The alpha plane. Each row has the image width. + /// The image width. + /// The image height. + /// The estimated best filter. + private static WebpAlphaFilterType EstimateBestFilter(Buffer2D alpha, int width, int height) + { + // A score uses only the presence of a bin, so one bit for each of the 16 bins holds the bins of a filter. + uint noneBins = 0; + uint horizontalBins = 0; + uint verticalBins = 0; + uint gradientBins = 0; + + // The sampled columns stop before the last column. The image width is at least 1, so the limit is not negative. + nuint end = (uint)(width - 1); + for (int y = 2; y < height - 1; y += 2) + { + ref byte rowRef = ref MemoryMarshal.GetReference(alpha.DangerousGetRowSpan(y)); + ref byte aboveRef = ref MemoryMarshal.GetReference(alpha.DangerousGetRowSpan(y - 1)); + + // Each row starts the running mean at its first value. + int mean = rowRef; + for (nuint x = 2; x < end; x += 2) + { + int value = Unsafe.Add(ref rowRef, x); + int left = Unsafe.Add(ref rowRef, x - 1); + int above = Unsafe.Add(ref aboveRef, x); + int aboveLeft = Unsafe.Add(ref aboveRef, x - 1); + + // The absolute difference is at most 255, so the bin index is at most 15. + noneBins |= 1u << (Numerics.Abs(value - mean) >> 4); + horizontalBins |= 1u << (Numerics.Abs(value - left) >> 4); + verticalBins |= 1u << (Numerics.Abs(value - above) >> 4); + gradientBins |= 1u << (Numerics.Abs(value - Numerics.ClampToByte(left + above - aboveLeft)) >> 4); + mean = ((3 * mean) + value + 2) >> 2; + } + } + + // A strict comparison keeps the first filter of equal scores. + WebpAlphaFilterType bestFilter = WebpAlphaFilterType.None; + int bestScore = GetBinScore(noneBins); + int score = GetBinScore(horizontalBins); + if (score < bestScore) + { + bestScore = score; + bestFilter = WebpAlphaFilterType.Horizontal; + } + + score = GetBinScore(verticalBins); + if (score < bestScore) + { + bestScore = score; + bestFilter = WebpAlphaFilterType.Vertical; + } + + score = GetBinScore(gradientBins); + if (score < bestScore) + { + bestFilter = WebpAlphaFilterType.Gradient; + } + + return bestFilter; + } + + /// + /// Gets the score of the used bins of a filter: the sum of the indices of the used bins. + /// + /// The used bins. Bit i is set when bin i is used. + /// The score. + private static int GetBinScore(uint bins) + { + int score = 0; + while (bins != 0) + { + // Add the index of the lowest set bit, then clear that bit. + score += BitOperations.TrailingZeroCount(bins); + bins &= bins - 1; + } + + return score; + } + + /// + /// Applies a filter to the alpha plane. + /// + /// + /// Each filtered value is the value minus its prediction, modulo 256. The horizontal filter predicts from the left value. The vertical filter + /// predicts from the value above. The gradient filter predicts the left value plus the value above minus the value above left, clipped to 0..255. + /// The first value has no prediction. Each filter predicts the other values of the first row from the left value. The horizontal and the + /// gradient filters predict the first value of the other rows from the value above. See the WebP Container Specification, the ALPH chunk, + /// filtering method: https://developers.google.com/speed/webp/docs/riff_container. All predictions use source values, so the values of a row + /// are independent. + /// + /// The alpha plane. Each row has the image width. + /// The filtered plane. It has the size of . + /// The image height. + /// The filter. It is not . + private static void FilterPlane(Buffer2D alpha, Buffer2D filtered, int height, WebpAlphaFilterType filter) + { + // The first row of each filter: the first value stays, and the other values subtract the value to their left. + // Byte subtraction wraps modulo 256, as the filter requires. + Span row = alpha.DangerousGetRowSpan(0); + Span output = filtered.DangerousGetRowSpan(0); + output[0] = row[0]; + TensorPrimitives.Subtract(row[1..], row[..^1], output[1..]); + + // The filter of the plane is chosen once, and each case runs its own row loop. + switch (filter) + { + case WebpAlphaFilterType.Horizontal: + for (int y = 1; y < height; y++) + { + row = alpha.DangerousGetRowSpan(y); + output = filtered.DangerousGetRowSpan(y); + output[0] = (byte)(row[0] - alpha.DangerousGetRowSpan(y - 1)[0]); + TensorPrimitives.Subtract(row[1..], row[..^1], output[1..]); + } + + break; + case WebpAlphaFilterType.Vertical: + for (int y = 1; y < height; y++) + { + TensorPrimitives.Subtract(alpha.DangerousGetRowSpan(y), alpha.DangerousGetRowSpan(y - 1), filtered.DangerousGetRowSpan(y)); + } + + break; + case WebpAlphaFilterType.Gradient: + for (int y = 1; y < height; y++) + { + row = alpha.DangerousGetRowSpan(y); + Span above = alpha.DangerousGetRowSpan(y - 1); + output = filtered.DangerousGetRowSpan(y); + output[0] = (byte)(row[0] - above[0]); + GradientFilterRow(row, above, output); + } + + break; + } + } + + /// + /// Applies the gradient filter to the values of a row after the first value. + /// + /// The source row. + /// The source row above. It has the length of . + /// The filtered row. It has the length of . The method does not write the first value. + private static void GradientFilterRow(ReadOnlySpan row, ReadOnlySpan above, Span output) + { + // Each value x subtracts clip(left + above - aboveLeft), with left = row[x - 1], above = above[x] and aboveLeft = above[x - 1]. + // All four inputs are source values. Thus each vector loads them at x and x - 1, and it filters all its lanes at the same time. + ref byte rowRef = ref MemoryMarshal.GetReference(row); + ref byte aboveRef = ref MemoryMarshal.GetReference(above); + ref byte outputRef = ref MemoryMarshal.GetReference(output); + nuint length = (uint)row.Length; + nuint x = 1; + + if (Vector512.IsHardwareAccelerated) + { + // Lane i of each vector holds the value of column x + i, or of its left neighbor for the loads at x - 1. + for (; x + (uint)Vector512.Count <= length; x += (uint)Vector512.Count) + { + Vector512 value = Vector512.LoadUnsafe(ref rowRef, x); + Vector512 left = Vector512.LoadUnsafe(ref rowRef, x - 1); + Vector512 top = Vector512.LoadUnsafe(ref aboveRef, x); + Vector512 topLeft = Vector512.LoadUnsafe(ref aboveRef, x - 1); + (value - GradientPredict(left, top, topLeft)).StoreUnsafe(ref outputRef, x); + } + } + + if (Vector256.IsHardwareAccelerated) + { + // The same lane layout as the 512-bit path, with 32 lanes. + for (; x + (uint)Vector256.Count <= length; x += (uint)Vector256.Count) + { + Vector256 value = Vector256.LoadUnsafe(ref rowRef, x); + Vector256 left = Vector256.LoadUnsafe(ref rowRef, x - 1); + Vector256 top = Vector256.LoadUnsafe(ref aboveRef, x); + Vector256 topLeft = Vector256.LoadUnsafe(ref aboveRef, x - 1); + (value - GradientPredict(left, top, topLeft)).StoreUnsafe(ref outputRef, x); + } + } + + if (Vector128.IsHardwareAccelerated) + { + // The same lane layout as the 512-bit path, with 16 lanes. + for (; x + (uint)Vector128.Count <= length; x += (uint)Vector128.Count) + { + Vector128 value = Vector128.LoadUnsafe(ref rowRef, x); + Vector128 left = Vector128.LoadUnsafe(ref rowRef, x - 1); + Vector128 top = Vector128.LoadUnsafe(ref aboveRef, x); + Vector128 topLeft = Vector128.LoadUnsafe(ref aboveRef, x - 1); + (value - GradientPredict(left, top, topLeft)).StoreUnsafe(ref outputRef, x); + } + } + + // Finish a partial vector, or the entire row when hardware acceleration is unavailable. + for (; x < length; x++) + { + int prediction = Numerics.ClampToByte(Unsafe.Add(ref rowRef, x - 1) + Unsafe.Add(ref aboveRef, x) - Unsafe.Add(ref aboveRef, x - 1)); + Unsafe.Add(ref outputRef, x) = (byte)(Unsafe.Add(ref rowRef, x) - prediction); + } + } + + /// + /// Gets the gradient prediction clip(left + top - topLeft) of each lane, clipped to 0..255. + /// + /// The left values. + /// The values above. + /// The values above left. + /// The predictions. + [MethodImpl(InliningOptions.AlwaysInline)] + private static Vector512 GradientPredict(Vector512 left, Vector512 top, Vector512 topLeft) + { + // Widen splits the 64 byte lanes into the lower and the upper 32 lanes, as 16-bit lanes. The sum is from -255 to 510. The 16-bit + // arithmetic wraps, so the lanes read as signed values hold the exact sum. Clamp clips it to 0..255, and Narrow then keeps the value + // and restores the lane order. + (Vector512 leftLower, Vector512 leftUpper) = Vector512.Widen(left); + (Vector512 topLower, Vector512 topUpper) = Vector512.Widen(top); + (Vector512 topLeftLower, Vector512 topLeftUpper) = Vector512.Widen(topLeft); + Vector512 max = Vector512.Create((short)byte.MaxValue); + Vector512 lower = Vector512.Clamp((leftLower + topLower - topLeftLower).AsInt16(), Vector512.Zero, max); + Vector512 upper = Vector512.Clamp((leftUpper + topUpper - topLeftUpper).AsInt16(), Vector512.Zero, max); + return Vector512.Narrow(lower.AsUInt16(), upper.AsUInt16()); + } + + /// + /// Gets the gradient prediction clip(left + top - topLeft) of each lane, clipped to 0..255. + /// + /// The left values. + /// The values above. + /// The values above left. + /// The predictions. + [MethodImpl(InliningOptions.AlwaysInline)] + private static Vector256 GradientPredict(Vector256 left, Vector256 top, Vector256 topLeft) + { + // The same steps as the 512-bit overload, with 32 byte lanes. + (Vector256 leftLower, Vector256 leftUpper) = Vector256.Widen(left); + (Vector256 topLower, Vector256 topUpper) = Vector256.Widen(top); + (Vector256 topLeftLower, Vector256 topLeftUpper) = Vector256.Widen(topLeft); + Vector256 max = Vector256.Create((short)byte.MaxValue); + Vector256 lower = Vector256.Clamp((leftLower + topLower - topLeftLower).AsInt16(), Vector256.Zero, max); + Vector256 upper = Vector256.Clamp((leftUpper + topUpper - topLeftUpper).AsInt16(), Vector256.Zero, max); + return Vector256.Narrow(lower.AsUInt16(), upper.AsUInt16()); + } + + /// + /// Gets the gradient prediction clip(left + top - topLeft) of each lane, clipped to 0..255. + /// + /// The left values. + /// The values above. + /// The values above left. + /// The predictions. + [MethodImpl(InliningOptions.AlwaysInline)] + private static Vector128 GradientPredict(Vector128 left, Vector128 top, Vector128 topLeft) + { + // The same steps as the 512-bit overload, with 16 byte lanes. + (Vector128 leftLower, Vector128 leftUpper) = Vector128.Widen(left); + (Vector128 topLower, Vector128 topUpper) = Vector128.Widen(top); + (Vector128 topLeftLower, Vector128 topLeftUpper) = Vector128.Widen(topLeft); + Vector128 max = Vector128.Create((short)byte.MaxValue); + Vector128 lower = Vector128.Clamp((leftLower + topLower - topLeftLower).AsInt16(), Vector128.Zero, max); + Vector128 upper = Vector128.Clamp((leftUpper + topUpper - topLeftUpper).AsInt16(), Vector128.Zero, max); + return Vector128.Narrow(lower.AsUInt16(), upper.AsUInt16()); + } } diff --git a/src/ImageSharp/Formats/Webp/BitWriter/BitWriterBase.cs b/src/ImageSharp/Formats/Webp/BitWriter/BitWriterBase.cs index 3bf4616381..80a0eaa126 100644 --- a/src/ImageSharp/Formats/Webp/BitWriter/BitWriterBase.cs +++ b/src/ImageSharp/Formats/Webp/BitWriter/BitWriterBase.cs @@ -55,6 +55,11 @@ protected BitWriterBase(MemoryAllocator memoryAllocator, int expectedSize) /// public Span Buffer => this.bufferOwner.GetSpan()[..this.capacity]; + /// + /// Gets the current capacity of the buffer in bytes. A capacity check reads it without a call to get the buffer. + /// + protected int Capacity => this.capacity; + /// /// Gets the number of bytes of the encoded image data. /// @@ -234,14 +239,18 @@ public static void WriteAnimationParameter(Stream stream, Color background, usho /// /// Writes the alpha chunk to the stream. /// + /// + /// The header byte holds the compression method in bits 0 and 1 and the filter in bits 2 and 3. The preprocessing bits 4 and 5 are 0, + /// because the encoder keeps all alpha levels. See the WebP Container Specification, the ALPH chunk: + /// https://developers.google.com/speed/webp/docs/riff_container. + /// /// The stream to write to. - /// The alpha channel data, compressed with the lossless WebP compression. - public static void WriteAlphaChunk(Stream stream, ReadOnlySpan dataBytes) + /// The alpha plane after the filter, compressed with the lossless WebP compression. + /// The filter that the encoder applied to the alpha plane before the compression. + public static void WriteAlphaChunk(Stream stream, ReadOnlySpan dataBytes, WebpAlphaFilterType filter) { long pos = RiffHelper.BeginWriteChunk(stream, (uint)WebpChunkType.Alpha); - - // TODO: Filtering and preprocessing - stream.WriteByte(1); + stream.WriteByte((byte)((int)WebpAlphaCompressionMethod.WebpLosslessCompression | ((int)filter << 2))); stream.Write(dataBytes); RiffHelper.EndWriteChunk(stream, pos); } @@ -249,14 +258,19 @@ public static void WriteAlphaChunk(Stream stream, ReadOnlySpan dataBytes) /// /// Writes an uncompressed alpha chunk to the stream: the alpha values of each row, in scan order. /// + /// + /// The header byte holds the compression method 0 in bits 0 and 1 and the filter in bits 2 and 3. The preprocessing bits 4 and 5 are 0, + /// because the encoder keeps all alpha levels. + /// /// The stream to write to. - /// The alpha plane. + /// The alpha plane. When is not , the plane after the filter. /// The image width. /// The image height. - public static void WriteAlphaChunk(Stream stream, Buffer2D alpha, int width, int height) + /// The filter that the encoder applied to the alpha plane. + public static void WriteAlphaChunk(Stream stream, Buffer2D alpha, int width, int height, WebpAlphaFilterType filter) { long pos = RiffHelper.BeginWriteChunk(stream, (uint)WebpChunkType.Alpha); - stream.WriteByte(0); + stream.WriteByte((byte)((int)WebpAlphaCompressionMethod.NoCompression | ((int)filter << 2))); for (int y = 0; y < height; y++) { stream.Write(alpha.DangerousGetRowSpan(y)[..width]); diff --git a/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs b/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs index 972c630530..e6fb17647b 100644 --- a/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs +++ b/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs @@ -2,6 +2,7 @@ // Licensed under the Six Labors Split License. using System.Buffers.Binary; +using System.Runtime.CompilerServices; using SixLabors.ImageSharp.Formats.Webp.Lossy; using SixLabors.ImageSharp.Memory; @@ -10,7 +11,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.BitWriter; /// /// A bit writer for writing lossy webp streams. /// -internal class Vp8BitWriter : BitWriterBase +internal sealed class Vp8BitWriter : BitWriterBase { #pragma warning disable SA1310 // Field names should not contain underscore /// @@ -261,13 +262,22 @@ public int PutCoeffs(int ctx, Vp8Residual residual, ReadOnlySpan coeffs) /// The final probabilities in the flat [type][band][context][proba] order. public void PutTokens(ReadOnlySpan tokens, ReadOnlySpan probas) { + // A token shifts out at most 7 bits, because Norm is at most 7. The pending bit count starts at 0 or less. Thus the call + // has at most (7 * tokens) / 8 + 1 flushes. Each flush adds one byte to the pending 0xFF bytes, or it writes them. + // Thus the call writes at most the pending 0xFF bytes plus one byte for each flush. One resize before the loop lets the + // loop write through one buffer span. + this.BitWriterResize(this.run + ((7 * tokens.Length) >> 3) + 2); + Span buffer = this.Buffer; + // This loop does the same steps as PutBit for each token. The coder state is kept in locals, so that it can stay - // in registers. The state goes back to the fields only around Flush, which reads and changes the value and the bit count. + // in registers. ReadOnlySpan norm = WebpLookupTables.Norm; ReadOnlySpan newRange = WebpLookupTables.NewRange; int range = this.range; int value = this.value; int nbBits = this.nbBits; + int run = this.run; + uint pos = this.pos; foreach (ushort token in tokens) { int proba = (token & Vp8Residual.FixedProbaBit) != 0 ? token & 0xff : probas[token & 0x3fff]; @@ -291,11 +301,7 @@ public void PutTokens(ReadOnlySpan tokens, ReadOnlySpan probas) nbBits += shift; if (nbBits > 0) { - this.value = value; - this.nbBits = nbBits; - this.Flush(); - value = this.value; - nbBits = this.nbBits; + FlushByte(buffer, ref value, ref nbBits, ref run, ref pos); } } } @@ -303,6 +309,8 @@ public void PutTokens(ReadOnlySpan tokens, ReadOnlySpan probas) this.range = range; this.value = value; this.nbBits = nbBits; + this.run = run; + this.pos = pos; } /// @@ -315,12 +323,12 @@ public override void BitWriterResize(int extraSize) // Compare against the current capacity and grow from it, so the buffer only reallocates // when it is actually full and grows geometrically. - if (neededSize <= this.Buffer.Length) + if (neededSize <= this.Capacity) { return; } - this.ResizeBuffer(this.Buffer.Length, (int)neededSize); + this.ResizeBuffer(this.Capacity, (int)neededSize); } /// @@ -536,40 +544,49 @@ private void PutSignedBits(int value, int nbBits) /// private void Flush() { - int s = 8 + this.nbBits; - int bits = this.value >> s; - this.value -= bits << s; - this.nbBits -= 8; - if ((bits & 0xff) != 0xff) - { - uint pos = this.pos; - this.BitWriterResize(this.run + 1); - - if ((bits & 0x100) != 0) - { - // overflow -> propagate carry over pending 0xff's - if (pos > 0) - { - this.Buffer[(int)pos - 1]++; - } - } + // One flush writes at most the pending 0xFF bytes and one byte. + this.BitWriterResize(this.run + 1); + FlushByte(this.Buffer, ref this.value, ref this.nbBits, ref this.run, ref this.pos); + } - if (this.run > 0) - { - int value = (bits & 0x100) != 0 ? 0x00 : 0xff; - for (; this.run > 0; --this.run) - { - this.Buffer[(int)pos++] = (byte)value; - } - } + /// + /// Moves the next complete byte from the coder value to the buffer, as describes. The caller passes the coder state, + /// so that a hot loop can keep it in locals. The caller makes sure that the buffer has space for the pending run and one byte. + /// + /// The output buffer. + /// The low end of the coder interval with the bits that are not flushed yet. + /// The number of pending bits. It is more than 0 on entry. + /// The number of pending 0xFF bytes. + /// The number of bytes written to the buffer. + [MethodImpl(InliningOptions.ShortMethod)] + private static void FlushByte(Span buffer, ref int value, ref int nbBits, ref int run, ref uint pos) + { + int s = 8 + nbBits; + int bits = value >> s; + value -= bits << s; + nbBits -= 8; + if ((bits & 0xff) == 0xff) + { + // Delay writing of bytes 0xff, pending eventual carry. + run++; + return; + } - this.Buffer[(int)pos++] = (byte)(bits & 0xff); - this.pos = pos; + // Bit 8 is the carry. It adds 1 to the last written byte, and the pending 0xFF bytes become 0x00. + bool carry = (bits & 0x100) != 0; + if (carry && pos > 0) + { + buffer[(int)pos - 1]++; } - else + + if (run > 0) { - this.run++; // Delay writing of bytes 0xff, pending eventual carry. + buffer.Slice((int)pos, run).Fill(carry ? (byte)0x00 : (byte)0xff); + pos += (uint)run; + run = 0; } + + buffer[(int)pos++] = (byte)bits; } /// diff --git a/src/ImageSharp/Formats/Webp/BitWriter/Vp8LBitWriter.cs b/src/ImageSharp/Formats/Webp/BitWriter/Vp8LBitWriter.cs index 6206156a31..965ff7613b 100644 --- a/src/ImageSharp/Formats/Webp/BitWriter/Vp8LBitWriter.cs +++ b/src/ImageSharp/Formats/Webp/BitWriter/Vp8LBitWriter.cs @@ -10,7 +10,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.BitWriter; /// /// A bit writer for writing lossless webp streams. /// -internal class Vp8LBitWriter : BitWriterBase +internal sealed class Vp8LBitWriter : BitWriterBase { /// /// This is the minimum amount of size the memory buffer is guaranteed to grow when extra space is needed. @@ -212,11 +212,11 @@ public override void BitWriterResize(int extraSize) int sizeRequired = this.cur + extraSize; // Grow only when the buffer is full. Finish calls this method for each image, and usually the bytes fit. - if (sizeRequired <= this.Buffer.Length) + if (sizeRequired <= this.Capacity) { return; } - this.ResizeBuffer(this.Buffer.Length, sizeRequired); + this.ResizeBuffer(this.Capacity, sizeRequired); } } diff --git a/src/ImageSharp/Formats/Webp/Lossless/Vp8LEncoder.cs b/src/ImageSharp/Formats/Webp/Lossless/Vp8LEncoder.cs index b52b91b302..d85083a892 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/Vp8LEncoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/Vp8LEncoder.cs @@ -417,7 +417,7 @@ public bool Encode( /// The image height. /// Receives the size of the compressed data in bytes, or 0 when the method returns null. /// - /// The compressed data, or null when the compressed data is not smaller than the pixel count. The caller owns and disposes the data. + /// The compressed data, or null when the compressed data is larger than the pixel count. The caller owns and disposes the data. /// public IMemoryOwner EncodeAlphaImageData(int width, int height, out int size) { @@ -432,9 +432,9 @@ public IMemoryOwner EncodeAlphaImageData(int width, int height, out int si this.EncodeStream(width, height); this.bitWriter.Finish(); size = this.bitWriter.NumBytes; - if (size >= pixelCount) + if (size > pixelCount) { - // Compressing would not yield in smaller data -> leave the data uncompressed. + // The compressed data is larger than the plane, so the plane stays uncompressed. Data of equal size stays compressed, as in libwebp. size = 0; return null; } diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs index 7d3a6b7294..b6deb66cbe 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs @@ -679,20 +679,6 @@ private bool Encode( // Store filter stats. this.AdjustFilterStrength(); - // Extract and encode alpha channel data, if present. The compressed data is used only when it is smaller than the plane. - int compressedAlphaSize = 0; - using IMemoryOwner compressedAlpha = hasAlpha - ? AlphaEncoder.EncodeAlpha( - alphaPlane, - width, - height, - this.configuration, - this.memoryAllocator, - this.skipMetadata, - this.alphaCompression, - out compressedAlphaSize) - : null; - this.bitWriter.Finish(); long prevPosition = 0; @@ -710,13 +696,19 @@ private bool Encode( .WriteHeaderTo(stream); } - if (compressedAlpha is not null) + // The ALPH chunk comes before the VP8 chunk. The alpha encoder selects the filter and the compression of the alpha plane and writes the chunk. + if (hasAlpha) { - BitWriterBase.WriteAlphaChunk(stream, compressedAlpha.GetSpan()[..compressedAlphaSize]); - } - else if (hasAlpha) - { - BitWriterBase.WriteAlphaChunk(stream, alphaPlane, width, height); + AlphaEncoder.EncodeAlpha( + stream, + alphaPlane, + width, + height, + this.configuration, + this.memoryAllocator, + this.skipMetadata, + this.alphaCompression, + this.method); } this.bitWriter.WriteEncodedImageToStream(stream); diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderIterator.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderIterator.cs index 925d0d22d1..c3de164c5e 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderIterator.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderIterator.cs @@ -1154,7 +1154,7 @@ public void MakeChroma8Preds() /// /// Writes the 4x4 luma predictions of the current 4x4 block to from the samples in . /// - public void MakeIntra4Preds() => Vp8Encoding.EncPredLuma4(this.YuvP, this.I4Boundary, this.I4BoundaryIdx, this.Scratch[..4]); + public void MakeIntra4Preds() => Vp8Encoding.EncPredLuma4(this.YuvP, this.I4Boundary, this.I4BoundaryIdx); /// /// Exchanges and , so that the best reconstruction so far stays in . diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.cs index 38d281b837..b0113d89d5 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoding.cs @@ -883,8 +883,7 @@ public static void EncPredChroma8(Span dst, Span left, Span to /// the top-left sample X, the top samples A B C D and the top-right samples E F G H. /// /// The index of the top sample A in . - /// A scratch buffer of 4 samples. Only the scalar path uses it. - public static void EncPredLuma4(Span dst, ReadOnlySpan top, int topOffset, Span vals) + public static void EncPredLuma4(Span dst, ReadOnlySpan top, int topOffset) { if (Vector128.IsHardwareAccelerated) { @@ -913,7 +912,7 @@ public static void EncPredLuma4(Span dst, ReadOnlySpan top, int topO ref byte scalarA = ref MemoryMarshal.GetReference(samples[5..]); Dc4(ref Unsafe.Add(ref scalarDst, (nuint)I4DC4), ref scalarA); Tm4(dst[I4TM4..], top, topOffset); - Ve4(dst[I4VE4..], top, topOffset, vals); + Ve4(ref Unsafe.Add(ref scalarDst, (nuint)I4VE4), ref scalarA); He4(ref Unsafe.Add(ref scalarDst, (nuint)I4HE4), ref scalarA); Rd4(dst[I4RD4..], top, topOffset); Vr4(dst[I4VR4..], top, topOffset); @@ -1399,21 +1398,17 @@ private static void Tm4(Span dst, ReadOnlySpan top, int topOffset) /// /// Writes the 4x4 vertical prediction. Each column is the smoothed top sample of that column. This is the scalar form. /// - /// The first sample of the block. - /// The boundary samples, in the layout of . - /// The index of the top sample A in . - /// A scratch buffer of 4 samples that gets the smoothed top row. - private static void Ve4(Span dst, ReadOnlySpan top, int topOffset, Span vals) + /// The first sample of the block. The rows have a stride of . + /// The top sample A. The sample before it is X, and the 4 after it are B C D E. + private static void Ve4(ref byte dst, ref byte a) { - // vertical - vals[0] = LossyUtils.Avg3(top[topOffset - 1], top[topOffset], top[topOffset + 1]); - vals[1] = LossyUtils.Avg3(top[topOffset], top[topOffset + 1], top[topOffset + 2]); - vals[2] = LossyUtils.Avg3(top[topOffset + 1], top[topOffset + 2], top[topOffset + 3]); - vals[3] = LossyUtils.Avg3(top[topOffset + 2], top[topOffset + 3], top[topOffset + 4]); - for (int i = 0; i < 4; i++) - { - vals.CopyTo(dst[(i * WebpConstants.Bps)..]); - } + byte x = Unsafe.Subtract(ref a, 1); + byte b = Unsafe.Add(ref a, 1); + byte c = Unsafe.Add(ref a, 2); + byte d = Unsafe.Add(ref a, 3); + byte e = Unsafe.Add(ref a, 4); + uint row = Pack(LossyUtils.Avg3(x, a, b), LossyUtils.Avg3(a, b, c), LossyUtils.Avg3(b, c, d), LossyUtils.Avg3(c, d, e)); + StoreRows(ref dst, row, row, row, row); } /// diff --git a/tests/ImageSharp.Tests/Formats/WebP/WebpEncoderTests.cs b/tests/ImageSharp.Tests/Formats/WebP/WebpEncoderTests.cs index 248e3ade1d..8cbd9ec042 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/WebpEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/WebpEncoderTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +using System.Buffers.Binary; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Gif; using SixLabors.ImageSharp.Formats.Heif; @@ -692,6 +693,78 @@ public void Encode_Lossy_WithAlphaUsingCompression_Works(TestImageProvid Assert.True(encodedBytes <= expectedFileSize, $"encoded bytes are {encodedBytes} and should be smaller then expected file size of {expectedFileSize}"); } + /// + /// The lossy encoder selects the alpha filter with the fast filter selection of libwebp. A plane with 16 alpha values or fewer uses no filter. + /// At efforts 0 to 3, a plane with 17 to 192 values makes one trial with the estimated filter. Thus the ALPH header records that filter. + /// The alpha data is lossless, so the decoded alpha is equal to the source alpha. + /// + /// + /// The alpha value at (x, y) is ((columnStep * x) & columnMask) + ((rowStep * y) & rowMask). The estimate samples every second value of + /// every second row. A sample puts |value - prediction| / 16 in a bin, and the filter with the lowest sum of used bin indices wins. A tie keeps + /// the first filter in the order None, Horizontal, Vertical, Gradient. The sums of the column term and the row term stay in 0..255, so the + /// gradient prediction of each case is exact. + /// + /// (80 * x) & 240 has 16 values, so the filter is None. + /// 7 * x + ((48 * y) & 48) has 80 values. The horizontal and the gradient differences are in bin 0. The vertical differences are 16 and + /// the running mean differences reach 24, so these filters use bin 1. Horizontal wins the tie with Gradient. + /// (40 * x) & 248 has 32 values and equal rows. The vertical and the gradient differences are 0. Vertical wins the tie. + /// ((40 * x) & 120) + ((24 * y) & 120) has 31 values. Only the gradient differences are 0, so the filter is Gradient. + /// + /// + /// The image width. + /// The step of the column term. + /// The mask of the column term. + /// The step of the row term. + /// The mask of the row term. + /// The expected filter in bits 2 and 3 of the ALPH header: 0 None, 1 Horizontal, 2 Vertical, 3 Gradient. + [Theory] + [InlineData(64, 80, 240, 0, 0, 0)] + [InlineData(20, 7, 255, 48, 48, 1)] + [InlineData(64, 40, 248, 0, 0, 2)] + [InlineData(64, 40, 120, 24, 120, 3)] + public void Encode_Lossy_AlphaFilter_FollowsFastFilterSelection(int width, int columnStep, int columnMask, int rowStep, int rowMask, int expectedFilter) + { + const int height = 64; + using Image expected = new(width, height); + expected.ProcessPixelRows(accessor => + { + for (int y = 0; y < accessor.Height; y++) + { + Span row = accessor.GetRowSpan(y); + for (int x = 0; x < row.Length; x++) + { + row[x] = new A8((byte)(((columnStep * x) & columnMask) + ((rowStep * y) & rowMask))); + } + } + }); + + // Effort 3 tries no filter as a second trial only for a plane with more than 192 values. + WebpEncoder encoder = new() + { + FileFormat = WebpFileFormatType.Lossy, + Method = WebpEncodingMethod.Level3 + }; + + using Image image = expected.CloneAs(); + using MemoryStream stream = new(); + image.Save(stream, encoder); + byte[] data = stream.ToArray(); + + // RIFF chunks start after the 12-byte file header. Each chunk has a 4-byte type, a 4-byte size, and a payload with padding to an even length. + // The first payload byte of ALPH is the alpha header. + int offset = 12; + while (!data.AsSpan(offset, 4).SequenceEqual("ALPH"u8)) + { + int size = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(offset + 4)); + offset += 8 + size + (size & 1); + } + + Assert.Equal(expectedFilter, (data[offset + 8] >> 2) & 0x03); + + using Image actual = Image.Load(data); + ImageComparer.Exact.VerifySimilarity(expected, actual); + } + [Theory] [WithFile(TestPatternOpaque, PixelTypes.Rgba32)] [WithFile(TestPatternOpaqueSmall, PixelTypes.Rgba32)] From c11771b332d9096f2ad17cdca706d9aa45d37e1e Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Tue, 1 Dec 2026 17:32:58 +1000 Subject: [PATCH 7/7] Finish the WebP performance work and follow the libwebp rules - Decode the lossy alpha rows per macroblock row, as libwebp does. - Merge equal segments and give unused segments the base quantizer, as libwebp does. - Quantize groups of blocks with 16-bit lanes for 256-bit and 512-bit vectors. - Saturate frame delays that the WebP, GIF, APNG and AVIF fields cannot hold. - Add XML docs to the undocumented members of the touched files. - Replace bitstream builders and pixel loops in the tests with fixtures and image comparers. - Update the WebP benchmark results. --- src/ImageSharp/Compression/HuffmanTree.cs | 6 + src/ImageSharp/Formats/Gif/GifEncoderCore.cs | 33 +- .../Formats/Heif/HeifEncoderCore.Sequence.cs | 29 +- .../Jxl/Components/Decoder/JxlIccReader.cs | 12 + .../Jxl/Components/Entropy/JxlHybridUint.cs | 16 + .../Jxl/Components/Modular/JxlModularTree.cs | 30 ++ .../VarDct/JxlVarDctDecoder.Coefficients.cs | 30 ++ .../Jxl/Components/VarDct/JxlVarDctDecoder.cs | 19 + src/ImageSharp/Formats/Png/PngEncoderCore.cs | 44 +- .../Readers/YCbCrPlanarTiffColor{TPixel}.cs | 25 ++ .../Tiff/Readers/YCbCrTiffColor{TPixel}.cs | 27 ++ .../Formats/Tiff/TiffDecoderCore.cs | 22 + .../Formats/Tiff/TiffDecoderOptionsParser.cs | 3 + src/ImageSharp/Formats/Webp/AlphaDecoder.cs | 279 ++++++++++--- .../Formats/Webp/BitWriter/Vp8BitWriter.cs | 18 +- .../Formats/Webp/Chunks/WebpFrameData.cs | 39 +- .../Formats/Webp/Lossless/Vp8LDecoder.cs | 9 + .../Webp/Lossless/WebpLosslessDecoder.cs | 232 +++++++---- .../Formats/Webp/Lossy/Vp8Encoder.cs | 205 ++++++--- .../Formats/Webp/Lossy/Vp8EncoderIterator.cs | 168 +++----- .../Webp/Lossy/Vp8EncoderProbabilities.cs | 5 +- .../Webp/Lossy/Vp8EncoderSegmentHeader.cs | 15 +- .../Formats/Webp/Lossy/Vp8Quantization.cs | 391 ++++++++++-------- .../Formats/Webp/Lossy/Vp8Residual.cs | 147 ++++--- .../Formats/Webp/Lossy/Vp8SegmentInfo.cs | 25 ++ .../Formats/Webp/Lossy/WebpLossyDecoder.cs | 14 +- .../Formats/Webp/WebpChunkParsingUtils.cs | 15 +- .../Formats/Webp/WebpLookupTables.cs | 266 ++++++------ .../Formats/Webp/WebpThrowHelper.cs | 12 + .../Codecs/Webp/DecodeWebp.cs | 12 +- .../Codecs/Webp/EncodeWebp.cs | 16 +- .../Formats/Exr/ExrZipDecoderTests.cs | 7 +- .../Formats/Gif/GifEncoderTests.cs | 23 +- .../Formats/Heif/HeifEncoderTests.cs | 39 +- .../Formats/Png/PngEncoderTests.cs | 24 ++ .../Formats/WebP/LosslessUtilsTests.cs | 20 +- .../Formats/WebP/Vp8QuantizationTests.cs | 43 +- .../Formats/WebP/Vp8ResidualTests.cs | 6 +- .../Formats/WebP/WebpDecoderTests.cs | 189 +++++---- .../Formats/WebP/WebpEncoderTests.cs | 146 ++++--- .../Formats/WebP/YuvConversionTests.cs | 6 + tests/ImageSharp.Tests/TestImages.cs | 17 + .../Input/Webp/alpha_filter_gradient.png | 3 + .../Input/Webp/alpha_filter_horizontal.png | 3 + tests/Images/Input/Webp/alpha_filter_none.png | 3 + .../Input/Webp/alpha_filter_vertical.png | 3 + .../lossless_code_lengths_incomplete.webp | 3 + .../lossless_code_lengths_max_symbol.webp | 3 + ...lossless_code_lengths_repeat_overflow.webp | 3 + ...lossless_huffman_groups_256_truncated.webp | 3 + .../Webp/lossless_huffman_groups_65536.webp | 3 + .../Webp/lossless_sparse_huffman_groups.webp | 3 + tests/Images/Input/Webp/lossy_flat_blocks.png | 3 + .../Input/Webp/lossy_flat_blocks_libwebp.webp | 3 + tests/Images/Input/Webp/lossy_non_square.png | 3 + .../Input/Webp/lossy_non_square_libwebp.webp | 3 + .../Webp/lossy_segment_map_without_data.webp | 3 + .../Input/Webp/lossy_segment_no_update.webp | 3 + .../Webp/lossy_segment_relative_delta.webp | 3 + 59 files changed, 1869 insertions(+), 866 deletions(-) create mode 100644 tests/Images/Input/Webp/alpha_filter_gradient.png create mode 100644 tests/Images/Input/Webp/alpha_filter_horizontal.png create mode 100644 tests/Images/Input/Webp/alpha_filter_none.png create mode 100644 tests/Images/Input/Webp/alpha_filter_vertical.png create mode 100644 tests/Images/Input/Webp/lossless_code_lengths_incomplete.webp create mode 100644 tests/Images/Input/Webp/lossless_code_lengths_max_symbol.webp create mode 100644 tests/Images/Input/Webp/lossless_code_lengths_repeat_overflow.webp create mode 100644 tests/Images/Input/Webp/lossless_huffman_groups_256_truncated.webp create mode 100644 tests/Images/Input/Webp/lossless_huffman_groups_65536.webp create mode 100644 tests/Images/Input/Webp/lossless_sparse_huffman_groups.webp create mode 100644 tests/Images/Input/Webp/lossy_flat_blocks.png create mode 100644 tests/Images/Input/Webp/lossy_flat_blocks_libwebp.webp create mode 100644 tests/Images/Input/Webp/lossy_non_square.png create mode 100644 tests/Images/Input/Webp/lossy_non_square_libwebp.webp create mode 100644 tests/Images/Input/Webp/lossy_segment_map_without_data.webp create mode 100644 tests/Images/Input/Webp/lossy_segment_no_update.webp create mode 100644 tests/Images/Input/Webp/lossy_segment_relative_delta.webp diff --git a/src/ImageSharp/Compression/HuffmanTree.cs b/src/ImageSharp/Compression/HuffmanTree.cs index 5caf1e0be6..99cbd8fa54 100644 --- a/src/ImageSharp/Compression/HuffmanTree.cs +++ b/src/ImageSharp/Compression/HuffmanTree.cs @@ -43,6 +43,12 @@ private HuffmanTree(HuffmanTree other) /// public int PoolIndexRight { get; set; } + /// + /// Compares two trees: the larger total count first, then the smaller value first. + /// + /// The first tree. + /// The second tree. + /// A negative value when comes first, a positive value when comes first, else 0. public static int Compare(HuffmanTree t1, HuffmanTree t2) { if (t1.TotalCount > t2.TotalCount) diff --git a/src/ImageSharp/Formats/Gif/GifEncoderCore.cs b/src/ImageSharp/Formats/Gif/GifEncoderCore.cs index 4237decb51..899a28bd45 100644 --- a/src/ImageSharp/Formats/Gif/GifEncoderCore.cs +++ b/src/ImageSharp/Formats/Gif/GifEncoderCore.cs @@ -21,6 +21,9 @@ namespace SixLabors.ImageSharp.Formats.Gif; /// internal sealed class GifEncoderCore { + /// + /// The encoder options. + /// private readonly GifEncoder encoder; /// @@ -269,6 +272,13 @@ public void Encode(Image image, Stream stream, CancellationToken } } + /// + /// Gets a copy of the GIF metadata of a frame. A frame of the global color table gets the transparency index of that table. + /// + /// The pixel format. + /// The frame. + /// The transparency index of the global color table, or -1 when it has none. + /// The metadata copy. private static GifFrameMetadata GetGifFrameMetadata(ImageFrame frame, int transparencyIndex) where TPixel : unmanaged, IPixel { @@ -475,6 +485,20 @@ private void EncodeAdditionalFrame( this.WriteImageData(indices, stream, quantized.Palette.Length, metadata.TransparencyIndex); } + /// + /// Quantizes the area of a frame with a local or the global palette, and sets the transparency of the frame metadata. + /// + /// The pixel format. + /// The frame to quantize. + /// The quantizer of the global color table. + /// The frame quantizer of the global palette. + /// The area of the frame to quantize. + /// The metadata of the frame. It gets the transparency. + /// Whether the frame uses a local color table. + /// Whether the frame needs a transparent index. + /// The transparency index of the global palette, or -1 when it has none. + /// The color of the transparent index. + /// The indexed frame. private IndexedImageFrame QuantizeFrameAndUpdateMetadata( ImageFrame encodingFrame, IQuantizer globalQuantizer, @@ -598,6 +622,11 @@ private IndexedImageFrame QuantizeFrameAndUpdateMetadata( return quantized; } + /// + /// Limits a palette index to the byte range. + /// + /// The index. + /// The index from 0 to 255. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static byte ClampIndex(int value) => (byte)Math.Clamp(value, byte.MinValue, byte.MaxValue); @@ -826,9 +855,11 @@ private void WriteGraphicalControlExtension(GifFrameMetadata metadata, Stream st disposalMode: metadata.DisposalMode, transparencyFlag: hasTransparency); + // The delay field has 16 bits. A delay outside the field is written as the nearest delay that the field holds. The other + // encoders also saturate a frame delay that their format cannot hold. GifGraphicControlExtension extension = new( packed: packedValue, - delayTime: (ushort)metadata.FrameDelay, + delayTime: (ushort)Math.Clamp(metadata.FrameDelay, 0, ushort.MaxValue), transparencyIndex: hasTransparency ? metadata.TransparencyIndex : byte.MinValue); this.WriteExtension(extension, stream); diff --git a/src/ImageSharp/Formats/Heif/HeifEncoderCore.Sequence.cs b/src/ImageSharp/Formats/Heif/HeifEncoderCore.Sequence.cs index bc82739911..1a0b322a34 100644 --- a/src/ImageSharp/Formats/Heif/HeifEncoderCore.Sequence.cs +++ b/src/ImageSharp/Formats/Heif/HeifEncoderCore.Sequence.cs @@ -1510,8 +1510,7 @@ private static int GetSequenceSyncSampleCount(ReadOnlySpan /// The frame delay in seconds. /// The number of time units in one second. - /// The sample duration. The value is at least 1. - /// The sample duration does not fit in the 32-bit duration field. + /// The sample duration. The value is at least 1 and at most . private static uint GetSequenceSampleDuration(Rational delay, uint timescale) { // HEIF metadata uses a zero numerator or a zero denominator for an unspecified duration. A sample needs a @@ -1525,13 +1524,9 @@ private static uint GetSequenceSampleDuration(Rational delay, uint timescale) ulong scaledDuration = ((ulong)delay.Numerator * timescale) + (delay.Denominator / 2U); ulong duration = Math.Max(1UL, scaledDuration / delay.Denominator); - // The time-to-sample box stores each sample duration in a 32-bit field. - if (duration > uint.MaxValue) - { - throw new ImageFormatException($"The frame delay of {delay} seconds is too long to encode for AVIF format."); - } - - return (uint)duration; + // The time-to-sample box stores each sample duration in a 32-bit field. A longer duration is written as the longest one that the + // field holds. The other encoders also saturate a frame delay that their format cannot hold. + return (uint)Math.Min(duration, uint.MaxValue); } /// @@ -1896,7 +1891,6 @@ private readonly struct HeifSequenceEncoding /// The Exif bytes, or . /// The offset of the TIFF header in . /// The XMP bytes, or . - /// The duration of all plays does not fit in the 64-bit duration field. public HeifSequenceEncoding( int width, int height, @@ -1923,14 +1917,10 @@ public HeifSequenceEncoding( this.XmpData = xmpData; this.MediaDuration = GetSequenceMediaDuration(colorTrack.Samples); - // The version 1 movie and track headers store the duration of all plays in a 64-bit field. - // The check runs here, before the encoder writes the first output byte. - if (repeatCount != 0 && this.MediaDuration > ulong.MaxValue / repeatCount) - { - throw new ImageFormatException($"The duration of {repeatCount} plays is too long to encode for AVIF format."); - } - - this.TrackDuration = repeatCount == 0 ? ulong.MaxValue : this.MediaDuration * repeatCount; + // The version 1 movie and track headers store the duration of all plays in a 64-bit field. A longer duration is written as the + // longest one that the field holds. The encoders also saturate a frame delay that their format cannot hold. + bool saturated = repeatCount == 0 || this.MediaDuration > ulong.MaxValue / repeatCount; + this.TrackDuration = saturated ? ulong.MaxValue : this.MediaDuration * repeatCount; } /// @@ -2005,6 +1995,9 @@ public HeifSequenceEncoding( /// private readonly struct HeifSequenceTrackEncoding { + /// + /// The samples of the track in decode order. + /// private readonly ReadOnlyMemory samples; /// diff --git a/src/ImageSharp/Formats/Jxl/Components/Decoder/JxlIccReader.cs b/src/ImageSharp/Formats/Jxl/Components/Decoder/JxlIccReader.cs index ccafb10c8c..421639224a 100644 --- a/src/ImageSharp/Formats/Jxl/Components/Decoder/JxlIccReader.cs +++ b/src/ImageSharp/Formats/Jxl/Components/Decoder/JxlIccReader.cs @@ -27,10 +27,22 @@ internal static class JxlIccReader // libjxl rejects a prediction stream more than 65536 bytes larger than its reconstructed profile, so this decoder rejects it too. // Combine that bound with the shared profile-size limit before allocating scratch. + + /// + /// The largest number of bytes by which the prediction stream can be larger than the reconstructed profile. + /// private const int MaximumPredictionOverhead = 65536; // JPEG XL's prediction dictionary includes kXYZ and gbd keywords even though the shared ICC enums do not name them. + + /// + /// The signature of the kXYZ tag type. + /// private const uint BlackMatrixColumnSignature = 0x6B58595A; + + /// + /// The signature of the gbd tag type. + /// private const uint GamutBoundaryDescriptionSignature = 0x67626420; /// diff --git a/src/ImageSharp/Formats/Jxl/Components/Entropy/JxlHybridUint.cs b/src/ImageSharp/Formats/Jxl/Components/Entropy/JxlHybridUint.cs index 5af75e199a..fc638d543b 100644 --- a/src/ImageSharp/Formats/Jxl/Components/Entropy/JxlHybridUint.cs +++ b/src/ImageSharp/Formats/Jxl/Components/Entropy/JxlHybridUint.cs @@ -21,9 +21,25 @@ internal readonly struct JxlHybridUint // Prefix alphabets have at most 15 bits; ANS alphabets and copy-length configurations have at most eight. // Read bounds each width by that alphabet before construction. Three byte widths and a cached uint token // occupy eight bytes with natural alignment. Cache the split once rather than shifting for every decoded value. + + /// + /// The smallest token that has extra bits. It is 2 to the power of the split exponent. + /// private readonly uint splitToken; + + /// + /// The threshold exponent. A value below 2 to this power is its own token. + /// private readonly byte splitExponent; + + /// + /// The number of leading bits of a value that the token keeps. + /// private readonly byte highBits; + + /// + /// The number of trailing bits of a value that the token keeps. + /// private readonly byte lowBits; /// diff --git a/src/ImageSharp/Formats/Jxl/Components/Modular/JxlModularTree.cs b/src/ImageSharp/Formats/Jxl/Components/Modular/JxlModularTree.cs index 72146c504b..b8eacde123 100644 --- a/src/ImageSharp/Formats/Jxl/Components/Modular/JxlModularTree.cs +++ b/src/ImageSharp/Formats/Jxl/Components/Modular/JxlModularTree.cs @@ -92,7 +92,14 @@ internal sealed class JxlModularTree : IDisposable /// private const int SmallChannelSampleCount = 64; + /// + /// The tree nodes. + /// private readonly IMemoryOwner nodes; + + /// + /// The number of nodes in use. + /// private readonly int nodeCount; /// @@ -879,11 +886,34 @@ public static ref readonly Node SelectLeaf( /// public readonly ref struct Lookup { + /// + /// The selected property IDs in ascending order. + /// private readonly ReadOnlySpan properties; + + /// + /// The 2048-entry interval or leaf lookup of each selected property. + /// private readonly ReadOnlySpan tables; + + /// + /// The first mask word of the intervals of each property. + /// private readonly ReadOnlySpan offsets; + + /// + /// The candidate leaf masks, with one, two or four words for each interval. + /// private readonly ReadOnlySpan masks; + + /// + /// The reduced tree node index of each candidate leaf. + /// private readonly ReadOnlySpan leaves; + + /// + /// The number of mask words of each interval. + /// private readonly int bucketStride; /// diff --git a/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.Coefficients.cs b/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.Coefficients.cs index 878c7363eb..c4e5aae6dd 100644 --- a/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.Coefficients.cs +++ b/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.Coefficients.cs @@ -13,7 +13,14 @@ namespace SixLabors.ImageSharp.Formats.Jxl.Components.VarDct; internal sealed partial class JxlVarDctDecoder { + /// + /// Owns the coefficients of the current group. + /// private IMemoryOwner? coefficientStorage; + + /// + /// Owns the non-zero counts of the current group. + /// private IMemoryOwner? nonzeroStorage; /// @@ -21,11 +28,34 @@ internal sealed partial class JxlVarDctDecoder /// private IMemoryOwner? entropyHistory; + /// + /// The coefficients of the current group, as bytes. + /// private Memory coefficientMemory; + + /// + /// The non-zero counts of the current group. + /// private Memory nonzeroMemory; + + /// + /// The LZ77 history of the coefficient decode. + /// private Memory coefficientHistoryMemory; + + /// + /// The first coefficient of each component in the coefficient storage. Index 3 is the total count. + /// private InlineArray4 coefficientOffsets; + + /// + /// The number of coefficients of each component. + /// private InlineArray4 coefficientCounts; + + /// + /// The number of AC group columns of the frame. + /// private int acGroupColumns; /// diff --git a/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.cs b/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.cs index eac3697534..7fea79137b 100644 --- a/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.cs +++ b/src/ImageSharp/Formats/Jxl/Components/VarDct/JxlVarDctDecoder.cs @@ -51,10 +51,29 @@ internal sealed partial class JxlVarDctDecoder : IDisposable /// private const float MaximumBaseCorrelation = 4F; + /// + /// The DC thresholds of the block context map. Each channel starts at a multiple of . + /// private InlineArray64 dcThresholds; + + /// + /// The number of DC thresholds of each channel. + /// private InlineArray4 dcThresholdCounts; + + /// + /// The quantization field thresholds of the block context map. + /// private InlineArray16 quantizationThresholds; + + /// + /// The number of quantization field thresholds. + /// private int quantizationThresholdCount; + + /// + /// The block context map of the frame, or null for the default map. + /// private IMemoryOwner? blockContextMap; /// diff --git a/src/ImageSharp/Formats/Png/PngEncoderCore.cs b/src/ImageSharp/Formats/Png/PngEncoderCore.cs index d70d00edf9..88dbb3a43d 100644 --- a/src/ImageSharp/Formats/Png/PngEncoderCore.cs +++ b/src/ImageSharp/Formats/Png/PngEncoderCore.cs @@ -1009,6 +1009,11 @@ private static string BuildRawProfileText(string header, ReadOnlySpan payl return sb.ToString(); } + /// + /// Appends the bytes as upper-case hexadecimal digits, two for each byte. + /// + /// The string builder. + /// The bytes. private static void AppendHex(StringBuilder sb, ReadOnlySpan data) { const string hex = "0123456789ABCDEF"; @@ -1256,6 +1261,36 @@ private void WriteTransparencyChunk(Stream stream, PngMetadata pngMetadata) } } + /// + /// Gets the fcTL delay fraction of a frame delay. Both parts of the fraction have 16 bits. A delay that the fraction cannot hold + /// exactly is written as the nearest delay that it holds. The other encoders also saturate a frame delay that their format cannot hold. + /// + /// + /// A delay whose parts fit is written as it is, so a zero denominator keeps its meaning of 1/100 second. See the APNG specification, + /// the fcTL chunk: https://wiki.mozilla.org/APNG_Specification. Another delay keeps its value in seconds: the denominator is the + /// largest one for which the rounded numerator fits. A delay of 65535 seconds or more is 65535/1. + /// + /// The frame delay in seconds. + /// The numerator and the denominator of the fcTL delay. + private static (ushort Numerator, ushort Denominator) GetFrameDelayFraction(Rational delay) + { + if (delay.Numerator <= ushort.MaxValue && delay.Denominator <= ushort.MaxValue) + { + return ((ushort)delay.Numerator, (ushort)delay.Denominator); + } + + // A zero denominator means 1/100 second, as in the fcTL chunk. The parts are 32-bit, so the value is exact in double. + double seconds = (double)delay.Numerator / (delay.Denominator == 0 ? 100U : delay.Denominator); + if (seconds >= ushort.MaxValue) + { + return (ushort.MaxValue, 1); + } + + // seconds * denominator stays at or below 65535, so the rounded numerator fits. + uint denominator = seconds == 0 ? 1U : (uint)Math.Min(ushort.MaxValue, Math.Floor(ushort.MaxValue / seconds)); + return ((ushort)Math.Round(seconds * denominator), (ushort)denominator); + } + /// /// Writes the animation control chunk to the stream. /// @@ -1263,16 +1298,18 @@ private void WriteTransparencyChunk(Stream stream, PngMetadata pngMetadata) /// The frame metadata. /// The frame area of interest. /// The frame sequence number. + /// The written frame control. private FrameControl WriteFrameControlChunk(Stream stream, PngFrameMetadata frameMetadata, Rectangle bounds, uint sequenceNumber) { + (ushort delayNumerator, ushort delayDenominator) = GetFrameDelayFraction(frameMetadata.FrameDelay); FrameControl fcTL = new( sequenceNumber: sequenceNumber, width: (uint)bounds.Width, height: (uint)bounds.Height, xOffset: (uint)bounds.Left, yOffset: (uint)bounds.Top, - delayNumerator: (ushort)frameMetadata.FrameDelay.Numerator, - delayDenominator: (ushort)frameMetadata.FrameDelay.Denominator, + delayNumerator: delayNumerator, + delayDenominator: delayDenominator, disposalMode: frameMetadata.DisposalMode, blendMode: frameMetadata.BlendMode); @@ -1641,6 +1678,9 @@ private void WriteFrameDataChunk(Stream stream, uint sequenceNumber, ReadOnlySpa stream.Write(buffer, 0, 4); // write the crc } + /// + /// Exchanges the previous and the current scanline buffers. + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] private void SwapScanlineBuffers() { diff --git a/src/ImageSharp/Formats/Tiff/Readers/YCbCrPlanarTiffColor{TPixel}.cs b/src/ImageSharp/Formats/Tiff/Readers/YCbCrPlanarTiffColor{TPixel}.cs index 8181f1209a..cdfb11a735 100644 --- a/src/ImageSharp/Formats/Tiff/Readers/YCbCrPlanarTiffColor{TPixel}.cs +++ b/src/ImageSharp/Formats/Tiff/Readers/YCbCrPlanarTiffColor{TPixel}.cs @@ -22,13 +22,29 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Readers; internal class YCbCrPlanarTiffColor : TiffBasePlanarColorDecoder where TPixel : unmanaged, IPixel { + /// + /// The conversion from YCbCr to RGB. + /// private readonly TiffYCbCrOperator colorOperator; + + /// + /// The horizontal and vertical chroma subsampling factors. + /// private readonly ushort[] ycbcrSubSampling; + /// + /// The configuration of the pixel operations. + /// private readonly Configuration configuration; + /// + /// The ICC profile conversion, or null when the frame has no profile to apply. + /// private readonly ColorProfileConverter? iccConverter; + /// + /// The options of the RGB source of the ICC conversion, or null without a conversion. + /// private readonly ColorConversionOptions? rgbSourceOptions; /// @@ -182,6 +198,15 @@ public override void Decode(IMemoryOwner[] data, Buffer2D pixels, } } + /// + /// Expands the subsampled Cb and Cr planes in place to one sample for each pixel. + /// + /// The width of the region. + /// The height of the region. + /// The horizontal subsampling factor. + /// The vertical subsampling factor. + /// The Cb plane. It has space for the expanded samples. + /// The Cr plane. It has space for the expanded samples. private static void ReverseChromaSubSampling( int width, int height, diff --git a/src/ImageSharp/Formats/Tiff/Readers/YCbCrTiffColor{TPixel}.cs b/src/ImageSharp/Formats/Tiff/Readers/YCbCrTiffColor{TPixel}.cs index b77437700b..846b6324b2 100644 --- a/src/ImageSharp/Formats/Tiff/Readers/YCbCrTiffColor{TPixel}.cs +++ b/src/ImageSharp/Formats/Tiff/Readers/YCbCrTiffColor{TPixel}.cs @@ -22,16 +22,34 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Readers; internal class YCbCrTiffColor : TiffBaseColorDecoder where TPixel : unmanaged, IPixel { + /// + /// The allocator for the chroma expansion buffer. + /// private readonly MemoryAllocator memoryAllocator; + /// + /// The conversion from YCbCr to RGB. + /// private readonly TiffYCbCrOperator colorOperator; + /// + /// The horizontal and vertical chroma subsampling factors. + /// private readonly ushort[] ycbcrSubSampling; + /// + /// The configuration of the pixel operations. + /// private readonly Configuration configuration; + /// + /// The ICC profile conversion, or null when the frame has no profile to apply. + /// private readonly ColorProfileConverter? iccConverter; + /// + /// The options of the RGB source of the ICC conversion, or null without a conversion. + /// private readonly ColorConversionOptions? rgbSourceOptions; /// @@ -194,6 +212,15 @@ private void DecodeYCbCrData(Buffer2D pixels, int left, int top, int wid } } + /// + /// Expands the subsampled chroma of chunky YCbCr data to one Cb and one Cr sample for each pixel. + /// + /// The width of the region. + /// The height of the region. + /// The horizontal subsampling factor. + /// The vertical subsampling factor. + /// The subsampled chunky data. + /// The data with three samples for each pixel. private static void ReverseChromaSubSampling( int width, int height, diff --git a/src/ImageSharp/Formats/Tiff/TiffDecoderCore.cs b/src/ImageSharp/Formats/Tiff/TiffDecoderCore.cs index 506663bde4..728981d451 100644 --- a/src/ImageSharp/Formats/Tiff/TiffDecoderCore.cs +++ b/src/ImageSharp/Formats/Tiff/TiffDecoderCore.cs @@ -403,6 +403,11 @@ private ImageFrame DecodeFrame( } } + /// + /// Creates the metadata of a frame from the tags of its directory. + /// + /// The tags of the directory. + /// The frame metadata and its TIFF metadata. private (ImageFrameMetadata FrameMetadata, TiffFrameMetadata TiffMetadata) CreateFrameMetadata(ExifProfile tags) { ImageFrameMetadata imageFrameMetaData = new(); @@ -1105,6 +1110,17 @@ private void ConfigureColorConversion(TiffBaseColorDecoder decoder, ImageFrameMe } } + /// + /// Creates the decompressor of the compression of the current directory. + /// + /// The pixel format. + /// The width of the frame or the tile. + /// The bits per pixel of the stored data. + /// The metadata of the frame. + /// Whether the data is tiled. + /// The tile width. + /// The tile height. + /// The decompressor. private TiffBaseDecompressor CreateDecompressor( int frameWidth, int bitsPerPixel, @@ -1131,6 +1147,12 @@ private TiffBaseDecompressor CreateDecompressor( tileWidth, tileHeight); + /// + /// Copies the values of a numeric tag to a buffer of unsigned 64-bit values. + /// + /// The tag values. + /// Receives the values. + /// The buffer that owns the values. private IMemoryOwner ConvertNumbers(Array array, out Span span) { if (array is Number[] numbers) diff --git a/src/ImageSharp/Formats/Tiff/TiffDecoderOptionsParser.cs b/src/ImageSharp/Formats/Tiff/TiffDecoderOptionsParser.cs index b6c611660f..e46e273d19 100644 --- a/src/ImageSharp/Formats/Tiff/TiffDecoderOptionsParser.cs +++ b/src/ImageSharp/Formats/Tiff/TiffDecoderOptionsParser.cs @@ -14,6 +14,9 @@ namespace SixLabors.ImageSharp.Formats.Tiff; /// internal static class TiffDecoderOptionsParser { + /// + /// The planar configuration of a directory without the PlanarConfiguration tag. See TIFF 6.0, page 38. + /// private const TiffPlanarConfiguration DefaultPlanarConfiguration = TiffPlanarConfiguration.Chunky; /// diff --git a/src/ImageSharp/Formats/Webp/AlphaDecoder.cs b/src/ImageSharp/Formats/Webp/AlphaDecoder.cs index b5b5727f7d..01b5861eb5 100644 --- a/src/ImageSharp/Formats/Webp/AlphaDecoder.cs +++ b/src/ImageSharp/Formats/Webp/AlphaDecoder.cs @@ -6,6 +6,7 @@ using System.Numerics.Tensors; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; using SixLabors.ImageSharp.Common.Helpers; using SixLabors.ImageSharp.Compression; using SixLabors.ImageSharp.Formats.Webp.BitReader; @@ -40,6 +41,16 @@ internal class AlphaDecoder : IDisposable /// private IMemoryOwner? alphaTable; + /// + /// The transform cache of compressed alpha that needs the ARGB values, or null for the other paths. allocates it. + /// + private IMemoryOwner? transformCache; + + /// + /// The number of complete rows in raw alpha data. sets it, and copies these rows. + /// + private int rawRows; + /// /// Initializes a new instance of the class. /// @@ -71,17 +82,18 @@ public AlphaDecoder( // Header bits 0 and 1 are the compression method, and bits 2 and 3 are the filter. this.Compressed = (WebpAlphaCompressionMethod)(alphaChunkHeader & 0x03) == WebpAlphaCompressionMethod.WebpLosslessCompression; - // As in the JPEG decoder, the rows come from the pool in blocks of whole rows. The allocation is not clean. Decode() writes each decoded row and - // sets the other alpha values to 0, the transparent fill of the other codecs. A complete decode writes every value, so it clears nothing. + // As in the JPEG decoder, the rows come from the pool in blocks of whole rows. The allocation is not clean. Decode() and DecodeRows() + // write each decoded row and set the other alpha values to 0, the transparent fill of the other codecs. A complete decode writes every + // value, so it clears nothing. this.Alpha = memoryAllocator.Allocate2D(width, height); this.AlphaFilterType = (WebpAlphaFilterType)((alphaChunkHeader >> 2) & 0x03); - this.Vp8LDec = new Vp8LDecoder(width, height); if (this.Compressed) { // Decode() reads the lossless header, because damage in the header is image data damage. Decode() runs // inside the using statement of the caller. Thus, that statement disposes the buffers when the integrity - // policy throws. + // policy throws. Raw alpha needs no lossless decoder. + this.Vp8LDec = new Vp8LDecoder(width, height); Vp8LBitReader bitReader = new(data); this.LosslessDecoder = new WebpLosslessDecoder(bitReader, memoryAllocator, configuration); } @@ -103,14 +115,15 @@ public AlphaDecoder( public WebpAlphaFilterType AlphaFilterType { get; } /// - /// Gets the row after the last row that the paletted path converted to alpha values. + /// Gets the row after the last row that has final alpha values. and the paletted path advance it. + /// After damaged compressed data in the ignore mode, all rows are final, and it is . /// public int LastRow { get; private set; } /// - /// Gets information for decoding Vp8L compressed alpha data. + /// Gets information for decoding Vp8L compressed alpha data, or null for raw alpha. /// - public Vp8LDecoder Vp8LDec { get; } + public Vp8LDecoder? Vp8LDec { get; } /// /// Gets the decoded alpha values, one row for each image row. @@ -120,7 +133,7 @@ public AlphaDecoder( /// /// Gets a value indicating whether the alpha channel uses compression. /// - [MemberNotNullWhen(true, nameof(LosslessDecoder))] + [MemberNotNullWhen(true, nameof(LosslessDecoder), nameof(Vp8LDec))] private bool Compressed { get; } /// @@ -143,35 +156,33 @@ public AlphaDecoder( public bool Use8BDecode { get; private set; } /// - /// Decodes and filters the maybe compressed alpha data. + /// Checks the alpha data, reads the lossless headers of compressed alpha and allocates the buffers of the decode. decodes + /// the rows when the color rows need them. /// + /// + /// As in libwebp, raw alpha that is too short is damaged image data. The lossy decoder runs this check before it decodes the color rows. + /// public void Decode() { - int rows; if (!this.Compressed) { - ReadOnlySpan data = this.Data.GetSpan(); - rows = this.Height; - if (data.Length < this.Width * this.Height) + int length = this.Data.GetSpan().Length; + this.rawRows = this.Height; + if (length < this.Width * this.Height) { // Raw alpha that is too short is truncated image data. The decoder keeps the complete rows. this.segmentIntegrityHandling.ThrowOrIgnoreImageDataError("Not enough data in the ALPH chunk."); - rows = data.Length / this.Width; - } - - // The filters work in place on the rows, so the raw rows are copied first. - for (int y = 0; y < rows; y++) - { - data.Slice(y * this.Width, this.Width).CopyTo(this.Alpha.DangerousGetRowSpan(y)); + this.rawRows = length / this.Width; } - this.UnfilterRows(0, rows); + return; } - else if (!this.LosslessDecoder.TryReadHeaders(this.Vp8LDec, this.segmentIntegrityHandling, true)) + + if (!this.LosslessDecoder.TryReadHeaders(this.Vp8LDec, this.segmentIntegrityHandling, true)) { // The color image exists before the alpha data. Thus, in the IgnoreImageData mode, the decoder does not throw for damaged headers. The header is // damaged, so the decoder cannot decode an alpha value, and all alpha values are 0. - rows = 0; + this.ClearRemainingRows(); } else { @@ -203,26 +214,84 @@ public void Decode() // The paletted path stores one palette index byte for each pixel, so its buffer is a quarter of the ARGB buffer. this.Vp8LDec.AllocatePaletteIndices(this.memoryAllocator); - this.LosslessDecoder.DecodeAlphaData(this, this.segmentIntegrityHandling); - rows = this.LastRow; } else { + // The transform cache lives as long as the decode. The batches of one image run in several DecodeRows calls. The first row + // of the cache carries the predictor output of the last row of a batch to the next batch. this.Vp8LDec.AllocatePixels(this.memoryAllocator); - rows = this.LosslessDecoder.DecodeImageRows( - this.Vp8LDec, - this.segmentIntegrityHandling, - "The WebP alpha data is damaged or ends before the last value."); + this.transformCache = WebpLosslessDecoder.AllocateTransformCache(this.memoryAllocator, this.Width); + } + } + } + + /// + /// Makes the alpha rows from up to final and sets to . + /// + /// + /// + /// As in libwebp, the lossy decoder requests the alpha rows of each macroblock row before it writes the color rows. Thus each row is + /// decoded and unfiltered while the color rows that read it are written, and the row stays in the cache. + /// + /// + /// Compressed alpha continues the lossless decode up to , as libwebp does. The lossless decoder reports damaged or truncated + /// data through the integrity mode when it finds it. In the ignore mode, the rows after the decoded rows get 0, the transparent fill of the other + /// codecs, and the decode stops. Raw alpha copies the rows from the data. A row after the complete raw rows gets 0. + /// + /// + /// The row after the last row that the caller reads. It is more than the value of the call before this call. + public void DecodeRows(int lastRow) + { + if (this.Compressed) + { + // Damaged data in an earlier call, or in the headers, made all rows final. + if (this.LastRow == this.Height) + { + return; + } - this.ExtractAlphaRows(rows); + if (this.Use8BDecode) + { + this.LosslessDecoder.DecodeAlphaData(this, this.segmentIntegrityHandling, lastRow); } + else + { + const string message = "The WebP alpha data is damaged or ends before the last value."; + int rows = this.LosslessDecoder.DecodeImageRows(this.Vp8LDec, this.segmentIntegrityHandling, message, lastRow); + + // A backward reference can end after lastRow. The next call converts the rows after lastRow. + this.ExtractAlphaRows(Math.Min(rows, lastRow)); + } + + // A decode that does not reach lastRow found damaged data, and the mode ignores it. No later call can continue the decode. + if (this.LastRow < lastRow) + { + this.ClearRemainingRows(); + } + + return; + } + + int firstRow = this.LastRow; + int width = this.Width; + int rawEnd = Math.Clamp(this.rawRows, firstRow, lastRow); + ReadOnlySpan data = this.Data.GetSpan(); + + // The filters work in place on the rows, so the raw rows are copied first. + for (int y = firstRow; y < rawEnd; y++) + { + data.Slice(y * width, width).CopyTo(this.Alpha.DangerousGetRowSpan(y)); } - // After damaged data, the rows after the decoded rows get 0. - for (int y = rows; y < this.Height; y++) + this.UnfilterRows(firstRow, rawEnd); + + // After truncated data, the rows after the complete rows get 0. + for (int y = rawEnd; y < lastRow; y++) { this.Alpha.DangerousGetRowSpan(y).Clear(); } + + this.LastRow = lastRow; } /// @@ -230,7 +299,7 @@ public void Decode() /// Then it reverses the alpha filter of these rows and sets to . /// /// - /// uses this path only when is . Then the palette index buffer holds one + /// uses this path only when is . Then the palette index buffer holds one /// palette index byte for each value. Small palettes pack 2, 4 or 8 indices in one byte, the first pixel in the low bits, so /// expands each row. See the WebP Lossless Bitstream Specification, section 4.4 /// "Color Indexing Transform": https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. @@ -241,10 +310,11 @@ public void ExtractPalettedAlphaRows(int lastRow) int firstRow = this.LastRow; if (lastRow > firstRow) { - // Decode() uses this path only for a stream with one transform, the color indexing transform. - int bitsPerIndex = 8 >> this.Vp8LDec.Transforms[0].Bits; + // DecodeRows() uses this path only for compressed alpha with one transform, the color indexing transform. + Vp8LDecoder vp8LDec = this.Vp8LDec!; + int bitsPerIndex = 8 >> vp8LDec.Transforms[0].Bits; ReadOnlySpan palette = ((ReadOnlySpan)this.alphaPalette)[..(1 << bitsPerIndex)]; - Buffer2D indices = this.Vp8LDec.PaletteIndices; + Buffer2D indices = vp8LDec.PaletteIndices; if (this.alphaTable is null) { for (int y = firstRow; y < lastRow; y++) @@ -272,18 +342,19 @@ public void ExtractPalettedAlphaRows(int lastRow) /// /// /// The inverse transforms run on batches of rows, as for the main image, so each batch stays in the L2 cache. - /// The filter of a batch runs while the batch is in the cache too. + /// The filter of a batch runs while the batch is in the cache too. As in libwebp, the batches start at . /// - /// The number of decoded rows. The caller clears the other rows. - private void ExtractAlphaRows(int rowCount) + /// The row after the last row to convert. The method converts the rows from , then sets it. + private void ExtractAlphaRows(int lastRow) { + // DecodeRows() uses this path only for compressed alpha that needs the ARGB values. Decode() allocates the transform cache for it. int width = this.Width; - using IMemoryOwner cacheOwner = WebpLosslessDecoder.AllocateTransformCache(this.memoryAllocator, width); - Span cache = cacheOwner.GetSpan(); - for (int firstRow = 0; firstRow < rowCount; firstRow += WebpConstants.NumArgbCacheRows) + Vp8LDecoder vp8LDec = this.Vp8LDec!; + Span cache = this.transformCache!.GetSpan(); + for (int firstRow = this.LastRow; firstRow < lastRow; firstRow += WebpConstants.NumArgbCacheRows) { - int batchRows = Math.Min(WebpConstants.NumArgbCacheRows, rowCount - firstRow); - ReadOnlySpan argb = WebpLosslessDecoder.ApplyInverseTransforms(this.Vp8LDec, firstRow, batchRows, cache, width); + int batchRows = Math.Min(WebpConstants.NumArgbCacheRows, lastRow - firstRow); + ReadOnlySpan argb = WebpLosslessDecoder.ApplyInverseTransforms(vp8LDec, firstRow, batchRows, cache, width); // The green channel holds the alpha value. for (int y = 0; y < batchRows; y++) @@ -293,6 +364,24 @@ private void ExtractAlphaRows(int rowCount) this.UnfilterRows(firstRow, firstRow + batchRows); } + + this.LastRow = lastRow; + } + + /// + /// Sets the alpha values of the rows from to the last row to 0 and sets to . + /// + /// + /// Damaged compressed data stops the decode. As in the other codecs, the rows after the decoded rows get the transparent fill. + /// + private void ClearRemainingRows() + { + for (int y = this.LastRow; y < this.Height; y++) + { + this.Alpha.DangerousGetRowSpan(y).Clear(); + } + + this.LastRow = this.Height; } /// @@ -373,8 +462,9 @@ private static void HorizontalUnfilter(ReadOnlySpan prev, Span row) /// The first value adds the value above it. /// /// - /// The first value has no left or top-left value. With both set to the value above, the gradient is the value above. Each value waits for the value to - /// its left, so the row is one serial chain. The top and top-left values are final, so only the left value is on the chain. + /// The first value has no left or top-left value. With both set to the value above, the gradient is the value above. Each value waits + /// for the value to its left, so the row is one serial chain. runs eight values of the chain in + /// one vector, and the scalar form finishes the row. /// /// The previous unfiltered row. /// The filtered row. On return, the unfiltered row. @@ -383,15 +473,25 @@ private static void GradientUnfilter(ReadOnlySpan prev, Span row) ref byte prevRef = ref MemoryMarshal.GetReference(prev); ref byte rowRef = ref MemoryMarshal.GetReference(row); nuint width = (uint)row.Length; - int topLeft = prevRef; - int left = prevRef; - for (nuint i = 0; i < width; i++) + + // The first value predicts from the value above it. + rowRef = (byte)(rowRef + prevRef); + nuint i = 1; + + if (Vector128.IsHardwareAccelerated) { - int top = Unsafe.Add(ref prevRef, i); - ref byte value = ref Unsafe.Add(ref rowRef, i); - left = (byte)(value + Numerics.ClampToByte(left + top - topLeft)); - value = (byte)left; - topLeft = top; + // Lane 0 holds the left value of the first value of each group of eight. The other lanes are 0. + Vector128 left = Vector128.CreateScalar((short)rowRef); + for (; i + 8 <= width; i += 8) + { + left = GradientUnfilterOperator.Invoke(ref Unsafe.Add(ref prevRef, i), ref Unsafe.Add(ref rowRef, i), left); + } + } + + int leftValue = Unsafe.Add(ref rowRef, i - 1); + for (; i < width; i++) + { + leftValue = GradientUnfilterOperator.Invoke(ref Unsafe.Add(ref prevRef, i), ref Unsafe.Add(ref rowRef, i), leftValue); } } @@ -437,7 +537,78 @@ public void Dispose() { this.Vp8LDec?.Dispose(); this.alphaTable?.Dispose(); + this.transformCache?.Dispose(); this.Data.Dispose(); this.Alpha?.Dispose(); } + + /// + /// Reverses the gradient filter for one value or for eight values of a row. Each value adds clip(left + top - topLeft) modulo 256. + /// + /// + /// All forms give the same values as the scalar form. Each overload reads the top-left value one byte before the top value. + /// + private static class GradientUnfilterOperator + { + /// + /// Reverses the gradient filter for one value, in place. + /// + /// The value above, in the previous unfiltered row. The byte before it is the top-left value. + /// The filtered value. On return, the unfiltered value. + /// The unfiltered value to the left. + /// The unfiltered value, the left value of the next value. + [MethodImpl(InliningOptions.ShortMethod)] + public static int Invoke(ref byte top, ref byte value, int left) + { + int unfiltered = (byte)(value + Numerics.ClampToByte(left + top - Unsafe.Subtract(ref top, 1))); + value = (byte)unfiltered; + return unfiltered; + } + + /// + /// Reverses the gradient filter for eight values, in place. + /// + /// + /// The form follows the SSE2 form of libwebp. Lane j of the 16-bit gradient holds top - topLeft of value j. Then eight steps follow. + /// Each step adds the left value in lane j, clips with an unsigned saturating pack to byte j, adds the filtered value, and keeps + /// byte j. The result of step j, widened, is the left value of step j + 1. + /// + /// The first value above, in the previous unfiltered row. The byte before it is the first top-left value. + /// The first of the eight filtered values. On return, the unfiltered values. + /// Lane 0 holds the unfiltered value to the left of the first value. The other lanes are 0. + /// Lane 0 holds the last unfiltered value, the left value of the next group. The other lanes are 0. + [MethodImpl(InliningOptions.ShortMethod)] + public static Vector128 Invoke(ref byte top, ref byte values, Vector128 left) + { + // The low eight bytes of each load hold the eight values of the group. + Vector128 above = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref top)).AsByte(); + Vector128 aboveLeft = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref Unsafe.Subtract(ref top, 1))).AsByte(); + Vector128 filtered = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned(ref values)).AsByte(); + Vector128 gradient = Vector128.WidenLower(above).AsInt16() - Vector128.WidenLower(aboveLeft).AsInt16(); + + Vector128 mask = Vector128.CreateScalar(byte.MaxValue); + Vector128 output = Vector128.Zero; + Vector128 value; + for (int k = 0; ; k++) + { + // Lane k of left + gradient is left + top - topLeft. The pack clips it to [0, 255] in byte k, and the byte addition wraps + // modulo 256, as the filter requires. The other bytes are not used, so the mask removes them. + value = (Vector128_.PackUnsignedSaturate(left + gradient, Vector128.Zero) + filtered) & mask; + output |= value; + if (k == 7) + { + break; + } + + // Move the value to byte k + 1, then widen it to lane k + 1, the left value of the next value. + left = Vector128.WidenLower(Vector128_.ShiftLeftBytesInVector(value, 1)).AsInt16(); + mask = Vector128_.ShiftLeftBytesInVector(mask, 1); + } + + Unsafe.WriteUnaligned(ref values, output.AsUInt64().ToScalar()); + + // Byte 7 holds the last value. Its move to byte 0 makes lane 0 the left value of the next group, because byte 1 is 0. + return Vector128_.ShiftRightBytesInVector(value, 7).AsInt16(); + } + } } diff --git a/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs b/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs index e6fb17647b..abc341732c 100644 --- a/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs +++ b/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs @@ -3,6 +3,7 @@ using System.Buffers.Binary; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using SixLabors.ImageSharp.Formats.Webp.Lossy; using SixLabors.ImageSharp.Memory; @@ -270,9 +271,12 @@ public void PutTokens(ReadOnlySpan tokens, ReadOnlySpan probas) Span buffer = this.Buffer; // This loop does the same steps as PutBit for each token. The coder state is kept in locals, so that it can stay - // in registers. - ReadOnlySpan norm = WebpLookupTables.Norm; - ReadOnlySpan newRange = WebpLookupTables.NewRange; + // in registers. The table reads need no range checks. The token recorder makes the index of a variable probability token + // from a coefficient type, a band, a context and a probability. Thus the index is in the full probability table. + // The renormalization runs only for a range below 127, and both renormalization tables have 128 entries. + ref byte probasRef = ref MemoryMarshal.GetReference(probas); + ref byte norm = ref MemoryMarshal.GetReference(WebpLookupTables.Norm); + ref byte newRange = ref MemoryMarshal.GetReference(WebpLookupTables.NewRange); int range = this.range; int value = this.value; int nbBits = this.nbBits; @@ -280,7 +284,7 @@ public void PutTokens(ReadOnlySpan tokens, ReadOnlySpan probas) uint pos = this.pos; foreach (ushort token in tokens) { - int proba = (token & Vp8Residual.FixedProbaBit) != 0 ? token & 0xff : probas[token & 0x3fff]; + int proba = (token & Vp8Residual.FixedProbaBit) != 0 ? token & 0xff : Unsafe.Add(ref probasRef, (uint)(token & 0x3fff)); int split = (range * proba) >> 8; if ((token >> 15) != 0) { @@ -295,8 +299,8 @@ public void PutTokens(ReadOnlySpan tokens, ReadOnlySpan probas) if (range < 127) { // Emit 'shift' bits out and renormalize. - int shift = norm[range]; - range = newRange[range]; + int shift = Unsafe.Add(ref norm, (uint)range); + range = Unsafe.Add(ref newRange, (uint)range); value <<= shift; nbBits += shift; if (nbBits > 0) @@ -654,7 +658,7 @@ private void WriteSegmentHeader() { Vp8EncoderSegmentHeader hdr = this.enc.SegmentHeader; Vp8EncoderProbabilities proba = this.enc.Proba; - if (this.PutBitUniform(hdr.NumSegments > 1 ? 1 : 0) != 0) + if (this.PutBitUniform(hdr.SegmentCount > 1 ? 1 : 0) != 0) { // We always 'update' the quant and filter strength values. int updateData = 1; diff --git a/src/ImageSharp/Formats/Webp/Chunks/WebpFrameData.cs b/src/ImageSharp/Formats/Webp/Chunks/WebpFrameData.cs index c439f1d6d4..950653bd37 100644 --- a/src/ImageSharp/Formats/Webp/Chunks/WebpFrameData.cs +++ b/src/ImageSharp/Formats/Webp/Chunks/WebpFrameData.cs @@ -12,6 +12,17 @@ internal readonly struct WebpFrameData /// public const uint HeaderSize = 16; + /// + /// Initializes a new instance of the struct. + /// + /// The size of the frame data in bytes. + /// The X offset of the frame, in units of 2 pixels. + /// The Y offset of the frame, in units of 2 pixels. + /// The frame width. + /// The frame height. + /// The frame duration in milliseconds. + /// The blend mode of the frame. + /// The disposal mode of the frame. public WebpFrameData(uint dataSize, uint x, uint y, uint width, uint height, uint duration, FrameBlendMode blendingMethod, FrameDisposalMode disposalMethod) { this.DataSize = dataSize; @@ -24,6 +35,16 @@ public WebpFrameData(uint dataSize, uint x, uint y, uint width, uint height, uin this.BlendingMethod = blendingMethod; } + /// + /// Initializes a new instance of the struct from the flags byte of an ANMF chunk. + /// + /// The size of the frame data in bytes. + /// The X offset of the frame, in units of 2 pixels. + /// The Y offset of the frame, in units of 2 pixels. + /// The frame width. + /// The frame height. + /// The frame duration in milliseconds. + /// The flags byte. Bit 1 is the blending method and bit 0 is the disposal method. public WebpFrameData(uint dataSize, uint x, uint y, uint width, uint height, uint duration, int flags) : this( dataSize, @@ -37,6 +58,16 @@ public WebpFrameData(uint dataSize, uint x, uint y, uint width, uint height, uin { } + /// + /// Initializes a new instance of the struct for a frame to encode. The data size is 0. + /// + /// The X offset of the frame, in units of 2 pixels. + /// The Y offset of the frame, in units of 2 pixels. + /// The frame width. + /// The frame height. + /// The frame duration in milliseconds. + /// The blend mode of the frame. + /// The disposal mode of the frame. public WebpFrameData(uint x, uint y, uint width, uint height, uint duration, FrameBlendMode blendingMethod, FrameDisposalMode disposalMethod) : this(0, x, y, width, height, duration, blendingMethod, disposalMethod) { @@ -83,6 +114,9 @@ public WebpFrameData(uint x, uint y, uint width, uint height, uint duration, Fra /// public FrameDisposalMode DisposalMethod { get; } + /// + /// Gets the area of the frame on the canvas. + /// public Rectangle Bounds => new((int)this.X, (int)this.Y, (int)this.Width, (int)this.Height); /// @@ -111,7 +145,10 @@ public long WriteHeaderTo(Stream stream) WebpChunkParsingUtils.WriteUInt24LittleEndian(stream, (uint)Math.Round(this.Y / 2f)); WebpChunkParsingUtils.WriteUInt24LittleEndian(stream, this.Width - 1); WebpChunkParsingUtils.WriteUInt24LittleEndian(stream, this.Height - 1); - WebpChunkParsingUtils.WriteUInt24LittleEndian(stream, this.Duration); + + // The duration field has 24 bits. A longer duration is written as the longest one that the field holds. The other + // encoders also saturate a frame delay that their format cannot hold. + WebpChunkParsingUtils.WriteUInt24LittleEndian(stream, Math.Min(this.Duration, (1U << 24) - 1)); stream.WriteByte(flags); return pos; diff --git a/src/ImageSharp/Formats/Webp/Lossless/Vp8LDecoder.cs b/src/ImageSharp/Formats/Webp/Lossless/Vp8LDecoder.cs index b8d8ebe0c9..be8300394d 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/Vp8LDecoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/Vp8LDecoder.cs @@ -39,6 +39,15 @@ public Vp8LDecoder(int width, int height) /// public Vp8LMetadata Metadata { get; set; } + /// + /// Gets or sets the position after the last decoded value of the main image stream. As in libwebp, a decode that stops at a row continues from + /// this position. A backward reference can end after the row, so the position can be after the start of that row. + /// + /// + /// After a decode that stops because of damaged data, the position is not a valid start, and no decode continues. + /// + public int LastPixel { get; set; } + /// /// Gets or sets the transformations which needs to be reversed. /// diff --git a/src/ImageSharp/Formats/Webp/Lossless/WebpLosslessDecoder.cs b/src/ImageSharp/Formats/Webp/Lossless/WebpLosslessDecoder.cs index 45d186fca6..64da9ecd26 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/WebpLosslessDecoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/WebpLosslessDecoder.cs @@ -51,6 +51,11 @@ internal sealed class WebpLosslessDecoder /// private const uint PackedTableMask = HuffmanUtils.HuffmanPackedTableSize - 1; + /// + /// The exception message for headers or a sub-image that read past the end of the data. + /// + private const string HeadersEndMessage = "The WebP lossless headers end before their last field."; + /// /// The worst case size of the lookup tables of the red, blue, alpha and distance codes of one Huffman tree group. /// @@ -142,7 +147,8 @@ public int Decode( decoder.AllocatePixels(this.memoryAllocator); // DecodePixelValues writes only the complete rows. - int rows = this.DecodeImageRows(decoder, segmentIntegrityHandling, "The WebP lossless image data is damaged or ends before the last pixel."); + const string message = "The WebP lossless image data is damaged or ends before the last pixel."; + int rows = this.DecodeImageRows(decoder, segmentIntegrityHandling, message, decoder.Height); this.DecodePixelValues(decoder, pixels, width, rows, colorProfileConverter); return rows; } @@ -176,7 +182,7 @@ public bool TryReadHeaders(Vp8LDecoder decoder, SegmentIntegrityHandling segment if (this.bitReader.IsEndOfStream()) { - segmentIntegrityHandling.ThrowOrIgnoreImageDataError(imageExists, "The WebP lossless headers end before their last field."); + segmentIntegrityHandling.ThrowOrIgnoreImageDataError(imageExists, HeadersEndMessage); return false; } @@ -184,26 +190,31 @@ public bool TryReadHeaders(Vp8LDecoder decoder, SegmentIntegrityHandling segment } /// - /// Decodes the entropy-coded pixels of the main image stream into the pixel buffer of the decoder. + /// Decodes the entropy-coded pixels of the main image stream into the pixel buffer of the decoder, from up to + /// . /// /// /// libwebp reports an error when the data ends before the last pixel, or when a read goes past the end. The method keeps the pixels that it decodes before - /// the damage. + /// the damage. As in libwebp, the lossy alpha decoder calls the method once for each macroblock row, and each call continues where the call before it + /// stopped. A decode that stops at is not damage. /// /// The decoder. read its headers. /// The image data integrity mode. It controls damaged or truncated data. /// The exception message for damaged or truncated data. + /// The row after the last row to decode. It is not more than the height of the decoder. /// - /// The number of complete rows. The color indexing transform packs the pixels of a row. Thus, the width of the decoder can be less than the image width, - /// but each packed row is one image row. + /// The number of complete rows from the top. It is at least , unless the data is damaged. A backward reference can end after + /// , so it can be more. The color indexing transform packs the pixels of a row. Thus, the width of the decoder can be less + /// than the image width, but each packed row is one image row. /// /// /// The data is damaged or truncated, and the mode does not ignore image data errors. /// - public int DecodeImageRows(Vp8LDecoder decoder, SegmentIntegrityHandling segmentIntegrityHandling, string message) + public int DecodeImageRows(Vp8LDecoder decoder, SegmentIntegrityHandling segmentIntegrityHandling, string message, int lastRow) { - int decodedPixels = this.DecodeImageData(decoder, decoder.Pixels); - if (decodedPixels < decoder.Width * decoder.Height || this.bitReader.IsEndOfStream()) + int decodedPixels = this.DecodeImageData(decoder, decoder.Pixels, decoder.LastPixel, lastRow); + decoder.LastPixel = decodedPixels; + if (decodedPixels < decoder.Width * lastRow || this.bitReader.IsEndOfStream()) { segmentIntegrityHandling.ThrowOrIgnoreImageDataError(message); } @@ -302,8 +313,8 @@ private bool TryReadImageStreamHeaders(Vp8LDecoder decoder, int xSize, int ySize /// Decodes a sub-image stream: the entropy image, the transform data or the color map. /// /// - /// The end of the data does not stop the sub-image here. The bit reader keeps the end-of-data state, so the check after the headers in - /// reports it. + /// As in libwebp, a sub-image is valid only when the decode writes each value and no read goes past the end of the data. Thus the method + /// returns no sub-image with values that the decode did not write. /// /// The decoder. /// The width of the sub-image. @@ -318,13 +329,21 @@ private bool TryDecodeSubImage(Vp8LDecoder decoder, int xSize, int ySize, [NotNu return false; } - // Use the Huffman trees to decode the LZ77 encoded data. - IMemoryOwner data = this.memoryAllocator.Allocate(decoder.Width * decoder.Height, AllocationOptions.Clean); + // The allocation is not clean. DecodeImageData writes the values in order. It reads only the values before the next value to write. A backward + // reference starts at or after the first value, and the color cache gets only decoded values. The method keeps the sub-image only when the + // decode writes each value. Thus no caller reads a value that the decode did not write. + int totalPixels = decoder.Width * decoder.Height; + IMemoryOwner data = this.memoryAllocator.Allocate(totalPixels); using Buffer2D view = Buffer2D.WrapMemory(data.Memory, decoder.Width, decoder.Height); - if (this.DecodeImageData(decoder, view) < decoder.Width * decoder.Height && !this.bitReader.IsEndOfStream()) + int decodedPixels = this.DecodeImageData(decoder, view, 0, decoder.Height); + bool endOfStream = this.bitReader.IsEndOfStream(); + if (decodedPixels < totalPixels || endOfStream) { data.Dispose(); - this.segmentIntegrityHandling.ThrowOrIgnoreImageDataError(this.imageExists, "The WebP lossless sub-image has a code that is not valid."); + + // DecodeImageData stops early at the end of the data or at a code that is not valid. + string message = endOfStream ? HeadersEndMessage : "The WebP lossless sub-image has a code that is not valid."; + this.segmentIntegrityHandling.ThrowOrIgnoreImageDataError(this.imageExists, message); return false; } @@ -389,29 +408,43 @@ private void DecodePixelValues( /// /// The decode stops when the data ends, or at a code or a backward reference that is not valid. /// The caller decides how to report the damage. The method keeps the pixels that it decodes before the damage. + /// As in libwebp, the decode can also stop at a row and continue later from the returned position. Before such a stop, all pixels go into the color + /// cache. Thus the next call starts with the same cache as one decode of all pixels. /// /// The decoder. /// /// The pixel data to decode to. It has the size of the stream. As in the JPEG decoder, the rows can be in several pooled buffers, and each buffer holds /// whole rows. /// - /// The number of decoded pixels. - public int DecodeImageData(Vp8LDecoder decoder, Buffer2D pixelData) + /// The first pixel to decode: 0, or the position that the call before this call returned. + /// The row after the last row to decode. The height of the stream decodes all pixels. + /// + /// The position after the last decoded pixel. It is at least the start of , unless the data is damaged. A backward reference can + /// end after that start. + /// + public int DecodeImageData(Vp8LDecoder decoder, Buffer2D pixelData, int startPixel, int lastRow) { const int lenCodeLimit = WebpConstants.NumLiteralCodes + WebpConstants.NumLengthCodes; int width = decoder.Width; int totalPixels = width * decoder.Height; + int lastPixel = width * lastRow; DebugGuard.IsTrue(pixelData.Width == width && pixelData.Height == decoder.Height, "The pixel data has the size of the stream."); + // A backward reference of an earlier call can end after the rows of this call. Then the rows are already decoded. + if (startPixel >= lastPixel) + { + return startPixel; + } + // The loop writes to one buffer of the group at a time. A buffer holds whole rows, so the decode moves to the next buffer only at the end of a row // or after a copy. Each buffer except the last has bufferLength pixels. A single contiguous buffer is the common case, and then the loop never - // changes the buffer. + // changes the buffer. The start is before the last pixel, so its buffer exists. MemoryGroup pixelGroup = pixelData.FastMemoryGroup; int bufferLength = pixelGroup.BufferLength; - int bufferIndex = 0; - Span buffer = pixelGroup[0].Span; - int bufferStart = 0; - int bufferEnd = buffer.Length; + int bufferIndex = startPixel / bufferLength; + Span buffer = pixelGroup[bufferIndex].Span; + int bufferStart = bufferIndex * bufferLength; + int bufferEnd = bufferStart + buffer.Length; Vp8LMetadata metadata = decoder.Metadata; int colorCacheLimit = lenCodeLimit + metadata.ColorCacheSize; @@ -435,16 +468,17 @@ public int DecodeImageData(Vp8LDecoder decoder, Buffer2D pixelData) int dataLength = this.bitReader.Length; this.bitReader.LoadState(out ulong bits, out int bitCount, out int next); - int decodedPixels = 0; - int col = 0; - int row = 0; - int lastCached = 0; + // A call that continues a decode starts with all earlier pixels in the color cache. + int decodedPixels = startPixel; + int col = startPixel % width; + int row = startPixel / width; + int lastCached = startPixel; // The end of the data gives zero bits, so the loop checks for it only at each row end and after each copy. The pixels before the last check that - // passed use only real data. - int checkedPixels = 0; - ref HuffmanTreeGroup group = ref groups[(int)huffmanImage[0]]; - while (decodedPixels < totalPixels) + // passed use only real data. The start passed that check in the call before this call. + int checkedPixels = startPixel; + ref HuffmanTreeGroup group = ref groups[(int)huffmanImage[(huffmanXSize * (row >> huffmanBits)) + (col >> huffmanBits)]]; + while (decodedPixels < lastPixel) { if ((col & mask) == 0) { @@ -618,6 +652,12 @@ public int DecodeImageData(Vp8LDecoder decoder, Buffer2D pixelData) this.bitReader.StoreState(bits, bitCount, next); + // A decode that stops at lastRow continues in a later call. That call starts with all earlier pixels in the color cache. + if (decodedPixels >= lastPixel && decodedPixels < totalPixels && !cacheColors.IsEmpty) + { + FillColorCache(pixelGroup, bufferLength, lastCached, decodedPixels, cacheColors, cacheShift); + } + // Pixels that used bits after the end of the data are not valid. return Vp8LBitReader.IsEndOfStream(dataLength, bitCount, next) ? checkedPixels : decodedPixels; } @@ -1165,8 +1205,14 @@ public static IMemoryOwner AllocateTransformCache(MemoryAllocator memoryAl /// all transforms and the conversion that follows read the batch from the L2 cache. A pass over the whole image for each transform would read and write /// the full pixel buffer from memory each time. The caller runs the batches in row order, because the predictor of a batch reads the last row of the /// batch before it. - /// Without the color indexing transform, the transforms work in place on the decoded rows, so the batch needs no copy. A batch that - /// has no row above in its buffer, and each batch of an image with the color indexing transform, is copied to the cache first. + /// Without the color indexing transform, the transforms work in place on the decoded rows, so the batch needs no copy. These batches are + /// copied to the cache first: + /// + /// A batch that has no row above in its buffer. + /// Each batch of an image with the color indexing transform. + /// Each batch before the end of the entropy decode, with before the last pixel. + /// + /// The caller keeps the cache between batches, because the first row of the cache holds the predictor output of the row above the next batch. /// /// The decoder that holds the transforms and the decoded pixels. /// The first row of the batch. @@ -1188,14 +1234,16 @@ public static ReadOnlySpan ApplyInverseTransforms(Vp8LDecoder decoder, int Span slot = cache[..width]; // Without the color indexing transform, each transform keeps the width, so the transforms can work in place on the decoded rows, with no copy. - // The entropy decode is complete, so no backward reference reads these rows again. The predictor reads the row above the batch at offset -width, - // so that row must be in the same buffer as the batch rows. A buffer of the group holds whole rows. The first batch has no row above, and it uses - // the cache. + // That is safe only when the entropy decode of all pixels is complete, so that no backward reference reads these rows again. The lossy alpha + // decoder applies the transforms while the decode of later rows is not complete, and then each batch uses the cache. The predictor reads the row + // above the batch at offset -width, so that row must be in the same buffer as the batch rows. A buffer of the group holds whole rows. The first + // batch has no row above, and it uses the cache. bool hasColorIndexing = streamWidth != width; + bool decodeComplete = decoder.LastPixel == streamWidth * decoder.Height; MemoryGroup group = pixels.FastMemoryGroup; int rowsPerBuffer = group.BufferLength / streamWidth; int upperRow = firstRow - 1; - bool inPlace = upperRow >= 0 && !hasColorIndexing && upperRow / rowsPerBuffer == (firstRow + rowCount - 1) / rowsPerBuffer; + bool inPlace = decodeComplete && upperRow >= 0 && !hasColorIndexing && upperRow / rowsPerBuffer == (firstRow + rowCount - 1) / rowsPerBuffer; // block is the row above the batch, then the batch rows. Span block; @@ -1268,24 +1316,42 @@ public static ReadOnlySpan ApplyInverseTransforms(Vp8LDecoder decoder, int /// This method will undo the compression. /// /// + /// /// The decoder uses this method only for streams that need 1 byte for each value: green codes and copies only, with no color cache. + /// + /// + /// As in libwebp, the lossy decoder calls the method once for each macroblock row. Each call decodes from up to + /// , and converts the decoded rows up to to alpha values. A decode that stops at + /// is not damage. After damage, is less than . + /// /// /// The alpha decoder. /// The image data integrity mode. It controls damaged or truncated alpha data. - public void DecodeAlphaData(AlphaDecoder dec, SegmentIntegrityHandling segmentIntegrityHandling) + /// The row after the last row to decode. It is more than . + public void DecodeAlphaData(AlphaDecoder dec, SegmentIntegrityHandling segmentIntegrityHandling, int lastRow) { const int lenCodeLimit = WebpConstants.NumLiteralCodes + WebpConstants.NumLengthCodes; Vp8LDecoder vp8LDec = dec.Vp8LDec; int width = vp8LDec.Width; int end = width * vp8LDec.Height; + int last = width * lastRow; + int pos = vp8LDec.LastPixel; - // As in DecodeImageData, the loop writes to one buffer of the group at a time, and each buffer holds whole rows. + // A backward reference of an earlier call can end after the rows of this call. The checks of that call passed, so the rows are final. + if (pos >= last) + { + dec.ExtractPalettedAlphaRows(lastRow); + return; + } + + // As in DecodeImageData, the loop writes to one buffer of the group at a time, and each buffer holds whole rows. The start is before the last + // value, so its buffer exists. MemoryGroup valueGroup = vp8LDec.PaletteIndices.FastMemoryGroup; int bufferLength = valueGroup.BufferLength; - int bufferIndex = 0; - Span buffer = valueGroup[0].Span; - int bufferStart = 0; - int bufferEnd = buffer.Length; + int bufferIndex = pos / bufferLength; + Span buffer = valueGroup[bufferIndex].Span; + int bufferStart = bufferIndex * bufferLength; + int bufferEnd = bufferStart + buffer.Length; Vp8LMetadata hdr = vp8LDec.Metadata; int mask = hdr.HuffmanMask; GetEntropyImage(hdr, out ReadOnlySpan huffmanImage, out int huffmanXSize, out int huffmanBits); @@ -1297,15 +1363,14 @@ public void DecodeAlphaData(AlphaDecoder dec, SegmentIntegrityHandling segmentIn int dataLength = this.bitReader.Length; this.bitReader.LoadState(out ulong bits, out int bitCount, out int next); - int pos = 0; - int col = 0; - int row = 0; + int col = pos % width; + int row = pos / width; // The end of the data gives zero bits, so the loop checks for it only when a row ends. The rows before the last check that passed use only real - // data. A code that is not valid leaves the loop with break. - int checkedRows = 0; - ref HuffmanTreeGroup group = ref groups[(int)huffmanImage[0]]; - while (pos < end) + // data. A code that is not valid leaves the loop with break. The rows before the start passed that check in the call before this call. + int checkedRows = row; + ref HuffmanTreeGroup group = ref groups[(int)huffmanImage[(huffmanXSize * (row >> huffmanBits)) + (col >> huffmanBits)]]; + while (pos < last) { if ((col & mask) == 0) { @@ -1395,23 +1460,25 @@ public void DecodeAlphaData(AlphaDecoder dec, SegmentIntegrityHandling segmentIn checkedRows = row; - // The palette and the filters process the rows in blocks of NumArgbCacheRows rows. + // The palette and the filters process the rows in blocks of NumArgbCacheRows rows. A copy can end after lastRow, and the next call + // converts the rows after lastRow. if (row / WebpConstants.NumArgbCacheRows != startRow / WebpConstants.NumArgbCacheRows) { - dec.ExtractPalettedAlphaRows(row - (row % WebpConstants.NumArgbCacheRows)); + dec.ExtractPalettedAlphaRows(Math.Min(row - (row % WebpConstants.NumArgbCacheRows), lastRow)); } } } this.bitReader.StoreState(bits, bitCount, next); + vp8LDec.LastPixel = pos; - // Process the remaining rows corresponding to last row-block. + // Process the remaining rows corresponding to last row-block, up to lastRow. // The method keeps the complete rows that it decodes before any damage. The caller clears the other rows. - dec.ExtractPalettedAlphaRows(checkedRows); + dec.ExtractPalettedAlphaRows(Math.Min(checkedRows, lastRow)); // Each stream uses one end-of-data rule, as in DecodeImageRows and libwebp. - // Values that are not decoded, or a read past the end of the data, are damage. - if (pos < end || Vp8LBitReader.IsEndOfStream(dataLength, bitCount, next)) + // Values that are not decoded up to lastRow, or a read past the end of the data, are damage. + if (pos < last || Vp8LBitReader.IsEndOfStream(dataLength, bitCount, next)) { segmentIntegrityHandling.ThrowOrIgnoreImageDataError("The WebP alpha data is damaged or ends before the last value."); } @@ -1559,13 +1626,17 @@ private static int PlaneCodeToDistance(int xSize, int planeCode) /// /// /// - /// Most copies are short, so a copy of at most 16 values is a forward loop of single values, with no call. A forward copy of one value at a time - /// also repeats the last 'dist' values when the distance is less than the length, because each read gets a value that the loop wrote before. + /// A copy with the distance less than the length repeats the last 'dist' values. When those values are 1, 2, 4 or 8 bytes, the copy is a fill with + /// an 8-byte pattern. libwebp uses the same fill for pixel distances 1 and 2. It also uses it for alpha distances 1, 2 and 4. A fill + /// reads no value that the copy wrote before, so the stores do not wait for loads. /// /// - /// For a longer copy with the distance less than the length, the copy repeats the last 'dist' values. A copy of distance 1 is a fill. For other - /// distances, the method copies chunks that double in size. Each chunk reads values that the copy wrote before, and the source and the destination of - /// a chunk do not overlap. + /// Most other copies are short, so a copy of at most 16 values is a forward loop of single values, with no call. When the distance is less than the + /// length, a forward copy of one value at a time also repeats the last 'dist' values. Each read gets a value that the loop wrote before. + /// + /// + /// For a longer copy with the distance less than the length, the method copies chunks that double in size. Each chunk reads values that the copy wrote + /// before, and the source and the destination of a chunk do not overlap. /// /// /// The value type: a pixel or an alpha value. @@ -1576,12 +1647,41 @@ private static int PlaneCodeToDistance(int xSize, int planeCode) private static void CopyBlock(Span values, int position, int dist, int length) where T : unmanaged { + // The caller checked that the source starts at or after the first value and that the destination ends at or before the last value. int start = position - dist; + ref T source = ref Unsafe.Add(ref MemoryMarshal.GetReference(values), (uint)start); + ref T destination = ref Unsafe.Add(ref MemoryMarshal.GetReference(values), (uint)position); + + // The 'dist' values before the destination are the pattern of the repeat. A pattern of 1, 2, 4 or 8 bytes fills each 8-byte block of the + // destination in the same way. A destination of less than 16 bytes uses the loop. For pixels, that is the libwebp limit of 4 values. + int patternBytes = dist * Unsafe.SizeOf(); + int destinationBytes = length * Unsafe.SizeOf(); + if (patternBytes <= sizeof(ulong) && (sizeof(ulong) % patternBytes) == 0 && destinationBytes >= 16) + { + // The multiply puts the pattern in each lane of its width. Each lane keeps the byte order of the source. Thus the 8 bytes of the result + // in memory are the pattern bytes in memory order, on little-endian and big-endian platforms. + ref byte sourceBytes = ref Unsafe.As(ref source); + ulong pattern = patternBytes switch + { + 1 => sourceBytes * 0x0101010101010101UL, + 2 => Unsafe.ReadUnaligned(ref sourceBytes) * 0x0001000100010001UL, + 4 => Unsafe.ReadUnaligned(ref sourceBytes) * 0x0000000100000001UL, + _ => Unsafe.ReadUnaligned(ref sourceBytes), + }; + + // The fill writes whole 8-byte blocks. The destination can start at any byte, so the blocks are not aligned. The last 0 to 7 bytes start + // a new block, so they are the first bytes of the pattern. + ref byte destinationBlock = ref Unsafe.As(ref destination); + int blockCount = destinationBytes / sizeof(ulong); + int tailBytes = destinationBytes - (blockCount * sizeof(ulong)); + MemoryMarshal.CreateSpan(ref Unsafe.As(ref destinationBlock), blockCount).Fill(pattern); + ref byte tail = ref Unsafe.Add(ref destinationBlock, (uint)(blockCount * sizeof(ulong))); + MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref pattern, 1))[..tailBytes].CopyTo(MemoryMarshal.CreateSpan(ref tail, tailBytes)); + return; + } + if (length <= 16) { - // The caller checked that the source starts at or after the first value and that the destination ends at or before the last value. - ref T source = ref Unsafe.Add(ref MemoryMarshal.GetReference(values), (uint)start); - ref T destination = ref Unsafe.Add(ref MemoryMarshal.GetReference(values), (uint)position); for (nuint i = 0; i < (uint)length; i++) { Unsafe.Add(ref destination, i) = Unsafe.Add(ref source, i); @@ -1596,12 +1696,6 @@ private static void CopyBlock(Span values, int position, int dist, int len return; } - if (dist == 1) - { - values.Slice(position, length).Fill(values[start]); - return; - } - int copied = 0; while (copied < length) { diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs index b6deb66cbe..5ba061f341 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs @@ -5,6 +5,7 @@ using System.Buffers; using System.Numerics; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using SixLabors.ImageSharp.ColorProfiles; using SixLabors.ImageSharp.Formats.Webp.BitWriter; using SixLabors.ImageSharp.Formats.Webp.Chunks; @@ -113,21 +114,27 @@ internal class Vp8Encoder : IDisposable private readonly IMemoryOwner preds; /// - /// The work sample buffer of the macroblock iterators, with bytes. + /// The storage of the work sample buffer of the macroblock iterators: 128 rows of samples. + /// The iterators use the first samples. /// /// - /// The encoder owns the buffer and disposes it in . Each iterator divides it into its sample buffers and - /// sets the initial values when it is created. The encoder uses one iterator at a time, so all iterators share the buffer. + /// The buffer has a fixed size, so the encoder keeps it inline, as it keeps the fixed-size probability and cost tables. + /// Only the buffers whose size depends on the image come from the memory allocator. The iterators read the buffer about + /// 100 times for each macroblock. A span over an inline field needs no virtual GetSpan call, as pooled memory does. + /// Each iterator divides the buffer into its sample buffers and sets the initial values when it is created. The encoder + /// uses one iterator at a time, so all iterators share the buffer. /// - private readonly IMemoryOwner iteratorSamples; + private InlineArray128> iteratorSamples; /// - /// The coefficient scratch buffer of the macroblock iterators, with values. + /// The storage of the coefficient scratch buffer of the macroblock iterators: 18 blocks of 16 coefficients. + /// The iterators use the first coefficients. /// /// - /// The encoder owns the buffer and disposes it in . Each iterator clears it when it is created. + /// The buffer has a fixed size, so the encoder keeps it inline for the same reason as . + /// Each iterator clears it when it is created. /// - private readonly IMemoryOwner iteratorCoefficients; + private InlineArray18> iteratorCoefficients; /// /// The top chroma diffusion errors, 4 for each macroblock column of the constructor size, or null when the encoder does not diffuse errors. @@ -307,10 +314,6 @@ public Vp8Encoder( // Without diffusion, TopDerr is empty. The iterator clears the errors before it reads them, so the buffer needs no clear. this.topDerr = this.quality <= 98 || this.entropyPasses > 1 ? this.memoryAllocator.Allocate(mbw * 4) : null; - // The iterator sets the initial values of its work buffers when it is created, so these buffers need no clear. - this.iteratorSamples = this.memoryAllocator.Allocate(Vp8EncoderIterator.SampleBufferLength); - this.iteratorCoefficients = this.memoryAllocator.Allocate(Vp8EncoderIterator.CoefficientScratchLength); - // The encoding passes set every field of the segment infos and of the filter header that the encoder changes before they read it, // so all frames use the same instances, as all passes of one frame do. this.SegmentInfos = new Vp8SegmentInfo[4]; @@ -468,12 +471,34 @@ public Vp8Encoder( /// /// Gets the work sample buffer of the macroblock iterators, with bytes. /// - public Memory IteratorSamples => this.iteratorSamples.Memory; + /// + /// The nested inline arrays are one block of contiguous samples, so one span covers the rows. The storage holds more samples + /// than the iterators use, so the span is in range. + /// + public Span IteratorSamples + { + get + { + ref byte first = ref Unsafe.As>, byte>(ref this.iteratorSamples); + return MemoryMarshal.CreateSpan(ref first, Vp8EncoderIterator.SampleBufferLength); + } + } /// /// Gets the coefficient scratch buffer of the macroblock iterators, with values. /// - public Memory IteratorCoefficients => this.iteratorCoefficients.Memory; + /// + /// The nested inline arrays are one block of contiguous coefficients, so one span covers the blocks. The storage holds more + /// coefficients than the iterators use, so the span is in range. + /// + public Span IteratorCoefficients + { + get + { + ref short first = ref Unsafe.As>, short>(ref this.iteratorCoefficients); + return MemoryMarshal.CreateSpan(ref first, Vp8EncoderIterator.CoefficientScratchLength); + } + } /// /// Gets or sets a rough limit for header bits per MB of the current frame. @@ -662,10 +687,9 @@ private bool Encode( this.alpha /= totalMb; this.uvAlpha /= totalMb; - // Analysis is done, proceed to actual encoding. + // Analysis is done, proceed to actual encoding. Each pass of the loops sets the segment parameters for its quality. this.SegmentHeader = new Vp8EncoderSegmentHeader(4); this.AssignSegments(alphas, map); - this.SetLoopParams(this.quality); if (this.tokens is null) { @@ -781,8 +805,6 @@ public void Dispose() this.nz.Dispose(); this.macroBlockInfos.Dispose(); this.preds.Dispose(); - this.iteratorSamples.Dispose(); - this.iteratorCoefficients.Dispose(); this.topDerr?.Dispose(); this.tokens?.Dispose(); this.bitWriter?.Dispose(); @@ -806,16 +828,16 @@ private void EncodeLoop(int width, int height, int yStride, int uvStride, Vp8Enc int yRowsStart = 0; int uvRowsStart = 0; - // Initialize the bitwriter. + // Stats-collection loop. Each pass sets the segment parameters, so the base quantizer is known after the loop. + Vp8ModeScore info = new(); + Vp8Residual residual = it.ResidualScratch; + this.StatLoop(width, height, yStride, uvStride, it, ref info, residual); + + // Initialize the bitwriter. The size estimate uses the base quantizer. int averageBytesPerMacroBlock = AverageBytesPerMb[this.BaseQuant >> 4]; int expectedSize = this.Mbw * this.Mbh * averageBytesPerMacroBlock; this.bitWriter?.Dispose(); this.bitWriter = new Vp8BitWriter(this.memoryAllocator, expectedSize, this); - - // Stats-collection loop. - Vp8ModeScore info = new(); - Vp8Residual residual = it.ResidualScratch; - this.StatLoop(width, height, yStride, uvStride, it, ref info, residual); it.Init(); Vp8EncoderIterator.InitFilter(); do @@ -1111,7 +1133,7 @@ private long OneStatPass( ++this.Proba.NbSkip; } - this.RecordResiduals(it, info, residual); + RecordResiduals(it, info, residual); size += info.R + info.H; sizeP0 += info.H; distortion += info.D; @@ -1263,7 +1285,7 @@ private void ResetBoundaryPredictions() /// private void AssignSegments(ReadOnlySpan alphas, Span map) { - int nb = this.SegmentHeader.NumSegments < NumMbSegments ? this.SegmentHeader.NumSegments : NumMbSegments; + int segmentCount = this.SegmentHeader.SegmentCount < NumMbSegments ? this.SegmentHeader.SegmentCount : NumMbSegments; // One entry for each of the NumMbSegments segments. A default inline array is zero, as the stack buffers were. InlineArray4 centersBuffer = default; @@ -1289,15 +1311,15 @@ private void AssignSegments(ReadOnlySpan alphas, Span map) int rangeA = maxA - minA; // Spread initial centers evenly. - for (k = 0, n = 1; k < nb; ++k, n += 2) + for (k = 0, n = 1; k < segmentCount; ++k, n += 2) { - centers[k] = minA + (n * rangeA / (2 * nb)); + centers[k] = minA + (n * rangeA / (2 * segmentCount)); } for (k = 0; k < MaxItersKMeans; ++k) { // Reset stats. - for (n = 0; n < nb; ++n) + for (n = 0; n < segmentCount; ++n) { accum[n] = 0; distAccum[n] = 0; @@ -1310,7 +1332,7 @@ private void AssignSegments(ReadOnlySpan alphas, Span map) { if (alphas[a] != 0) { - while (n + 1 < nb && Math.Abs(a - centers[n + 1]) < Math.Abs(a - centers[n])) + while (n + 1 < segmentCount && Math.Abs(a - centers[n + 1]) < Math.Abs(a - centers[n])) { n++; } @@ -1327,7 +1349,7 @@ private void AssignSegments(ReadOnlySpan alphas, Span map) int displaced = 0; weightedAverage = 0; int totalWeight = 0; - for (n = 0; n < nb; ++n) + for (n = 0; n < segmentCount; ++n) { if (accum[n] != 0) { @@ -1350,10 +1372,10 @@ private void AssignSegments(ReadOnlySpan alphas, Span map) Span mbInfo = this.MbInfo.Span[..(this.Mbw * this.Mbh)]; for (n = 0; n < mbInfo.Length; ++n) { - ref Vp8MacroBlockInfo mb = ref mbInfo[n]; - int alpha = mb.Alpha; - mb.Segment = map[alpha]; - mb.Alpha = centers[map[alpha]]; + ref Vp8MacroBlockInfo macroBlock = ref mbInfo[n]; + int alpha = macroBlock.Alpha; + macroBlock.Segment = map[alpha]; + macroBlock.Alpha = centers[map[alpha]]; } // TODO: add possibility for SmoothSegmentMap @@ -1368,14 +1390,14 @@ private void AssignSegments(ReadOnlySpan alphas, Span map) /// The weighted mean of the centers. private void SetSegmentAlphas(ReadOnlySpan centers, int mid) { - int nb = this.SegmentHeader.NumSegments; + int segmentCount = this.SegmentHeader.SegmentCount; Vp8SegmentInfo[] dqm = this.SegmentInfos; int min = centers[0], max = centers[0]; int n; - if (nb > 1) + if (segmentCount > 1) { - for (n = 0; n < nb; ++n) + for (n = 0; n < segmentCount; ++n) { if (min > centers[n]) { @@ -1394,7 +1416,7 @@ private void SetSegmentAlphas(ReadOnlySpan centers, int mid) max = min + 1; } - for (n = 0; n < nb; ++n) + for (n = 0; n < segmentCount; ++n) { int alpha = 255 * (centers[n] - mid) / (max - min); int beta = 255 * (centers[n] - min) / (max - min); @@ -1411,11 +1433,11 @@ private void SetSegmentAlphas(ReadOnlySpan centers, int mid) /// The quality, from 0 to 100. private void SetSegmentParams(float quality) { - int nb = this.SegmentHeader.NumSegments; + int segmentCount = this.SegmentHeader.SegmentCount; Vp8SegmentInfo[] dqm = this.SegmentInfos; double amp = WebpConstants.SnsToDq * this.spatialNoiseShaping / 100.0d / 128.0d; double cBase = QualityToCompression(quality / 100.0d); - for (int i = 0; i < nb; i++) + for (int i = 0; i < segmentCount; i++) { // We modulate the base coefficient to accommodate for the quantization // susceptibility and allow denser segments to be quantized more. @@ -1428,6 +1450,12 @@ private void SetSegmentParams(float quality) // Purely indicative in the bitstream (except for the 1-segment case). this.BaseQuant = dqm[0].Quant; + // The bitstream has the quantizer of each of the NumMbSegments segments, so the unused segments get the base quantizer. + for (int i = segmentCount; i < WebpConstants.NumMbSegments; i++) + { + dqm[i].Quant = this.BaseQuant; + } + // uvAlpha is normally spread around ~60. The useful range is // typically ~30 (quite bad) to ~100 (ok to decimate UV more). // We map it to the safe maximal range of MAX/MIN_DQ_UV for dq_uv. @@ -1452,9 +1480,71 @@ private void SetSegmentParams(float quality) // Initialize segments' filtering. this.SetupFilterStrength(); + if (segmentCount > 1) + { + this.SimplifySegments(); + } + this.SetupMatrices(dqm); } + /// + /// Merges the segments that have the same quantizer and the same filter strength. The first segment of each group stays, and the + /// method moves the kept segments to the front. The macroblocks get the new segment numbers. The unused segments at the end get a + /// copy of the last kept segment. + /// + /// + /// Equal segments quantize and filter their macroblocks in the same way, so the merge saves segment map bits. + /// + private void SimplifySegments() + { + // The new segment of each old segment. The segments that are not merged keep their order. + InlineArray4 newSegmentsBuffer = default; + Span newSegments = newSegmentsBuffer; + Vp8SegmentInfo[] segments = this.SegmentInfos; + int segmentCount = Math.Min(this.SegmentHeader.SegmentCount, NumMbSegments); + int keptCount = 1; + for (int segmentIndex = 1; segmentIndex < segmentCount; segmentIndex++) + { + // Find a kept segment that is equal to this segment. Without one, the segment moves to the next kept position. + Vp8SegmentInfo segment = segments[segmentIndex]; + int keptIndex = 0; + while (keptIndex < keptCount && (segments[keptIndex].Quant != segment.Quant || segments[keptIndex].FStrength != segment.FStrength)) + { + keptIndex++; + } + + newSegments[segmentIndex] = keptIndex; + if (keptIndex == keptCount) + { + if (keptCount != segmentIndex) + { + segments[keptCount].CopyFrom(segment); + } + + keptCount++; + } + } + + if (keptCount < segmentCount) + { + Span macroBlocks = this.MbInfo.Span[..(this.Mbw * this.Mbh)]; + for (int i = 0; i < macroBlocks.Length; i++) + { + ref Vp8MacroBlockInfo macroBlock = ref macroBlocks[i]; + macroBlock.Segment = newSegments[macroBlock.Segment]; + } + + this.SegmentHeader.SegmentCount = keptCount; + + // The bitstream has the parameters of all segments, so the unused segments repeat the last kept segment. + for (int segmentIndex = keptCount; segmentIndex < segmentCount; segmentIndex++) + { + segments[segmentIndex].CopyFrom(segments[keptCount - 1]); + } + } + } + /// /// Sets the initial loop filter strength of each segment from its AC quantizer step, its complexity and the filter strength option. /// The method also sets the frame filter level, type and sharpness. @@ -1511,7 +1601,7 @@ private void SetSegmentProbas() ++p[mbInfo[n].Segment]; } - if (this.SegmentHeader.NumSegments > 1) + if (this.SegmentHeader.SegmentCount > 1) { byte[] probas = this.Proba.Segments; probas[0] = (byte)GetProba(p[0] + p[1], p[2] + p[3]); @@ -1734,7 +1824,7 @@ private bool Decimate(Vp8EncoderIterator it, ref Vp8ModeScore rd, Vp8RateDistort Vp8Quantization.PickBestIntra4(it, ref rd, this.SegmentInfos, this.Proba, this.maxI4HeaderBits); } - Vp8Quantization.PickBestUv(it, ref rd, this.SegmentInfos, this.Proba); + Vp8Quantization.PickBestUv(it, ref rd, this.SegmentInfos); if (rdOpt == Vp8RateDistortionLevel.RdOptTrellis) { // Quantize the selected modes again, with the trellis. @@ -1773,22 +1863,23 @@ private bool Decimate(Vp8EncoderIterator it, ref Vp8ModeScore rd, Vp8RateDistort private void CodeResiduals(Vp8EncoderIterator it, Vp8ModeScore rd, Vp8Residual residual) { int x, y, ch; - bool i16 = it.CurrentMacroBlockInfo.MacroBlockType == Vp8MacroBlockType.I16X16; - int segment = it.CurrentMacroBlockInfo.Segment; + ref Vp8MacroBlockInfo macroBlock = ref it.CurrentMacroBlockInfo; + bool i16 = macroBlock.MacroBlockType == Vp8MacroBlockType.I16X16; + int segment = macroBlock.Segment; it.NzToBytes(); int pos1 = this.bitWriter.NumBytes; if (i16) { - residual.Init(0, 1, this.Proba); + residual.Init(0, 1); int res = this.bitWriter.PutCoeffs(it.TopNz[8] + it.LeftNz[8], residual, rd.YDcLevels); it.TopNz[8] = it.LeftNz[8] = res; - residual.Init(1, 0, this.Proba); + residual.Init(1, 0); } else { - residual.Init(0, 3, this.Proba); + residual.Init(0, 3); } // luma-AC @@ -1805,7 +1896,7 @@ private void CodeResiduals(Vp8EncoderIterator it, Vp8ModeScore rd, Vp8Residual r int pos2 = this.bitWriter.NumBytes; // U/V - residual.Init(0, 2, this.Proba); + residual.Init(0, 2); for (ch = 0; ch <= 2; ch += 2) { for (y = 0; y < 2; y++) @@ -1835,7 +1926,7 @@ private void CodeResiduals(Vp8EncoderIterator it, Vp8ModeScore rd, Vp8Residual r /// The iterator. /// The score accumulator. /// The residual reused across the macroblocks of one pass. - private void RecordResiduals(Vp8EncoderIterator it, Vp8ModeScore rd, Vp8Residual residual) + private static void RecordResiduals(Vp8EncoderIterator it, Vp8ModeScore rd, Vp8Residual residual) { int x, y, ch; bool i16 = it.CurrentMacroBlockInfo.MacroBlockType == Vp8MacroBlockType.I16X16; @@ -1845,15 +1936,15 @@ private void RecordResiduals(Vp8EncoderIterator it, Vp8ModeScore rd, Vp8Residual if (i16) { // i16x16 - residual.Init(0, 1, this.Proba); + residual.Init(0, 1); int res = residual.RecordCoeffs(it.TopNz[8] + it.LeftNz[8], rd.YDcLevels); it.TopNz[8] = res; it.LeftNz[8] = res; - residual.Init(1, 0, this.Proba); + residual.Init(1, 0); } else { - residual.Init(0, 3, this.Proba); + residual.Init(0, 3); } // luma-AC @@ -1869,7 +1960,7 @@ private void RecordResiduals(Vp8EncoderIterator it, Vp8ModeScore rd, Vp8Residual } // U/V - residual.Init(0, 2, this.Proba); + residual.Init(0, 2); for (ch = 0; ch <= 2; ch += 2) { for (y = 0; y < 2; y++) @@ -1908,15 +1999,15 @@ private void RecordTokens(Vp8EncoderIterator it, Vp8ModeScore rd, Vp8Residual re if (i16) { // i16x16 - residual.Init(0, 1, this.Proba); + residual.Init(0, 1); int res = residual.RecordCoeffTokens(it.TopNz[8] + it.LeftNz[8], rd.YDcLevels, tokens, ref count); it.TopNz[8] = res; it.LeftNz[8] = res; - residual.Init(1, 0, this.Proba); + residual.Init(1, 0); } else { - residual.Init(0, 3, this.Proba); + residual.Init(0, 3); } // luma-AC @@ -1932,7 +2023,7 @@ private void RecordTokens(Vp8EncoderIterator it, Vp8ModeScore rd, Vp8Residual re } // U/V - residual.Init(0, 2, this.Proba); + residual.Init(0, 2); for (ch = 0; ch <= 2; ch += 2) { for (y = 0; y < 2; y++) diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderIterator.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderIterator.cs index c3de164c5e..8b16f359df 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderIterator.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderIterator.cs @@ -49,6 +49,16 @@ internal class Vp8EncoderIterator /// private const int PredictionBufferLength = (32 * WebpConstants.Bps) + (16 * WebpConstants.Bps) + (8 * WebpConstants.Bps); + /// + /// The position of in the work sample buffer. It follows the input block and the two output blocks. + /// + private const int ScratchOffset = 3 * BlockBufferLength; + + /// + /// The position of in the work sample buffer. It follows the four block buffers. + /// + private const int PredictionOffset = 4 * BlockBufferLength; + /// /// The number of 16x16 luma modes that the analysis tests. It tests only the DC and TrueMotion modes. /// @@ -110,41 +120,28 @@ internal class Vp8EncoderIterator private readonly Memory preds; /// - /// The storage of . It is a part of the work sample buffer of the encoder. - /// - private readonly Memory yuvIn; - - /// - /// The storage of . It is a part of the work sample buffer of the encoder. - /// - private readonly Memory yuvP; - - /// - /// The storage of . It is a part of the work sample buffer of the encoder. + /// The storage of . It is empty when the encoder does not diffuse errors. /// - private readonly Memory scratch; + private readonly Memory topDerr; /// - /// The storage of . It is the coefficient scratch buffer of the encoder. + /// The encoder. It owns the fixed-size work sample buffer and the coefficient scratch buffer of the iterator. /// - private readonly Memory scratch2; - - /// - /// The storage of . It is empty when the encoder does not diffuse errors. - /// - private readonly Memory topDerr; + /// + /// The encoder keeps these two buffers in inline array fields, so a span over them is a field address and a length. + /// Thus each access is a direct read, not a virtual GetSpan call on pooled memory. + /// + private readonly Vp8Encoder enc; /// - /// The storage of . It is a part of the work sample buffer of the encoder. - /// exchanges it with . + /// The position of in the work sample buffer. exchanges it with . /// - private Memory yuvOut; + private int yuvOutOffset; /// - /// The storage of . It is a part of the work sample buffer of the encoder. - /// exchanges it with . + /// The position of in the work sample buffer. exchanges it with . /// - private Memory yuvOut2; + private int yuvOut2Offset; /// /// The index of the current macroblock in raster order. @@ -215,76 +212,47 @@ internal class Vp8EncoderIterator /// Initializes a new instance of the class that shares the macroblock state and the work buffers /// of the encoder. The iterator starts at the first macroblock. /// - /// The encoder. - public Vp8EncoderIterator(Vp8Encoder enc) - : this(enc.YTop, enc.UvTop, enc.Nz, enc.MbInfo, enc.Preds, enc.TopDerr, enc.IteratorSamples, enc.IteratorCoefficients, enc.Mbw, enc.Mbh) - { - } - - /// - /// Initializes a new instance of the class. The iterator starts at the first macroblock. - /// /// - /// The iterator does not own the buffers. The caller owns them and keeps them alive while it uses the iterator. - /// The constructor sets the initial values of the work buffers, so the iterators of one owner must not be used at the same time. + /// The iterator does not own the buffers. The encoder owns them and keeps them alive while it uses the iterator. + /// The constructor sets all work samples to 204 and clears the coefficient scratch buffer. Thus the iterators of one encoder + /// must not be used at the same time. /// - /// The top luma samples, 16 for each macroblock column. - /// The top chroma samples, 8 U and 8 V for each macroblock column. - /// The non-zero patterns, one for each macroblock column plus one for the left context. - /// The macroblock infos in raster order. - /// The intra mode predictors. - /// The top chroma diffusion errors, 4 for each macroblock column, or empty when the encoder does not diffuse errors. - /// The work sample buffer of bytes. The constructor sets all samples to 204. - /// The coefficient scratch buffer of values. The constructor clears it. - /// The image width in macroblocks. - /// The image height in macroblocks. - public Vp8EncoderIterator( - Memory yTop, - Memory uvTop, - Memory nz, - Memory mb, - Memory preds, - Memory topDerr, - Memory samples, - Memory coefficients, - int mbw, - int mbh) + /// The encoder. + public Vp8EncoderIterator(Vp8Encoder enc) { - this.yTop = yTop; - this.uvTop = uvTop; - this.nz = nz; - this.mb = mb; - this.preds = preds; - this.topDerr = topDerr; - this.mbw = mbw; - this.mbh = mbh; + this.enc = enc; + this.yTop = enc.YTop; + this.uvTop = enc.UvTop; + this.nz = enc.Nz; + this.mb = enc.MbInfo; + this.preds = enc.Preds; + this.topDerr = enc.TopDerr; + this.mbw = enc.Mbw; + this.mbh = enc.Mbh; this.currentMbIdx = 0; this.nzIdx = 1; this.yTopIdx = 0; this.uvTopIdx = 0; - this.predsWidth = (4 * mbw) + 1; + this.predsWidth = (4 * this.mbw) + 1; this.PredIdx = this.predsWidth; // The sample buffer holds four block buffers and then the prediction buffer (I16 + chroma + I4 predictions). - this.yuvIn = samples[..BlockBufferLength]; - this.yuvOut = samples.Slice(BlockBufferLength, BlockBufferLength); - this.yuvOut2 = samples.Slice(2 * BlockBufferLength, BlockBufferLength); - this.scratch = samples.Slice(3 * BlockBufferLength, BlockBufferLength); - this.yuvP = samples.Slice(4 * BlockBufferLength, PredictionBufferLength); - this.scratch2 = coefficients[..CoefficientScratchLength]; + // The input block is first, then the two output blocks, then the scratch block. + this.yuvOutOffset = BlockBufferLength; + this.yuvOut2Offset = 2 * BlockBufferLength; this.RdScratch = new Vp8ModeScore(); this.RdScratch2 = new Vp8ModeScore(); this.RdScratch3 = new Vp8ModeScore(); - this.ResidualScratch = new Vp8Residual(); + this.ResidualScratch = new Vp8Residual(enc.Proba); // To match the C initial values of the reference implementation, initialize all with 204. // One fill covers YuvIn, YuvOut, YuvOut2, Scratch and YuvP, because they are the parts of the sample buffer. const byte defaultInitVal = 204; - samples.Span[..SampleBufferLength].Fill(defaultInitVal); + enc.IteratorSamples.Fill(defaultInitVal); this.YLeft.Fill(defaultInitVal); this.UvLeft.Fill(defaultInitVal); - // The pooled coefficient buffer can hold the values of an earlier iterator. Each iterator starts with zero coefficients. + // The shared coefficient buffer can hold the values of an earlier iterator. Each iterator starts with zero coefficients. this.Scratch2.Clear(); this.Init(); @@ -317,10 +285,7 @@ public Vp8EncoderIterator( /// /// Gets the input samples of the current macroblock. The row stride is . /// - /// - /// Each access gets the span from pooled memory. Callers get the span once for a method. - /// - public Span YuvIn => this.yuvIn.Span; + public Span YuvIn => this.enc.IteratorSamples[..BlockBufferLength]; /// /// Gets the output samples: the best reconstruction of the current macroblock. The row stride is . @@ -328,7 +293,7 @@ public Vp8EncoderIterator( /// /// exchanges this buffer with . Callers get the span again after a swap. /// - public Span YuvOut => this.yuvOut.Span; + public Span YuvOut => this.enc.IteratorSamples.Slice(this.yuvOutOffset, BlockBufferLength); /// /// Gets the secondary output samples that the mode search writes. The row stride is . @@ -336,12 +301,12 @@ public Vp8EncoderIterator( /// /// exchanges this buffer with . Callers get the span again after a swap. /// - public Span YuvOut2 => this.yuvOut2.Span; + public Span YuvOut2 => this.enc.IteratorSamples.Slice(this.yuvOut2Offset, BlockBufferLength); /// /// Gets the prediction samples: the 16x16 luma, the chroma and the 4x4 luma predictions. The row stride is . /// - public Span YuvP => this.yuvP.Span; + public Span YuvP => this.enc.IteratorSamples.Slice(PredictionOffset, PredictionBufferLength); /// /// Gets the 32 left luma samples. Entry 0 is the top-left sample, and entries 1 to 16 are the left samples. @@ -450,12 +415,12 @@ public Vp8EncoderIterator( /// /// Gets the byte scratch buffer of * 16 bytes. /// - public Span Scratch => this.scratch.Span; + public Span Scratch => this.enc.IteratorSamples.Slice(ScratchOffset, BlockBufferLength); /// /// Gets the coefficient scratch buffer of values. /// - public Span Scratch2 => this.scratch2.Span; + public Span Scratch2 => this.enc.IteratorCoefficients; /// /// Gets the int scratch buffer of 16 values. @@ -858,10 +823,9 @@ public void SetIntra4Mode(ReadOnlySpan modes) /// context first and updates and with the result of each AC block. /// /// The score with the quantized luma levels. - /// The probabilities with the level costs. - /// The residual to reuse. + /// The residual to reuse. Its probabilities have the level costs. /// The cost in 1/256 bit units. - public int GetCostLuma16(Vp8ModeScore rd, Vp8EncoderProbabilities proba, Vp8Residual res) + public int GetCostLuma16(Vp8ModeScore rd, Vp8Residual res) { int r = 0; @@ -871,11 +835,11 @@ public int GetCostLuma16(Vp8ModeScore rd, Vp8EncoderProbabilities proba, Vp8Resi // DC Span topNz = this.TopNz; Span leftNz = this.LeftNz; - res.Init(0, 1, proba); + res.Init(0, 1); r += res.GetResidualCost(topNz[8] + leftNz[8], ref MemoryMarshal.GetArrayDataReference(rd.YDcLevels)); // AC. The level array holds 16 blocks of 16 levels in raster order. - res.Init(1, 0, proba); + res.Init(1, 0); ref short levels = ref MemoryMarshal.GetArrayDataReference(rd.YAcLevels); for (int y = 0; y < 4; y++) { @@ -895,8 +859,8 @@ public int GetCostLuma16(Vp8ModeScore rd, Vp8EncoderProbabilities proba, Vp8Resi /// these come from . At the macroblock edge, they come from . /// /// The modes that the current macroblock selected for the previous 4x4 blocks. - /// The cost of each 4x4 mode in 1/256 bit units. - public short[] GetCostModeI4(byte[] modes) + /// The cost of each of the 4x4 modes in 1/256 bit units. + public ReadOnlySpan GetCostModeI4(byte[] modes) { int predsWidth = this.predsWidth; int predIdx = this.PredIdx; @@ -905,7 +869,12 @@ public short[] GetCostModeI4(byte[] modes) Span preds = this.Preds; int left = x == 0 ? preds[predIdx + (y * predsWidth) - 1] : modes[this.I4 - 1]; int top = y == 0 ? preds[predIdx - predsWidth + x] : modes[this.I4 - 4]; - return WebpLookupTables.Vp8FixedCostsI4[top, left]; + + // The flat table has NumBModes costs for each pair of top and left modes. Each stored mode is less than NumBModes, + // so the costs of the pair are in the table, and the span needs no range check. + ref short costs = ref MemoryMarshal.GetReference(WebpLookupTables.Vp8FixedCostsI4); + nuint offset = (nuint)(((top * WebpConstants.NumBModes) + left) * WebpConstants.NumBModes); + return MemoryMarshal.CreateReadOnlySpan(ref Unsafe.Add(ref costs, offset), WebpConstants.NumBModes); } /// @@ -913,10 +882,9 @@ public short[] GetCostModeI4(byte[] modes) /// updates and with the result of each block. /// /// The score with the quantized chroma levels. - /// The probabilities with the level costs. - /// The residual to reuse. + /// The residual to reuse. Its probabilities have the level costs. /// The cost in 1/256 bit units. - public int GetCostUv(Vp8ModeScore rd, Vp8EncoderProbabilities proba, Vp8Residual res) + public int GetCostUv(Vp8ModeScore rd, Vp8Residual res) { int r = 0; @@ -926,7 +894,7 @@ public int GetCostUv(Vp8ModeScore rd, Vp8EncoderProbabilities proba, Vp8Residual // The level array holds the 4 U blocks, then the 4 V blocks, each in raster order. Span topNz = this.TopNz; Span leftNz = this.LeftNz; - res.Init(0, 2, proba); + res.Init(0, 2); ref short levels = ref MemoryMarshal.GetArrayDataReference(rd.UvLevels); for (int ch = 0; ch <= 2; ch += 2) { @@ -1160,15 +1128,15 @@ public void MakeChroma8Preds() /// Exchanges and , so that the best reconstruction so far stays in . /// /// - /// The method exchanges the two memory regions, not the samples, so no data is copied. + /// The method exchanges the positions of the two blocks in the work sample buffer, not the samples, so no data is copied. /// public void SwapOut() { // Tuple swap uses 2 more IL bytes #pragma warning disable IDE0180 // Use tuple to swap values - Memory tmp = this.yuvOut; - this.yuvOut = this.yuvOut2; - this.yuvOut2 = tmp; + int offset = this.yuvOutOffset; + this.yuvOutOffset = this.yuvOut2Offset; + this.yuvOut2Offset = offset; #pragma warning restore IDE0180 // Use tuple to swap values } diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderProbabilities.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderProbabilities.cs index 9979ff8262..fcfee0d7b3 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderProbabilities.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderProbabilities.cs @@ -293,8 +293,9 @@ public void Reset() /// The cost in 1/256 bit units. private static int VariableLevelCost(int level, ReadOnlySpan probas) { - int pattern = WebpLookupTables.Vp8LevelCodes[level - 1][0]; - int bits = WebpLookupTables.Vp8LevelCodes[level - 1][1]; + ReadOnlySpan levelCode = WebpLookupTables.Vp8LevelCodes.Slice(2 * (level - 1), 2); + int pattern = levelCode[0]; + int bits = levelCode[1]; int cost = 0; for (int i = 2; pattern != 0; i++) { diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderSegmentHeader.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderSegmentHeader.cs index 71d21b0a83..3ff1b36494 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderSegmentHeader.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncoderSegmentHeader.cs @@ -11,18 +11,21 @@ internal class Vp8EncoderSegmentHeader /// /// Initializes a new instance of the class. /// - /// Number of segments. - public Vp8EncoderSegmentHeader(int numSegments) + /// Number of segments. + public Vp8EncoderSegmentHeader(int segmentCount) { - this.NumSegments = numSegments; - this.UpdateMap = this.NumSegments > 1; + this.SegmentCount = segmentCount; + this.UpdateMap = this.SegmentCount > 1; this.Size = 0; } /// - /// Gets the actual number of segments. 1 segment only = unused. + /// Gets or sets the actual number of segments. 1 segment only = unused. /// - public int NumSegments { get; } + /// + /// The encoder lowers the number when it merges equal segments. + /// + public int SegmentCount { get; set; } /// /// Gets or sets a value indicating whether to update the segment map or not. Must be false if there's only 1 segment. diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Quantization.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Quantization.cs index fa2da3c898..5c2a6a0158 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Quantization.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Quantization.cs @@ -56,12 +56,6 @@ internal static class Vp8Quantization /// private const int DSCALE = 1; // storage descaling, needed to make the error fit byte - /// - /// The offset between the two reconstruction buffers of the 4x4 mode pairs in . - /// Each buffer has 4 rows of 8 samples: the reconstructions of the two modes of a pair side by side. - /// - private const int PairBufferOffset = 8; - /// /// Gets the luma weights of the spectral distortion, one for each coefficient of a 4x4 block in raster order. /// Low frequencies have larger weights. @@ -155,7 +149,7 @@ public static void PickBestIntra16(Vp8EncoderIterator it, ref Vp8ModeScore rd, V rdCur.SD = Mult8B(tlambda, LossyUtils.Vp8Disto16X16(ref srcSums, ref tmpDstRef, ref weights, ref scratch)); rdCur.SD = doubled ? 2 * rdCur.SD : rdCur.SD; rdCur.H = header; - rdCur.R = it.GetCostLuma16(rdCur, proba, res); + rdCur.R = it.GetCostLuma16(rdCur, res); // The search always checks Intra16 first, so it can overwrite *rd directly. rdCur.SetRdScore(lambda); @@ -241,9 +235,14 @@ public static bool PickBestIntra4( Vp8Residual res = it.ResidualScratch; // The base references are taken once for the macroblock. The kernels get references at known offsets from them. - // - recon holds two pair buffers at offsets 0 and PairBufferOffset. Each mode pair writes its two reconstructions - // side by side into one buffer. The buffer with the best reconstruction of the block so far is kept, so the next - // pair writes into the other buffer. No clear is necessary: each pair writes its buffer before it is read. + // - Each mode pair writes its two reconstructions side by side, 8 samples wide, into one of two pair buffers. The buffer + // with the best reconstruction of the block so far is kept, so the next pair writes into the other buffer. One buffer + // is recon in Scratch. The other buffer starts at the block position in bestBlocks. When the first mode of a pair in + // that buffer stays the best, the block is already in place and needs no copy. No clear is necessary. Each pair writes + // its buffer before it is read. + // - The second reconstruction of a pair in bestBlocks covers the next 4 columns. In the same block row, these are the + // samples of a later block, which that block writes again before it is read. Right of the last block column, these are + // the first U columns of YuvOut2. The chroma search writes all chroma samples of YuvOut2 before it reads them. // - coeffs holds the 32 coefficients of a mode pair, and levels the 32 quantized levels after them. // The quantizer writes all levels before the flatness and cost checks read them. // - bestBlocks is YuvOut2 from the luma offset. No swap occurs in the loop, so the span stays valid for the whole loop. @@ -262,18 +261,22 @@ public static bool PickBestIntra4( Span srcSums = it.SourceSums; // All blocks have the coefficient type of intra 4x4 luma. - res.Init(0, 3, proba); + res.Init(0, 3); do { int i4 = it.I4; int bestMode = -1; nuint blockOffset = (nuint)WebpLookupTables.Vp8Scan[i4]; ref byte src = ref Unsafe.Add(ref src0, blockOffset); - short[] modeCosts = it.GetCostModeI4(rd.ModesI4); + ReadOnlySpan modeCosts = it.GetCostModeI4(rd.ModesI4); int ctx = it.TopNz[i4 & 3] + it.LeftNz[i4 >> 2]; int srcSum = srcSums[i4]; - nuint freeBuffer = 0; - nuint bestRecon = 0; + ref byte inPlace = ref Unsafe.Add(ref bestBlocksRef, blockOffset); + + // The first pair writes into the block position, so a best first mode needs no copy. + bool freeIsInPlace = true; + bool bestIsInPlace = false; + nuint bestColumn = 0; rdi4.InitScore(); it.MakeIntra4Preds(); @@ -284,7 +287,7 @@ public static bool PickBestIntra4( for (int pair = 0; pair < WebpConstants.NumBModes; pair += 2) { ref byte pred = ref Unsafe.Add(ref preds, (uint)Vp8Encoding.Vp8I4ModeOffsets[pair]); - ref byte pairRecon = ref Unsafe.Add(ref recon, freeBuffer); + ref byte pairRecon = ref freeIsInPlace ? ref inPlace : ref recon; // Reconstruct. Each 4x4 block has its own non-zero bit. Vp8Encoding.FTransform2(ref src, ref pred, ref coeffs, ref Unsafe.Add(ref coeffs, (nuint)16), ref scratch); @@ -305,7 +308,7 @@ ref Unsafe.Add(ref levels, (nuint)16), } else { - nz01 = Quantize2Blocks(ref coeffs, ref levels, ref dqm.Y1); + nz01 = QuantizeBlocks(ref coeffs, ref levels, ref dqm.Y1, 2); } int nz0 = nz01 & 1; @@ -359,7 +362,8 @@ ref Unsafe.Add(ref levels, (nuint)16), { rdi4.CopyScore(rdTmp); bestMode = mode; - bestRecon = freeBuffer + (nuint)((mode - pair) * 4); + bestIsInPlace = freeIsInPlace; + bestColumn = (nuint)((mode - pair) * 4); pairHasBest = true; Unsafe.CopyBlockUnaligned( ref Unsafe.As(ref Unsafe.Add(ref bestLevels, (uint)(i4 * 16))), @@ -378,7 +382,7 @@ ref Unsafe.As(ref modeLevels), // Keep the buffer with the best reconstruction. The next pair writes into the other buffer. if (pairHasBest) { - freeBuffer ^= PairBufferOffset; + freeIsInPlace = !freeIsInPlace; } } @@ -395,8 +399,13 @@ ref Unsafe.As(ref modeLevels), return false; } - // Copy the selected samples to the right place. - LossyUtils.Vp8Copy4X4(ref Unsafe.Add(ref recon, bestRecon), ref Unsafe.Add(ref bestBlocksRef, blockOffset)); + // Copy the selected samples to the right place, unless they are already there. The source and the destination do not + // overlap: a second reconstruction in the block position starts 4 columns to the right of the block. + if (!bestIsInPlace || bestColumn != 0) + { + ref byte best = ref bestIsInPlace ? ref inPlace : ref recon; + LossyUtils.Vp8Copy4X4(ref Unsafe.Add(ref best, bestColumn), ref inPlace); + } rd.ModesI4[i4] = (byte)bestMode; it.TopNz[i4 & 3] = it.LeftNz[i4 >> 2] = rdi4.Nz != 0 ? 1 : 0; @@ -423,8 +432,7 @@ ref Unsafe.As(ref modeLevels), /// The iterator at the current macroblock. /// The score that gets the selected mode, its levels and its diffusion errors. The method adds the chroma score to it. /// The segment parameters. The segment of the macroblock selects the entry. - /// The probabilities that give the coefficient costs. - public static void PickBestUv(Vp8EncoderIterator it, ref Vp8ModeScore rd, Vp8SegmentInfo[] segmentInfos, Vp8EncoderProbabilities proba) + public static void PickBestUv(Vp8EncoderIterator it, ref Vp8ModeScore rd, Vp8SegmentInfo[] segmentInfos) { const int numBlocks = 8; Vp8SegmentInfo dqm = segmentInfos[it.CurrentMacroBlockInfo.Segment]; @@ -461,7 +469,7 @@ public static void PickBestUv(Vp8EncoderIterator it, ref Vp8ModeScore rd, Vp8Seg continue; } - rdUv.R = it.GetCostUv(rdUv, proba, res); + rdUv.R = it.GetCostUv(rdUv, res); if (mode > 0 && IsFlat(ref MemoryMarshal.GetArrayDataReference(rdUv.UvLevels), numBlocks, WebpConstants.FlatnessLimitIUv)) { rdUv.R += WebpConstants.FlatnessPenality * numBlocks; @@ -537,7 +545,7 @@ ref Unsafe.Add(ref tmp, (uint)((n + 1) * 16)), } Vp8Encoding.FTransformWht(ref tmp, ref dcTmp, ref scratch); - nz |= QuantizeBlock(ref dcTmp, ref MemoryMarshal.GetArrayDataReference(rd.YDcLevels), ref dqm.Y2) << 24; + nz |= QuantizeBlocks(ref dcTmp, ref MemoryMarshal.GetArrayDataReference(rd.YDcLevels), ref dqm.Y2, 1) << 24; if (it.DoTrellis) { @@ -563,13 +571,14 @@ ref Unsafe.Add(ref tmp, (uint)((n + 1) * 16)), } else { - for (n = 0; n < 16; n += 2) + for (n = 0; n < 16; n++) { // Zero-out the first coeff, so that: a) nz is correct below, and // b) finding 'last' non-zero coeffs in SetResidualCoeffs() is simplified. - Unsafe.Add(ref tmp, (uint)(n * 16)) = Unsafe.Add(ref tmp, (uint)((n + 1) * 16)) = 0; - nz |= Quantize2Blocks(ref Unsafe.Add(ref tmp, (uint)(n * 16)), ref Unsafe.Add(ref yAcLevels, (uint)(n * 16)), ref dqm.Y1) << n; + Unsafe.Add(ref tmp, (uint)(n * 16)) = 0; } + + nz |= QuantizeBlocks(ref tmp, ref yAcLevels, ref dqm.Y1, 16); } // Transform back. @@ -628,7 +637,7 @@ public static int ReconstructIntra4( } else { - nz = QuantizeBlock(ref tmp, ref levels, ref dqm.Y1); + nz = QuantizeBlocks(ref tmp, ref levels, ref dqm.Y1, 1); } Vp8Encoding.ITransformOne(ref reference, ref tmp, ref yuvOut, ref scratch); @@ -675,10 +684,7 @@ ref Unsafe.Add(ref tmp, (uint)((n + 1) * 16)), CorrectDcValues(it, ref dqm.Uv, ref tmp, rd); } - for (n = 0; n < 8; n += 2) - { - nz |= Quantize2Blocks(ref Unsafe.Add(ref tmp, (uint)(n * 16)), ref Unsafe.Add(ref uvLevels, (uint)(n * 16)), ref dqm.Uv) << n; - } + nz |= QuantizeBlocks(ref tmp, ref uvLevels, ref dqm.Uv, 8); for (n = 0; n < 8; n += 2) { @@ -746,8 +752,11 @@ public static void RefineUsingDistortion( long bestScore = Vp8ModeScore.MaxCost; int nz = 0; int mode; - bool isI16 = tryBothModes || it.CurrentMacroBlockInfo.MacroBlockType == Vp8MacroBlockType.I16X16; - Vp8SegmentInfo dqm = segmentInfos[it.CurrentMacroBlockInfo.Segment]; + + // The info of the macroblock does not move while the method runs. The mode setters of the iterator write the same info. + ref Vp8MacroBlockInfo macroBlock = ref it.CurrentMacroBlockInfo; + bool isI16 = tryBothModes || macroBlock.MacroBlockType == Vp8MacroBlockType.I16X16; + Vp8SegmentInfo dqm = segmentInfos[macroBlock.Segment]; // Some empiric constants, of approximate order of magnitude. const int lambdaDi16 = 106; @@ -813,7 +822,7 @@ public static void RefineUsingDistortion( int bestI4Mode = -1; long bestI4Score = Vp8ModeScore.MaxCost; Span src = yuvIn[(Vp8EncoderIterator.YOffEnc + WebpLookupTables.Vp8Scan[it.I4])..]; - short[] modeCosts = it.GetCostModeI4(rd.ModesI4); + ReadOnlySpan modeCosts = it.GetCostModeI4(rd.ModesI4); it.MakeIntra4Preds(); for (mode = 0; mode < WebpConstants.NumBModes; ++mode) @@ -889,7 +898,7 @@ ref Unsafe.Add(ref MemoryMarshal.GetReference(it.YuvOut), (nuint)Vp8EncoderItera // SwapOut above can exchange the output buffers, so YuvOut is read after it. ref byte uvOut = ref Unsafe.Add(ref MemoryMarshal.GetReference(it.YuvOut), (nuint)Vp8EncoderIterator.UOffEnc); - nz |= ReconstructUv(it, dqm, rd, ref uvOut, it.CurrentMacroBlockInfo.UvMode); + nz |= ReconstructUv(it, dqm, rd, ref uvOut, macroBlock.UvMode); rd.Nz = (uint)nz; rd.Score = bestScore; @@ -908,11 +917,12 @@ ref Unsafe.Add(ref MemoryMarshal.GetReference(it.YuvOut), (nuint)Vp8EncoderItera /// The probabilities that give the coefficient costs of the trellis quantization. public static void SimpleQuantize(Vp8EncoderIterator it, Vp8ModeScore rd, Vp8SegmentInfo[] segmentInfos, Vp8EncoderProbabilities proba) { - Vp8SegmentInfo dqm = segmentInfos[it.CurrentMacroBlockInfo.Segment]; + ref Vp8MacroBlockInfo macroBlock = ref it.CurrentMacroBlockInfo; + Vp8SegmentInfo dqm = segmentInfos[macroBlock.Segment]; Span yuvOut = it.YuvOut[Vp8EncoderIterator.YOffEnc..]; ref byte yOut = ref MemoryMarshal.GetReference(yuvOut); int nz; - if (it.CurrentMacroBlockInfo.MacroBlockType == Vp8MacroBlockType.I16X16) + if (macroBlock.MacroBlockType == Vp8MacroBlockType.I16X16) { nz = ReconstructIntra16(it, dqm, rd, proba, ref yOut, it.Preds[it.PredIdx]); } @@ -941,7 +951,7 @@ ref Unsafe.Add(ref yOut, offset), } ref byte uvOut = ref Unsafe.Add(ref MemoryMarshal.GetReference(it.YuvOut), (nuint)Vp8EncoderIterator.UOffEnc); - nz |= ReconstructUv(it, dqm, rd, ref uvOut, it.CurrentMacroBlockInfo.UvMode); + nz |= ReconstructUv(it, dqm, rd, ref uvOut, macroBlock.UvMode); rd.Nz = (uint)nz; } @@ -1160,145 +1170,163 @@ private static int LevelCost(ReadOnlySpan costs, int offset, int level) => WebpLookupTables.Vp8LevelFixedCosts[level] + costs[offset + Math.Min(level, WebpConstants.MaxVariableLevel)]; /// - /// Quantizes two 4x4 blocks. See . + /// Quantizes consecutive 4x4 blocks with one matrix. Each level is (|coefficient| + sharpen) * iQ + bias, shifted right by QFix + /// bits and limited to 2047, with the sign of the coefficient. The input gets the dequantized coefficients level * q. /// - /// The first of the 32 coefficients: 16 of the first block, then 16 of the second block. - /// The first of the 32 levels, in the same block order. + /// + /// + /// The method loads the matrix vectors once for all blocks, not once for each block. + /// + /// + /// With 256-bit and 512-bit vectors, the products use 16-bit lanes. A low multiply and a high multiply give the two halves of + /// each 32-bit product, and an unpack joins them. The 128-bit form widens the magnitudes and the reciprocals to 32-bit lanes + /// before one multiply. On Arm, the 16-bit high multiply is itself two widening multiplies, so the widen is the shorter form there. + /// + /// + /// + /// The first of the 16 * coefficients, block after block, each block in raster order. On return, + /// the dequantized coefficients. + /// + /// The first of the 16 * levels, block after block, each block in zigzag order. /// The quantization matrix. - /// The non-zero bits: bit 0 for the first block, bit 1 for the second block. - [MethodImpl(InliningOptions.ShortMethod)] - public static int Quantize2Blocks(ref short input, ref short output, ref Vp8Matrix mtx) + /// The number of blocks, from 1 to 16. + /// The non-zero bits: bit n is set when a level of block n is not zero. + public static int QuantizeBlocks(ref short input, ref short output, ref Vp8Matrix mtx, int count) { - if (Vector512.IsHardwareAccelerated) + int nz = 0; + int n = 0; + if (Vector256.IsHardwareAccelerated) { - // Lanes 0 to 15 hold the first block and lanes 16 to 31 the second block, both in raster order. Both blocks use - // the same matrix, so each matrix vector holds the 16 entries twice. The widen of the coefficients gives the - // first block in the low result and the second block in the high result, so both bias vectors are the 16 biases. - Vector256 sharpen = Vector256.LoadUnsafe(ref mtx.Sharpen[0]); + // Lane i of the 16-bit matrix vectors holds matrix entry i, as the coefficients of a block in raster order. + // The unpacks of the 16-bit products work in each 128-bit lane. The low unpack gives the products of the + // coefficients 0 to 3 and 8 to 11. The high unpack gives the products of the coefficients 4 to 7 and 12 to 15. + // The two bias vectors have the same lane layout. The pack also works in each 128-bit lane, so it puts the levels + // back in raster order. + ref uint bias = ref mtx.Bias[0]; + Vector256 sharpen = Vector256.LoadUnsafe(ref mtx.Sharpen[0]).AsUInt16(); Vector256 iq = Vector256.LoadUnsafe(ref mtx.IQ[0]); Vector256 q = Vector256.LoadUnsafe(ref mtx.Q[0]).AsInt16(); - Vector512 bias = Vector512.LoadUnsafe(ref mtx.Bias[0]); - Vector512 level = Quantize( - Vector512.LoadUnsafe(ref input), - Vector512.Create(sharpen, sharpen), - Vector512.Create(iq, iq), - bias, - bias, - Vector512.Create(q, q), - out Vector512 dequantized); - - dequantized.StoreUnsafe(ref input); - Vector256 level0 = level.GetLower(); - Vector256 level1 = level.GetUpper(); - StoreZigzag(level0.GetLower(), level0.GetUpper(), ref output); - StoreZigzag(level1.GetLower(), level1.GetUpper(), ref Unsafe.Add(ref output, (nuint)16)); - return (Vector256.EqualsAll(level0, Vector256.Zero) ? 0 : 1) | (Vector256.EqualsAll(level1, Vector256.Zero) ? 0 : 2); - } + Vector256 biasLow = Vector256.Create(Vector128.LoadUnsafe(ref bias), Vector128.LoadUnsafe(ref bias, 8)).AsInt32(); + Vector256 biasHigh = Vector256.Create(Vector128.LoadUnsafe(ref bias, 4), Vector128.LoadUnsafe(ref bias, 12)).AsInt32(); - int nz = QuantizeBlock(ref input, ref output, ref mtx); - nz |= QuantizeBlock(ref Unsafe.Add(ref input, (nuint)16), ref Unsafe.Add(ref output, (nuint)16), ref mtx) << 1; - return nz; - } + if (Vector512.IsHardwareAccelerated) + { + // Lanes 0 to 15 hold the first block and lanes 16 to 31 the second block. Each 256-bit half has the lane layout + // of one block above. All blocks use the same matrix, so each matrix vector holds the 256-bit vector twice. + Vector512 sharpen2 = Vector512.Create(sharpen, sharpen); + Vector512 iq2 = Vector512.Create(iq, iq); + Vector512 q2 = Vector512.Create(q, q); + Vector512 biasLow2 = Vector512.Create(biasLow, biasLow); + Vector512 biasHigh2 = Vector512.Create(biasHigh, biasHigh); + for (; n + 2 <= count; n += 2) + { + ref short coefficients = ref Unsafe.Add(ref input, (uint)(n * 16)); + ref short levels = ref Unsafe.Add(ref output, (uint)(n * 16)); + Vector512 c = Vector512.LoadUnsafe(ref coefficients); + Vector512 level = Quantize(c, sharpen2, iq2, biasLow2, biasHigh2, q2, out Vector512 dequantized); + dequantized.StoreUnsafe(ref coefficients); + + Vector256 level0 = level.GetLower(); + Vector256 level1 = level.GetUpper(); + StoreZigzag(level0.GetLower(), level0.GetUpper(), ref levels); + StoreZigzag(level1.GetLower(), level1.GetUpper(), ref Unsafe.Add(ref levels, (nuint)16)); + int nz01 = (Vector256.EqualsAll(level0, Vector256.Zero) ? 0 : 1) | (Vector256.EqualsAll(level1, Vector256.Zero) ? 0 : 2); + nz |= nz01 << n; + } + } - /// - /// Quantizes one 4x4 block. Each level is (|coefficient| + sharpen) * iQ + bias, shifted right by QFix bits and - /// limited to 2047, with the sign of the coefficient. The input gets the dequantized coefficient level * q. - /// - /// The first of the 16 coefficients in raster order. On return, the dequantized coefficients. - /// The first of the 16 levels in zigzag order. - /// The quantization matrix. - /// 1 if a level is not zero, else 0. - public static int QuantizeBlock(ref short input, ref short output, ref Vp8Matrix mtx) - { - if (Vector256.IsHardwareAccelerated) - { - // Lane i holds coefficient i in raster order. The widen of the coefficients gives the coefficients 0 to 7 in the - // low result and 8 to 15 in the high result, so the bias vectors are the first 8 and the last 8 biases. - ref uint bias = ref mtx.Bias[0]; - Vector256 level = Quantize( - Vector256.LoadUnsafe(ref input), - Vector256.LoadUnsafe(ref mtx.Sharpen[0]), - Vector256.LoadUnsafe(ref mtx.IQ[0]), - Vector256.LoadUnsafe(ref bias), - Vector256.LoadUnsafe(ref bias, 8), - Vector256.LoadUnsafe(ref mtx.Q[0]).AsInt16(), - out Vector256 dequantized); - - dequantized.StoreUnsafe(ref input); - StoreZigzag(level.GetLower(), level.GetUpper(), ref output); - return Vector256.EqualsAll(level, Vector256.Zero) ? 0 : 1; + // One block for each step: all blocks without 512-bit vectors, else the last block of an odd count. + for (; n < count; n++) + { + ref short coefficients = ref Unsafe.Add(ref input, (uint)(n * 16)); + Vector256 c = Vector256.LoadUnsafe(ref coefficients); + Vector256 level = Quantize(c, sharpen, iq, biasLow, biasHigh, q, out Vector256 dequantized); + dequantized.StoreUnsafe(ref coefficients); + StoreZigzag(level.GetLower(), level.GetUpper(), ref Unsafe.Add(ref output, (uint)(n * 16))); + nz |= (Vector256.EqualsAll(level, Vector256.Zero) ? 0 : 1) << n; + } + + return nz; } if (Vector128.IsHardwareAccelerated) { - // The first call takes the coefficients 0 to 7 and the second call the coefficients 8 to 15. - ref short sharpen = ref mtx.Sharpen[0]; - ref ushort iq = ref mtx.IQ[0]; + // Each block takes two steps: the coefficients 0 to 7, then the coefficients 8 to 15. The bias vectors of each step are + // the biases of its first 4 and its last 4 coefficients, because the widen keeps the lane order. ref uint bias = ref mtx.Bias[0]; ref short q = ref Unsafe.As(ref mtx.Q[0]); - Vector128 level0 = Quantize( - Vector128.LoadUnsafe(ref input), - Vector128.LoadUnsafe(ref sharpen), - Vector128.LoadUnsafe(ref iq), - Vector128.LoadUnsafe(ref bias), - Vector128.LoadUnsafe(ref bias, 4), - Vector128.LoadUnsafe(ref q), - out Vector128 dequantized0); - - Vector128 level8 = Quantize( - Vector128.LoadUnsafe(ref input, 8), - Vector128.LoadUnsafe(ref sharpen, 8), - Vector128.LoadUnsafe(ref iq, 8), - Vector128.LoadUnsafe(ref bias, 8), - Vector128.LoadUnsafe(ref bias, 12), - Vector128.LoadUnsafe(ref q, 8), - out Vector128 dequantized8); - - dequantized0.StoreUnsafe(ref input); - dequantized8.StoreUnsafe(ref input, 8); - StoreZigzag(level0, level8, ref output); - return Vector128.EqualsAll(level0 | level8, Vector128.Zero) ? 0 : 1; + Vector128 sharpen0 = Vector128.LoadUnsafe(ref mtx.Sharpen[0]); + Vector128 sharpen8 = Vector128.LoadUnsafe(ref mtx.Sharpen[0], 8); + Vector128 iq0 = Vector128.LoadUnsafe(ref mtx.IQ[0]); + Vector128 iq8 = Vector128.LoadUnsafe(ref mtx.IQ[0], 8); + Vector128 q0 = Vector128.LoadUnsafe(ref q); + Vector128 q8 = Vector128.LoadUnsafe(ref q, 8); + Vector128 bias0 = Vector128.LoadUnsafe(ref bias); + Vector128 bias4 = Vector128.LoadUnsafe(ref bias, 4); + Vector128 bias8 = Vector128.LoadUnsafe(ref bias, 8); + Vector128 bias12 = Vector128.LoadUnsafe(ref bias, 12); + for (; n < count; n++) + { + ref short coefficients = ref Unsafe.Add(ref input, (uint)(n * 16)); + Vector128 c0 = Vector128.LoadUnsafe(ref coefficients); + Vector128 c8 = Vector128.LoadUnsafe(ref coefficients, 8); + Vector128 level0 = Quantize(c0, sharpen0, iq0, bias0, bias4, q0, out Vector128 dequantized0); + Vector128 level8 = Quantize(c8, sharpen8, iq8, bias8, bias12, q8, out Vector128 dequantized8); + dequantized0.StoreUnsafe(ref coefficients); + dequantized8.StoreUnsafe(ref coefficients, 8); + StoreZigzag(level0, level8, ref Unsafe.Add(ref output, (uint)(n * 16))); + nz |= (Vector128.EqualsAll(level0 | level8, Vector128.Zero) ? 0 : 1) << n; + } + + return nz; } - int last = -1; ref byte zigzag = ref MemoryMarshal.GetReference(WebpConstants.Zigzag); - for (nuint n = 0; n < 16; ++n) + for (; n < count; n++) { - int j = Unsafe.Add(ref zigzag, n); - ref short inJ = ref Unsafe.Add(ref input, (nuint)j); - bool sign = inJ < 0; - uint coeff = (uint)((sign ? -inJ : inJ) + mtx.Sharpen[j]); - if (coeff > mtx.ZThresh[j]) + ref short coefficients = ref Unsafe.Add(ref input, (uint)(n * 16)); + ref short levels = ref Unsafe.Add(ref output, (uint)(n * 16)); + int last = -1; + for (nuint i = 0; i < 16; ++i) { - uint q = mtx.Q[j]; - uint iQ = mtx.IQ[j]; - uint b = mtx.Bias[j]; - int level = QuantDiv(coeff, iQ, b); - if (level > MaxLevel) + int j = Unsafe.Add(ref zigzag, i); + ref short inJ = ref Unsafe.Add(ref coefficients, (nuint)j); + bool sign = inJ < 0; + uint coeff = (uint)((sign ? -inJ : inJ) + mtx.Sharpen[j]); + if (coeff > mtx.ZThresh[j]) { - level = MaxLevel; - } + uint qj = mtx.Q[j]; + uint iQ = mtx.IQ[j]; + uint b = mtx.Bias[j]; + int level = QuantDiv(coeff, iQ, b); + if (level > MaxLevel) + { + level = MaxLevel; + } - if (sign) - { - level = -level; - } + if (sign) + { + level = -level; + } - inJ = (short)(level * (int)q); - Unsafe.Add(ref output, n) = (short)level; - if (level != 0) + inJ = (short)(level * (int)qj); + Unsafe.Add(ref levels, i) = (short)level; + if (level != 0) + { + last = (int)i; + } + } + else { - last = (int)n; + Unsafe.Add(ref levels, i) = 0; + inJ = 0; } } - else - { - Unsafe.Add(ref output, n) = 0; - inJ = 0; - } + + nz |= (last >= 0 ? 1 : 0) << n; } - return last >= 0 ? 1 : 0; + return nz; } /// @@ -1349,31 +1377,46 @@ private static Vector128 Quantize( } /// - /// Quantizes the coefficients of a vector, one coefficient in each lane, with the steps of the 128-bit form. + /// Quantizes the coefficients of one 4x4 block in raster order, one coefficient in each 16-bit lane, with 16-bit products. /// + /// + /// + /// The low multiply and the high multiply give the low and high 16 bits of each product |coefficient| + sharpen times iQ. + /// The unpacks join the halves to the exact 32-bit products. Then the steps and the limits are the same as in the 128-bit form, + /// so the levels are the same. + /// + /// + /// The signed saturating pack keeps each level up to 32767 and gives 32767 for a larger level. The limit then gives 2047 for + /// both, as the scalar form does. + /// + /// /// The coefficients. /// The sharpening biases, one for each lane. /// The fixed-point reciprocals of the steps, one for each lane. - /// The rounding biases of the lanes in the low half. - /// The rounding biases of the lanes in the high half. + /// The rounding biases of the products of the low unpack: the coefficients 0 to 3, then 8 to 11. + /// The rounding biases of the products of the high unpack: the coefficients 4 to 7, then 12 to 15. /// The steps, one for each lane. /// The dequantized coefficients, level * q, in the low 16 bits. /// The signed levels, limited to 2047 in magnitude. [MethodImpl(InliningOptions.ShortMethod)] private static Vector256 Quantize( Vector256 coefficients, - Vector256 sharpen, + Vector256 sharpen, Vector256 iq, - Vector256 biasLow, - Vector256 biasHigh, + Vector256 biasLow, + Vector256 biasHigh, Vector256 q, out Vector256 dequantized) { - (Vector256 magnitudeLow, Vector256 magnitudeHigh) = Vector256.Widen((Vector256.Abs(coefficients) + sharpen).AsUInt16()); - (Vector256 iqLow, Vector256 iqHigh) = Vector256.Widen(iq); - Vector256 levelLow = Vector256.ShiftRightLogical((magnitudeLow * iqLow) + biasLow, WebpConstants.QFix); - Vector256 levelHigh = Vector256.ShiftRightLogical((magnitudeHigh * iqHigh) + biasHigh, WebpConstants.QFix); - Vector256 level = Vector256.Min(Vector256.Narrow(levelLow, levelHigh), Vector256.Create((ushort)MaxLevel)).AsInt16(); + Vector256 magnitude = Vector256.Abs(coefficients).AsUInt16() + sharpen; + Vector256 productLow = (magnitude * iq).AsInt16(); + Vector256 productHigh = Vector256_.MultiplyHigh(magnitude, iq).AsInt16(); + + // Each 32-bit lane of an unpack holds one product. The low half is in its low 16 bits, and the high half is in its high 16 bits. + // The sum with the bias does not wrap, so the logical shift gives the same level as the unsigned scalar division. + Vector256 levelLow = Vector256.ShiftRightLogical(Vector256_.UnpackLow(productLow, productHigh).AsInt32() + biasLow, WebpConstants.QFix); + Vector256 levelHigh = Vector256.ShiftRightLogical(Vector256_.UnpackHigh(productLow, productHigh).AsInt32() + biasHigh, WebpConstants.QFix); + Vector256 level = Vector256.Min(Vector256_.PackSignedSaturate(levelLow, levelHigh), Vector256.Create((short)MaxLevel)); Vector256 sign = Vector256.ShiftRightArithmetic(coefficients, 15); level = (level ^ sign) - sign; dequantized = level * q; @@ -1381,31 +1424,33 @@ private static Vector256 Quantize( } /// - /// Quantizes the coefficients of a vector, one coefficient in each lane, with the steps of the 128-bit form. + /// Quantizes the coefficients of two 4x4 blocks, one coefficient in each 16-bit lane, with 16-bit products. Each 256-bit half + /// holds one block with the lane layout of the 256-bit form. /// /// The coefficients. /// The sharpening biases, one for each lane. /// The fixed-point reciprocals of the steps, one for each lane. - /// The rounding biases of the lanes in the low half. - /// The rounding biases of the lanes in the high half. + /// The rounding biases of the products of the low unpack, in each 256-bit half as in the 256-bit form. + /// The rounding biases of the products of the high unpack, in each 256-bit half as in the 256-bit form. /// The steps, one for each lane. /// The dequantized coefficients, level * q, in the low 16 bits. /// The signed levels, limited to 2047 in magnitude. [MethodImpl(InliningOptions.ShortMethod)] private static Vector512 Quantize( Vector512 coefficients, - Vector512 sharpen, + Vector512 sharpen, Vector512 iq, - Vector512 biasLow, - Vector512 biasHigh, + Vector512 biasLow, + Vector512 biasHigh, Vector512 q, out Vector512 dequantized) { - (Vector512 magnitudeLow, Vector512 magnitudeHigh) = Vector512.Widen((Vector512.Abs(coefficients) + sharpen).AsUInt16()); - (Vector512 iqLow, Vector512 iqHigh) = Vector512.Widen(iq); - Vector512 levelLow = Vector512.ShiftRightLogical((magnitudeLow * iqLow) + biasLow, WebpConstants.QFix); - Vector512 levelHigh = Vector512.ShiftRightLogical((magnitudeHigh * iqHigh) + biasHigh, WebpConstants.QFix); - Vector512 level = Vector512.Min(Vector512.Narrow(levelLow, levelHigh), Vector512.Create((ushort)MaxLevel)).AsInt16(); + Vector512 magnitude = Vector512.Abs(coefficients).AsUInt16() + sharpen; + Vector512 productLow = (magnitude * iq).AsInt16(); + Vector512 productHigh = Vector512_.MultiplyHigh(magnitude, iq).AsInt16(); + Vector512 levelLow = Vector512.ShiftRightLogical(Vector512_.UnpackLow(productLow, productHigh).AsInt32() + biasLow, WebpConstants.QFix); + Vector512 levelHigh = Vector512.ShiftRightLogical(Vector512_.UnpackHigh(productLow, productHigh).AsInt32() + biasHigh, WebpConstants.QFix); + Vector512 level = Vector512.Min(Vector512_.PackSignedSaturate(levelLow, levelHigh), Vector512.Create((short)MaxLevel)); Vector512 sign = Vector512.ShiftRightArithmetic(coefficients, 15); level = (level ^ sign) - sign; dequantized = level * q; diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Residual.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Residual.cs index 6829f30e45..b37c8bcd89 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Residual.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Residual.cs @@ -24,9 +24,9 @@ internal class Vp8Residual public const int FixedProbaBit = 1 << 14; /// - /// The probabilities and statistics of the current coefficient type. + /// The probabilities, statistics and level costs of the encoder. The encoder keeps one instance for its lifetime. /// - private Vp8EncoderProbabilities proba; + private readonly Vp8EncoderProbabilities proba; /// /// The start of the current coefficient type in the flat probability and statistics tables. @@ -38,6 +38,12 @@ internal class Vp8Residual /// private int costOffset; + /// + /// Initializes a new instance of the class. + /// + /// The probabilities, statistics and level costs of the encoder. + public Vp8Residual(Vp8EncoderProbabilities proba) => this.proba = proba; + /// /// Gets or sets the position of the first coefficient to code: 1 for the AC blocks of an intra 16x16 macroblock, else 0. /// @@ -63,12 +69,10 @@ internal class Vp8Residual /// /// The position of the first coefficient to code. /// The coefficient type. - /// The encoder probabilities. - public void Init(int first, int coeffType, Vp8EncoderProbabilities prob) + public void Init(int first, int coeffType) { this.First = first; this.CoeffType = coeffType; - this.proba = prob; this.probaOffset = coeffType * Vp8EncoderProbabilities.ProbasPerType; this.costOffset = coeffType * Vp8EncoderProbabilities.CostsPerType; } @@ -122,33 +126,41 @@ public void SetCoeffs(ReadOnlySpan coeffs) public int RecordCoeffs(int ctx, ReadOnlySpan coeffs) { this.SetCoeffs(coeffs); - Span stats = this.proba.Stats.AsSpan(this.probaOffset, Vp8EncoderProbabilities.ProbasPerType); + + // All reads below are in range. The statistics of the coefficient type have NumBands * NumCtx * NumProbas entries. Each + // index is a (band, context) start plus a probability less than NumProbas. The coefficient positions are less than 16, and the + // band table has 17 entries. The levels are limited to MaxVariableLevel, which has an entry in the level code table. + ref uint stats = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(this.proba.Stats), (uint)this.probaOffset); + ref short coeffsRef = ref MemoryMarshal.GetReference(coeffs); + ref byte bands = ref MemoryMarshal.GetReference(WebpConstants.Vp8EncBands); + ref ushort levelCodes = ref MemoryMarshal.GetReference(WebpLookupTables.Vp8LevelCodes); + int last = this.Last; int n = this.First; // The band of the positions 0 and 1 is the position itself. int s = Vp8EncoderProbabilities.ProbaIndex(n, ctx); - if (this.Last < 0) + if (last < 0) { - RecordStats(0, ref stats[s]); + RecordStats(0, ref Unsafe.Add(ref stats, (uint)s)); return 0; } - while (n <= this.Last) + while (n <= last) { int v; - RecordStats(1, ref stats[s]); // order of record doesn't matter - while ((v = coeffs[n++]) == 0) + RecordStats(1, ref Unsafe.Add(ref stats, (uint)s)); // order of record doesn't matter + while ((v = Unsafe.Add(ref coeffsRef, (uint)n++)) == 0) { - RecordStats(0, ref stats[s + 1]); - s = Vp8EncoderProbabilities.ProbaIndex(WebpConstants.Vp8EncBands[n], 0); + RecordStats(0, ref Unsafe.Add(ref stats, (uint)(s + 1))); + s = Vp8EncoderProbabilities.ProbaIndex(Unsafe.Add(ref bands, (uint)n), 0); } - RecordStats(1, ref stats[s + 1]); + RecordStats(1, ref Unsafe.Add(ref stats, (uint)(s + 1))); bool bit = (uint)(v + 1) > 2u; - if (RecordStats(bit ? 1 : 0, ref stats[s + 2]) == 0) + if (RecordStats(bit ? 1 : 0, ref Unsafe.Add(ref stats, (uint)(s + 2))) == 0) { // v = -1 or 1 - s = Vp8EncoderProbabilities.ProbaIndex(WebpConstants.Vp8EncBands[n], 1); + s = Vp8EncoderProbabilities.ProbaIndex(Unsafe.Add(ref bands, (uint)n), 1); } else { @@ -158,25 +170,27 @@ public int RecordCoeffs(int ctx, ReadOnlySpan coeffs) v = WebpConstants.MaxVariableLevel; } - int bits = WebpLookupTables.Vp8LevelCodes[v - 1][1]; - int pattern = WebpLookupTables.Vp8LevelCodes[v - 1][0]; + // The level code table holds the pattern and then the bits of each level. + nuint codeOffset = (uint)(2 * (v - 1)); + int pattern = Unsafe.Add(ref levelCodes, codeOffset); + int bits = Unsafe.Add(ref levelCodes, codeOffset + 1); int i; for (i = 0; (pattern >>= 1) != 0; i++) { int mask = 2 << i; if ((pattern & 1) != 0) { - RecordStats((bits & mask) != 0 ? 1 : 0, ref stats[s + 3 + i]); + RecordStats((bits & mask) != 0 ? 1 : 0, ref Unsafe.Add(ref stats, (uint)(s + 3 + i))); } } - s = Vp8EncoderProbabilities.ProbaIndex(WebpConstants.Vp8EncBands[n], 2); + s = Vp8EncoderProbabilities.ProbaIndex(Unsafe.Add(ref bands, (uint)n), 2); } } if (n < 16) { - RecordStats(0, ref stats[s]); + RecordStats(0, ref Unsafe.Add(ref stats, (uint)s)); } return 1; @@ -199,109 +213,118 @@ public int RecordCoeffs(int ctx, ReadOnlySpan coeffs) public int RecordCoeffTokens(int ctx, ReadOnlySpan coeffs, Span tokens, ref int count) { this.SetCoeffs(coeffs); - Span stats = this.proba.Stats; + + // All accesses below are in range. The token span has space for the tokens of a full macroblock. Each probability index is the + // start of the coefficient type plus a (band, context) start plus a probability less than NumProbas. Thus it is in the statistics + // table. The coefficient positions are less than 16, and the band table has 17 entries. + ref uint stats = ref MemoryMarshal.GetArrayDataReference(this.proba.Stats); + ref ushort tokensRef = ref MemoryMarshal.GetReference(tokens); + ref short coeffsRef = ref MemoryMarshal.GetReference(coeffs); + ref byte bands = ref MemoryMarshal.GetReference(WebpConstants.Vp8EncBands); int last = this.Last; int n = this.First; // The band of the positions 0 and 1 is the position itself. int baseId = this.probaOffset + Vp8EncoderProbabilities.ProbaIndex(n, ctx); - if (!AddToken(tokens, ref count, stats, last >= 0, baseId)) + if (!AddToken(ref tokensRef, ref count, ref stats, last >= 0, baseId)) { return 0; } while (n < 16) { - int c = coeffs[n++]; + int c = Unsafe.Add(ref coeffsRef, (uint)n++); bool sign = c < 0; int v = sign ? -c : c; - if (!AddToken(tokens, ref count, stats, v != 0, baseId + 1)) + if (!AddToken(ref tokensRef, ref count, ref stats, v != 0, baseId + 1)) { - baseId = this.probaOffset + Vp8EncoderProbabilities.ProbaIndex(WebpConstants.Vp8EncBands[n], 0); + baseId = this.probaOffset + Vp8EncoderProbabilities.ProbaIndex(Unsafe.Add(ref bands, (uint)n), 0); continue; } - if (!AddToken(tokens, ref count, stats, v > 1, baseId + 2)) + if (!AddToken(ref tokensRef, ref count, ref stats, v > 1, baseId + 2)) { - baseId = this.probaOffset + Vp8EncoderProbabilities.ProbaIndex(WebpConstants.Vp8EncBands[n], 1); + baseId = this.probaOffset + Vp8EncoderProbabilities.ProbaIndex(Unsafe.Add(ref bands, (uint)n), 1); } else { - if (!AddToken(tokens, ref count, stats, v > 4, baseId + 3)) + if (!AddToken(ref tokensRef, ref count, ref stats, v > 4, baseId + 3)) { - if (AddToken(tokens, ref count, stats, v != 2, baseId + 4)) + if (AddToken(ref tokensRef, ref count, ref stats, v != 2, baseId + 4)) { - AddToken(tokens, ref count, stats, v == 4, baseId + 5); + AddToken(ref tokensRef, ref count, ref stats, v == 4, baseId + 5); } } - else if (!AddToken(tokens, ref count, stats, v > 10, baseId + 6)) + else if (!AddToken(ref tokensRef, ref count, ref stats, v > 10, baseId + 6)) { - if (!AddToken(tokens, ref count, stats, v > 6, baseId + 7)) + if (!AddToken(ref tokensRef, ref count, ref stats, v > 6, baseId + 7)) { - AddConstantToken(tokens, ref count, v == 6, 159); + AddConstantToken(ref tokensRef, ref count, v == 6, 159); } else { - AddConstantToken(tokens, ref count, v >= 9, 165); - AddConstantToken(tokens, ref count, (v & 1) == 0, 145); + AddConstantToken(ref tokensRef, ref count, v >= 9, 165); + AddConstantToken(ref tokensRef, ref count, (v & 1) == 0, 145); } } else { int mask; - ReadOnlySpan tab; + ReadOnlySpan extraProbas; int residue = v - 3; if (residue < (8 << 1)) { // Cat3 (3b) - AddToken(tokens, ref count, stats, false, baseId + 8); - AddToken(tokens, ref count, stats, false, baseId + 9); + AddToken(ref tokensRef, ref count, ref stats, false, baseId + 8); + AddToken(ref tokensRef, ref count, ref stats, false, baseId + 9); residue -= 8 << 0; mask = 1 << 2; - tab = WebpConstants.Cat3; + extraProbas = WebpConstants.Cat3; } else if (residue < (8 << 2)) { // Cat4 (4b) - AddToken(tokens, ref count, stats, false, baseId + 8); - AddToken(tokens, ref count, stats, true, baseId + 9); + AddToken(ref tokensRef, ref count, ref stats, false, baseId + 8); + AddToken(ref tokensRef, ref count, ref stats, true, baseId + 9); residue -= 8 << 1; mask = 1 << 3; - tab = WebpConstants.Cat4; + extraProbas = WebpConstants.Cat4; } else if (residue < (8 << 3)) { // Cat5 (5b) - AddToken(tokens, ref count, stats, true, baseId + 8); - AddToken(tokens, ref count, stats, false, baseId + 10); + AddToken(ref tokensRef, ref count, ref stats, true, baseId + 8); + AddToken(ref tokensRef, ref count, ref stats, false, baseId + 10); residue -= 8 << 2; mask = 1 << 4; - tab = WebpConstants.Cat5; + extraProbas = WebpConstants.Cat5; } else { // Cat6 (11b) - AddToken(tokens, ref count, stats, true, baseId + 8); - AddToken(tokens, ref count, stats, true, baseId + 10); + AddToken(ref tokensRef, ref count, ref stats, true, baseId + 8); + AddToken(ref tokensRef, ref count, ref stats, true, baseId + 10); residue -= 8 << 3; mask = 1 << 10; - tab = WebpConstants.Cat6; + extraProbas = WebpConstants.Cat6; } - int tabIdx = 0; + // The table of each category has one probability for each extra bit, and the mask has one bit for each extra bit. + ref byte tab = ref MemoryMarshal.GetReference(extraProbas); while (mask != 0) { - AddConstantToken(tokens, ref count, (residue & mask) != 0, tab[tabIdx++]); + AddConstantToken(ref tokensRef, ref count, (residue & mask) != 0, tab); + tab = ref Unsafe.Add(ref tab, 1); mask >>= 1; } } - baseId = this.probaOffset + Vp8EncoderProbabilities.ProbaIndex(WebpConstants.Vp8EncBands[n], 2); + baseId = this.probaOffset + Vp8EncoderProbabilities.ProbaIndex(Unsafe.Add(ref bands, (uint)n), 2); } // The sign bit has the probability 128. This gives the same bits as a uniform bit. - AddConstantToken(tokens, ref count, sign, 128); - if (n == 16 || !AddToken(tokens, ref count, stats, n <= last, baseId)) + AddConstantToken(ref tokensRef, ref count, sign, 128); + if (n == 16 || !AddToken(ref tokensRef, ref count, ref stats, n <= last, baseId)) { return 1; // EOB } @@ -411,31 +434,31 @@ public int GetResidualCost(int ctx0, ref short coeffs) /// /// Adds a token with a variable probability and records its statistics. /// - /// The destination of the tokens. + /// The first token of the destination. The caller keeps the destination large enough. /// The number of tokens in . - /// The flat statistics table. + /// The first entry of the flat statistics table. The caller keeps the index in the table. /// The bit value. /// The index of the probability in the flat probability table. /// The value of . [MethodImpl(InliningOptions.ShortMethod)] - private static bool AddToken(Span tokens, ref int count, Span stats, bool bit, int probaIndex) + private static bool AddToken(ref ushort tokens, ref int count, ref uint stats, bool bit, int probaIndex) { int b = bit ? 1 : 0; - tokens[count++] = (ushort)((b << 15) | probaIndex); - RecordStats(b, ref stats[probaIndex]); + Unsafe.Add(ref tokens, (uint)count++) = (ushort)((b << 15) | probaIndex); + RecordStats(b, ref Unsafe.Add(ref stats, (uint)probaIndex)); return bit; } /// /// Adds a token with a constant probability. /// - /// The destination of the tokens. + /// The first token of the destination. The caller keeps the destination large enough. /// The number of tokens in . /// The bit value. /// The probability. [MethodImpl(InliningOptions.ShortMethod)] - private static void AddConstantToken(Span tokens, ref int count, bool bit, int proba) - => tokens[count++] = (ushort)(((bit ? 1 : 0) << 15) | FixedProbaBit | proba); + private static void AddConstantToken(ref ushort tokens, ref int count, bool bit, int proba) + => Unsafe.Add(ref tokens, (uint)count++) = (ushort)(((bit ? 1 : 0) << 15) | FixedProbaBit | proba); /// /// Records one bit in a statistics entry. diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8SegmentInfo.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8SegmentInfo.cs index debedac62e..4d578ce745 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8SegmentInfo.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8SegmentInfo.cs @@ -95,6 +95,31 @@ internal class Vp8SegmentInfo /// public int LambdaTrellisI16 { get; set; } + /// + /// Sets all values of this segment to the values of another segment. The matrices are copied, not shared. + /// + /// The segment to copy. + public void CopyFrom(Vp8SegmentInfo other) + { + this.Y1 = other.Y1; + this.Y2 = other.Y2; + this.Uv = other.Uv; + this.Alpha = other.Alpha; + this.Beta = other.Beta; + this.Quant = other.Quant; + this.FStrength = other.FStrength; + this.MaxEdge = other.MaxEdge; + this.I4Penalty = other.I4Penalty; + this.MinDisto = other.MinDisto; + this.LambdaI16 = other.LambdaI16; + this.LambdaI4 = other.LambdaI4; + this.TLambda = other.TLambda; + this.LambdaUv = other.LambdaUv; + this.LambdaMode = other.LambdaMode; + this.LambdaTrellisI4 = other.LambdaTrellisI4; + this.LambdaTrellisI16 = other.LambdaTrellisI16; + } + /// /// Raises to the largest magnitude of the first three AC coefficients of the Y2 block, when it is larger. /// diff --git a/src/ImageSharp/Formats/Webp/Lossy/WebpLossyDecoder.cs b/src/ImageSharp/Formats/Webp/Lossy/WebpLossyDecoder.cs index f11018cb79..5ff0eb0249 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/WebpLossyDecoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/WebpLossyDecoder.cs @@ -168,7 +168,8 @@ public int Decode( InitializeMacroBlockRange(decoder); // As in libwebp, only ALPH data adds alpha. A VP8X alpha flag without an ALPH chunk gives opaque pixels. - // The alpha plane is decoded first, so that each color row can join its alpha row when it is written. + // Decode() checks the alpha data first. Each macroblock row then makes its alpha rows final before it writes the color rows. + // Thus each color row can join its alpha row when it is written. using AlphaDecoder alphaDecoder = alphaData is null ? null : new AlphaDecoder( @@ -186,7 +187,7 @@ public int Decode( using YuvToRgbConverter writer = new(this.configuration, this.memoryAllocator, pixels, width, alphaDecoder?.Alpha, colorConverter, colorProfileConverter); - this.ParseFrame(decoder, writer, segmentIntegrityHandling); + this.ParseFrame(decoder, writer, alphaDecoder, segmentIntegrityHandling); return writer.RowsWritten; } @@ -198,10 +199,12 @@ public int Decode( /// /// The decoder. /// The writer of the destination rows. + /// The alpha decoder, or null when the image has no ALPH chunk. /// The image data integrity mode. It controls data that ends early. private void ParseFrame( Vp8Decoder dec, YuvToRgbConverter writer, + AlphaDecoder alphaDecoder, SegmentIntegrityHandling segmentIntegrityHandling) where TPixel : unmanaged, IPixel { @@ -251,7 +254,7 @@ private void ParseFrame( // Reconstruct, filter and emit the row. ReconstructRow(dec); - FinishRow(dec, writer); + FinishRow(dec, writer, alphaDecoder); } } @@ -769,7 +772,8 @@ private static void DoFilter(Vp8Decoder dec, Vp8FilterInfo filterInfo, int mbx, /// /// The decoder. /// The writer of the destination rows. - private static void FinishRow(Vp8Decoder dec, YuvToRgbConverter writer) + /// The alpha decoder, or null when the image has no ALPH chunk. + private static void FinishRow(Vp8Decoder dec, YuvToRgbConverter writer, AlphaDecoder alphaDecoder) where TPixel : unmanaged, IPixel { int extraYRows = WebpConstants.FilterExtraRows[(int)dec.Filter]; @@ -820,6 +824,8 @@ private static void FinishRow(Vp8Decoder dec, YuvToRgbConverter if (yStart < yEnd) { + // As in libwebp, the alpha rows of the color rows are made final first. The writer reads rows below yEnd only. + alphaDecoder?.DecodeRows(yEnd); EmitRgb(dec, y, u, v, yStart, yEnd, writer); } diff --git a/src/ImageSharp/Formats/Webp/WebpChunkParsingUtils.cs b/src/ImageSharp/Formats/Webp/WebpChunkParsingUtils.cs index 216f940b03..313d968a9f 100644 --- a/src/ImageSharp/Formats/Webp/WebpChunkParsingUtils.cs +++ b/src/ImageSharp/Formats/Webp/WebpChunkParsingUtils.cs @@ -140,20 +140,15 @@ public static uint ReadUInt24LittleEndian(BufferedReadStream stream, Span } /// - /// Writes a unsigned 24 bit integer. + /// Writes an unsigned 24-bit value. /// + /// + /// The callers limit each value before the write. The encoder checks the image size, and the frame header saturates the duration. + /// /// The stream to write to. - /// The uint24 data to write. - /// - /// Thrown if the data is not a valid unsigned 24 bit integer. - /// + /// The value to write. It is less than 2^24. public static void WriteUInt24LittleEndian(Stream stream, uint data) { - if (data >= 1 << 24) - { - throw new InvalidDataException($"Invalid data, {data} is not a unsigned 24 bit integer."); - } - // Write the data in little endian: the low byte first. stream.WriteByte((byte)data); stream.WriteByte((byte)(data >> 8)); diff --git a/src/ImageSharp/Formats/Webp/WebpLookupTables.cs b/src/ImageSharp/Formats/Webp/WebpLookupTables.cs index ae1ace5afe..d1e50eead5 100644 --- a/src/ImageSharp/Formats/Webp/WebpLookupTables.cs +++ b/src/ImageSharp/Formats/Webp/WebpLookupTables.cs @@ -136,10 +136,116 @@ internal static class WebpLookupTables public static readonly int[] LinearToGammaTab = new int[WebpConstants.GammaTabSize + 1]; /// - /// The cost of each 4x4 luma intra mode in 1/256 bits, for each pair of top and left modes. The index is [top, left]. The costs come from the + /// Gets the cost of each 4x4 luma intra mode in 1/256 bits, for each pair of top and left modes. The costs come from the /// fixed key frame probabilities of RFC 6386, section 11.5: https://www.rfc-editor.org/rfc/rfc6386#section-11.5. /// - public static readonly short[,][] Vp8FixedCostsI4 = new short[10, 10][]; + /// + /// The table is flat. The 10 costs of the top mode t and the left mode l start at ((t * 10) + l) * 10. The data comes from the static + /// data of the assembly, so the property allocates nothing. + /// + public static ReadOnlySpan Vp8FixedCostsI4 => + [ + 40, 1151, 1723, 1874, 2103, 2019, 1628, 1777, 2226, 2137, // top 0, left 0 + 192, 469, 1296, 1308, 1849, 1794, 1781, 1703, 1713, 1522, // top 0, left 1 + 142, 910, 762, 1684, 1849, 1576, 1460, 1305, 1801, 1657, // top 0, left 2 + 559, 641, 1370, 421, 1182, 1569, 1612, 1725, 863, 1007, // top 0, left 3 + 299, 1059, 1256, 1108, 636, 1068, 1581, 1883, 869, 1142, // top 0, left 4 + 277, 1111, 707, 1362, 1089, 672, 1603, 1541, 1545, 1291, // top 0, left 5 + 214, 781, 1609, 1303, 1632, 2229, 726, 1560, 1713, 918, // top 0, left 6 + 152, 1037, 1046, 1759, 1983, 2174, 1358, 742, 1740, 1390, // top 0, left 7 + 512, 1046, 1420, 753, 752, 1297, 1486, 1613, 460, 1207, // top 0, left 8 + 424, 827, 1362, 719, 1462, 1202, 1199, 1476, 1199, 538, // top 0, left 9 + 240, 402, 1134, 1491, 1659, 1505, 1517, 1555, 1979, 2099, // top 1, left 0 + 467, 242, 960, 1232, 1714, 1620, 1834, 1570, 1676, 1391, // top 1, left 1 + 500, 455, 463, 1507, 1699, 1282, 1564, 982, 2114, 2114, // top 1, left 2 + 672, 643, 1372, 331, 1589, 1667, 1453, 1938, 996, 876, // top 1, left 3 + 458, 783, 1037, 911, 738, 968, 1165, 1518, 859, 1033, // top 1, left 4 + 504, 815, 504, 1139, 1219, 719, 1506, 1085, 1268, 1268, // top 1, left 5 + 333, 630, 1445, 1239, 1883, 3672, 799, 1548, 1865, 598, // top 1, left 6 + 399, 644, 746, 1342, 1856, 1350, 1493, 613, 1855, 1015, // top 1, left 7 + 622, 749, 1205, 608, 1066, 1408, 1290, 1406, 546, 971, // top 1, left 8 + 500, 753, 1041, 668, 1230, 1617, 1297, 1425, 1383, 523, // top 1, left 9 + 394, 553, 523, 1502, 1536, 981, 1608, 1142, 1666, 2181, // top 2, left 0 + 655, 430, 375, 1411, 1861, 1220, 1677, 1135, 1978, 1553, // top 2, left 1 + 690, 640, 245, 1954, 2070, 1194, 1528, 982, 1972, 2232, // top 2, left 2 + 559, 834, 741, 867, 1131, 980, 1225, 852, 1092, 784, // top 2, left 3 + 690, 875, 516, 959, 673, 894, 1056, 1190, 1528, 1126, // top 2, left 4 + 740, 951, 384, 1277, 1177, 492, 1579, 1155, 1846, 1513, // top 2, left 5 + 323, 775, 1062, 1776, 3062, 1274, 813, 1188, 1372, 655, // top 2, left 6 + 488, 971, 484, 1767, 1515, 1775, 1115, 503, 1539, 1461, // top 2, left 7 + 740, 1006, 998, 709, 851, 1230, 1337, 788, 741, 721, // top 2, left 8 + 522, 1073, 573, 1045, 1346, 887, 1046, 1146, 1203, 697, // top 2, left 9 + 105, 864, 1442, 1009, 1934, 1840, 1519, 1920, 1673, 1579, // top 3, left 0 + 534, 305, 1193, 683, 1388, 2164, 1802, 1894, 1264, 1170, // top 3, left 1 + 305, 518, 877, 1108, 1426, 3215, 1425, 1064, 1320, 1242, // top 3, left 2 + 683, 732, 1927, 257, 1493, 2048, 1858, 1552, 1055, 947, // top 3, left 3 + 394, 814, 1024, 660, 959, 1556, 1282, 1289, 893, 1047, // top 3, left 4 + 528, 615, 996, 940, 1201, 635, 1094, 2515, 803, 1358, // top 3, left 5 + 347, 614, 1609, 1187, 3133, 1345, 1007, 1339, 1017, 667, // top 3, left 6 + 218, 740, 878, 1605, 3650, 3650, 1345, 758, 1357, 1617, // top 3, left 7 + 672, 750, 1541, 558, 1257, 1599, 1870, 2135, 402, 1087, // top 3, left 8 + 592, 684, 1161, 430, 1092, 1497, 1475, 1489, 1095, 822, // top 3, left 9 + 228, 1056, 1059, 1368, 752, 982, 1512, 1518, 987, 1782, // top 4, left 0 + 494, 514, 818, 942, 965, 892, 1610, 1356, 1048, 1363, // top 4, left 1 + 512, 648, 591, 1042, 761, 991, 1196, 1454, 1309, 1463, // top 4, left 2 + 683, 749, 1043, 676, 841, 1396, 1133, 1138, 654, 939, // top 4, left 3 + 622, 1101, 1126, 994, 361, 1077, 1203, 1318, 877, 1219, // top 4, left 4 + 631, 1068, 857, 1650, 651, 477, 1650, 1419, 828, 1170, // top 4, left 5 + 555, 727, 1068, 1335, 3127, 1339, 820, 1331, 1077, 429, // top 4, left 6 + 504, 879, 624, 1398, 889, 889, 1392, 808, 891, 1406, // top 4, left 7 + 683, 1602, 1289, 977, 578, 983, 1280, 1708, 406, 1122, // top 4, left 8 + 399, 865, 1433, 1070, 1072, 764, 968, 1477, 1223, 678, // top 4, left 9 + 333, 760, 935, 1638, 1010, 529, 1646, 1410, 1472, 2219, // top 5, left 0 + 512, 494, 750, 1160, 1215, 610, 1870, 1868, 1628, 1169, // top 5, left 1 + 572, 646, 492, 1934, 1208, 603, 1580, 1099, 1398, 1995, // top 5, left 2 + 786, 789, 942, 581, 1018, 951, 1599, 1207, 731, 768, // top 5, left 3 + 690, 1015, 672, 1078, 582, 504, 1693, 1438, 1108, 2897, // top 5, left 4 + 768, 1267, 571, 2005, 1243, 244, 2881, 1380, 1786, 1453, // top 5, left 5 + 452, 899, 1293, 903, 1311, 3100, 465, 1311, 1319, 813, // top 5, left 6 + 394, 927, 942, 1103, 1358, 1104, 946, 593, 1363, 1109, // top 5, left 7 + 559, 1005, 1007, 1016, 658, 1173, 1021, 1164, 623, 1028, // top 5, left 8 + 564, 796, 632, 1005, 1014, 863, 2316, 1268, 938, 764, // top 5, left 9 + 266, 606, 1098, 1228, 1497, 1243, 948, 1030, 1734, 1461, // top 6, left 0 + 366, 585, 901, 1060, 1407, 1247, 876, 1134, 1620, 1054, // top 6, left 1 + 452, 565, 542, 1729, 1479, 1479, 1016, 886, 2938, 1150, // top 6, left 2 + 555, 1088, 1533, 950, 1354, 895, 834, 1019, 1021, 496, // top 6, left 3 + 704, 815, 1193, 971, 973, 640, 1217, 2214, 832, 578, // top 6, left 4 + 672, 1245, 579, 871, 875, 774, 872, 1273, 1027, 949, // top 6, left 5 + 296, 1134, 2050, 1784, 1636, 3425, 442, 1550, 2076, 722, // top 6, left 6 + 342, 982, 1259, 1846, 1848, 1848, 622, 568, 1847, 1052, // top 6, left 7 + 555, 1064, 1304, 828, 746, 1343, 1075, 1329, 1078, 494, // top 6, left 8 + 288, 1167, 1285, 1174, 1639, 1639, 833, 2254, 1304, 509, // top 6, left 9 + 342, 719, 767, 1866, 1757, 1270, 1246, 550, 1746, 2151, // top 7, left 0 + 483, 653, 694, 1509, 1459, 1410, 1218, 507, 1914, 1266, // top 7, left 1 + 488, 757, 447, 2979, 1813, 1268, 1654, 539, 1849, 2109, // top 7, left 2 + 522, 1097, 1085, 851, 1365, 1111, 851, 901, 961, 605, // top 7, left 3 + 709, 716, 841, 728, 736, 945, 941, 862, 2845, 1057, // top 7, left 4 + 512, 1323, 500, 1336, 1083, 681, 1342, 717, 1604, 1350, // top 7, left 5 + 452, 1155, 1372, 1900, 1501, 3290, 311, 944, 1919, 922, // top 7, left 6 + 403, 1520, 977, 2132, 1733, 3522, 1076, 276, 3335, 1547, // top 7, left 7 + 559, 1374, 1101, 615, 673, 2462, 974, 795, 984, 984, // top 7, left 8 + 547, 1122, 1062, 812, 1410, 951, 1140, 622, 1268, 651, // top 7, left 9 + 165, 982, 1235, 938, 1334, 1366, 1659, 1578, 964, 1612, // top 8, left 0 + 592, 422, 925, 847, 1139, 1112, 1387, 2036, 861, 1041, // top 8, left 1 + 403, 837, 732, 770, 941, 1658, 1250, 809, 1407, 1407, // top 8, left 2 + 896, 874, 1071, 381, 1568, 1722, 1437, 2192, 480, 1035, // top 8, left 3 + 640, 1098, 1012, 1032, 684, 1382, 1581, 2106, 416, 865, // top 8, left 4 + 559, 1005, 819, 914, 710, 770, 1418, 920, 838, 1435, // top 8, left 5 + 415, 1258, 1245, 870, 1278, 3067, 770, 1021, 1287, 522, // top 8, left 6 + 406, 990, 601, 1009, 1265, 1265, 1267, 759, 1017, 1277, // top 8, left 7 + 968, 1182, 1329, 788, 1032, 1292, 1705, 1714, 203, 1403, // top 8, left 8 + 732, 877, 1279, 471, 901, 1161, 1545, 1294, 755, 755, // top 8, left 9 + 111, 931, 1378, 1185, 1933, 1648, 1148, 1714, 1873, 1307, // top 9, left 0 + 406, 414, 1030, 1023, 1910, 1404, 1313, 1647, 1509, 793, // top 9, left 1 + 342, 640, 575, 1088, 1241, 1349, 1161, 1350, 1756, 1502, // top 9, left 2 + 559, 766, 1185, 357, 1682, 1428, 1329, 1897, 1219, 802, // top 9, left 3 + 473, 909, 1164, 771, 719, 2508, 1427, 1432, 722, 782, // top 9, left 4 + 342, 892, 785, 1145, 1150, 794, 1296, 1550, 973, 1057, // top 9, left 5 + 208, 1036, 1326, 1343, 1606, 3395, 815, 1455, 1618, 712, // top 9, left 6 + 228, 928, 890, 1046, 3499, 1711, 994, 829, 1720, 1318, // top 9, left 7 + 768, 724, 1058, 636, 991, 1075, 1319, 1324, 616, 825, // top 9, left 8 + 305, 1167, 1358, 899, 1587, 1587, 987, 1988, 1332, 501 // top 9, left 9 + ]; /// /// Gets the offset of each 4x4 block in a work buffer with a stride of : the 16 luma blocks, then the 4 U @@ -489,29 +595,32 @@ internal static class WebpLookupTables ]; /// - /// The DCT token tree path of each coefficient level from 1 to . Entry level - 1 holds a pattern and - /// the bits. Bit k of the pattern is set when the path uses the tree probability k + 2. Bit k of the bits is the bit at that node. - /// See RFC 6386, section 13.2: https://www.rfc-editor.org/rfc/rfc6386#section-13.2. + /// Gets the DCT token tree path of each coefficient level from 1 to . The pattern of level v is + /// entry 2 * (v - 1) and the bits are entry 2 * (v - 1) + 1. Bit k of the pattern is set when the path uses the tree probability k + 2. + /// Bit k of the bits is the bit at that node. See RFC 6386, section 13.2: https://www.rfc-editor.org/rfc/rfc6386#section-13.2. /// - public static readonly ushort[][] Vp8LevelCodes = + /// + /// The data comes from the static data of the assembly, so the property allocates nothing. + /// + public static ReadOnlySpan Vp8LevelCodes => [ - [0x001, 0x000], [0x007, 0x001], [0x00f, 0x005], - [0x00f, 0x00d], [0x033, 0x003], [0x033, 0x003], [0x033, 0x023], - [0x033, 0x023], [0x033, 0x023], [0x033, 0x023], [0x0d3, 0x013], - [0x0d3, 0x013], [0x0d3, 0x013], [0x0d3, 0x013], [0x0d3, 0x013], - [0x0d3, 0x013], [0x0d3, 0x013], [0x0d3, 0x013], [0x0d3, 0x093], - [0x0d3, 0x093], [0x0d3, 0x093], [0x0d3, 0x093], [0x0d3, 0x093], - [0x0d3, 0x093], [0x0d3, 0x093], [0x0d3, 0x093], [0x0d3, 0x093], - [0x0d3, 0x093], [0x0d3, 0x093], [0x0d3, 0x093], [0x0d3, 0x093], - [0x0d3, 0x093], [0x0d3, 0x093], [0x0d3, 0x093], [0x153, 0x053], - [0x153, 0x053], [0x153, 0x053], [0x153, 0x053], [0x153, 0x053], - [0x153, 0x053], [0x153, 0x053], [0x153, 0x053], [0x153, 0x053], - [0x153, 0x053], [0x153, 0x053], [0x153, 0x053], [0x153, 0x053], - [0x153, 0x053], [0x153, 0x053], [0x153, 0x053], [0x153, 0x053], - [0x153, 0x053], [0x153, 0x053], [0x153, 0x053], [0x153, 0x053], - [0x153, 0x053], [0x153, 0x053], [0x153, 0x053], [0x153, 0x053], - [0x153, 0x053], [0x153, 0x053], [0x153, 0x053], [0x153, 0x053], - [0x153, 0x053], [0x153, 0x053], [0x153, 0x053], [0x153, 0x153] + 0x001, 0x000, 0x007, 0x001, 0x00f, 0x005, 0x00f, 0x00d, + 0x033, 0x003, 0x033, 0x003, 0x033, 0x023, 0x033, 0x023, + 0x033, 0x023, 0x033, 0x023, 0x0d3, 0x013, 0x0d3, 0x013, + 0x0d3, 0x013, 0x0d3, 0x013, 0x0d3, 0x013, 0x0d3, 0x013, + 0x0d3, 0x013, 0x0d3, 0x013, 0x0d3, 0x093, 0x0d3, 0x093, + 0x0d3, 0x093, 0x0d3, 0x093, 0x0d3, 0x093, 0x0d3, 0x093, + 0x0d3, 0x093, 0x0d3, 0x093, 0x0d3, 0x093, 0x0d3, 0x093, + 0x0d3, 0x093, 0x0d3, 0x093, 0x0d3, 0x093, 0x0d3, 0x093, + 0x0d3, 0x093, 0x0d3, 0x093, 0x153, 0x053, 0x153, 0x053, + 0x153, 0x053, 0x153, 0x053, 0x153, 0x053, 0x153, 0x053, + 0x153, 0x053, 0x153, 0x053, 0x153, 0x053, 0x153, 0x053, + 0x153, 0x053, 0x153, 0x053, 0x153, 0x053, 0x153, 0x053, + 0x153, 0x053, 0x153, 0x053, 0x153, 0x053, 0x153, 0x053, + 0x153, 0x053, 0x153, 0x053, 0x153, 0x053, 0x153, 0x053, + 0x153, 0x053, 0x153, 0x053, 0x153, 0x053, 0x153, 0x053, + 0x153, 0x053, 0x153, 0x053, 0x153, 0x053, 0x153, 0x053, + 0x153, 0x053, 0x153, 0x053, 0x153, 0x153 ]; /// @@ -1468,7 +1577,7 @@ public static readonly (int Code, int ExtraBits)[] PrefixEncodeCode = ]; /// - /// Initializes static members of the class. It computes the gamma tables and sets the 4x4 mode costs. + /// Initializes static members of the class. It computes the gamma tables. /// static WebpLookupTables() { @@ -1483,8 +1592,6 @@ static WebpLookupTables() { LinearToGammaTab[v] = (int)((255.0d * Math.Pow(scale * v, 1.0d / WebpConstants.Gamma)) + .5); } - - InitializeFixedCostsI4(); } /// @@ -1720,111 +1827,4 @@ static WebpLookupTables() 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 ]; - - /// - /// Sets the cost arrays of . - /// - private static void InitializeFixedCostsI4() - { - Vp8FixedCostsI4[0, 0] = [40, 1151, 1723, 1874, 2103, 2019, 1628, 1777, 2226, 2137]; - Vp8FixedCostsI4[0, 1] = [192, 469, 1296, 1308, 1849, 1794, 1781, 1703, 1713, 1522]; - Vp8FixedCostsI4[0, 2] = [142, 910, 762, 1684, 1849, 1576, 1460, 1305, 1801, 1657]; - Vp8FixedCostsI4[0, 3] = [559, 641, 1370, 421, 1182, 1569, 1612, 1725, 863, 1007]; - Vp8FixedCostsI4[0, 4] = [299, 1059, 1256, 1108, 636, 1068, 1581, 1883, 869, 1142]; - Vp8FixedCostsI4[0, 5] = [277, 1111, 707, 1362, 1089, 672, 1603, 1541, 1545, 1291]; - Vp8FixedCostsI4[0, 6] = [214, 781, 1609, 1303, 1632, 2229, 726, 1560, 1713, 918]; - Vp8FixedCostsI4[0, 7] = [152, 1037, 1046, 1759, 1983, 2174, 1358, 742, 1740, 1390]; - Vp8FixedCostsI4[0, 8] = [512, 1046, 1420, 753, 752, 1297, 1486, 1613, 460, 1207]; - Vp8FixedCostsI4[0, 9] = [424, 827, 1362, 719, 1462, 1202, 1199, 1476, 1199, 538]; - Vp8FixedCostsI4[1, 0] = [240, 402, 1134, 1491, 1659, 1505, 1517, 1555, 1979, 2099]; - Vp8FixedCostsI4[1, 1] = [467, 242, 960, 1232, 1714, 1620, 1834, 1570, 1676, 1391]; - Vp8FixedCostsI4[1, 2] = [500, 455, 463, 1507, 1699, 1282, 1564, 982, 2114, 2114]; - Vp8FixedCostsI4[1, 3] = [672, 643, 1372, 331, 1589, 1667, 1453, 1938, 996, 876]; - Vp8FixedCostsI4[1, 4] = [458, 783, 1037, 911, 738, 968, 1165, 1518, 859, 1033]; - Vp8FixedCostsI4[1, 5] = [504, 815, 504, 1139, 1219, 719, 1506, 1085, 1268, 1268]; - Vp8FixedCostsI4[1, 6] = [333, 630, 1445, 1239, 1883, 3672, 799, 1548, 1865, 598]; - Vp8FixedCostsI4[1, 7] = [399, 644, 746, 1342, 1856, 1350, 1493, 613, 1855, 1015]; - Vp8FixedCostsI4[1, 8] = [622, 749, 1205, 608, 1066, 1408, 1290, 1406, 546, 971]; - Vp8FixedCostsI4[1, 9] = [500, 753, 1041, 668, 1230, 1617, 1297, 1425, 1383, 523]; - Vp8FixedCostsI4[2, 0] = [394, 553, 523, 1502, 1536, 981, 1608, 1142, 1666, 2181]; - Vp8FixedCostsI4[2, 1] = [655, 430, 375, 1411, 1861, 1220, 1677, 1135, 1978, 1553]; - Vp8FixedCostsI4[2, 2] = [690, 640, 245, 1954, 2070, 1194, 1528, 982, 1972, 2232]; - Vp8FixedCostsI4[2, 3] = [559, 834, 741, 867, 1131, 980, 1225, 852, 1092, 784]; - Vp8FixedCostsI4[2, 4] = [690, 875, 516, 959, 673, 894, 1056, 1190, 1528, 1126]; - Vp8FixedCostsI4[2, 5] = [740, 951, 384, 1277, 1177, 492, 1579, 1155, 1846, 1513]; - Vp8FixedCostsI4[2, 6] = [323, 775, 1062, 1776, 3062, 1274, 813, 1188, 1372, 655]; - Vp8FixedCostsI4[2, 7] = [488, 971, 484, 1767, 1515, 1775, 1115, 503, 1539, 1461]; - Vp8FixedCostsI4[2, 8] = [740, 1006, 998, 709, 851, 1230, 1337, 788, 741, 721]; - Vp8FixedCostsI4[2, 9] = [522, 1073, 573, 1045, 1346, 887, 1046, 1146, 1203, 697]; - Vp8FixedCostsI4[3, 0] = [105, 864, 1442, 1009, 1934, 1840, 1519, 1920, 1673, 1579]; - Vp8FixedCostsI4[3, 1] = [534, 305, 1193, 683, 1388, 2164, 1802, 1894, 1264, 1170]; - Vp8FixedCostsI4[3, 2] = [305, 518, 877, 1108, 1426, 3215, 1425, 1064, 1320, 1242]; - Vp8FixedCostsI4[3, 3] = [683, 732, 1927, 257, 1493, 2048, 1858, 1552, 1055, 947]; - Vp8FixedCostsI4[3, 4] = [394, 814, 1024, 660, 959, 1556, 1282, 1289, 893, 1047]; - Vp8FixedCostsI4[3, 5] = [528, 615, 996, 940, 1201, 635, 1094, 2515, 803, 1358]; - Vp8FixedCostsI4[3, 6] = [347, 614, 1609, 1187, 3133, 1345, 1007, 1339, 1017, 667]; - Vp8FixedCostsI4[3, 7] = [218, 740, 878, 1605, 3650, 3650, 1345, 758, 1357, 1617]; - Vp8FixedCostsI4[3, 8] = [672, 750, 1541, 558, 1257, 1599, 1870, 2135, 402, 1087]; - Vp8FixedCostsI4[3, 9] = [592, 684, 1161, 430, 1092, 1497, 1475, 1489, 1095, 822]; - Vp8FixedCostsI4[4, 0] = [228, 1056, 1059, 1368, 752, 982, 1512, 1518, 987, 1782]; - Vp8FixedCostsI4[4, 1] = [494, 514, 818, 942, 965, 892, 1610, 1356, 1048, 1363]; - Vp8FixedCostsI4[4, 2] = [512, 648, 591, 1042, 761, 991, 1196, 1454, 1309, 1463]; - Vp8FixedCostsI4[4, 3] = [683, 749, 1043, 676, 841, 1396, 1133, 1138, 654, 939]; - Vp8FixedCostsI4[4, 4] = [622, 1101, 1126, 994, 361, 1077, 1203, 1318, 877, 1219]; - Vp8FixedCostsI4[4, 5] = [631, 1068, 857, 1650, 651, 477, 1650, 1419, 828, 1170]; - Vp8FixedCostsI4[4, 6] = [555, 727, 1068, 1335, 3127, 1339, 820, 1331, 1077, 429]; - Vp8FixedCostsI4[4, 7] = [504, 879, 624, 1398, 889, 889, 1392, 808, 891, 1406]; - Vp8FixedCostsI4[4, 8] = [683, 1602, 1289, 977, 578, 983, 1280, 1708, 406, 1122]; - Vp8FixedCostsI4[4, 9] = [399, 865, 1433, 1070, 1072, 764, 968, 1477, 1223, 678]; - Vp8FixedCostsI4[5, 0] = [333, 760, 935, 1638, 1010, 529, 1646, 1410, 1472, 2219]; - Vp8FixedCostsI4[5, 1] = [512, 494, 750, 1160, 1215, 610, 1870, 1868, 1628, 1169]; - Vp8FixedCostsI4[5, 2] = [572, 646, 492, 1934, 1208, 603, 1580, 1099, 1398, 1995]; - Vp8FixedCostsI4[5, 3] = [786, 789, 942, 581, 1018, 951, 1599, 1207, 731, 768]; - Vp8FixedCostsI4[5, 4] = [690, 1015, 672, 1078, 582, 504, 1693, 1438, 1108, 2897]; - Vp8FixedCostsI4[5, 5] = [768, 1267, 571, 2005, 1243, 244, 2881, 1380, 1786, 1453]; - Vp8FixedCostsI4[5, 6] = [452, 899, 1293, 903, 1311, 3100, 465, 1311, 1319, 813]; - Vp8FixedCostsI4[5, 7] = [394, 927, 942, 1103, 1358, 1104, 946, 593, 1363, 1109]; - Vp8FixedCostsI4[5, 8] = [559, 1005, 1007, 1016, 658, 1173, 1021, 1164, 623, 1028]; - Vp8FixedCostsI4[5, 9] = [564, 796, 632, 1005, 1014, 863, 2316, 1268, 938, 764]; - Vp8FixedCostsI4[6, 0] = [266, 606, 1098, 1228, 1497, 1243, 948, 1030, 1734, 1461]; - Vp8FixedCostsI4[6, 1] = [366, 585, 901, 1060, 1407, 1247, 876, 1134, 1620, 1054]; - Vp8FixedCostsI4[6, 2] = [452, 565, 542, 1729, 1479, 1479, 1016, 886, 2938, 1150]; - Vp8FixedCostsI4[6, 3] = [555, 1088, 1533, 950, 1354, 895, 834, 1019, 1021, 496]; - Vp8FixedCostsI4[6, 4] = [704, 815, 1193, 971, 973, 640, 1217, 2214, 832, 578]; - Vp8FixedCostsI4[6, 5] = [672, 1245, 579, 871, 875, 774, 872, 1273, 1027, 949]; - Vp8FixedCostsI4[6, 6] = [296, 1134, 2050, 1784, 1636, 3425, 442, 1550, 2076, 722]; - Vp8FixedCostsI4[6, 7] = [342, 982, 1259, 1846, 1848, 1848, 622, 568, 1847, 1052]; - Vp8FixedCostsI4[6, 8] = [555, 1064, 1304, 828, 746, 1343, 1075, 1329, 1078, 494]; - Vp8FixedCostsI4[6, 9] = [288, 1167, 1285, 1174, 1639, 1639, 833, 2254, 1304, 509]; - Vp8FixedCostsI4[7, 0] = [342, 719, 767, 1866, 1757, 1270, 1246, 550, 1746, 2151]; - Vp8FixedCostsI4[7, 1] = [483, 653, 694, 1509, 1459, 1410, 1218, 507, 1914, 1266]; - Vp8FixedCostsI4[7, 2] = [488, 757, 447, 2979, 1813, 1268, 1654, 539, 1849, 2109]; - Vp8FixedCostsI4[7, 3] = [522, 1097, 1085, 851, 1365, 1111, 851, 901, 961, 605]; - Vp8FixedCostsI4[7, 4] = [709, 716, 841, 728, 736, 945, 941, 862, 2845, 1057]; - Vp8FixedCostsI4[7, 5] = [512, 1323, 500, 1336, 1083, 681, 1342, 717, 1604, 1350]; - Vp8FixedCostsI4[7, 6] = [452, 1155, 1372, 1900, 1501, 3290, 311, 944, 1919, 922]; - Vp8FixedCostsI4[7, 7] = [403, 1520, 977, 2132, 1733, 3522, 1076, 276, 3335, 1547]; - Vp8FixedCostsI4[7, 8] = [559, 1374, 1101, 615, 673, 2462, 974, 795, 984, 984]; - Vp8FixedCostsI4[7, 9] = [547, 1122, 1062, 812, 1410, 951, 1140, 622, 1268, 651]; - Vp8FixedCostsI4[8, 0] = [165, 982, 1235, 938, 1334, 1366, 1659, 1578, 964, 1612]; - Vp8FixedCostsI4[8, 1] = [592, 422, 925, 847, 1139, 1112, 1387, 2036, 861, 1041]; - Vp8FixedCostsI4[8, 2] = [403, 837, 732, 770, 941, 1658, 1250, 809, 1407, 1407]; - Vp8FixedCostsI4[8, 3] = [896, 874, 1071, 381, 1568, 1722, 1437, 2192, 480, 1035]; - Vp8FixedCostsI4[8, 4] = [640, 1098, 1012, 1032, 684, 1382, 1581, 2106, 416, 865]; - Vp8FixedCostsI4[8, 5] = [559, 1005, 819, 914, 710, 770, 1418, 920, 838, 1435]; - Vp8FixedCostsI4[8, 6] = [415, 1258, 1245, 870, 1278, 3067, 770, 1021, 1287, 522]; - Vp8FixedCostsI4[8, 7] = [406, 990, 601, 1009, 1265, 1265, 1267, 759, 1017, 1277]; - Vp8FixedCostsI4[8, 8] = [968, 1182, 1329, 788, 1032, 1292, 1705, 1714, 203, 1403]; - Vp8FixedCostsI4[8, 9] = [732, 877, 1279, 471, 901, 1161, 1545, 1294, 755, 755]; - Vp8FixedCostsI4[9, 0] = [111, 931, 1378, 1185, 1933, 1648, 1148, 1714, 1873, 1307]; - Vp8FixedCostsI4[9, 1] = [406, 414, 1030, 1023, 1910, 1404, 1313, 1647, 1509, 793]; - Vp8FixedCostsI4[9, 2] = [342, 640, 575, 1088, 1241, 1349, 1161, 1350, 1756, 1502]; - Vp8FixedCostsI4[9, 3] = [559, 766, 1185, 357, 1682, 1428, 1329, 1897, 1219, 802]; - Vp8FixedCostsI4[9, 4] = [473, 909, 1164, 771, 719, 2508, 1427, 1432, 722, 782]; - Vp8FixedCostsI4[9, 5] = [342, 892, 785, 1145, 1150, 794, 1296, 1550, 973, 1057]; - Vp8FixedCostsI4[9, 6] = [208, 1036, 1326, 1343, 1606, 3395, 815, 1455, 1618, 712]; - Vp8FixedCostsI4[9, 7] = [228, 928, 890, 1046, 3499, 1711, 994, 829, 1720, 1318]; - Vp8FixedCostsI4[9, 8] = [768, 724, 1058, 636, 991, 1075, 1319, 1324, 616, 825]; - Vp8FixedCostsI4[9, 9] = [305, 1167, 1358, 899, 1587, 1587, 987, 1988, 1332, 501]; - } } diff --git a/src/ImageSharp/Formats/Webp/WebpThrowHelper.cs b/src/ImageSharp/Formats/Webp/WebpThrowHelper.cs index 277af943fb..c273de900b 100644 --- a/src/ImageSharp/Formats/Webp/WebpThrowHelper.cs +++ b/src/ImageSharp/Formats/Webp/WebpThrowHelper.cs @@ -5,11 +5,23 @@ namespace SixLabors.ImageSharp.Formats.Webp; +/// +/// Throws the exceptions of the WebP decoder and encoder. +/// internal static class WebpThrowHelper { + /// + /// Throws an for a WebP stream that the decoder cannot decode. + /// + /// The error message. [DoesNotReturn] public static void ThrowInvalidImageContentException(string errorMessage) => throw new InvalidImageContentException(errorMessage); + /// + /// Throws an for an image that is larger than the WebP format allows. + /// + /// The image width in pixels. + /// The image height in pixels. [DoesNotReturn] public static void ThrowDimensionsTooLarge(int width, int height) => throw new ImageFormatException($"Image is too large to encode at {width}x{height} for WEBP format."); diff --git a/tests/ImageSharp.Benchmarks/Codecs/Webp/DecodeWebp.cs b/tests/ImageSharp.Benchmarks/Codecs/Webp/DecodeWebp.cs index 499e35f27e..36a432b0e4 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Webp/DecodeWebp.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Webp/DecodeWebp.cs @@ -87,11 +87,11 @@ .NET SDK 11.0.100 | Method | Layout | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | |-------------------|-------------|----------:|---------:|---------:|------:|--------:|-----:|-----:|-----:|----------:|------------:| - | 'Magick Webp' | Lossless | 105.57 ms | 1.163 ms | 0.769 ms | 1.00 | 0.01 | - | - | - | 17.55 KB | 1.00 | - | 'ImageSharp Webp' | Lossless | 62.39 ms | 1.506 ms | 0.896 ms | 0.59 | 0.01 | - | - | - | 14.43 KB | 0.82 | - | 'Magick Webp' | LossyAlpha | 68.24 ms | 1.338 ms | 0.885 ms | 1.00 | 0.02 | - | - | - | 20.45 KB | 1.00 | - | 'ImageSharp Webp' | LossyAlpha | 32.81 ms | 0.607 ms | 0.402 ms | 0.48 | 0.01 | - | - | - | 14.13 KB | 0.69 | - | 'Magick Webp' | LossyOpaque | 62.05 ms | 1.971 ms | 1.304 ms | 1.00 | 0.03 | - | - | - | 13.47 KB | 1.00 | - | 'ImageSharp Webp' | LossyOpaque | 34.08 ms | 0.528 ms | 0.314 ms | 0.55 | 0.01 | - | - | - | 89.36 KB | 6.63 | + | 'Magick Webp' | Lossless | 107.18 ms | 1.768 ms | 1.169 ms | 1.00 | 0.01 | - | - | - | 17.49 KB | 1.00 | + | 'ImageSharp Webp' | Lossless | 64.30 ms | 1.786 ms | 1.181 ms | 0.60 | 0.01 | - | - | - | 13.83 KB | 0.79 | + | 'Magick Webp' | LossyAlpha | 69.86 ms | 1.796 ms | 1.069 ms | 1.00 | 0.02 | - | - | - | 23.96 KB | 1.00 | + | 'ImageSharp Webp' | LossyAlpha | 33.50 ms | 0.938 ms | 0.621 ms | 0.48 | 0.01 | - | - | - | 20.02 KB | 0.84 | + | 'Magick Webp' | LossyOpaque | 63.01 ms | 1.192 ms | 0.788 ms | 1.00 | 0.02 | - | - | - | 13.66 KB | 1.00 | + | 'ImageSharp Webp' | LossyOpaque | 34.70 ms | 0.544 ms | 0.323 ms | 0.55 | 0.01 | - | - | - | 90.09 KB | 6.60 | */ } diff --git a/tests/ImageSharp.Benchmarks/Codecs/Webp/EncodeWebp.cs b/tests/ImageSharp.Benchmarks/Codecs/Webp/EncodeWebp.cs index 41ff966eee..f97a9d2b01 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Webp/EncodeWebp.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Webp/EncodeWebp.cs @@ -119,13 +119,13 @@ .NET SDK 11.0.100 Toolchain=InProcessEmitToolchain IterationCount=10 IterationTime=100ms WarmupCount=10 DOTNET_GCHighMemPercent=0x63 - | Method | Layout | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | - |-------------------|-------------|-----------:|----------:|---------:|------:|--------:|----------:|----------:|----------:|----------:|------------:| - | 'Magick Webp' | Lossless | 2,175.6 ms | 14.72 ms | 9.73 ms | 1.00 | 0.01 | - | - | - | 14.61 KB | 1.00 | - | 'ImageSharp Webp' | Lossless | 1,288.6 ms | 103.56 ms | 68.50 ms | 0.59 | 0.03 | 1000.0000 | 1000.0000 | 1000.0000 | 183.45 KB | 12.56 | - | 'Magick Webp' | LossyAlpha | 517.9 ms | 39.91 ms | 26.40 ms | 1.00 | 0.07 | - | - | - | 16.61 KB | 1.00 | - | 'ImageSharp Webp' | LossyAlpha | 520.6 ms | 42.81 ms | 25.47 ms | 1.01 | 0.07 | - | - | - | 152.94 KB | 9.21 | - | 'Magick Webp' | LossyOpaque | 207.9 ms | 24.39 ms | 16.13 ms | 1.01 | 0.10 | - | - | - | 19.05 KB | 1.00 | - | 'ImageSharp Webp' | LossyOpaque | 209.8 ms | 6.14 ms | 4.06 ms | 1.01 | 0.08 | - | - | - | 48.63 KB | 2.55 | + | Method | Layout | Mean | Error | StdDev | Ratio | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | + |-------------------|-------------|-----------:|---------:|--------:|------:|----------:|----------:|----------:|----------:|------------:| + | 'Magick Webp' | Lossless | 2,178.8 ms | 12.10 ms | 6.33 ms | 1.00 | - | - | - | 21.08 KB | 1.00 | + | 'ImageSharp Webp' | Lossless | 1,180.2 ms | 12.38 ms | 8.19 ms | 0.54 | 1000.0000 | 1000.0000 | 1000.0000 | 186.6 KB | 8.85 | + | 'Magick Webp' | LossyAlpha | 434.3 ms | 3.67 ms | 2.43 ms | 1.00 | - | - | - | 15.25 KB | 1.00 | + | 'ImageSharp Webp' | LossyAlpha | 410.6 ms | 6.60 ms | 3.45 ms | 0.95 | - | - | - | 163.19 KB | 10.70 | + | 'Magick Webp' | LossyOpaque | 182.5 ms | 1.75 ms | 1.04 ms | 1.00 | - | - | - | 21.72 KB | 1.00 | + | 'ImageSharp Webp' | LossyOpaque | 166.5 ms | 4.50 ms | 2.68 ms | 0.91 | - | - | - | 56.77 KB | 2.61 | */ } diff --git a/tests/ImageSharp.Tests/Formats/Exr/ExrZipDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Exr/ExrZipDecoderTests.cs index f23ab18d69..785bceb2cf 100644 --- a/tests/ImageSharp.Tests/Formats/Exr/ExrZipDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Exr/ExrZipDecoderTests.cs @@ -3,7 +3,6 @@ using System.Buffers.Binary; using System.IO.Compression; -using System.Numerics; using System.Text; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Exr.Constants; @@ -164,10 +163,8 @@ public void Decode_SingleRedChannel_InitializesMissingColorChannels(ExrPixelType using Image image = Image.Load(options, data); Assert.Equal(new Size(256, 1), image.Size); - for (int x = 0; x < image.Width; x++) - { - Assert.Equal(new Vector4(0, 0, 0, 1), image[x, 0].ToVector4()); - } + using Image expected = new(image.Width, image.Height, new RgbaVector(0, 0, 0, 1)); + ImageComparer.Exact.VerifySimilarity(expected, image); } /// diff --git a/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs index 931ef5366c..07c6c6be46 100644 --- a/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs @@ -397,7 +397,7 @@ public void Encode_AnimatedFormatTransform_FromHeif(TestImageProvider TestImages.Gif.Animated; - [Theory]//(Skip = "Enable for visual animated testing")] + [Theory] // (Skip = "Enable for visual animated testing")] [WithFileCollection(nameof(Animated), PixelTypes.Rgba32)] public void Encode_Animated_VisualTest(TestImageProvider provider) where TPixel : unmanaged, IPixel @@ -533,4 +533,25 @@ public void Encode_PaletteFromMetadata_KeepsExactColors(FrameColorTableMode colo ImageComparer.Exact.VerifySimilarity(image, output); } + + /// + /// The delay field of the graphic control extension has 16 bits, in units of 1/100 second. A delay outside the field is written as + /// the nearest delay that the field holds. A longer delay is 65535, and a negative delay is 0. + /// + [Fact] + public void Encode_FrameDelayOutsideField_IsSaturated() + { + using Image image = new(8, 8); + image.Frames.AddFrame(image.Frames.RootFrame); + image.Frames.RootFrame.Metadata.GetGifMetadata().FrameDelay = 70000; + image.Frames[1].Metadata.GetGifMetadata().FrameDelay = -5; + + using MemoryStream stream = new(); + image.Save(stream, new GifEncoder()); + stream.Position = 0; + using Image decoded = Image.Load(stream); + + Assert.Equal(ushort.MaxValue, decoded.Frames.RootFrame.Metadata.GetGifMetadata().FrameDelay); + Assert.Equal(0, decoded.Frames[1].Metadata.GetGifMetadata().FrameDelay); + } } diff --git a/tests/ImageSharp.Tests/Formats/Heif/HeifEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Heif/HeifEncoderTests.cs index 5a3433f0d0..1c9c70b75c 100644 --- a/tests/ImageSharp.Tests/Formats/Heif/HeifEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Heif/HeifEncoderTests.cs @@ -385,11 +385,15 @@ public void EncodeScreenContent(TestImageProvider provider, HeifEncoding ChromaSubsampling = HeifChromaSubsampling.Yuv444 }; - IImageDecoder referenceDecoder = MagickReferenceDecoder.Heif; + MagickReferenceDecoder referenceDecoder = MagickReferenceDecoder.Heif; string outputFile = provider.Utility.SaveTestOutputFile(image, "avif", encoder, speed); using FileStream stream = File.OpenRead(outputFile); + + // The only Decode overload that takes a CancellationToken is protected. https://github.com/xunit/xunit/issues/3673 +#pragma warning disable xUnit1051 using Image reference = referenceDecoder.Decode(DecoderOptions.Default, stream); +#pragma warning restore xUnit1051 stream.Position = 0; using Image managed = Image.Load(stream); Assert.Empty(ImageComparer.Exact.CompareImages(reference, managed)); @@ -412,7 +416,7 @@ public void LosslessRgba(TestImageProvider provider) Speed = HeifEncodingSpeed.Level9, }; - IImageDecoder referenceDecoder = MagickReferenceDecoder.Heif; + MagickReferenceDecoder referenceDecoder = MagickReferenceDecoder.Heif; string outputFile = image.VerifyEncoder( provider, "avif", @@ -422,7 +426,11 @@ public void LosslessRgba(TestImageProvider provider) referenceDecoder: referenceDecoder); using FileStream stream = File.OpenRead(outputFile); + + // The only Decode overload that takes a CancellationToken is protected. https://github.com/xunit/xunit/issues/3673 +#pragma warning disable xUnit1051 using Image reference = referenceDecoder.Decode(DecoderOptions.Default, stream); +#pragma warning restore xUnit1051 reference.DebugSave(provider, extension: "png", encoder: new PngEncoder()); } @@ -589,7 +597,7 @@ public void Av1LosslessRoundTripPreservesHighBitDepthSourcePixels(TestImageProvi Speed = HeifEncodingSpeed.Level9, }; - IImageDecoder referenceDecoder = MagickReferenceDecoder.Heif; + MagickReferenceDecoder referenceDecoder = MagickReferenceDecoder.Heif; string outputFile = image.VerifyEncoder( provider, "avif", @@ -599,7 +607,11 @@ public void Av1LosslessRoundTripPreservesHighBitDepthSourcePixels(TestImageProvi referenceDecoder: referenceDecoder); using FileStream stream = File.OpenRead(outputFile); + + // The only Decode overload that takes a CancellationToken is protected. https://github.com/xunit/xunit/issues/3673 +#pragma warning disable xUnit1051 using Image reference = referenceDecoder.Decode(DecoderOptions.Default, stream); +#pragma warning restore xUnit1051 reference.DebugSave(provider, bitDepth, encoder: new PngEncoder { BitDepth = PngBitDepth.Bit16 @@ -2881,4 +2893,25 @@ private static Span GetMetadataChild(Span file, Heif4CharCode childT // The bounds allow for the image tune, whose quality curve quantizes more coarsely than the PSNR curve. private static ImageComparer GetLossyComparer(int quality) => ImageComparer.Tolerant(quality >= 75 ? 0.015F : quality >= 50 ? 0.02F : 0.04F); + + /// + /// The time-to-sample box stores each sample duration in a 32-bit field. A longer duration is written as the longest duration that + /// the field holds. The delays 4294967295/1 and 1/20 second give the timescale 1000, so the first sample duration saturates. + /// + [Fact] + public void Av1ImageSequence_FrameDelayOutsideField_IsSaturated() + { + using Image image = new(8, 8); + image.Frames.AddFrame(image.Frames.RootFrame); + image.Frames.RootFrame.Metadata.GetHeifMetadata().FrameDelay = new Rational(uint.MaxValue, 1); + image.Frames[1].Metadata.GetHeifMetadata().FrameDelay = new Rational(1, 20); + + using MemoryStream stream = new(); + image.Save(stream, new HeifEncoder { Speed = HeifEncodingSpeed.Level9 }); + stream.Position = 0; + using Image decoded = Image.Load(stream); + + Assert.Equal(new Rational(uint.MaxValue, 1000), decoded.Frames.RootFrame.Metadata.GetHeifMetadata().FrameDelay); + Assert.Equal(new Rational(1, 20), decoded.Frames[1].Metadata.GetHeifMetadata().FrameDelay); + } } diff --git a/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs index 774ee1122d..befaecd27f 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs @@ -848,4 +848,28 @@ public void Encode_PaletteFromMetadata_KeepsExactColors() ImageComparer.Exact.VerifySimilarity(image, output); } + + /// + /// The fcTL delay is a fraction of two 16-bit values. A delay that the fraction cannot hold is written as the nearest delay that it + /// holds. A delay of 65535 seconds or more is 65535/1. A short delay gets the largest denominator for which the rounded numerator fits. + /// See the APNG specification, the fcTL chunk: https://wiki.mozilla.org/APNG_Specification. + /// + [Fact] + public void Encode_FrameDelayOutsideFraction_IsNearestFraction() + { + using Image image = new(8, 8); + image.Frames.AddFrame(image.Frames.RootFrame); + image.Frames.RootFrame.Metadata.GetPngMetadata().FrameDelay = new Rational(100000, 1); + + // 1/100000 second times 65535 is 0.65535, which rounds to 1. Thus the nearest fraction is 1/65535. + image.Frames[1].Metadata.GetPngMetadata().FrameDelay = new Rational(1, 100000); + + using MemoryStream stream = new(); + image.Save(stream, new PngEncoder()); + stream.Position = 0; + using Image decoded = Image.Load(stream); + + Assert.Equal(new Rational(ushort.MaxValue, 1), decoded.Frames.RootFrame.Metadata.GetPngMetadata().FrameDelay); + Assert.Equal(new Rational(1, ushort.MaxValue), decoded.Frames[1].Metadata.GetPngMetadata().FrameDelay); + } } diff --git a/tests/ImageSharp.Tests/Formats/WebP/LosslessUtilsTests.cs b/tests/ImageSharp.Tests/Formats/WebP/LosslessUtilsTests.cs index bb7039f369..3a4cdca9d8 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/LosslessUtilsTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/LosslessUtilsTests.cs @@ -89,26 +89,32 @@ private static void RunCombinedShannonEntropyTest() private static void RunSubtractGreenTest() { + // The first and the last three pixels have red or blue less than green, so each difference borrows. A borrow must not change the next + // channel. They are at both ends, so the vector loops and the scalar tail get them. Each expected red and blue is the input minus green, mod 256. uint[] pixelData = [ + 4279271456, 256, 2130837248, 4293035898, 4293101432, 4292903793, 4292838511, 4292837995, 4292771950, 4292903791, 4293299316, 4293563769, 4293629303, 4293363312, 4291913575, 4289282905, 4288692313, 4289349210, 4289809240, 4289743703, 4289874775, 4289940567, 4289743701, 4290137943, 4290860378, 4291058267, 4291386715, 4291583836, 4291715937, 4291585379, 4291650657, 4291650143, 4291584863, 4291716451, 4291847521, 4291913571, 4292044130, 4291978850, 4291847521, 4291847524, 4291847779, 4291913571, 4291848293, 4291651689, 4291585895, 4291519584, 4291715936, 4291520355, 4291650658, 4291847263, 4291913313, - 4291847777, 4291781731, 4291783015 + 4291847777, 4291781731, 4291783015, + 4279271456, 2130837248, 256 ]; uint[] expectedOutput = [ + 4287660192, 16712191, 2130902785, 4284188659, 4284254193, 4284318702, 4284187883, 4284318441, 4284383470, 4284318700, 4284124392, 4283799012, 4283864546, 4284581610, 4285163264, 4284891926, 4284497945, 4284761620, 4284893965, 4284828428, 4284959500, 4284959755, 4284828426, 4284960520, 4285289733, 4285159937, 4285292030, 4285358077, 4285228030, 4284966398, 4285097213, 4285227773, 4285096956, 4285097470, 4285228540, 4285163516, 4285425149, 4285294332, 4285228540, 4285228543, 4285163261, 4285163516, 4285032701, 4284835841, 4284835584, 4284966140, 4285228029, 4284770300, 4285097214, 4285293819, 4285228795, - 4285163259, 4285228287, 4284901886 + 4285163259, 4285228287, 4284901886, + 4287660192, 2130902785, 16712191 ]; LosslessUtils.SubtractGreenFromBlueAndRed(pixelData); @@ -118,26 +124,32 @@ private static void RunSubtractGreenTest() private static void RunAddGreenToBlueAndRedTest() { + // The first and the last three pixels have red or blue sums of 256 or more, so each sum carries. A carry must not change the next + // channel. They are at both ends, so the vector loops and the scalar tail get them. Each expected red and blue is the input plus green, mod 256. uint[] pixelData = [ + 4287660192, 16712191, 2130902785, 4284188659, 4284254193, 4284318702, 4284187883, 4284318441, 4284383470, 4284318700, 4284124392, 4283799012, 4283864546, 4284581610, 4285163264, 4284891926, 4284497945, 4284761620, 4284893965, 4284828428, 4284959500, 4284959755, 4284828426, 4284960520, 4285289733, 4285159937, 4285292030, 4285358077, 4285228030, 4284966398, 4285097213, 4285227773, 4285096956, 4285097470, 4285228540, 4285163516, 4285425149, 4285294332, 4285228540, 4285228543, 4285163261, 4285163516, 4285032701, 4284835841, 4284835584, 4284966140, 4285228029, 4284770300, 4285097214, 4285293819, 4285228795, - 4285163259, 4285228287, 4284901886 + 4285163259, 4285228287, 4284901886, + 4287660192, 2130902785, 16712191 ]; uint[] expectedOutput = [ + 4279271456, 256, 2130837248, 4293035898, 4293101432, 4292903793, 4292838511, 4292837995, 4292771950, 4292903791, 4293299316, 4293563769, 4293629303, 4293363312, 4291913575, 4289282905, 4288692313, 4289349210, 4289809240, 4289743703, 4289874775, 4289940567, 4289743701, 4290137943, 4290860378, 4291058267, 4291386715, 4291583836, 4291715937, 4291585379, 4291650657, 4291650143, 4291584863, 4291716451, 4291847521, 4291913571, 4292044130, 4291978850, 4291847521, 4291847524, 4291847779, 4291913571, 4291848293, 4291651689, 4291585895, 4291519584, 4291715936, 4291520355, 4291650658, 4291847263, 4291913313, - 4291847777, 4291781731, 4291783015 + 4291847777, 4291781731, 4291783015, + 4279271456, 2130837248, 256 ]; LosslessUtils.AddGreenToBlueAndRed(pixelData); diff --git a/tests/ImageSharp.Tests/Formats/WebP/Vp8QuantizationTests.cs b/tests/ImageSharp.Tests/Formats/WebP/Vp8QuantizationTests.cs index 28313afae3..a3ff658b19 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/Vp8QuantizationTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/Vp8QuantizationTests.cs @@ -32,7 +32,7 @@ private static unsafe void RunQuantizeBlockTest() } // act - int actualResult = Vp8Quantization.QuantizeBlock(ref input[0], ref output[0], ref vp8Matrix); + int actualResult = Vp8Quantization.QuantizeBlocks(ref input[0], ref output[0], ref vp8Matrix, 1); // assert Assert.True(output.SequenceEqual(expectedOutput)); @@ -59,7 +59,7 @@ private static void RunQuantizeBlockWithSharpeningTest() vp8Matrix.Expand(0); // act - int actualResult = Vp8Quantization.QuantizeBlock(ref input[0], ref output[0], ref vp8Matrix); + int actualResult = Vp8Quantization.QuantizeBlocks(ref input[0], ref output[0], ref vp8Matrix, 1); // assert Assert.Equal(expectedOutput, output); @@ -67,9 +67,48 @@ private static void RunQuantizeBlockWithSharpeningTest() Assert.Equal(1, actualResult); } + /// + /// Checks that each block of a group gets the levels and the non-zero bit of a single block. + /// + private static void RunQuantizeBlocksTest() + { + // arrange + // The matrix is the matrix of RunQuantizeBlockTest: Expand gives the same reciprocals, biases and thresholds from the steps. + // The second block is zero. Three blocks run the two-block and the one-block steps of the 512-bit form. + short[] block = [378, 777, -851, 888, 259, 148, 0, -111, -185, -185, -74, -37, 148, 74, 111, 74]; + short[] expectedBlock = [9, 21, 7, -5, 4, -23, 24, 0, -5, 4, 2, -2, -3, -1, 3, 2]; + short[] input = [.. block, .. new short[16], .. block]; + short[] expectedOutput = [.. expectedBlock, .. new short[16], .. expectedBlock]; + short[] output = new short[48]; + Vp8Matrix vp8Matrix = default; + vp8Matrix.Q[0] = 42; + vp8Matrix.Q[1] = 37; + vp8Matrix.Expand(1); + + // act + int actualResult = Vp8Quantization.QuantizeBlocks(ref input[0], ref output[0], ref vp8Matrix, 3); + + // assert + Assert.Equal(expectedOutput, output); + Assert.Equal(0b101, actualResult); + } + [Fact] public void QuantizeBlock_Works() => RunQuantizeBlockTest(); + [Fact] + public void QuantizeBlocks_Works() => FeatureTestRunner.RunWithHwIntrinsicsFeature(RunQuantizeBlocksTest, HwIntrinsics.AllowAll); + + [Fact] + public void QuantizeBlocks_WithoutAVX512_Works() => FeatureTestRunner.RunWithHwIntrinsicsFeature(RunQuantizeBlocksTest, HwIntrinsics.DisableAVX512F); + + [Fact] + public void QuantizeBlocks_WithoutAVX2_Works() => FeatureTestRunner.RunWithHwIntrinsicsFeature(RunQuantizeBlocksTest, HwIntrinsics.DisableAVX2); + + [Fact] + public void QuantizeBlocks_WithoutHardwareIntrinsics_Works() + => FeatureTestRunner.RunWithHwIntrinsicsFeature(RunQuantizeBlocksTest, HwIntrinsics.DisableHWIntrinsic); + [Fact] public void QuantizeBlock_WithHardwareIntrinsics_Works() => FeatureTestRunner.RunWithHwIntrinsicsFeature(RunQuantizeBlockTest, HwIntrinsics.AllowAll); diff --git a/tests/ImageSharp.Tests/Formats/WebP/Vp8ResidualTests.cs b/tests/ImageSharp.Tests/Formats/WebP/Vp8ResidualTests.cs index 9de330c626..4b4b0e6208 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/Vp8ResidualTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/Vp8ResidualTests.cs @@ -53,8 +53,8 @@ private static Vp8Residual ReadVp8Residual(string fileName, out short[] coeffs) } } - Vp8Residual residual = new(); - residual.Init(first, coeffType, proba); + Vp8Residual residual = new(proba); + residual.Init(first, coeffType); return residual; } @@ -83,7 +83,7 @@ public void GetResidualCost_WithoutHwIntrinsics_Works() private static void RunSetCoeffsTest() { // arrange - Vp8Residual residual = new(); + Vp8Residual residual = new(new Vp8EncoderProbabilities()); short[] coeffs = [110, 0, -2, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0]; // act diff --git a/tests/ImageSharp.Tests/Formats/WebP/WebpDecoderTests.cs b/tests/ImageSharp.Tests/Formats/WebP/WebpDecoderTests.cs index 0a59e5ae87..93d3c16ef8 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/WebpDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/WebpDecoderTests.cs @@ -10,6 +10,7 @@ using SixLabors.ImageSharp.Metadata; using SixLabors.ImageSharp.Metadata.Profiles.Exif; using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Tests.Memory; using SixLabors.ImageSharp.Tests.TestUtilities; using SixLabors.ImageSharp.Tests.TestUtilities.ImageComparison; using SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs; @@ -200,10 +201,12 @@ public void WebpDecoder_CanDecode_Issue2801(TestImageProvider pr /// /// Compares lossy decoding with uncompressed alpha against the reference decoder across hardware configurations. + /// The gradient filter has a scalar and a vector unfilter, so its image runs in each configuration too. /// /// The source image provider. [Theory] [WithFile(Lossy.AlphaNoCompression, PixelTypes.Rgba32)] + [WithFile(Lossy.AlphaNoCompressionGradientFilter, PixelTypes.Rgba32)] public void WebpDecoder_CanDecode_Lossy_WithUncompressedAlpha(TestImageProvider provider) => FeatureTestRunner.RunWithHwIntrinsicsFeature( RunUncompressedAlphaDecode, @@ -392,7 +395,11 @@ public void Info_AnimatedLossless_VerifyAllFrames(string imagePath) { TestFile testFile = TestFile.Create(imagePath); using MemoryStream stream = new(testFile.Bytes, false); + + // The only Identify overload that takes a CancellationToken is protected. https://github.com/xunit/xunit/issues/3673 +#pragma warning disable xUnit1051 ImageInfo image = WebpDecoder.Instance.Identify(DecoderOptions.Default, stream); +#pragma warning restore xUnit1051 WebpMetadata webpMetaData = image.Metadata.GetWebpMetadata(); WebpFrameMetadata frameMetaData = image.FrameMetadataCollection[0].GetWebpMetadata(); @@ -424,7 +431,11 @@ public void Info_AnimatedLossy_VerifyAllFrames(string imagePath) { TestFile testFile = TestFile.Create(imagePath); using MemoryStream stream = new(testFile.Bytes, false); + + // The only Identify overload that takes a CancellationToken is protected. https://github.com/xunit/xunit/issues/3673 +#pragma warning disable xUnit1051 ImageInfo image = WebpDecoder.Instance.Identify(DecoderOptions.Default, stream); +#pragma warning restore xUnit1051 WebpMetadata webpMetaData = image.Metadata.GetWebpMetadata(); WebpFrameMetadata frameMetaData = image.FrameMetadataCollection[0].GetWebpMetadata(); @@ -491,15 +502,20 @@ public void WebpDecoder_CanDecode_Lossless_WithIssues(TestImageProvider< } /// - /// Sets a reserved bit of the ALPH header byte. libwebp rejects the header, so the alpha data is damaged image data. In the Strict and IgnoreAncillary - /// modes, the decoder throws. In the IgnoreImageData mode, the decoder keeps the color pixels and sets each alpha value to 0, the transparent fill of - /// damaged data. + /// Sets a reserved bit or an undefined pre-processing value in the ALPH header byte. libwebp rejects the header, so the alpha data is damaged + /// image data. In the Strict and IgnoreAncillary modes, the decoder throws. In the IgnoreImageData mode, the decoder keeps the color pixels + /// and sets each alpha value to 0, the transparent fill of damaged data. /// /// The lossy image with an ALPH chunk. + /// The bits to set in the ALPH header byte: reserved bit 6 or 7, or the undefined pre-processing value 2. [Theory] - [InlineData(Lossy.AlphaNoCompression)] - [InlineData(Lossy.AlphaCompressedNoFilter)] - public void WebpDecoder_Decode_AlphaHeaderWithReservedBit_FollowsIntegrityHandling(string imagePath) + [InlineData(Lossy.AlphaNoCompression, 0x40)] + [InlineData(Lossy.AlphaNoCompression, 0x80)] + [InlineData(Lossy.AlphaNoCompression, 0x20)] + [InlineData(Lossy.AlphaCompressedNoFilter, 0x40)] + [InlineData(Lossy.AlphaCompressedNoFilter, 0x80)] + [InlineData(Lossy.AlphaCompressedNoFilter, 0x20)] + public void WebpDecoder_Decode_AlphaHeaderWithReservedBit_FollowsIntegrityHandling(string imagePath, int headerBits) { byte[] bytes = TestFile.Create(imagePath).Bytes; byte[] damaged = (byte[])bytes.Clone(); @@ -513,7 +529,7 @@ public void WebpDecoder_Decode_AlphaHeaderWithReservedBit_FollowsIntegrityHandli offset += 8 + size + (size & 1); } - damaged[offset + 8] |= 0x40; + damaged[offset + 8] |= (byte)headerBits; DecoderOptions strict = new(Configuration.Default) { SegmentIntegrityHandling = SegmentIntegrityHandling.Strict }; DecoderOptions ancillary = new(Configuration.Default) { SegmentIntegrityHandling = SegmentIntegrityHandling.IgnoreAncillary }; @@ -797,22 +813,17 @@ public void Decode_DamagedLaterAnimationFrame_KeepsDecodedFrames(string damage) /// /// A lossy image whose ALPH data ends early decodes with the default options. The color rows decode, the alpha /// rows before the end match a full decode, and the alpha values after it are 0. Strict mode throws. + /// Compressed and raw alpha data both keep the complete rows. /// - [Fact] - public void Decode_TruncatedAlphaData_KeepsDecodedAlphaByDefaultAndThrowsWithStrict() + /// Whether the ALPH data is compressed. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Decode_TruncatedAlphaData_KeepsDecodedAlphaByDefaultAndThrowsWithStrict(bool useAlphaCompression) { - Random random = new(3); - using Image source = new(64, 64); - for (int y = 0; y < source.Height; y++) - { - for (int x = 0; x < source.Width; x++) - { - source[x, y] = new Rgba32((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256)); - } - } - + using Image source = Image.Load(TestFile.Create(Lossless.Alpha).Bytes); using MemoryStream stream = new(); - source.Save(stream, new WebpEncoder { FileFormat = WebpFileFormatType.Lossy }); + source.Save(stream, new WebpEncoder { FileFormat = WebpFileFormatType.Lossy, UseAlphaCompression = useAlphaCompression }); byte[] data = stream.ToArray(); // Halve the ALPH payload and set the ALPH and RIFF sizes to the new length. The VP8 chunk follows unchanged, @@ -866,66 +877,28 @@ public void Decode_AlphaFlagWithoutAlphaChunk_DecodesOpaqueImage() } /// - /// A VP8L stream whose entropy image names more Huffman groups than the data can hold is not valid. Each group needs at least 20 bits, and libwebp rejects - /// the stream before it allocates the tables. The headers come before the image, so the decoder throws in each mode. + /// A VP8L stream whose entropy image names more Huffman groups than the data can hold is not valid. Each group needs at least 20 bits, + /// and libwebp rejects the stream before it allocates the tables. The headers come before the image, so the decoder throws in each mode. + /// The first file names group 65535 with one entropy pixel. The second file uses each of 256 groups and ends before their codes, whose + /// tables need 256 * 2954 entries of 8 bytes. /// - [Fact] - public void Decode_LosslessHuffmanGroupsLargerThanData_Throws() + /// The crafted file. + [Theory] + [InlineData(Lossless.HuffmanGroups65536)] + [InlineData(Lossless.HuffmanGroups256Truncated)] + public void Decode_LosslessHuffmanGroupsLargerThanData_Throws(string imagePath) { - // The VP8L bits are in least-significant-bit-first order. See the WebP Lossless Bitstream Specification - // (https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification). - List payload = []; - ulong bits = 0; - int bitCount = 0; - - void WriteBits(uint value, int count) - { - bits |= (ulong)value << bitCount; - bitCount += count; - while (bitCount >= 8) - { - payload.Add((byte)bits); - bits >>= 8; - bitCount -= 8; - } - } - - // The header: the 0x2F signature, a 4x4 size, no alpha and version 0. - WriteBits(0x2F, 8); - WriteBits(3, 14); - WriteBits(3, 14); - WriteBits(0, 1); - WriteBits(0, 3); - - // No transform, no color cache, and an entropy image with a precision of 2 bits. Thus, the entropy image of the 4x4 image has one pixel. The entropy - // image has no color cache. - WriteBits(0, 1); - WriteBits(0, 1); - WriteBits(1, 1); - WriteBits(0, 3); - WriteBits(0, 1); - - // Five simple codes with one 8-bit symbol each: green 255, red 255, blue 0, alpha 0 and distance 0. The entropy pixel has red 255 and green 255, so it - // names group 0xFFFF, and the image needs 65536 groups. - foreach (uint symbol in new uint[] { 255, 255, 0, 0, 0 }) - { - WriteBits(1, 1); - WriteBits(0, 1); - WriteBits(1, 1); - WriteBits(symbol, 8); - } - - WriteBits(0, 8 - bitCount); - payload.AddRange(new byte[4]); - - byte[] data = [.. "RIFF"u8, 0, 0, 0, 0, .. "WEBP"u8, .. "VP8L"u8, 0, 0, 0, 0, .. payload]; - BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(4), (uint)(data.Length - 8)); - BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(16), (uint)payload.Count); - + byte[] data = TestFile.Create(imagePath).Bytes; foreach (SegmentIntegrityHandling integrity in Enum.GetValues()) { - DecoderOptions options = new(Configuration.Default) { SegmentIntegrityHandling = integrity }; + TestMemoryAllocator allocator = new(); + allocator.EnableNonThreadSafeLogging(); + Configuration configuration = Configuration.CreateDefaultInstance(); + configuration.MemoryAllocator = allocator; + DecoderOptions options = new(configuration) { SegmentIntegrityHandling = integrity }; + Assert.Throws(() => Image.Load(options, data)); + Assert.True(allocator.PeakBufferBytes < 256L * 2954 * 8); } } @@ -1103,7 +1076,11 @@ public void Decode_VerifyRatio(string imagePath) { TestFile testFile = TestFile.Create(imagePath); using MemoryStream stream = new(testFile.Bytes, false); + + // The only Decode overload that takes a CancellationToken is protected. https://github.com/xunit/xunit/issues/3673 +#pragma warning disable xUnit1051 using Image image = WebpDecoder.Instance.Decode(DecoderOptions.Default, stream); +#pragma warning restore xUnit1051 ImageMetadata meta = image.Metadata; Assert.Equal(37.8, meta.HorizontalResolution); @@ -1117,7 +1094,11 @@ public void Identify_VerifyRatio(string imagePath) { TestFile testFile = TestFile.Create(imagePath); using MemoryStream stream = new(testFile.Bytes, false); + + // The only Identify overload that takes a CancellationToken is protected. https://github.com/xunit/xunit/issues/3673 +#pragma warning disable xUnit1051 ImageInfo image = WebpDecoder.Instance.Identify(DecoderOptions.Default, stream); +#pragma warning restore xUnit1051 ImageMetadata meta = image.Metadata; Assert.Equal(37.8, meta.HorizontalResolution); @@ -1296,4 +1277,62 @@ public void Decode_FrameImageOutsideAnmf_RejectsInvalidFraming() Assert.Throws(() => Image.Load(options, data)); } } + + /// + /// Decodes VP8 key frames with segment headers that encoders seldom write, and compares the result with libwebp. + /// See RFC 6386, section 9.3 "Segment-Based Adjustments": https://datatracker.ietf.org/doc/html/rfc6386#section-9.3. + /// + /// The image provider. + /// The pixel type. + [Theory] + [WithFile(Lossy.SegmentMapWithoutData, PixelTypes.Rgba32)] + [WithFile(Lossy.SegmentNoUpdate, PixelTypes.Rgba32)] + [WithFile(Lossy.SegmentRelativeDelta, PixelTypes.Rgba32)] + public void WebpDecoder_Decode_Vp8SegmentHeader_MatchesReference(TestImageProvider provider) + where TPixel : unmanaged, IPixel + { + using Image image = provider.GetImage(WebpDecoder.Instance); + image.CompareToOriginal(provider, ImageComparer.Exact, ReferenceDecoder); + } + + /// + /// libwebp rejects VP8L code lengths that name more symbols than the alphabet has, that repeat a length past the alphabet, or that do + /// not give a complete prefix code. The codes come before the image, so the decoder throws in each mode. See the WebP Lossless Bitstream + /// Specification, section 3.7.2.1.2: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// + /// The crafted file. + [Theory] + [InlineData(Lossless.CodeLengthsMaxSymbol)] + [InlineData(Lossless.CodeLengthsRepeatOverflow)] + [InlineData(Lossless.CodeLengthsIncomplete)] + public void WebpDecoder_Decode_InvalidLosslessCodeLengths_Throws(string imagePath) + { + byte[] data = TestFile.Create(imagePath).Bytes; + foreach (SegmentIntegrityHandling integrity in Enum.GetValues()) + { + DecoderOptions options = new(Configuration.Default) { SegmentIntegrityHandling = integrity }; + Assert.Throws(() => Image.Load(options, data)); + } + } + + /// + /// The entropy image names group 4095, so the stream has the codes of 4096 groups, but the image uses one of them. As libwebp does, the + /// decoder keeps the tables of the used group only. The tables of all groups need 4096 * 2954 entries of 8 bytes. + /// See the WebP Lossless Bitstream Specification, section 6.2.2: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification. + /// + /// The image provider. + /// The pixel type. + [Theory] + [WithFile(Lossless.SparseHuffmanGroups, PixelTypes.Rgba32)] + public void WebpDecoder_Decode_LosslessSparseHuffmanGroups_KeepsOnlyUsedGroups(TestImageProvider provider) + where TPixel : unmanaged, IPixel + { + TestMemoryAllocator allocator = new(); + allocator.EnableNonThreadSafeLogging(); + provider.Configuration.MemoryAllocator = allocator; + + using Image image = provider.GetImage(WebpDecoder.Instance); + image.CompareToOriginal(provider, ImageComparer.Exact, ReferenceDecoder); + Assert.True(allocator.PeakBufferBytes < 4096L * 2954 * 8); + } } diff --git a/tests/ImageSharp.Tests/Formats/WebP/WebpEncoderTests.cs b/tests/ImageSharp.Tests/Formats/WebP/WebpEncoderTests.cs index 8cbd9ec042..eb5645838f 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/WebpEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/WebpEncoderTests.cs @@ -694,73 +694,29 @@ public void Encode_Lossy_WithAlphaUsingCompression_Works(TestImageProvid } /// - /// The lossy encoder selects the alpha filter with the fast filter selection of libwebp. A plane with 16 alpha values or fewer uses no filter. - /// At efforts 0 to 3, a plane with 17 to 192 values makes one trial with the estimated filter. Thus the ALPH header records that filter. - /// The alpha data is lossless, so the decoded alpha is equal to the source alpha. + /// The lossy encoder selects the alpha filter as the fast filter selection of libwebp does. At effort 3 the encoder makes one trial, + /// so the ALPH header holds the selected filter. Each fixture has an alpha plane for which one filter wins. The alpha is lossless. /// - /// - /// The alpha value at (x, y) is ((columnStep * x) & columnMask) + ((rowStep * y) & rowMask). The estimate samples every second value of - /// every second row. A sample puts |value - prediction| / 16 in a bin, and the filter with the lowest sum of used bin indices wins. A tie keeps - /// the first filter in the order None, Horizontal, Vertical, Gradient. The sums of the column term and the row term stay in 0..255, so the - /// gradient prediction of each case is exact. - /// - /// (80 * x) & 240 has 16 values, so the filter is None. - /// 7 * x + ((48 * y) & 48) has 80 values. The horizontal and the gradient differences are in bin 0. The vertical differences are 16 and - /// the running mean differences reach 24, so these filters use bin 1. Horizontal wins the tie with Gradient. - /// (40 * x) & 248 has 32 values and equal rows. The vertical and the gradient differences are 0. Vertical wins the tie. - /// ((40 * x) & 120) + ((24 * y) & 120) has 31 values. Only the gradient differences are 0, so the filter is Gradient. - /// - /// - /// The image width. - /// The step of the column term. - /// The mask of the column term. - /// The step of the row term. - /// The mask of the row term. - /// The expected filter in bits 2 and 3 of the ALPH header: 0 None, 1 Horizontal, 2 Vertical, 3 Gradient. + /// The image provider. + /// The expected filter in bits 2 and 3 of the ALPH header. + /// The pixel type. [Theory] - [InlineData(64, 80, 240, 0, 0, 0)] - [InlineData(20, 7, 255, 48, 48, 1)] - [InlineData(64, 40, 248, 0, 0, 2)] - [InlineData(64, 40, 120, 24, 120, 3)] - public void Encode_Lossy_AlphaFilter_FollowsFastFilterSelection(int width, int columnStep, int columnMask, int rowStep, int rowMask, int expectedFilter) + [WithFile(Lossy.AlphaFilterNone, PixelTypes.Rgba32, (int)WebpAlphaFilterType.None)] + [WithFile(Lossy.AlphaFilterHorizontal, PixelTypes.Rgba32, (int)WebpAlphaFilterType.Horizontal)] + [WithFile(Lossy.AlphaFilterVertical, PixelTypes.Rgba32, (int)WebpAlphaFilterType.Vertical)] + [WithFile(Lossy.AlphaFilterGradient, PixelTypes.Rgba32, (int)WebpAlphaFilterType.Gradient)] + public void Encode_Lossy_AlphaFilter_FollowsFastFilterSelection(TestImageProvider provider, int expectedFilter) + where TPixel : unmanaged, IPixel { - const int height = 64; - using Image expected = new(width, height); - expected.ProcessPixelRows(accessor => - { - for (int y = 0; y < accessor.Height; y++) - { - Span row = accessor.GetRowSpan(y); - for (int x = 0; x < row.Length; x++) - { - row[x] = new A8((byte)(((columnStep * x) & columnMask) + ((rowStep * y) & rowMask))); - } - } - }); - - // Effort 3 tries no filter as a second trial only for a plane with more than 192 values. - WebpEncoder encoder = new() - { - FileFormat = WebpFileFormatType.Lossy, - Method = WebpEncodingMethod.Level3 - }; - - using Image image = expected.CloneAs(); + using Image image = provider.GetImage(); using MemoryStream stream = new(); - image.Save(stream, encoder); + image.Save(stream, new WebpEncoder { FileFormat = WebpFileFormatType.Lossy, Method = WebpEncodingMethod.Level3 }); byte[] data = stream.ToArray(); - // RIFF chunks start after the 12-byte file header. Each chunk has a 4-byte type, a 4-byte size, and a payload with padding to an even length. // The first payload byte of ALPH is the alpha header. - int offset = 12; - while (!data.AsSpan(offset, 4).SequenceEqual("ALPH"u8)) - { - int size = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(offset + 4)); - offset += 8 + size + (size & 1); - } - - Assert.Equal(expectedFilter, (data[offset + 8] >> 2) & 0x03); + Assert.Equal(expectedFilter, (GetChunk(data, "ALPH"u8)[0] >> 2) & 0x03); + using Image expected = image.CloneAs(); using Image actual = Image.Load(data); ImageComparer.Exact.VerifySimilarity(expected, actual); } @@ -859,6 +815,55 @@ public void Encode_Lossy_WithClearTransparentColor_EncodesClearedPixels( ImageComparer.Exact.VerifySimilarity(unchanged, source); } + /// + /// The lossy encoder writes the same VP8 bitstream as libwebp for the same source and settings. The libwebp file comes from the one-call + /// API (quality 75, method 4, the default preset). The non-square image checks that the chroma quantizer uses all macroblocks. The + /// image with flat 4x4 blocks checks the flat block test of the 4x4 mode search. + /// + /// The source image provider. + /// The libwebp encode of the source. + /// The pixel type. + [Theory] + [WithFile(Lossy.NonSquareSource, PixelTypes.Rgba32, Lossy.NonSquareLibwebp)] + [WithFile(Lossy.FlatBlocksSource, PixelTypes.Rgba32, Lossy.FlatBlocksLibwebp)] + public void Encode_Lossy_MatchesLibwebp(TestImageProvider provider, string libwebpFile) + where TPixel : unmanaged, IPixel + { + using Image image = provider.GetImage(); + using MemoryStream stream = new(); + image.Save(stream, new WebpEncoder + { + FileFormat = WebpFileFormatType.Lossy, + Quality = 75, + Method = WebpEncodingMethod.Level4, + SpatialNoiseShaping = 50, + FilterStrength = 60, + EntropyPasses = 1 + }); + + byte[] expected = TestFile.Create(libwebpFile).Bytes; + Assert.Equal(GetChunk(expected, "VP8 "u8).ToArray(), GetChunk(stream.ToArray(), "VP8 "u8).ToArray()); + } + + /// + /// Gets the payload of the first chunk of a type. RIFF chunks start after the 12-byte file header. Each chunk has a 4-byte type, a + /// 4-byte size, and a payload with padding to an even length. + /// + /// The WebP file. + /// The chunk type. + /// The chunk payload. + private static ReadOnlySpan GetChunk(byte[] data, ReadOnlySpan type) + { + int offset = 12; + while (!data.AsSpan(offset, 4).SequenceEqual(type)) + { + int size = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(offset + 4)); + offset += 8 + size + (size & 1); + } + + return data.AsSpan(offset + 8, BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(offset + 4))); + } + public static void RunEncodeLossy_WithPeakImage() { TestImageProvider provider = TestImageProvider.File(TestImageLossyFullPath); @@ -909,7 +914,7 @@ public async Task CanSave_NonSeekableStream_Async(TestImageProvider + /// The duration field of the ANMF chunk has 24 bits, in milliseconds. A longer duration is written as the longest duration that the + /// field holds. See the WebP Container Specification, the ANMF chunk: https://developers.google.com/speed/webp/docs/riff_container. + /// + [Fact] + public void Encode_FrameDurationOutsideField_IsSaturated() + { + using Image image = new(8, 8); + image.Frames.AddFrame(image.Frames.RootFrame); + image.Frames.RootFrame.Metadata.GetWebpMetadata().FrameDelay = 1U << 25; + image.Frames[1].Metadata.GetWebpMetadata().FrameDelay = 100; + + using MemoryStream stream = new(); + image.Save(stream, new WebpEncoder { FileFormat = WebpFileFormatType.Lossless }); + stream.Position = 0; + using Image decoded = Image.Load(stream); + + Assert.Equal((1U << 24) - 1, decoded.Frames.RootFrame.Metadata.GetWebpMetadata().FrameDelay); + Assert.Equal(100U, decoded.Frames[1].Metadata.GetWebpMetadata().FrameDelay); + } } diff --git a/tests/ImageSharp.Tests/Formats/WebP/YuvConversionTests.cs b/tests/ImageSharp.Tests/Formats/WebP/YuvConversionTests.cs index f4d692c087..31be2d5e78 100644 --- a/tests/ImageSharp.Tests/Formats/WebP/YuvConversionTests.cs +++ b/tests/ImageSharp.Tests/Formats/WebP/YuvConversionTests.cs @@ -178,6 +178,9 @@ private static void AssertRgbToYuv(string providerDump) Assert.True(expectedY.AsSpan().SequenceEqual(y)); Assert.True(expectedU.AsSpan().SequenceEqual(u[..expectedU.Length])); Assert.True(expectedV.AsSpan().SequenceEqual(v[..expectedV.Length])); + + // The fixture is opaque, so the converter gives no alpha plane. + Assert.Null(alpha); } /// @@ -307,5 +310,8 @@ private static void AssertRgbToYuvWithAlpha(string providerDump) Assert.True(expectedY.AsSpan().SequenceEqual(y)); Assert.True(expectedU.AsSpan().SequenceEqual(u[..expectedU.Length])); Assert.True(expectedV.AsSpan().SequenceEqual(v[..expectedV.Length])); + + // The fixture has transparent pixels, so the converter gives an alpha plane. + Assert.NotNull(alpha); } } diff --git a/tests/ImageSharp.Tests/TestImages.cs b/tests/ImageSharp.Tests/TestImages.cs index fa75cb4ee0..0329670040 100644 --- a/tests/ImageSharp.Tests/TestImages.cs +++ b/tests/ImageSharp.Tests/TestImages.cs @@ -827,6 +827,12 @@ public static class Webp public static class Lossless { + public const string CodeLengthsMaxSymbol = "Webp/lossless_code_lengths_max_symbol.webp"; + public const string CodeLengthsRepeatOverflow = "Webp/lossless_code_lengths_repeat_overflow.webp"; + public const string CodeLengthsIncomplete = "Webp/lossless_code_lengths_incomplete.webp"; + public const string SparseHuffmanGroups = "Webp/lossless_sparse_huffman_groups.webp"; + public const string HuffmanGroups256Truncated = "Webp/lossless_huffman_groups_256_truncated.webp"; + public const string HuffmanGroups65536 = "Webp/lossless_huffman_groups_65536.webp"; public const string Animated = "Webp/leo_animated_lossless.webp"; public const string Earth = "Webp/earth_lossless.webp"; public const string Alpha = "Webp/lossless_alpha_small.webp"; @@ -900,6 +906,17 @@ public static class Lossless public static class Lossy { + public const string NonSquareSource = "Webp/lossy_non_square.png"; + public const string NonSquareLibwebp = "Webp/lossy_non_square_libwebp.webp"; + public const string FlatBlocksSource = "Webp/lossy_flat_blocks.png"; + public const string FlatBlocksLibwebp = "Webp/lossy_flat_blocks_libwebp.webp"; + public const string AlphaFilterNone = "Webp/alpha_filter_none.png"; + public const string AlphaFilterHorizontal = "Webp/alpha_filter_horizontal.png"; + public const string AlphaFilterVertical = "Webp/alpha_filter_vertical.png"; + public const string AlphaFilterGradient = "Webp/alpha_filter_gradient.png"; + public const string SegmentMapWithoutData = "Webp/lossy_segment_map_without_data.webp"; + public const string SegmentNoUpdate = "Webp/lossy_segment_no_update.webp"; + public const string SegmentRelativeDelta = "Webp/lossy_segment_relative_delta.webp"; public const string AnimatedLandscape = "Webp/landscape.webp"; public const string Earth = "Webp/earth_lossy.webp"; public const string WithExif = "Webp/exif_lossy.webp"; diff --git a/tests/Images/Input/Webp/alpha_filter_gradient.png b/tests/Images/Input/Webp/alpha_filter_gradient.png new file mode 100644 index 0000000000..67a46cc35c --- /dev/null +++ b/tests/Images/Input/Webp/alpha_filter_gradient.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64648e3213a69697dc293496b3a6bb41390c1555cc94e9d3ca56ce4a26f95174 +size 354 diff --git a/tests/Images/Input/Webp/alpha_filter_horizontal.png b/tests/Images/Input/Webp/alpha_filter_horizontal.png new file mode 100644 index 0000000000..707c73c505 --- /dev/null +++ b/tests/Images/Input/Webp/alpha_filter_horizontal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:804573794500d1e188fc093053e849c051dda4ae4b693d85b7d2da4593400e05 +size 255 diff --git a/tests/Images/Input/Webp/alpha_filter_none.png b/tests/Images/Input/Webp/alpha_filter_none.png new file mode 100644 index 0000000000..f43c6c5d83 --- /dev/null +++ b/tests/Images/Input/Webp/alpha_filter_none.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f7988c4ca11a37a966e807eb7dffd595a56e8d0975858122210fba314539ca2 +size 201 diff --git a/tests/Images/Input/Webp/alpha_filter_vertical.png b/tests/Images/Input/Webp/alpha_filter_vertical.png new file mode 100644 index 0000000000..aec3e7a7a9 --- /dev/null +++ b/tests/Images/Input/Webp/alpha_filter_vertical.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c1b85b933eaf646e724e146d8d875ad92b092fc532d5674b6a9ba9cc494a085 +size 231 diff --git a/tests/Images/Input/Webp/lossless_code_lengths_incomplete.webp b/tests/Images/Input/Webp/lossless_code_lengths_incomplete.webp new file mode 100644 index 0000000000..18eb712b4d --- /dev/null +++ b/tests/Images/Input/Webp/lossless_code_lengths_incomplete.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4aa7446d285570b54d2ea6d4331b167a411bd9352206a4b491e30967bf9ed7f6 +size 70 diff --git a/tests/Images/Input/Webp/lossless_code_lengths_max_symbol.webp b/tests/Images/Input/Webp/lossless_code_lengths_max_symbol.webp new file mode 100644 index 0000000000..583ed17b86 --- /dev/null +++ b/tests/Images/Input/Webp/lossless_code_lengths_max_symbol.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1dfa587e4977057cc80256df7d7c1093172f430126a60c57c7e26897e4bb4e15 +size 72 diff --git a/tests/Images/Input/Webp/lossless_code_lengths_repeat_overflow.webp b/tests/Images/Input/Webp/lossless_code_lengths_repeat_overflow.webp new file mode 100644 index 0000000000..4dcd321fe8 --- /dev/null +++ b/tests/Images/Input/Webp/lossless_code_lengths_repeat_overflow.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb4b75d71207be042b50d04aa1d2bfb30269e27abe6a3a3662562449e9bf2169 +size 38 diff --git a/tests/Images/Input/Webp/lossless_huffman_groups_256_truncated.webp b/tests/Images/Input/Webp/lossless_huffman_groups_256_truncated.webp new file mode 100644 index 0000000000..e930f12790 --- /dev/null +++ b/tests/Images/Input/Webp/lossless_huffman_groups_256_truncated.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b1c803185f8de1685e40a61fdab9f69a301c9be3f1de5d8cf80e9d0fc019e82 +size 330 diff --git a/tests/Images/Input/Webp/lossless_huffman_groups_65536.webp b/tests/Images/Input/Webp/lossless_huffman_groups_65536.webp new file mode 100644 index 0000000000..05a5528a0c --- /dev/null +++ b/tests/Images/Input/Webp/lossless_huffman_groups_65536.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:232020d8959d1ebae3f4851e9e761441012f83201958642d6725f98edd37357b +size 38 diff --git a/tests/Images/Input/Webp/lossless_sparse_huffman_groups.webp b/tests/Images/Input/Webp/lossless_sparse_huffman_groups.webp new file mode 100644 index 0000000000..868d6db4b5 --- /dev/null +++ b/tests/Images/Input/Webp/lossless_sparse_huffman_groups.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:750d98a5a2ae10e0dbee46e5bf3dcc064d481f54ce04c80580a25598aa75f1ad +size 10282 diff --git a/tests/Images/Input/Webp/lossy_flat_blocks.png b/tests/Images/Input/Webp/lossy_flat_blocks.png new file mode 100644 index 0000000000..15b6d5af6f --- /dev/null +++ b/tests/Images/Input/Webp/lossy_flat_blocks.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:20b55caa49bb59736824d114b728d8b4e65cdc12acfc64f274bf164954f055d8 +size 1841 diff --git a/tests/Images/Input/Webp/lossy_flat_blocks_libwebp.webp b/tests/Images/Input/Webp/lossy_flat_blocks_libwebp.webp new file mode 100644 index 0000000000..fb59abde36 --- /dev/null +++ b/tests/Images/Input/Webp/lossy_flat_blocks_libwebp.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51a966427cf687c572be16fb6eab8767d2bbeb9a2c3f1a7166de589f7ea361c2 +size 414 diff --git a/tests/Images/Input/Webp/lossy_non_square.png b/tests/Images/Input/Webp/lossy_non_square.png new file mode 100644 index 0000000000..92c88832c6 --- /dev/null +++ b/tests/Images/Input/Webp/lossy_non_square.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ffd8b99d463271bdeb808c579ae0d690b60dc7be0c80a6dd9a8cd36f5bb10783 +size 3448 diff --git a/tests/Images/Input/Webp/lossy_non_square_libwebp.webp b/tests/Images/Input/Webp/lossy_non_square_libwebp.webp new file mode 100644 index 0000000000..da8468b0bd --- /dev/null +++ b/tests/Images/Input/Webp/lossy_non_square_libwebp.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:07363d7c2dedb61971b669b2a09e86bf1c7df33b3706b84f52fac16cc6909023 +size 374 diff --git a/tests/Images/Input/Webp/lossy_segment_map_without_data.webp b/tests/Images/Input/Webp/lossy_segment_map_without_data.webp new file mode 100644 index 0000000000..b3447dabbf --- /dev/null +++ b/tests/Images/Input/Webp/lossy_segment_map_without_data.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:670c7250db9e7f00013104a1eda41353c19115f18c95cd9d5d8d9470a05643d0 +size 46 diff --git a/tests/Images/Input/Webp/lossy_segment_no_update.webp b/tests/Images/Input/Webp/lossy_segment_no_update.webp new file mode 100644 index 0000000000..8da1b6b712 --- /dev/null +++ b/tests/Images/Input/Webp/lossy_segment_no_update.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a81fedef91f648f5dc93a3e9d129f92b1f38863773f2f1c362b70850c2440557 +size 42 diff --git a/tests/Images/Input/Webp/lossy_segment_relative_delta.webp b/tests/Images/Input/Webp/lossy_segment_relative_delta.webp new file mode 100644 index 0000000000..52a1fdf5a7 --- /dev/null +++ b/tests/Images/Input/Webp/lossy_segment_relative_delta.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc6d851cb594cd43efa6f77d4f6c0369c67d1207bd5750e7c21fa1d5ada36a98 +size 44