Files
Chronos/src/Titano.Core/Motion/PlaneOps.cs
T
Claude 5738fc1694 perf(motion): vectorise the flow median filter and parallelise stabiliser patches
The flow median filter runs the odd-even transposition network on
Vector<float> blocks in the interior (shared with the temporal median),
which removes the dominant cost of Best-quality flow. The stabiliser
analyses its nine patches in parallel with one correlator each and
gathers results in patch order, so output stays deterministic. Adds
brute-force reference tests for the median, box and binomial kernels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-02 09:53:03 +00:00

262 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Numerics;
using System.Runtime.CompilerServices;
using Titano.Core.Imaging;
namespace Titano.Core.Motion;
/// <summary>Row-parallel kernels on single-channel float planes shared by the motion modules.</summary>
internal static class PlaneOps
{
/// <summary>Below this many pixels per pass the Parallel.For overhead outweighs the work.</summary>
public const int ParallelThreshold = 1 << 15;
/// <summary>Runs <paramref name="body"/> for every row, in parallel when the plane is large.</summary>
public static void ForRows(int height, int width, Action<int> body)
{
if ((long)height * width < ParallelThreshold)
{
for (var y = 0; y < height; y++) body(y);
}
else
{
Parallel.For(0, height, body);
}
}
/// <summary>
/// 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.
/// </summary>
public static void PerceptualLuminance(ImageBuffer image, Span<float> destination)
{
ColorSpace.Luminance(image, destination);
for (var i = 0; i < destination.Length; i++) destination[i] = ColorSpace.EncodeFast(destination[i]);
}
/// <summary>Bilinear sample with edge clamping at pixel-centre coordinates.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Bilinear(ReadOnlySpan<float> 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;
}
/// <summary>
/// Mean over a (2r+1)² box with replicated edges, by running sums: horizontal pass per row, then a
/// vertical pass that keeps Vector&lt;float&gt; column sums for blocks of columns.
/// </summary>
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<float> 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);
}
}
/// <summary>Separable 5-tap binomial [1 4 6 4 1]/16 blur (σ = 1 px) with replicated edges; may run in place.</summary>
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<float>.Count; i += Vector<float>.Count)
{
var sum = new Vector<float>(r0[i..]) + new Vector<float>(r4[i..])
+ 4 * (new Vector<float>(r1[i..]) + new Vector<float>(r3[i..]))
+ 6 * new Vector<float>(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);
});
}
/// <summary>
/// Median over a (2r+1)² window with replicated edges. Interior pixels run the vectorised sorting network
/// on Vector&lt;float&gt; blocks of neighbouring pixels; borders use scalar selection.
/// </summary>
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<float> window = stackalloc float[count];
var vc = Vector<float>.Count;
var interior = Vector.IsHardwareAccelerated && y >= radius && y < height - radius;
Span<Vector<float>> lanes = interior ? stackalloc Vector<float>[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<float>(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++;
}
});
}
/// <summary>
/// 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 <paramref name="lanes"/>.
/// </summary>
public static Vector<float> MedianOfLanes(Span<Vector<float>> 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;
}
/// <summary>Exact median (mean of the two middle values for even counts); reorders <paramref name="values"/>.</summary>
public static float Median(Span<float> 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);
}
/// <summary>k-th smallest value by Wirth/Hoare selection (in place, O(n) expected).</summary>
public static float Select(Span<float> 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<float> acc, ReadOnlySpan<float> row, float sign)
{
var i = 0;
if (Vector.IsHardwareAccelerated)
{
var s = new Vector<float>(sign);
for (; i <= acc.Length - Vector<float>.Count; i += Vector<float>.Count)
(new Vector<float>(acc[i..]) + new Vector<float>(row[i..]) * s).CopyTo(acc[i..]);
}
for (; i < acc.Length; i++) acc[i] += row[i] * sign;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void Scale(ReadOnlySpan<float> acc, Span<float> output, float factor)
{
var i = 0;
if (Vector.IsHardwareAccelerated)
{
for (; i <= acc.Length - Vector<float>.Count; i += Vector<float>.Count)
(new Vector<float>(acc[i..]) * factor).CopyTo(output[i..]);
}
for (; i < acc.Length; i++) output[i] = acc[i] * factor;
}
}