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/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