using System.Numerics; using System.Runtime.CompilerServices; using Chronos.Core.Imaging; namespace Chronos.Core.Motion; /// Row-parallel kernels on single-channel float planes shared by the motion modules. internal static class PlaneOps { /// Below this many pixels per pass the Parallel.For overhead outweighs the work. public const int ParallelThreshold = 1 << 15; /// Runs for every row, in parallel when the plane is large. public static void ForRows(int height, int width, Action body) { if ((long)height * width < ParallelThreshold) { for (var y = 0; y < height; y++) body(y); } else { Parallel.For(0, height, body); } } /// /// Perceptually uniform luminance (sRGB-encoded Rec.709 Y, 0..1). Motion estimation works on it so that /// shadows carry texture weight comparable to highlights, unlike linear light. /// public static void PerceptualLuminance(ImageBuffer image, Span destination) { ColorSpace.Luminance(image, destination); for (var i = 0; i < destination.Length; i++) destination[i] = ColorSpace.EncodeFast(destination[i]); } /// Bilinear sample with edge clamping at pixel-centre coordinates. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Bilinear(ReadOnlySpan plane, int width, int height, float x, float y) { x = float.Clamp(x, 0, width - 1); y = float.Clamp(y, 0, height - 1); var x0 = int.Min((int)x, width - 2 < 0 ? 0 : width - 2); var y0 = int.Min((int)y, height - 2 < 0 ? 0 : height - 2); var fx = x - x0; var fy = y - y0; var x1 = int.Min(x0 + 1, width - 1); var y1 = int.Min(y0 + 1, height - 1); var r0 = y0 * width; var r1 = y1 * width; var top = plane[r0 + x0] + (plane[r0 + x1] - plane[r0 + x0]) * fx; var bottom = plane[r1 + x0] + (plane[r1 + x1] - plane[r1 + x0]) * fx; return top + (bottom - top) * fy; } /// /// Mean over a (2r+1)² box with replicated edges, by running sums: horizontal pass per row, then a /// vertical pass that keeps Vector<float> column sums for blocks of columns. /// public static void BoxFilter(float[] source, float[] destination, float[] scratch, int width, int height, int radius) { var inv = 1f / (2 * radius + 1); ForRows(height, width, y => { var row = source.AsSpan(y * width, width); var output = scratch.AsSpan(y * width, width); float sum = 0; for (var k = -radius; k <= radius; k++) sum += row[int.Clamp(k, 0, width - 1)]; for (var x = 0; x < width; x++) { output[x] = sum * inv; sum += row[int.Min(x + radius + 1, width - 1)] - row[int.Max(x - radius, 0)]; } }); const int Block = 256; var blocks = (width + Block - 1) / Block; void Columns(int b) { var x0 = b * Block; var n = int.Min(Block, width - x0); Span acc = stackalloc float[Block]; acc = acc[..n]; acc.Clear(); for (var k = -radius; k <= radius; k++) Add(acc, scratch.AsSpan(int.Clamp(k, 0, height - 1) * width + x0, n), 1f); for (var y = 0; y < height; y++) { Scale(acc, destination.AsSpan(y * width + x0, n), inv); Add(acc, scratch.AsSpan(int.Min(y + radius + 1, height - 1) * width + x0, n), 1f); Add(acc, scratch.AsSpan(int.Max(y - radius, 0) * width + x0, n), -1f); } } if ((long)width * height < ParallelThreshold || blocks == 1) { for (var b = 0; b < blocks; b++) Columns(b); } else { Parallel.For(0, blocks, Columns); } } /// Separable 5-tap binomial [1 4 6 4 1]/16 blur (σ = 1 px) with replicated edges; may run in place. public static void Binomial5(float[] source, float[] destination, float[] scratch, int width, int height) { ForRows(height, width, y => { var row = source.AsSpan(y * width, width); var output = scratch.AsSpan(y * width, width); var last = width - 1; for (var x = 0; x < width; x++) { output[x] = (row[int.Max(x - 2, 0)] + row[int.Min(x + 2, last)] + 4 * (row[int.Max(x - 1, 0)] + row[int.Min(x + 1, last)]) + 6 * row[x]) * (1f / 16); } }); ForRows(height, width, y => { var last = height - 1; var r0 = scratch.AsSpan(int.Max(y - 2, 0) * width, width); var r1 = scratch.AsSpan(int.Max(y - 1, 0) * width, width); var r2 = scratch.AsSpan(y * width, width); var r3 = scratch.AsSpan(int.Min(y + 1, last) * width, width); var r4 = scratch.AsSpan(int.Min(y + 2, last) * width, width); var output = destination.AsSpan(y * width, width); var i = 0; if (Vector.IsHardwareAccelerated) { for (; i <= width - Vector.Count; i += Vector.Count) { var sum = new Vector(r0[i..]) + new Vector(r4[i..]) + 4 * (new Vector(r1[i..]) + new Vector(r3[i..])) + 6 * new Vector(r2[i..]); (sum * (1f / 16)).CopyTo(output[i..]); } } for (; i < width; i++) output[i] = (r0[i] + r4[i] + 4 * (r1[i] + r3[i]) + 6 * r2[i]) * (1f / 16); }); } /// /// Median over a (2r+1)² window with replicated edges. Interior pixels run the vectorised sorting network /// on Vector<float> blocks of neighbouring pixels; borders use scalar selection. /// public static void MedianFilter(float[] source, float[] destination, int width, int height, int radius) { ForRows(height, width, y => { var size = 2 * radius + 1; var count = size * size; Span window = stackalloc float[count]; var vc = Vector.Count; var interior = Vector.IsHardwareAccelerated && y >= radius && y < height - radius; Span> lanes = interior ? stackalloc Vector[count] : default; for (var x = 0; x < width;) { if (interior && x >= radius && x + vc + radius <= width) { var n = 0; for (var dy = -radius; dy <= radius; dy++) { var row = (y + dy) * width + x; for (var dx = -radius; dx <= radius; dx++) lanes[n++] = new Vector(source, row + dx); } MedianOfLanes(lanes).CopyTo(destination, y * width + x); x += vc; continue; } var k = 0; for (var dy = -radius; dy <= radius; dy++) { var row = int.Clamp(y + dy, 0, height - 1) * width; for (var dx = -radius; dx <= radius; dx++) window[k++] = source[row + int.Clamp(x + dx, 0, width - 1)]; } destination[y * width + x] = Select(window, count / 2); x++; } }); } /// /// Lane-wise exact median of the vectors (mean of the middle pair for even counts) by odd–even /// transposition sort (Habermann 1972): n passes of branch-free min/max; reorders . /// public static Vector MedianOfLanes(Span> lanes) { var n = lanes.Length; for (var pass = 0; pass < n; pass++) { for (var k = pass & 1; k + 1 < n; k += 2) { var lo = Vector.Min(lanes[k], lanes[k + 1]); lanes[k + 1] = Vector.Max(lanes[k], lanes[k + 1]); lanes[k] = lo; } } return (n & 1) != 0 ? lanes[n / 2] : (lanes[n / 2 - 1] + lanes[n / 2]) * 0.5f; } /// Exact median (mean of the two middle values for even counts); reorders . public static float Median(Span values) { var n = values.Length; var upper = Select(values, n / 2); if ((n & 1) != 0) return upper; // After selection everything left of n/2 is ≤ upper: the lower middle is their maximum. var lower = values[0]; for (var i = 1; i < n / 2; i++) lower = float.Max(lower, values[i]); return 0.5f * (lower + upper); } /// k-th smallest value by Wirth/Hoare selection (in place, O(n) expected). public static float Select(Span values, int k) { int left = 0, right = values.Length - 1; while (left < right) { var pivot = values[k]; int i = left, j = right; do { while (values[i] < pivot) i++; while (pivot < values[j]) j--; if (i <= j) { (values[i], values[j]) = (values[j], values[i]); i++; j--; } } while (i <= j); if (j < k) left = i; if (k < i) right = j; } return values[k]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Add(Span acc, ReadOnlySpan row, float sign) { var i = 0; if (Vector.IsHardwareAccelerated) { var s = new Vector(sign); for (; i <= acc.Length - Vector.Count; i += Vector.Count) (new Vector(acc[i..]) + new Vector(row[i..]) * s).CopyTo(acc[i..]); } for (; i < acc.Length; i++) acc[i] += row[i] * sign; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Scale(ReadOnlySpan acc, Span output, float factor) { var i = 0; if (Vector.IsHardwareAccelerated) { for (; i <= acc.Length - Vector.Count; i += Vector.Count) (new Vector(acc[i..]) * factor).CopyTo(output[i..]); } for (; i < acc.Length; i++) output[i] = acc[i] * factor; } }