Skip to content
Merged
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
1 change: 1 addition & 0 deletions .github/docs/specs/standardqr-decoder.md
Original file line number Diff line number Diff line change
Expand Up @@ -681,6 +681,7 @@ End-to-end numbers are in `src/FeatherQR.Benchmark`. `QRCodeDecodeEndToEnd` cove
- The isomorphism root matters. β = 0x03 makes φ its own inverse, so one matrix constant serves both directions. The ×4 unroll measured 29 % over unroll ×2 and 47 % over the plain recurrence. Unrolling beyond ×4 stalls, because the loop moves from latency-bound (accumulator chain) to bound by GFNI-port throughput. Pre-mapping the whole codeword to remove the in-loop affine measured slower: that affine was off the carried dependency chain, so removing it saved nothing, while the extra pass cost real time.
- The large symbols had stopped using the sampler that was vectorized for them. Version 14 and up then sampled through the piecewise mesh first, and that loop had stayed scalar: a cell walk, a division, two lerps and a scattered load per module, 94 to 137 µs at version 40, half of a clean 3 px image decode once the threshold was fast. It became cheap through where things are computed, not only through vector width. The cell a column falls in and the fraction across it are the same for every row, so they go in a table once a call and the division leaves the module loop (0.78 on its own. This step is portable, and it is what the netstandard builds run. Every .NET build class has had a vector tier since, below). A cell's start and span are taken once a row, and an 8-module vector step is built from them by broadcast. Only the steps that straddle two cells need a select, and the version alone decides which those are. Version 40 sampling went 114 → 19 µs, version 20 33 → 6.3, and 135 → 28 on a 3.5 MB rotated image where the loads were expected to be the limit. It is now cheaper than the global transform's vector rows on the same grid, which cannot hoist their division out of the loop.
- A sampler is right only when it picks the same pixel, and three things decided that. The multiply and the add stay separate, because fused they can differ by an ulp and truncate into the next pixel. The float-to-int conversion has to match the reference's, whose cast differed by runtime: before .NET 9 it was the raw x64 conversion (INT_MIN for NaN and for anything out of range, 0 after the clamp), from .NET 9 it saturates, and on WebAssembly it differs again between interpreted and AOT-compiled code. The tier at first had a form for each .NET, found only because the parity test runs on net8.0 as well as net10.0. The kernel search had run on one. Since the 128-bit tier (2026-09-30), the reference takes each coordinate through `PixelIndex.Clamp`, which clamps to the far edge before the conversion and gives the same pixel on every runtime, and every tier has one form. The upper clamp is a float minimum with the limit as the first operand, so a NaN lane passes through, converts to INT_MIN and becomes 0 at the integer maximum, where the reference puts it. The other operand order turns NaN into the far edge of the image. None of these show on a symbol inside its image with finite nodes, so the test scenes are built from what can go wrong: every mesh version, bent meshes, nodes off their predictions, symbols pushed past all four image edges, and nodes that are NaN, infinite or past int range.
- Every sampler, grid or single point, takes a coordinate to a pixel the same way (2026-11-26). The grid samplers and the timing checks that clamp use `PixelIndex.Clamp` or `VectorCast.ToPixel`. The point checks that must tell outside from inside use a negated range test on the float, so NaN is outside. Before, the Standard QR timing check and the Micro QR timing-line fit cast NaN themselves, which the netstandard2.0 build on .NET 8 or .NET Framework turns into a negative index. The finder ring walk cast before its bound check, so a point just left of or above the image read column or row 0. The 256-bit grid sampler was the last to convert with the saturating `Vector256.ConvertToInt32` and clamp the integers. Clamping the floats first and converting with the plain instruction took it from 0.89 to 0.84 ns a module at version 40 and 0.90 to 0.87 at version 10 (AVX2). Reads on 720 rotated renders, a third of them with no quiet zone, did not change.
- Several variants were refuted on the way, each for a reason worth keeping.
- Spreading a start and a span to all 177 columns every row, to get the cell index out of the loop, cost more in stores than the indirection it removed (77 → 102 µs). The first vector form built on it measured 0.72 and nearly closed the question, because a variant whose parent was refuted also measures the parent's cost.
- Branchless clamps gained nothing, since a symbol inside its image never takes those branches.
Expand Down
10 changes: 6 additions & 4 deletions src/FeatherQR/Internals/ImageDecoders/FinderAxisEstimator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -377,9 +377,11 @@ public static bool TryDarkLightDarkRun(ReadOnlySpan<byte> luminance, int width,
var phase = 0;
for (var step = 1f; step <= maxRunLength; step += 1f)
{
var x = (int)(startX + dirX * step);
var y = (int)(startY + dirY * step);
if (x < 0 || x >= width || y < 0 || y >= height)
var pointX = startX + dirX * step;
var pointY = startY + dirY * step;
// Bounds on the float: the cast truncates toward zero, so a point just left of or above the image would read column or row 0.
// Negated so a NaN point is outside.
if (!(pointX >= 0f && pointX < width && pointY >= 0f && pointY < height))
{
// The outer dark ring may end exactly at the image edge (zero or
// cropped quiet zone): the run is complete, not clipped.
Expand All @@ -389,7 +391,7 @@ public static bool TryDarkLightDarkRun(ReadOnlySpan<byte> luminance, int width,
return true;
}

var dark = luminance[y * width + x] < threshold;
var dark = luminance[(int)pointY * width + (int)pointX] < threshold;
switch (phase)
{
case 0: // inside the 3-module center square
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ internal static void SampleVector256(ReadOnlySpan<byte> luminance, int width, in
var a11 = Vector256.Create(transform.a11);
var a12 = Vector256.Create(transform.a12);
var a13 = Vector256.Create(transform.a13);
var zero = Vector256<int>.Zero;
var maxPx = Vector256.Create(width - 1);
var maxPy = Vector256.Create(height - 1);
var lastX = Vector256.Create((float)(width - 1));
var lastY = Vector256.Create((float)(height - 1));
var widthVector = Vector256.Create(width);

Span<int> indices = stackalloc int[8];
Expand All @@ -34,11 +33,9 @@ internal static void SampleVector256(ReadOnlySpan<byte> luminance, int width, in
var x = (a11 * gridX + rowNumeratorX) * reciprocal;
var y = (a12 * gridX + rowNumeratorY) * reciprocal;

// ConvertToInt32 truncates toward zero like the scalar cast, so both take the pixel containing the point.
var px = Vector256.ConvertToInt32(x);
var py = Vector256.ConvertToInt32(y);
px = Vector256.Max(Vector256.Min(px, maxPx), zero);
py = Vector256.Max(Vector256.Min(py, maxPy), zero);
// The pixel the scalar tier's PixelIndex.Clamp takes
var px = VectorCast.ToPixel(x, lastX);
var py = VectorCast.ToPixel(y, lastY);

var index = py * widthVector + px;
index.CopyTo(indices);
Expand Down
11 changes: 11 additions & 0 deletions src/FeatherQR/Internals/ImageDecoders/VectorCast.Simd.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,17 @@ internal static Vector128<int> ToPixel(Vector128<float> coordinate, Vector128<fl
return Vector128.ConvertToUInt32(Vector128.Min(coordinate, last)).AsInt32();
}

/// <inheritdoc cref="ToPixel(Vector128{float}, Vector128{float})"/>
/// <remarks>On x64, 256-bit vectors need AVX2, so the AVX2 check is the one a caller on them passes.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static Vector256<int> ToPixel(Vector256<float> coordinate, Vector256<float> last)
{
// As on SSE2: both edges clamped first, and the max's operand order sends NaN to 0
if (Avx2.IsSupported)
return Avx.ConvertToVector256Int32WithTruncation(Avx.Min(Avx.Max(coordinate, Vector256<float>.Zero), last));
return Vector256.ConvertToUInt32(Vector256.Min(coordinate, last)).AsInt32();
}

/// <summary>
/// Truncated toward zero, exact from -1 (exclusive) up to 2^31. Outside that range or at NaN the lane depends on the platform,
/// for callers that do not read such lanes.
Expand Down
11 changes: 4 additions & 7 deletions src/FeatherQR/Internals/MicroQR/MicroQRImageDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -752,16 +752,13 @@ internal static bool TryFitTimingLine(ReadOnlySpan<byte> luminance, int width, i
}

/// <summary>Whether the pixel containing the point is dark. False (and not dark) outside the image.</summary>
private static bool IsDarkAt(ReadOnlySpan<byte> luminance, int width, int height, byte threshold, float x, float y, out bool dark)
internal static bool IsDarkAt(ReadOnlySpan<byte> luminance, int width, int height, byte threshold, float x, float y, out bool dark)
{
dark = false;
if (x < 0f || y < 0f)
// Negated so a NaN point is outside, as in the quiet-zone check
if (!(x >= 0f && y >= 0f && x < width && y < height))
return false;
var px = (int)x;
var py = (int)y;
if (px >= width || py >= height)
return false;
dark = luminance[py * width + px] < threshold;
dark = luminance[(int)y * width + (int)x] < threshold;
return true;
}

Expand Down
14 changes: 2 additions & 12 deletions src/FeatherQR/Internals/RmQR/RmQRImageDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1294,7 +1294,7 @@ private static void FormatBitModule(int bit, bool subFinderSide, int symbolWidth
}
}

private static bool SampleDark(ReadOnlySpan<byte> luminance, int width, int height, byte threshold, in PerspectiveTransform transform, float gridX, float gridY)
internal static bool SampleDark(ReadOnlySpan<byte> luminance, int width, int height, byte threshold, in PerspectiveTransform transform, float gridX, float gridY)
{
float x, y;
// An affine frame's denominator is exactly 1 at any grid point, and a division by 1 returns its dividend bit for bit
Expand All @@ -1309,17 +1309,7 @@ private static bool SampleDark(ReadOnlySpan<byte> luminance, int width, int heig
}
if (float.IsNaN(x) || float.IsNaN(y))
return false;
var px = (int)x;
var py = (int)y;
if (px < 0)
px = 0;
else if (px >= width)
px = width - 1;
if (py < 0)
py = 0;
else if (py >= height)
py = height - 1;
return luminance[py * width + px] < threshold;
return luminance[PixelIndex.Clamp(y, height) * width + PixelIndex.Clamp(x, width)] < threshold;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ internal static partial class QRImageDecoder
/// for one compare and one store. ARM64, x64 without AVX2 and WebAssembly take it.
/// </summary>
/// <remarks>
/// The same float operations in the reference's order, and each coordinate to its pixel through <see cref="VectorCast.ToPixel"/>,
/// The same float operations in the reference's order, and each coordinate to its pixel through <see cref="VectorCast.ToPixel(System.Runtime.Intrinsics.Vector128{float}, System.Runtime.Intrinsics.Vector128{float})"/>,
/// which lands where the reference's <see cref="PixelIndex.Clamp(float, int)"/> does for every float.
/// </remarks>
internal static void SampleGridPiecewiseVector128(ReadOnlySpan<byte> luminance, int width, int height, byte threshold, ReadOnlySpan<float> gridCoords, ReadOnlySpan<float> nodeXs, ReadOnlySpan<float> nodeYs, int meshSize, int dimension, Span<byte> modules)
Expand Down
6 changes: 2 additions & 4 deletions src/FeatherQR/Internals/StandardQR/QRImageDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1149,14 +1149,12 @@ internal static int MatchTimingDimension(ReadOnlySpan<byte> luminance, int width
}

/// <summary>Whether the module at grid point (<paramref name="u"/>, <paramref name="v"/>) through <paramref name="transform"/> is dark: interpolated against the grey midpoint where the image has grey levels, else the pixel against the threshold.</summary>
private static bool IsDarkAt(ReadOnlySpan<byte> luminance, int width, int height, byte threshold, in GreyLevels grey, in PerspectiveTransform transform, float u, float v)
internal static bool IsDarkAt(ReadOnlySpan<byte> luminance, int width, int height, byte threshold, in GreyLevels grey, in PerspectiveTransform transform, float u, float v)
{
transform.Transform(u, v, out var x, out var y);
if (grey.IsEnabled)
return LuminanceSampler.Bilinear(luminance, width, height, x, y) < grey.Midpoint;
var px = x < 0f ? 0 : x >= width ? width - 1 : (int)x;
var py = y < 0f ? 0 : y >= height ? height - 1 : (int)y;
return luminance[py * width + px] < threshold;
return luminance[PixelIndex.Clamp(y, height) * width + PixelIndex.Clamp(x, width)] < threshold;
}

/// <summary>
Expand Down
15 changes: 14 additions & 1 deletion tests/FeatherQR.Tests/Rendering/FinderAxisEstimatorTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,21 @@ public async Task FirstOrientation_IsTheFinderAxis(int pixelsPerModule, int degr
[Arguments(2)]
[Arguments(3)]
public async Task DarkLightDarkRun_PixelAlignedFinder_FindsTheRingEdges(int pixelsPerModule)
=> await AssertRingEdges(pixelsPerModule, quietZone: 2);

/// <summary>
/// The finder's dark ring ends at the image edge on every side. The walk stops at the first step outside the image,
/// so the outer edge is the same toward the left and top edges as toward the right and bottom ones.
/// </summary>
[Test]
[Arguments(1)]
[Arguments(2)]
[Arguments(3)]
public async Task DarkLightDarkRun_RingAtTheImageEdge_FindsTheRingEdges(int pixelsPerModule)
=> await AssertRingEdges(pixelsPerModule, quietZone: 0);

private static async Task AssertRingEdges(int pixelsPerModule, int quietZone)
{
const int quietZone = 2;
var side = (7 + 2 * quietZone) * pixelsPerModule;
var luminance = new byte[side * side];
for (var y = 0; y < side; y++)
Expand Down
41 changes: 41 additions & 0 deletions tests/FeatherQR.Tests/Shared/PixelCoordinateEdgeTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,47 @@ public async Task RmQRSamplers_ReadTheEdgeColumn(float x, int column)
}
}

/// <summary>The Standard QR timing check reads one point at a time and takes the same pixel as the grid.</summary>
[Test]
[MethodDataSource(nameof(Coordinates))]
public async Task StandardQRPointReader_ReadsTheEdgeColumn(float x, int column)
{
var luminance = DarkColumn(column);
var transform = PerspectiveTransform.FromCoefficients(0f, 0f, x, 0f, 0f, 1.5f, 0f, 0f, 1f);

await Assert.That(Internals.StandardQR.QRImageDecoder.IsDarkAt(luminance, Width, Height, 128, default, transform, 0.5f, 0.5f)).IsTrue().Because($"x = {x:R}");
}

/// <summary>The rMQR format and timing checks read one point at a time: NaN reads light, anything else the pixel the grid takes.</summary>
[Test]
[MethodDataSource(nameof(Coordinates))]
public async Task RmQRPointReader_ReadsTheEdgeColumn(float x, int column)
{
var luminance = DarkColumn(column);
foreach (var transform in new[]
{
PerspectiveTransform.FromCoefficients(0f, 0f, x, 0f, 0f, 1.5f, 0f, 0f, 1f),
PerspectiveTransform.FromCoefficients(0f, 0f, x * 2f, 0f, 0f, 3f, 0f, 0f, 2f),
})
{
var dark = RmQRImageDecoder.SampleDark(luminance, Width, Height, 128, transform, 0.5f, 0.5f);
await Assert.That(dark).IsEqualTo(!float.IsNaN(x)).Because($"x = {x:R}, a33 = {transform.a33}");
}
}

/// <summary>The Micro QR timing-line fit reads a point only inside the image: NaN, left of it and past its right edge are outside.</summary>
[Test]
[MethodDataSource(nameof(Coordinates))]
public async Task MicroQRPointReader_ReadsInsideTheImageOnly(float x, int column)
{
var luminance = DarkColumn(column);
var inside = MicroQRImageDecoder.IsDarkAt(luminance, Width, Height, 128, x, 1.5f, out var dark);

var expected = x >= 0f && x < Width;
await Assert.That(inside).IsEqualTo(expected).Because($"x = {x:R}");
await Assert.That(dark).IsEqualTo(expected).Because($"x = {x:R}");
}

/// <summary>A lattice point at NaN is neither inside nor outside the image: it is skipped, not read, on every tier.</summary>
[Test]
public async Task SubFinderLattice_SkipsNaNPoints()
Expand Down
52 changes: 50 additions & 2 deletions tests/FeatherQR.Tests/Shared/VectorCastParityTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
namespace FeatherQR.Tests;

/// <summary>
/// <see cref="VectorCast.ToPixel"/> lands every lane on the pixel <see cref="PixelIndex.Clamp(float, int)"/> takes, for any float,
/// which is what keeps the 128-bit samplers byte-identical to their scalar tiers. <see cref="VectorCast.ToInt32Native"/> truncates
/// <c>VectorCast.ToPixel</c> lands every lane on the pixel <see cref="PixelIndex.Clamp(float, int)"/> takes, for any float, on 128 and 256 bits,
/// which is what keeps the vector samplers byte-identical to their scalar tiers. <see cref="VectorCast.ToInt32Native"/> truncates
/// exactly from -1 (exclusive) up to 2^31, the only lanes the sub-finder lattice reads.
/// </summary>
public class VectorCastParityTest
Expand Down Expand Up @@ -73,6 +73,43 @@ public async Task ToPixel_MatchesScalarClamp_OnRandomBitPatterns()
await Assert.That(mismatches).IsEmpty().Because(string.Join("; ", mismatches.Take(8)));
}

[Test]
public async Task ToPixel256_MatchesScalarClamp_OnTheEdgesAndRandomBitPatterns()
{
if (!Vector256.IsHardwareAccelerated)
{
Skip.Test("Vector256 not accelerated on this machine");
return;
}

var mismatches = new List<string>();
foreach (var limit in Limits)
{
foreach (var value in Edges)
{
for (var lane = 0; lane < 8; lane++)
{
var lanes = new[] { 3.7f, float.NaN, 2147483648f, -2.5f, float.NegativeInfinity, 4095.5f, -0.5f, 1e20f };
lanes[lane] = value;
ComparePixel256(lanes, limit, mismatches);
}
}
}
var random = new Random(20261126);
var four = new float[4];
var eight = new float[8];
for (var trial = 0; trial < 20_000; trial++)
{
RandomLanes(random, trial, four);
four.CopyTo(eight, 0);
RandomLanes(random, trial, four);
four.CopyTo(eight, 4);
ComparePixel256(eight, Limits[trial % Limits.Length], mismatches);
}

await Assert.That(mismatches).IsEmpty().Because(string.Join("; ", mismatches.Take(8)));
}

[Test]
public async Task ToInt32Native_Truncates_InsideTheIntRange()
{
Expand Down Expand Up @@ -121,6 +158,17 @@ private static void ComparePixel(float[] lanes, int limit, List<string> mismatch
}
}

private static void ComparePixel256(float[] lanes, int limit, List<string> mismatches)
{
var actual = VectorCast.ToPixel(Vector256.Create(lanes), Vector256.Create((float)(limit - 1)));
for (var lane = 0; lane < 8; lane++)
{
var expected = PixelIndex.Clamp(lanes[lane], limit);
if (actual.GetElement(lane) != expected)
mismatches.Add($"{lanes[lane]:R} (0x{BitConverter.SingleToInt32Bits(lanes[lane]):X8}) in lane {lane}, limit {limit}: {actual.GetElement(lane)}, scalar {expected}");
}
}

private static void CompareNative(float[] lanes, List<string> mismatches)
{
var actual = VectorCast.ToInt32Native(Vector128.Create(lanes));
Expand Down
Loading