Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
184 changes: 174 additions & 10 deletions src/ImageSharp/Common/Helpers/SimdUtils.HwIntrinsics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ internal static partial class SimdUtils
{
public static partial class HwIntrinsics
{
/// <summary>
/// The high part of 1 / 255 as a float. <c>FusedMultiplyAdd(b, ByteReciprocalHigh, b * ByteReciprocalLow)</c> gives
/// the correctly rounded <c>b / 255F</c> for every byte <c>b</c> without a division. The main loops and the tails of
/// the byte-to-float conversions share these parts, so a float does not depend on the step that converts it.
/// </summary>
private const float ByteReciprocalHigh = (float)(1D / byte.MaxValue);

/// <summary>
/// The low part of 1 / 255: the difference between 1 / 255 in double precision and <see cref="ByteReciprocalHigh"/>.
/// </summary>
private const float ByteReciprocalLow = (float)((1D / byte.MaxValue) - ByteReciprocalHigh);

/// <summary>
/// Count the number of leading zero bits in a mask.
/// Similar in behavior to the x86 instruction LZCNT.
Expand Down Expand Up @@ -78,7 +90,77 @@ public static void ByteToNormalizedFloatReduce<TAlpha>(
source = source[adjustedCount..];
destination = destination[adjustedCount..];
}

// The rest is shorter than one step of the main loop. Convert whole pixels of it with narrower vectors,
// so that short rows and row tails do not take the scalar path. A row of whole steps skips the call.
if (source.Length >= 4)
{
ByteToNormalizedFloatTail<TAlpha>(ref source, ref destination);
}
}
}

/// <summary>
/// Converts the bytes that remain after the main loop of <see cref="ByteToNormalizedFloat{TAlpha}"/> with narrower vectors:
/// 16 bytes per step with 512-bit vectors, 8 bytes per step with 256-bit vectors, then 4 bytes (one pixel) per step
/// with 128-bit vectors. It slices the spans past the converted bytes and keeps the last 0 to 3 bytes.
/// </summary>
/// <remarks>
/// Each step computes every float as the main loop does: the byte as a float, times the high part of 1 / 255 fused with
/// the product of the low part, so the floats do not depend on the width. Each step is a multiple of 4 bytes and
/// starts at a multiple of 4, so <typeparamref name="TAlpha"/> sees whole RGBA groups. Each step loads its bytes
/// before it stores its floats and the steps move forward, the order that the staging in
/// <c>Rgba32CompatiblePixelOperations{TPixel}.Unpack</c> needs.
/// </remarks>
/// <typeparam name="TAlpha">The alpha step that the conversion applies before each store.</typeparam>
/// <param name="source">The source buffer.</param>
/// <param name="destination">The destination buffer.</param>
private static void ByteToNormalizedFloatTail<TAlpha>(
ref ReadOnlySpan<byte> source,
ref Span<float> destination)
where TAlpha : struct, PixelFormats.PixelOperations.IAlphaOperator
{
nuint length = (uint)source.Length;
nuint i = 0;
ref byte sourceBase = ref MemoryMarshal.GetReference(source);
ref float destinationBase = ref MemoryMarshal.GetReference(destination);

if (Vector512.IsHardwareAccelerated)
{
Vector512<float> high = Vector512.Create(ByteReciprocalHigh);
Vector512<float> low = Vector512.Create(ByteReciprocalLow);
for (; i + 16 <= length; i += 16)
{
// 16 bytes widen to sixteen 32-bit lanes: four RGBA pixels.
Vector512<float> f = Vector512.ConvertToSingle(Vector512_.Widen(Vector128.LoadUnsafe(ref sourceBase, i)));
TAlpha.Apply(Vector512.FusedMultiplyAdd(f, high, f * low)).StoreUnsafe(ref destinationBase, i);
}
}
else if (Vector256.IsHardwareAccelerated)
{
Vector256<float> high = Vector256.Create(ByteReciprocalHigh);
Vector256<float> low = Vector256.Create(ByteReciprocalLow);
for (; i + 8 <= length; i += 8)
{
// 8 bytes widen to eight 32-bit lanes: two RGBA pixels.
Vector256<float> f = Vector256.ConvertToSingle(Vector256_.Widen(Vector64.LoadUnsafe(ref sourceBase, i)));
TAlpha.Apply(Vector256.FusedMultiplyAdd(f, high, f * low)).StoreUnsafe(ref destinationBase, i);
}
}

Vector128<float> high128 = Vector128.Create(ByteReciprocalHigh);
Vector128<float> low128 = Vector128.Create(ByteReciprocalLow);
for (; i + 4 <= length; i += 4)
{
// One pixel: 4 bytes in the low lane widen to four 32-bit lanes. The values are below 256, so the
// signed conversion is exact.
Vector128<byte> bytes = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref sourceBase, i))).AsByte();
Vector128<float> f = Vector128.ConvertToSingle(Vector128.WidenLower(Vector128.WidenLower(bytes)).AsInt32());
TAlpha.Apply(Vector128.FusedMultiplyAdd(f, high128, f * low128)).StoreUnsafe(ref destinationBase, i);
}

source = source[(int)i..];
destination = destination[(int)i..];
}

/// <summary>
Expand Down Expand Up @@ -110,10 +192,6 @@ public static void ByteToNormalizedFloat<TAlpha>(
Span<float> destination)
where TAlpha : struct, PixelFormats.PixelOperations.IAlphaOperator
{
const double reciprocal = 1D / byte.MaxValue;
const float reciprocalHigh = (float)reciprocal;
const float reciprocalLow = (float)(reciprocal - reciprocalHigh);

if (Vector512.IsHardwareAccelerated)
{
DebugVerifySpanInput(source, destination, Vector512<byte>.Count);
Expand All @@ -122,8 +200,8 @@ public static void ByteToNormalizedFloat<TAlpha>(

ref byte sourceBase = ref MemoryMarshal.GetReference(source);
ref Vector512<float> destinationBase = ref Unsafe.As<float, Vector512<float>>(ref MemoryMarshal.GetReference(destination));
Vector512<float> high = Vector512.Create(reciprocalHigh);
Vector512<float> low = Vector512.Create(reciprocalLow);
Vector512<float> high = Vector512.Create(ByteReciprocalHigh);
Vector512<float> low = Vector512.Create(ByteReciprocalLow);

for (nuint i = 0; i < n; i++)
{
Expand Down Expand Up @@ -163,8 +241,8 @@ public static void ByteToNormalizedFloat<TAlpha>(

ref byte sourceBase = ref MemoryMarshal.GetReference(source);
ref Vector256<float> destinationBase = ref Unsafe.As<float, Vector256<float>>(ref MemoryMarshal.GetReference(destination));
Vector256<float> high = Vector256.Create(reciprocalHigh);
Vector256<float> low = Vector256.Create(reciprocalLow);
Vector256<float> high = Vector256.Create(ByteReciprocalHigh);
Vector256<float> low = Vector256.Create(ByteReciprocalLow);

for (nuint i = 0; i < n; i++)
{
Expand Down Expand Up @@ -204,8 +282,8 @@ public static void ByteToNormalizedFloat<TAlpha>(
ref byte sourceBase = ref MemoryMarshal.GetReference(source);
ref Vector128<float> destinationBase = ref Unsafe.As<float, Vector128<float>>(ref MemoryMarshal.GetReference(destination));

Vector128<float> high = Vector128.Create(reciprocalHigh);
Vector128<float> low = Vector128.Create(reciprocalLow);
Vector128<float> high = Vector128.Create(ByteReciprocalHigh);
Vector128<float> low = Vector128.Create(ByteReciprocalLow);

for (nuint i = 0; i < n; i++)
{
Expand Down Expand Up @@ -309,7 +387,93 @@ public static void FloatToByteSaturateReduce<TAlpha>(
source = source[adjustedCount..];
destination = destination[adjustedCount..];
}

// The rest is shorter than one step of the main loop. Convert whole pixels of it with narrower vectors,
// so that short rows and row tails do not take the scalar path. A row of whole steps skips the call.
if (source.Length >= 4)
{
FloatToByteSaturateTail<TAlpha>(ref source, ref destination, scaleFactor);
}
}
}

/// <summary>
/// Converts the floats that remain after the main loop of <see cref="FloatToByteSaturate{TAlpha}"/> with narrower
/// vectors: 16 floats per step with 512-bit vectors, 8 floats per step with 256-bit vectors, then 4 floats (one pixel)
/// per step with 128-bit vectors. It slices the spans past the converted floats and keeps the last 0 to 3 floats.
/// </summary>
/// <remarks>
/// Each step computes every byte as the main loop does: <typeparamref name="TAlpha"/>, the clamp to
/// [0, 255 / <paramref name="scaleFactor"/>] (NaN to 0), then truncate(x * scale + 0.5). The clamped value gives an
/// integer from 0 to 255, so the truncating narrows equal the saturating narrow of the main loop. Each step is a
/// multiple of 4 floats and starts at a multiple of 4, so <typeparamref name="TAlpha"/> sees whole RGBA groups.
/// Each step loads its floats before it stores its bytes, and the steps move forward: a destination that starts at
/// the source (the three-byte formats of <c>Rgba32CompatiblePixelOperations{TPixel}.Pack</c>) stays valid.
/// </remarks>
/// <typeparam name="TAlpha">The alpha step that the conversion applies before the scale.</typeparam>
/// <param name="source">The source buffer.</param>
/// <param name="destination">The destination buffer.</param>
/// <param name="scaleFactor">The factor applied before conversion.</param>
private static void FloatToByteSaturateTail<TAlpha>(
ref ReadOnlySpan<float> source,
ref Span<byte> destination,
float scaleFactor)
where TAlpha : struct, PixelFormats.PixelOperations.IAlphaOperator
{
nuint length = (uint)source.Length;
nuint i = 0;
ref float sourceBase = ref MemoryMarshal.GetReference(source);
ref byte destinationBase = ref MemoryMarshal.GetReference(destination);
float upperBound = byte.MaxValue / scaleFactor;

if (Vector512.IsHardwareAccelerated)
{
Vector512<float> scale = Vector512.Create(scaleFactor);
Vector512<float> upper = Vector512.Create(upperBound);
Vector512<float> half = Vector512.Create(.5F);
for (; i + 16 <= length; i += 16)
{
Vector512<float> f = ColorNumerics.ClampToFinite(TAlpha.Apply(Vector512.LoadUnsafe(ref sourceBase, i)), Vector512<float>.Zero, upper);
Vector512<int> n = Vector512.ConvertToInt32Native((f * scale) + half);

// The first 16 lanes of each narrow hold n in order.
Vector512<short> s = Vector512.Narrow(n, n);
Vector512.Narrow(s, s).AsByte().GetLower().GetLower().StoreUnsafe(ref destinationBase, i);
}
}
else if (Vector256.IsHardwareAccelerated)
{
Vector256<float> scale = Vector256.Create(scaleFactor);
Vector256<float> upper = Vector256.Create(upperBound);
Vector256<float> half = Vector256.Create(.5F);
for (; i + 8 <= length; i += 8)
{
Vector256<float> f = ColorNumerics.ClampToFinite(TAlpha.Apply(Vector256.LoadUnsafe(ref sourceBase, i)), Vector256<float>.Zero, upper);
Vector256<int> n = Vector256.ConvertToInt32Native((f * scale) + half);

// Narrow(x, x) puts the narrowed lanes of x first, so the low 8 bytes of the second narrow hold n in order.
Vector256<short> s = Vector256.Narrow(n, n);
ulong bytes = Vector256.Narrow(s, s).AsUInt64().ToScalar();
Unsafe.WriteUnaligned(ref Unsafe.Add(ref destinationBase, i), bytes);
}
}

Vector128<float> scale128 = Vector128.Create(scaleFactor);
Vector128<float> upper128 = Vector128.Create(upperBound);
Vector128<float> half128 = Vector128.Create(.5F);
for (; i + 4 <= length; i += 4)
{
Vector128<float> f = ColorNumerics.ClampToFinite(TAlpha.Apply(Vector128.LoadUnsafe(ref sourceBase, i)), Vector128<float>.Zero, upper128);
Vector128<int> n = Vector128.ConvertToInt32Native((f * scale128) + half128);

// As above: the low 4 bytes of the second narrow hold n in order.
Vector128<short> s = Vector128.Narrow(n, n);
uint bytes = Vector128.Narrow(s, s).AsUInt32().ToScalar();
Unsafe.WriteUnaligned(ref Unsafe.Add(ref destinationBase, i), bytes);
}

source = source[(int)i..];
destination = destination[(int)i..];
}

/// <summary>
Expand Down
84 changes: 84 additions & 0 deletions tests/ImageSharp.Tests/Common/SimdUtilsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,90 @@ public void BulkConvertFloatToByteRoundsMidpointsAwayFromZeroAndClampsOverflows(
Assert.Equal(expected, actual);
}

[Fact]
public void ByteToNormalizedFloat_EveryShortLength_MatchesOracle_AtEveryVectorWidth() =>
FeatureTestRunner.RunWithHwIntrinsicsFeature(
RunByteToNormalizedFloatEveryShortLength,
HwIntrinsics.AllowAll | HwIntrinsics.DisableAVX512F | HwIntrinsics.DisableAVX2 | HwIntrinsics.DisableHWIntrinsic);

[Fact]
public void FloatToByteSaturate_EveryShortLength_MatchesOracle_AtEveryVectorWidth() =>
FeatureTestRunner.RunWithHwIntrinsicsFeature(
RunFloatToByteSaturateEveryShortLength,
HwIntrinsics.AllowAll | HwIntrinsics.DisableAVX512F | HwIntrinsics.DisableAVX2 | HwIntrinsics.DisableHWIntrinsic);

private static void RunByteToNormalizedFloatEveryShortLength()
{
// The lengths cover rows shorter than one main-loop step and every tail length after whole steps
// (64, 32, or 16 bytes per step), so each narrower step and the final single bytes run.
Random random = new(42);
for (int count = 0; count <= 130; count++)
{
byte[] source = new byte[count];
random.NextBytes(source);
float[] result = new float[count];
float[] expected = [.. source.Select(b => (float)(b / (double)byte.MaxValue))];

SimdUtils.ByteToNormalizedFloat(source, result);
Assert.Equal(expected, result);

// The alpha forms take whole RGBA pixels; the oracle applies the operator to each pixel of the oracle row.
int pixelBytes = count & ~3;
float[] associated = new float[pixelBytes];
SimdUtils.ByteToNormalizedFloat<PixelOperations.AssociateOperator>(source.AsSpan(0, pixelBytes), associated);
for (int i = 0; i < pixelBytes; i += 4)
{
Vector128<float> pixel = PixelOperations.AssociateOperator.Apply(Vector128.Create(expected[i], expected[i + 1], expected[i + 2], expected[i + 3]));
Assert.Equal(pixel, Vector128.Create(associated, i));
}
}
}

private static void RunFloatToByteSaturateEveryShortLength()
{
Random random = new(43);
float[] specials = [float.NaN, float.PositiveInfinity, float.NegativeInfinity, -0F, 0F, 1F, -1F, 2F, 1e30F, .5F / byte.MaxValue, 254.5F / byte.MaxValue];

// Scalar rule of the conversion: NaN to 0, clamp to [0, 1], then truncate(x * 255 + 0.5).
static byte Oracle(float x)
{
float clamped = x >= 0F ? (x > 1F ? 1F : x) : 0F;
return (byte)((clamped * byte.MaxValue) + .5F);
}

for (int count = 0; count <= 130; count++)
{
float[] source = new float[count];
for (int i = 0; i < count; i++)
{
source[i] = random.Next(5) == 0 ? specials[random.Next(specials.Length)] : (float)((random.NextDouble() * 1.5) - .25);
}

byte[] result = new byte[count];
SimdUtils.NormalizedFloatToByteSaturate(source, result);
Assert.Equal([.. source.Select(Oracle)], result);

// The byte-magnitude form (scale 1, used for associated pixels) clamps to [0, 255] and then rounds the same way.
float[] magnitudes = [.. source.Select(x => x * byte.MaxValue)];
byte[] magnitudeResult = new byte[count];
SimdUtils.FloatToByteSaturate(magnitudes, magnitudeResult);
Assert.Equal([.. magnitudes.Select(x => (byte)((x >= 0F ? (x > byte.MaxValue ? byte.MaxValue : x) : 0F) + .5F))], magnitudeResult);

// The unassociate form takes whole RGBA pixels: the operator per pixel, then the same rule per component.
int pixelFloats = count & ~3;
byte[] unassociated = new byte[pixelFloats];
SimdUtils.NormalizedFloatToByteSaturate<PixelOperations.UnassociateOperator>(source.AsSpan(0, pixelFloats), unassociated);
for (int i = 0; i < pixelFloats; i += 4)
{
Vector128<float> pixel = PixelOperations.UnassociateOperator.Apply(Vector128.Create(source, i));
for (int c = 0; c < 4; c++)
{
Assert.Equal(Oracle(pixel.GetElement(c)), unassociated[i + c]);
}
}
}
}

[Theory]
[MemberData(nameof(ArbitraryArraySizes))]
public void PackFromRgbPlanes_Rgb24(int count) => TestPackFromRgbPlanes<Rgb24>(
Expand Down
Loading