refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

+84
View File
@@ -0,0 +1,84 @@
namespace Chronos.Core.Motion;
/// <summary>
/// Cubic Bézier timing curve from (0, 0) to (1, 1) with control points (X1, Y1) and (X2, Y2), as in CSS
/// <c>cubic-bezier()</c>. X1 and X2 must lie in [0, 1] so time is monotonic; Y values may overshoot.
/// </summary>
public readonly record struct BezierEasing
{
public BezierEasing(double x1, double y1, double x2, double y2)
{
if (!(x1 is >= 0 and <= 1) || !(x2 is >= 0 and <= 1)) throw new ArgumentOutOfRangeException(nameof(x1), "Control-point x must be within [0, 1].");
if (!double.IsFinite(y1) || !double.IsFinite(y2)) throw new ArgumentOutOfRangeException(nameof(y1));
(X1, Y1, X2, Y2) = (x1, y1, x2, y2);
}
public double X1 { get; }
public double Y1 { get; }
public double X2 { get; }
public double Y2 { get; }
public static BezierEasing Linear { get; } = new(0, 0, 1, 1);
/// <summary>Starts at rest, arrives at speed.</summary>
public static BezierEasing EaseIn { get; } = new(0.42, 0, 1, 1);
/// <summary>Starts at speed, arrives at rest.</summary>
public static BezierEasing EaseOut { get; } = new(0, 0, 0.58, 1);
/// <summary>At rest at both ends: chains of these segments are C1-continuous.</summary>
public static BezierEasing EaseInOut { get; } = new(0.42, 0, 0.58, 1);
/// <summary>Eased progress y for time fraction t ∈ [0, 1] (exactly 0 and 1 at the ends).</summary>
public double Evaluate(double t)
{
if (t <= 0) return 0;
if (t >= 1) return 1;
return Polynomial(Y1, Y2, Parameter(t));
}
/// <summary>Curve parameter s with x(s) = t: Newton's method from s = t, bisection when it stalls.</summary>
private double Parameter(double t)
{
var s = t;
for (var i = 0; i < 8; i++)
{
var error = Polynomial(X1, X2, s) - t;
if (double.Abs(error) < 1e-12) return s;
var slope = Derivative(X1, X2, s);
if (double.Abs(slope) < 1e-9) break;
var next = s - error / slope;
if (next is < 0 or > 1) break;
s = next;
}
double lo = 0, hi = 1;
s = t;
for (var i = 0; i < 60 && hi - lo > 1e-14; i++)
{
if (Polynomial(X1, X2, s) < t) lo = s;
else hi = s;
s = 0.5 * (lo + hi);
}
return s;
}
/// <summary>B(s) = 3(1−s)²s·p1 + 3(1−s)s²·p2 + s³ in Horner form.</summary>
private static double Polynomial(double p1, double p2, double s)
{
var c = 3 * p1;
var b = 3 * (p2 - p1) - c;
var a = 1 - c - b;
return ((a * s + b) * s + c) * s;
}
private static double Derivative(double p1, double p2, double s)
{
var c = 3 * p1;
var b = 3 * (p2 - p1) - c;
var a = 1 - c - b;
return (3 * a * s + 2 * b) * s + c;
}
}
+276
View File
@@ -0,0 +1,276 @@
using System.Buffers;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Chronos.Core.Motion;
/// <summary>
/// Precomputed complex DFT of one length on split real/imaginary arrays: iterative radix-2
/// Cooley–Tukey (1965) for powers of two, Bluestein (1970) chirp-z convolution otherwise.
/// Forward uses e^(−2πikn/N); <see cref="Inverse(Span{double}, Span{double})"/> is normalised by 1/N.
/// Immutable and thread-safe; obtain shared instances from <see cref="Fourier.Plan"/>.
/// </summary>
public sealed class FftPlan
{
private readonly int[]? _bitReverse;
// Stage-major twiddles: the stage with half-size h occupies [h − 1, 2h − 1), so SIMD loads are contiguous.
private readonly double[]? _twiddleRe, _twiddleIm;
private readonly FftPlan? _convolution;
private readonly double[]? _chirpRe, _chirpIm;
private readonly double[]? _kernelRe, _kernelIm;
internal FftPlan(int length)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(length);
Length = length;
IsPowerOfTwo = BitOperations.IsPow2(length);
// e^(−iπk/N), k = 0..N: the post-processing twiddles of a real transform of length 2N.
HalfTwiddleRe = new double[length + 1];
HalfTwiddleIm = new double[length + 1];
for (var k = 0; k <= length; k++)
{
var (s, c) = double.SinCos(double.Pi * k / length);
HalfTwiddleRe[k] = c;
HalfTwiddleIm[k] = -s;
}
if (IsPowerOfTwo)
{
var bits = BitOperations.Log2((uint)length);
_bitReverse = new int[length];
for (var i = 0; i < length; i++)
_bitReverse[i] = bits == 0 ? 0 : (int)(ReverseBits((uint)i) >> (32 - bits));
_twiddleRe = new double[int.Max(1, length - 1)];
_twiddleIm = new double[_twiddleRe.Length];
for (var h = 1; h < length; h <<= 1)
{
for (var k = 0; k < h; k++)
{
var (s, c) = double.SinCos(double.Pi * k / h);
_twiddleRe[h - 1 + k] = c;
_twiddleIm[h - 1 + k] = -s;
}
}
return;
}
// Bluestein: X_k = c_k · Σ_n (x_n c_n) · conj(c_(k−n)), c_k = e^(−iπk²/N), as a power-of-two circular convolution.
var m = (int)BitOperations.RoundUpToPowerOf2((uint)(2 * length - 1));
_convolution = Fourier.Plan(m);
ScratchLength = 2 * m;
_chirpRe = new double[length];
_chirpIm = new double[length];
_kernelRe = new double[m];
_kernelIm = new double[m];
for (var k = 0; k < length; k++)
{
// k² mod 2N keeps the angle argument small and exact for large N.
var q = (long)k * k % (2L * length);
var (s, c) = double.SinCos(double.Pi * q / length);
_chirpRe[k] = c;
_chirpIm[k] = -s;
_kernelRe[k] = c;
_kernelIm[k] = s;
if (k > 0)
{
_kernelRe[m - k] = c;
_kernelIm[m - k] = s;
}
}
_convolution.Radix2(_kernelRe, _kernelIm);
var scale = 1.0 / m;
for (var i = 0; i < m; i++)
{
_kernelRe[i] *= scale;
_kernelIm[i] *= scale;
}
}
/// <summary>Transform length N.</summary>
public int Length { get; }
/// <summary>True when the radix-2 path is used.</summary>
public bool IsPowerOfTwo { get; }
/// <summary>Doubles of scratch the scratch-taking overloads need (0 for powers of two).</summary>
public int ScratchLength { get; }
internal double[] HalfTwiddleRe { get; }
internal double[] HalfTwiddleIm { get; }
/// <summary>In-place forward DFT. Bluestein lengths rent their scratch from the shared pool.</summary>
public void Forward(Span<double> re, Span<double> im)
{
if (ScratchLength == 0)
{
Forward(re, im, Span<double>.Empty);
return;
}
var scratch = ArrayPool<double>.Shared.Rent(ScratchLength);
try
{
Forward(re, im, scratch);
}
finally
{
ArrayPool<double>.Shared.Return(scratch);
}
}
/// <summary>In-place forward DFT using caller-provided scratch of at least <see cref="ScratchLength"/> doubles.</summary>
public void Forward(Span<double> re, Span<double> im, Span<double> scratch)
{
CheckLengths(re, im, scratch);
if (IsPowerOfTwo) Radix2(re, im);
else Bluestein(re, im, scratch);
}
/// <summary>In-place inverse DFT, normalised by 1/N.</summary>
public void Inverse(Span<double> re, Span<double> im)
{
// Swapping the real and imaginary parts turns a forward DFT into an unnormalised inverse one.
Forward(im, re);
Scale(re, im, 1.0 / Length);
}
/// <summary>In-place inverse DFT (normalised by 1/N) using caller-provided scratch.</summary>
public void Inverse(Span<double> re, Span<double> im, Span<double> scratch)
{
Forward(im, re, scratch);
Scale(re, im, 1.0 / Length);
}
/// <summary>Unnormalised radix-2 transform; the caller guarantees a power-of-two length.</summary>
internal void Radix2(Span<double> re, Span<double> im)
{
var n = Length;
var rev = _bitReverse!;
for (var i = 0; i < n; i++)
{
var j = rev[i];
if (j <= i) continue;
(re[i], re[j]) = (re[j], re[i]);
(im[i], im[j]) = (im[j], im[i]);
}
ref var r0 = ref MemoryMarshal.GetReference(re);
ref var i0 = ref MemoryMarshal.GetReference(im);
ref var wr0 = ref MemoryMarshal.GetArrayDataReference(_twiddleRe!);
ref var wi0 = ref MemoryMarshal.GetArrayDataReference(_twiddleIm!);
var vc = Vector<double>.Count;
for (var h = 1; h < n; h <<= 1)
{
ref var wr = ref Unsafe.Add(ref wr0, h - 1);
ref var wi = ref Unsafe.Add(ref wi0, h - 1);
for (var start = 0; start < n; start += h << 1)
{
ref var ar = ref Unsafe.Add(ref r0, start);
ref var ai = ref Unsafe.Add(ref i0, start);
ref var br = ref Unsafe.Add(ref r0, start + h);
ref var bi = ref Unsafe.Add(ref i0, start + h);
var k = 0;
if (Vector.IsHardwareAccelerated && h >= vc)
{
// h and vc are powers of two, so h is a multiple of vc: no remainder loop needed.
for (; k < h; k += vc)
{
var u = (nuint)k;
var cr = Vector.LoadUnsafe(ref wr, u);
var ci = Vector.LoadUnsafe(ref wi, u);
var xr = Vector.LoadUnsafe(ref br, u);
var xi = Vector.LoadUnsafe(ref bi, u);
var tr = xr * cr - xi * ci;
var ti = xr * ci + xi * cr;
var yr = Vector.LoadUnsafe(ref ar, u);
var yi = Vector.LoadUnsafe(ref ai, u);
(yr - tr).StoreUnsafe(ref br, u);
(yi - ti).StoreUnsafe(ref bi, u);
(yr + tr).StoreUnsafe(ref ar, u);
(yi + ti).StoreUnsafe(ref ai, u);
}
}
for (; k < h; k++)
{
var cr = Unsafe.Add(ref wr, k);
var ci = Unsafe.Add(ref wi, k);
ref var xr = ref Unsafe.Add(ref br, k);
ref var xi = ref Unsafe.Add(ref bi, k);
ref var yr = ref Unsafe.Add(ref ar, k);
ref var yi = ref Unsafe.Add(ref ai, k);
var tr = xr * cr - xi * ci;
var ti = xr * ci + xi * cr;
xr = yr - tr;
xi = yi - ti;
yr += tr;
yi += ti;
}
}
}
}
private void Bluestein(Span<double> re, Span<double> im, Span<double> scratch)
{
var n = Length;
var conv = _convolution!;
var m = conv.Length;
var ar = scratch[..m];
var ai = scratch.Slice(m, m);
var cr = _chirpRe!;
var ci = _chirpIm!;
for (var k = 0; k < n; k++)
{
ar[k] = re[k] * cr[k] - im[k] * ci[k];
ai[k] = re[k] * ci[k] + im[k] * cr[k];
}
ar[n..].Clear();
ai[n..].Clear();
conv.Radix2(ar, ai);
var kr = _kernelRe!;
var ki = _kernelIm!;
for (var k = 0; k < m; k++)
{
var xr = ar[k];
var xi = ai[k];
ar[k] = xr * kr[k] - xi * ki[k];
ai[k] = xr * ki[k] + xi * kr[k];
}
// Unnormalised inverse via the real/imaginary swap; 1/M is folded into the kernel.
conv.Radix2(ai, ar);
for (var k = 0; k < n; k++)
{
re[k] = ar[k] * cr[k] - ai[k] * ci[k];
im[k] = ar[k] * ci[k] + ai[k] * cr[k];
}
}
private void CheckLengths(Span<double> re, Span<double> im, Span<double> scratch)
{
if (re.Length != Length || im.Length != Length)
throw new ArgumentException($"Expected {Length} samples, got {re.Length} and {im.Length}.");
if (scratch.Length < ScratchLength)
throw new ArgumentException($"Scratch must hold {ScratchLength} doubles.", nameof(scratch));
}
private static void Scale(Span<double> re, Span<double> im, double factor)
{
for (var i = 0; i < re.Length; i++)
{
re[i] *= factor;
im[i] *= factor;
}
}
private static uint ReverseBits(uint v)
{
v = ((v >> 1) & 0x55555555u) | ((v & 0x55555555u) << 1);
v = ((v >> 2) & 0x33333333u) | ((v & 0x33333333u) << 2);
v = ((v >> 4) & 0x0F0F0F0Fu) | ((v & 0x0F0F0F0Fu) << 4);
v = ((v >> 8) & 0x00FF00FFu) | ((v & 0x00FF00FFu) << 8);
return (v >> 16) | (v << 16);
}
}
+269
View File
@@ -0,0 +1,269 @@
using System.Buffers;
using System.Collections.Concurrent;
namespace Chronos.Core.Motion;
/// <summary>
/// Discrete Fourier transforms on split real/imaginary <see cref="double"/> arrays: cached
/// <see cref="FftPlan"/>s (twiddles computed once per length), separable 2D transforms (rows then
/// columns, parallel for large images), real-input transforms through the half-length packing trick,
/// and analysis windows.
/// </summary>
public static class Fourier
{
// Below this many samples a 2D transform is cheaper than the Parallel.For overhead.
private const int ParallelThreshold = 1 << 15;
private static readonly ConcurrentDictionary<int, FftPlan> Plans = new();
/// <summary>Shared, thread-safe plan for the given length.</summary>
public static FftPlan Plan(int length)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(length);
return Plans.GetOrAdd(length, static n => new FftPlan(n));
}
/// <summary>In-place forward DFT of any length.</summary>
public static void Forward(Span<double> re, Span<double> im) => Plan(re.Length).Forward(re, im);
/// <summary>In-place inverse DFT of any length, normalised by 1/N.</summary>
public static void Inverse(Span<double> re, Span<double> im) => Plan(re.Length).Inverse(re, im);
/// <summary>In-place forward 2D DFT of a row-major <paramref name="width"/>×<paramref name="height"/> array.</summary>
public static void Forward2D(double[] re, double[] im, int width, int height) => Transform2D(re, im, width, height, inverse: false);
/// <summary>In-place inverse 2D DFT, normalised by 1/(width·height).</summary>
public static void Inverse2D(double[] re, double[] im, int width, int height) => Transform2D(re, im, width, height, inverse: true);
/// <summary>
/// Spectrum bins 0..N/2 of a real signal. Even lengths run one complex transform of length N/2
/// (even samples as real part, odd samples as imaginary part) and split it with the standard
/// post-processing butterflies; odd lengths fall back to a full complex transform.
/// </summary>
public static void ForwardReal(ReadOnlySpan<double> signal, Span<double> re, Span<double> im)
{
var n = signal.Length;
ArgumentOutOfRangeException.ThrowIfZero(n, nameof(signal));
var bins = n / 2 + 1;
if (re.Length < bins || im.Length < bins) throw new ArgumentException($"Spectrum spans must hold {bins} bins.");
if (n == 1)
{
re[0] = signal[0];
im[0] = 0;
return;
}
if ((n & 1) != 0)
{
var buffer = ArrayPool<double>.Shared.Rent(2 * n);
try
{
var fr = buffer.AsSpan(0, n);
var fi = buffer.AsSpan(n, n);
signal.CopyTo(fr);
fi.Clear();
Plan(n).Forward(fr, fi);
fr[..bins].CopyTo(re);
fi[..bins].CopyTo(im);
}
finally
{
ArrayPool<double>.Shared.Return(buffer);
}
return;
}
var m = n / 2;
for (var j = 0; j < m; j++)
{
re[j] = signal[2 * j];
im[j] = signal[2 * j + 1];
}
var plan = Plan(m);
plan.Forward(re[..m], im[..m]);
re[m] = re[0];
im[m] = im[0];
var wr = plan.HalfTwiddleRe;
var wi = plan.HalfTwiddleIm;
for (var k = 0; k <= m / 2; k++)
{
var k2 = m - k;
double zr = re[k], zi = im[k], yr = re[k2], yi = im[k2];
// E = (Z_k + conj Z_(m−k)) / 2 is the even-sample spectrum, O = (Z_k − conj Z_(m−k)) / 2i the odd one.
var er = 0.5 * (zr + yr);
var ei = 0.5 * (zi - yi);
var or = 0.5 * (zi + yi);
var oi = -0.5 * (zr - yr);
re[k] = er + wr[k] * or - wi[k] * oi;
im[k] = ei + wr[k] * oi + wi[k] * or;
// X_(m−k) = conj E + W^(m−k) conj O.
re[k2] = er + wr[k2] * or + wi[k2] * oi;
im[k2] = -ei + wi[k2] * or - wr[k2] * oi;
}
}
/// <summary>Inverse of <see cref="ForwardReal"/>: real signal of length <c>signal.Length</c> from bins 0..N/2.</summary>
public static void InverseReal(ReadOnlySpan<double> re, ReadOnlySpan<double> im, Span<double> signal)
{
var n = signal.Length;
ArgumentOutOfRangeException.ThrowIfZero(n, nameof(signal));
var bins = n / 2 + 1;
if (re.Length < bins || im.Length < bins) throw new ArgumentException($"Spectrum spans must hold {bins} bins.");
if (n == 1)
{
signal[0] = re[0];
return;
}
var odd = (n & 1) != 0;
var buffer = ArrayPool<double>.Shared.Rent(odd ? 2 * n : n);
try
{
if (odd)
{
var fr = buffer.AsSpan(0, n);
var fi = buffer.AsSpan(n, n);
for (var k = 0; k < bins; k++)
{
fr[k] = re[k];
fi[k] = im[k];
if (k == 0) continue;
fr[n - k] = re[k];
fi[n - k] = -im[k];
}
Plan(n).Inverse(fr, fi);
fr.CopyTo(signal);
return;
}
var m = n / 2;
var zr = buffer.AsSpan(0, m);
var zi = buffer.AsSpan(m, m);
var plan = Plan(m);
var wr = plan.HalfTwiddleRe;
var wi = plan.HalfTwiddleIm;
for (var k = 0; k < m; k++)
{
// E = (X_k + conj X_(m−k)) / 2, O = (X_k − conj X_(m−k)) · conj(W^k) / 2, Z = E + iO.
double xr = re[k], xi = im[k], yr = re[m - k], yi = -im[m - k];
var er = 0.5 * (xr + yr);
var ei = 0.5 * (xi + yi);
var dr = 0.5 * (xr - yr);
var di = 0.5 * (xi - yi);
var or = dr * wr[k] + di * wi[k];
var oi = di * wr[k] - dr * wi[k];
zr[k] = er - oi;
zi[k] = ei + or;
}
plan.Inverse(zr, zi);
for (var j = 0; j < m; j++)
{
signal[2 * j] = zr[j];
signal[2 * j + 1] = zi[j];
}
}
finally
{
ArrayPool<double>.Shared.Return(buffer);
}
}
/// <summary>Symmetric Hann window (zero at both ends).</summary>
public static void Hann(Span<double> window) => Tukey(window, 1.0);
/// <summary>
/// Symmetric Tukey (tapered cosine) window: flat top with raised-cosine flanks covering a fraction
/// <paramref name="alpha"/> of the length; 0 is rectangular, 1 is Hann.
/// </summary>
public static void Tukey(Span<double> window, double alpha)
{
ArgumentOutOfRangeException.ThrowIfLessThan(alpha, 0.0);
ArgumentOutOfRangeException.ThrowIfGreaterThan(alpha, 1.0);
var n = window.Length;
if (n == 1 || alpha == 0)
{
window.Fill(1.0);
return;
}
var half = alpha / 2;
for (var i = 0; i < n; i++)
{
var x = i / (double)(n - 1);
var edge = double.Min(x, 1 - x);
window[i] = edge >= half ? 1.0 : 0.5 * (1 - double.Cos(double.Pi * edge / half));
}
}
private static void Transform2D(double[] re, double[] im, int width, int height, bool inverse)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
var length = checked(width * height);
if (re.Length < length || im.Length < length) throw new ArgumentException($"Arrays must hold {length} samples.");
// The inverse is the forward transform with real and imaginary parts swapped, then scaled.
var (a, b) = inverse ? (im, re) : (re, im);
var rows = Plan(width);
var columns = Plan(height);
if (length < ParallelThreshold)
{
var scratch = ArrayPool<double>.Shared.Rent(int.Max(rows.ScratchLength, 2 * height + columns.ScratchLength));
try
{
for (var y = 0; y < height; y++) rows.Forward(a.AsSpan(y * width, width), b.AsSpan(y * width, width), scratch);
for (var x = 0; x < width; x++) TransformColumn(a, b, width, height, x, columns, scratch);
}
finally
{
ArrayPool<double>.Shared.Return(scratch);
}
}
else
{
Parallel.For(
0,
height,
() => ArrayPool<double>.Shared.Rent(int.Max(1, rows.ScratchLength)),
(y, _, scratch) =>
{
rows.Forward(a.AsSpan(y * width, width), b.AsSpan(y * width, width), scratch);
return scratch;
},
scratch => ArrayPool<double>.Shared.Return(scratch));
Parallel.For(
0,
width,
() => ArrayPool<double>.Shared.Rent(2 * height + columns.ScratchLength),
(x, _, scratch) =>
{
TransformColumn(a, b, width, height, x, columns, scratch);
return scratch;
},
scratch => ArrayPool<double>.Shared.Return(scratch));
}
if (!inverse) return;
var scale = 1.0 / length;
for (var i = 0; i < length; i++)
{
re[i] *= scale;
im[i] *= scale;
}
}
private static void TransformColumn(double[] re, double[] im, int width, int height, int x, FftPlan plan, double[] scratch)
{
var cr = scratch.AsSpan(0, height);
var ci = scratch.AsSpan(height, height);
for (int y = 0, i = x; y < height; y++, i += width)
{
cr[y] = re[i];
ci[y] = im[i];
}
plan.Forward(cr, ci, scratch.AsSpan(2 * height));
for (int y = 0, i = x; y < height; y++, i += width)
{
re[i] = cr[y];
im[i] = ci[y];
}
}
}
@@ -0,0 +1,150 @@
using System.Runtime.Intrinsics;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Geometry;
namespace Chronos.Core.Motion;
/// <summary>
/// Synthesises a frame at fractional time t between frames A and B from the bidirectional flow. The
/// content at output pixel x moves with one of two candidate velocities: A's flow at x, or B's reversed
/// flow at x (they differ only near motion boundaries, where each belongs to a different object). Each
/// candidate v gives the samples A(x − t·v) and B(x + (1−t)·v); the candidate whose path is forward–backward
/// consistent through both frames, |F(A→B)(x − t·v) − v| + |F(B→A)(x + (1−t)·v) + v| smallest, is taken.
/// The two Catmull-Rom samples are blended by (1−t, t), each weighted by how well its own flow agrees with v,
/// so a sample that is occluded in the other frame or belongs to another object drops out (occlusion
/// reasoning after Baker et al. 2011).
/// </summary>
public sealed class FrameInterpolator : IDisposable
{
private readonly OpticalFlowEngine _engine;
public FrameInterpolator(FlowQuality quality = FlowQuality.Best) => _engine = new OpticalFlowEngine(quality);
/// <summary>Flow disagreement (px) at which a sample's weight halves.</summary>
public double OcclusionThreshold { get; init; } = 3.0;
/// <summary>Computes both flows and writes the frame at <paramref name="t"/> ∈ [0, 1] into <paramref name="destination"/>.</summary>
public void Interpolate(ImageBuffer a, ImageBuffer b, double t, ImageBuffer destination, CancellationToken cancellationToken = default)
{
var (forward, backward) = _engine.ComputeBidirectional(a, b, cancellationToken);
using (forward)
using (backward)
{
Synthesize(a, b, forward, backward, t, destination, OcclusionThreshold, cancellationToken);
}
}
/// <summary>Frame at <paramref name="t"/> from precomputed flows (forward = A→B, backward = B→A).</summary>
public static void Synthesize(ImageBuffer a, ImageBuffer b, MotionField forward, MotionField backward, double t, ImageBuffer destination,
double occlusionThreshold = 3.0, CancellationToken cancellationToken = default)
{
if (b.Width != a.Width || b.Height != a.Height || b.Channels != a.Channels
|| destination.Width != a.Width || destination.Height != a.Height || destination.Channels != a.Channels)
throw new ArgumentException("Frames and destination must share size and channels.", nameof(destination));
if (!(t is >= 0 and <= 1)) throw new ArgumentOutOfRangeException(nameof(t), "t must lie in [0, 1].");
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(occlusionThreshold);
var w = a.Width;
var h = a.Height;
var channels = a.Channels;
var tau2 = occlusionThreshold * occlusionThreshold;
var dst = destination.Storage;
var plane = destination.PlaneLength;
void Row(int y)
{
Span<float> va = stackalloc float[4];
Span<float> vb = stackalloc float[4];
for (var x = 0; x < w; x++)
{
// Candidate velocities: A's motion at x, and B's motion at x reversed.
var (fu, fv) = forward.Sample(x, y);
var (bu, bv) = backward.Sample(x, y);
var errorF = PathError(forward, backward, x, y, fu, fv, t, out var agreeAF, out var agreeBF);
var errorB = PathError(forward, backward, x, y, -bu, -bv, t, out var agreeAB, out var agreeBB);
var useForward = errorF <= errorB;
double vu = useForward ? fu : -bu, vv = useForward ? fv : -bv;
var ax = x - t * vu;
var ay = y - t * vv;
var bx = x + (1 - t) * vu;
var by = y + (1 - t) * vv;
var wa = (1 - t) * Reliability(useForward ? agreeAF : agreeAB, tau2);
var wb = t * Reliability(useForward ? agreeBF : agreeBB, tau2);
if (wa + wb < 1e-6)
{
wa = 1 - t;
wb = t;
}
var norm = 1 / (wa + wb);
wa *= norm;
wb *= norm;
var o = y * w + x;
va.Clear();
vb.Clear();
if (wa > 0) CatmullRom(a, ax, ay, va);
if (wb > 0) CatmullRom(b, bx, by, vb);
for (var c = 0; c < channels; c++) dst[c * plane + o] = (float)(wa * va[c] + wb * vb[c]);
}
}
if ((long)w * h < PlaneOps.ParallelThreshold)
{
for (var y = 0; y < h; y++)
{
cancellationToken.ThrowIfCancellationRequested();
Row(y);
}
}
else
{
Parallel.For(0, h, new ParallelOptions { CancellationToken = cancellationToken }, Row);
}
}
public void Dispose() => _engine.Dispose();
private static double Reliability(double disagreement, double tau2) => tau2 / (tau2 + disagreement * disagreement);
/// <summary>
/// Forward–backward consistency of moving with velocity (vu, vv) through x at time t: how far A's flow at
/// the A sample and B's reversed flow at the B sample are from that velocity.
/// </summary>
private static double PathError(MotionField forward, MotionField backward, int x, int y, double vu, double vv, double t, out double agreeA, out double agreeB)
{
var (au, av) = forward.Sample(x - t * vu, y - t * vv);
var (bu, bv) = backward.Sample(x + (1 - t) * vu, y + (1 - t) * vv);
agreeA = double.Hypot(au - vu, av - vv);
agreeB = double.Hypot(bu + vu, bv + vv);
return agreeA + agreeB;
}
/// <summary>Adds the clamped Catmull-Rom sample of every channel at pixel-centre coordinates to <paramref name="values"/>.</summary>
private static void CatmullRom(ImageBuffer image, double x, double y, Span<float> values)
{
var w = image.Width;
var h = image.Height;
x = double.Clamp(x, 0, w - 1);
y = double.Clamp(y, 0, h - 1);
var fx = double.Floor(x);
var fy = double.Floor(y);
var ix = (int)fx;
var iy = (int)fy;
var wx = GeometryStage.CatmullRomWeights((float)(x - fx));
var wy = GeometryStage.CatmullRomWeights((float)(y - fy));
var data = image.Storage;
var plane = image.PlaneLength;
for (var j = 0; j < 4; j++)
{
var row = int.Clamp(iy - 1 + j, 0, h - 1) * w;
for (var i = 0; i < 4; i++)
{
var weight = wy.GetElement(j) * wx.GetElement(i);
if (weight == 0) continue;
var s = row + int.Clamp(ix - 1 + i, 0, w - 1);
for (var c = 0; c < image.Channels; c++) values[c] += weight * data[c * plane + s];
}
}
}
}
+144
View File
@@ -0,0 +1,144 @@
using System.Buffers;
using System.Numerics;
using Chronos.Core.Imaging;
namespace Chronos.Core.Motion;
/// <summary>
/// Gaussian pyramid of a single-channel plane (Burt &amp; Adelson 1983): each level is the previous one
/// filtered with the 5-tap binomial [1 4 6 4 1]/16 (replicated edges) and decimated by 2, keeping even
/// samples, so level-ℓ pixel k sits at full-resolution coordinate k·2^ℓ. Planes are pooled and reused
/// by every <see cref="Build(ReadOnlySpan{float})"/>.
/// </summary>
public sealed class GrayPyramid : IDisposable
{
private readonly float[][] _levels;
private readonly int[] _widths;
private readonly int[] _heights;
private float[]? _scratch;
public GrayPyramid(int width, int height, int levels)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(levels);
Width = width;
Height = height;
Levels = levels;
_levels = new float[levels][];
_widths = new int[levels];
_heights = new int[levels];
for (var l = 0; l < levels; l++)
{
_widths[l] = l == 0 ? width : (_widths[l - 1] + 1) / 2;
_heights[l] = l == 0 ? height : (_heights[l - 1] + 1) / 2;
_levels[l] = ArrayPool<float>.Shared.Rent(_widths[l] * _heights[l]);
}
_scratch = ArrayPool<float>.Shared.Rent(int.Max(1, _widths[int.Min(1, levels - 1)] * height));
}
public int Width { get; }
public int Height { get; }
public int Levels { get; }
/// <summary>Levels needed until the smaller side would drop below <paramref name="minimumSize"/>, capped.</summary>
public static int LevelsFor(int width, int height, int minimumSize = 16, int maximumLevels = 8)
{
var levels = 1;
while (levels < maximumLevels && (int.Min(width, height) + 1) / 2 >= minimumSize)
{
width = (width + 1) / 2;
height = (height + 1) / 2;
levels++;
}
return levels;
}
public int LevelWidth(int level) => _widths[level];
public int LevelHeight(int level) => _heights[level];
/// <summary>Row-major samples of one level.</summary>
public ReadOnlySpan<float> Level(int level) => LevelArray(level).AsSpan(0, _widths[level] * _heights[level]);
internal float[] LevelArray(int level)
{
ObjectDisposedException.ThrowIf(_scratch is null, this);
return _levels[level];
}
/// <summary>Builds the pyramid from a plane of <see cref="Width"/>×<see cref="Height"/> samples.</summary>
public void Build(ReadOnlySpan<float> plane)
{
if (plane.Length < Width * Height) throw new ArgumentException("Plane is smaller than the pyramid base.", nameof(plane));
plane[..(Width * Height)].CopyTo(LevelArray(0));
BuildUpperLevels();
}
/// <summary>Builds the pyramid from the perceptual (sRGB-encoded) luminance of an image.</summary>
public void Build(ImageBuffer image)
{
if (image.Width != Width || image.Height != Height) throw new ArgumentException("Image size differs from the pyramid.", nameof(image));
PlaneOps.PerceptualLuminance(image, LevelArray(0).AsSpan(0, Width * Height));
BuildUpperLevels();
}
public void Dispose()
{
var scratch = Interlocked.Exchange(ref _scratch, null);
if (scratch is null) return;
ArrayPool<float>.Shared.Return(scratch);
foreach (var level in _levels) ArrayPool<float>.Shared.Return(level);
}
private void BuildUpperLevels()
{
for (var l = 1; l < Levels; l++) Downsample(_levels[l - 1], _widths[l - 1], _heights[l - 1], _levels[l], _widths[l], _heights[l], _scratch!);
}
private static void Downsample(float[] source, int width, int height, float[] destination, int halfWidth, int halfHeight, float[] scratch)
{
// Horizontal: filter and keep even columns (scratch is halfWidth × height).
PlaneOps.ForRows(height, width, y =>
{
var row = source.AsSpan(y * width, width);
var output = scratch.AsSpan(y * halfWidth, halfWidth);
var last = width - 1;
for (var k = 0; k < halfWidth; k++)
{
var x = 2 * k;
output[k] = (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[int.Min(x, last)]) * (1f / 16);
}
});
// Vertical: five rows combined per output row, vectorised across columns.
PlaneOps.ForRows(halfHeight, halfWidth, k =>
{
var y = 2 * k;
var last = height - 1;
var r0 = scratch.AsSpan(int.Max(y - 2, 0) * halfWidth, halfWidth);
var r1 = scratch.AsSpan(int.Max(y - 1, 0) * halfWidth, halfWidth);
var r2 = scratch.AsSpan(int.Min(y, last) * halfWidth, halfWidth);
var r3 = scratch.AsSpan(int.Min(y + 1, last) * halfWidth, halfWidth);
var r4 = scratch.AsSpan(int.Min(y + 2, last) * halfWidth, halfWidth);
var output = destination.AsSpan(k * halfWidth, halfWidth);
var i = 0;
if (Vector.IsHardwareAccelerated)
{
var vc = Vector<float>.Count;
for (; i <= halfWidth - vc; i += vc)
{
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 < halfWidth; i++) output[i] = (r0[i] + r4[i] + 4 * (r1[i] + r3[i]) + 6 * r2[i]) * (1f / 16);
});
}
}
@@ -0,0 +1,143 @@
using Chronos.Core.Imaging;
namespace Chronos.Core.Motion;
/// <summary>Shutter-angle arithmetic for synthetic motion blur.</summary>
public static class ShutterAngle
{
/// <summary>Shutter angle actually used by the camera, 360° × exposure / interval.</summary>
public static double FromExposure(double exposureSeconds, double intervalSeconds)
{
ArgumentOutOfRangeException.ThrowIfNegative(exposureSeconds);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(intervalSeconds);
return 360.0 * exposureSeconds / intervalSeconds;
}
/// <summary>
/// Fraction of the frame-to-frame motion to smear so that the real exposure composed with the synthetic
/// blur behaves like the target shutter: √(target² − real²) / 360, and 0 when the real angle already
/// reaches the target (the blur would only be added on top of blur that is already there).
/// </summary>
public static double BlurFraction(double targetDegrees, double realDegrees)
{
ArgumentOutOfRangeException.ThrowIfNegative(targetDegrees);
ArgumentOutOfRangeException.ThrowIfNegative(realDegrees);
if (realDegrees >= targetDegrees) return 0;
return double.Sqrt(targetDegrees * targetDegrees - realDegrees * realDegrees) / 360.0;
}
}
/// <summary>Tuning for <see cref="MotionBlurRenderer"/>.</summary>
public sealed record MotionBlurOptions
{
/// <summary>Samples per pixel of blur length (≥ 1 keeps the bilinear taps overlapping).</summary>
public double TapsPerPixel { get; init; } = 1.0;
/// <summary>Upper bound on samples per pixel.</summary>
public int MaxTaps { get; init; } = 64;
}
/// <summary>
/// Motion blur by a gather filter: every output pixel averages bilinear samples of the source along a
/// segment centred on it, oriented by its motion vector and as long as the vector times the blur fraction
/// (a box shutter: uniform weights, tap count adaptive to the length). Equal weights and bilinear taps
/// preserve energy; zero vectors copy the pixel. Rows run in parallel.
/// </summary>
public sealed class MotionBlurRenderer
{
private const double MinimumLength = 1e-3;
public MotionBlurRenderer(MotionBlurOptions? options = null)
{
Options = options ?? new MotionBlurOptions();
ArgumentOutOfRangeException.ThrowIfLessThan(Options.TapsPerPixel, 0.25);
ArgumentOutOfRangeException.ThrowIfLessThan(Options.MaxTaps, 2);
}
public MotionBlurOptions Options { get; }
/// <summary>
/// Renders <paramref name="source"/> blurred along <paramref name="motion"/> (frame-to-frame vectors)
/// scaled by <paramref name="blurFraction"/> (see <see cref="ShutterAngle.BlurFraction"/>).
/// </summary>
public void Render(ImageBuffer source, MotionField motion, double blurFraction, ImageBuffer destination, CancellationToken cancellationToken = default)
{
if (destination.Width != source.Width || destination.Height != source.Height || destination.Channels != source.Channels)
throw new ArgumentException("Destination must match the source.", nameof(destination));
if (motion.ImageWidth != source.Width || motion.ImageHeight != source.Height)
throw new ArgumentException("Motion field describes a different image size.", nameof(motion));
ArgumentOutOfRangeException.ThrowIfNegative(blurFraction);
if (blurFraction == 0)
{
source.CopyTo(destination);
return;
}
var w = source.Width;
var h = source.Height;
var channels = source.Channels;
var plane = source.PlaneLength;
var src = source.Storage;
var dst = destination.Storage;
var tapsPerPixel = Options.TapsPerPixel;
var maxTaps = Options.MaxTaps;
void Row(int y)
{
Span<float> sum = stackalloc float[4];
for (var x = 0; x < w; x++)
{
var o = y * w + x;
var (mu, mv) = motion.Sample(x, y);
var du = mu * blurFraction;
var dv = mv * blurFraction;
var length = double.Sqrt(du * du + dv * dv);
if (length < MinimumLength)
{
for (var c = 0; c < channels; c++) dst[c * plane + o] = src[c * plane + o];
continue;
}
var taps = int.Clamp((int)double.Ceiling(length * tapsPerPixel) + 1, 2, maxTaps);
sum.Clear();
for (var k = 0; k < taps; k++)
{
var t = k / (double)(taps - 1) - 0.5;
var sx = double.Clamp(x + t * du, 0, w - 1);
var sy = double.Clamp(y + t * dv, 0, h - 1);
var x0 = int.Min((int)sx, int.Max(w - 2, 0));
var y0 = int.Min((int)sy, int.Max(h - 2, 0));
var x1 = int.Min(x0 + 1, w - 1);
var y1 = int.Min(y0 + 1, h - 1);
var fx = (float)(sx - x0);
var fy = (float)(sy - y0);
var w00 = (1 - fx) * (1 - fy);
var w10 = fx * (1 - fy);
var w01 = (1 - fx) * fy;
var w11 = fx * fy;
int i00 = y0 * w + x0, i10 = y0 * w + x1, i01 = y1 * w + x0, i11 = y1 * w + x1;
for (var c = 0; c < channels; c++)
{
var p = c * plane;
sum[c] += w00 * src[p + i00] + w10 * src[p + i10] + w01 * src[p + i01] + w11 * src[p + i11];
}
}
var inv = 1f / taps;
for (var c = 0; c < channels; c++) dst[c * plane + o] = sum[c] * inv;
}
}
if ((long)w * h < PlaneOps.ParallelThreshold)
{
for (var y = 0; y < h; y++)
{
cancellationToken.ThrowIfCancellationRequested();
Row(y);
}
}
else
{
Parallel.For(0, h, new ParallelOptions { CancellationToken = cancellationToken }, Row);
}
}
}
+154
View File
@@ -0,0 +1,154 @@
using System.Buffers;
namespace Chronos.Core.Motion;
/// <summary>Summary of a motion field's vector magnitudes (pixels per frame).</summary>
public readonly record struct MotionStatistics(
double MeanMagnitude,
double MedianMagnitude,
double P95Magnitude,
double MaxMagnitude,
double MeanU,
double MeanV,
double ReliableFraction);
/// <summary>
/// Dense motion vectors (full-resolution pixels per frame) on a regular grid: node (i, j) describes the
/// pixel at (i·Step, j·Step). A vector (u, v) at p means the content at p in the first frame is found at
/// p + (u, v) in the second. <see cref="Error"/> holds the forward–backward consistency error in pixels
/// (NaN when not checked). Storage is pooled; dispose the field when done.
/// </summary>
public sealed class MotionField : IDisposable
{
private float[]? _u;
private float[]? _v;
private float[]? _error;
public MotionField(int imageWidth, int imageHeight, int step)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(imageWidth);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(imageHeight);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(step);
ImageWidth = imageWidth;
ImageHeight = imageHeight;
Step = step;
Columns = (imageWidth - 1) / step + 1;
Rows = (imageHeight - 1) / step + 1;
var n = Columns * Rows;
_u = ArrayPool<float>.Shared.Rent(n);
_v = ArrayPool<float>.Shared.Rent(n);
_error = ArrayPool<float>.Shared.Rent(n);
U.Clear();
V.Clear();
Error.Fill(float.NaN);
}
public int ImageWidth { get; }
public int ImageHeight { get; }
/// <summary>Grid spacing in full-resolution pixels.</summary>
public int Step { get; }
public int Columns { get; }
public int Rows { get; }
public int Count => Columns * Rows;
/// <summary>Horizontal components, row-major over the grid.</summary>
public Span<float> U => Storage(_u);
/// <summary>Vertical components, row-major over the grid.</summary>
public Span<float> V => Storage(_v);
/// <summary>Forward–backward error |w(p) + w'(p + w(p))| in pixels; NaN when unchecked.</summary>
public Span<float> Error => Storage(_error);
/// <summary>True when <see cref="Error"/> has been filled by a forward–backward check.</summary>
public bool HasConsistency { get; internal set; }
/// <summary>Bilinearly interpolated vector at a full-resolution pixel-centre position (clamped to the grid).</summary>
public (float U, float V) Sample(double x, double y)
{
var gx = (float)(x / Step);
var gy = (float)(y / Step);
return (PlaneOps.Bilinear(U, Columns, Rows, gx, gy), PlaneOps.Bilinear(V, Columns, Rows, gx, gy));
}
/// <summary>Bilinearly interpolated forward–backward error (NaN when unchecked).</summary>
public float SampleError(double x, double y) =>
HasConsistency ? PlaneOps.Bilinear(Error, Columns, Rows, (float)(x / Step), (float)(y / Step)) : float.NaN;
/// <summary>Counts of vector magnitudes in <paramref name="bins"/> equal bins over [0, max]; larger values land in the last bin.</summary>
public int[] MagnitudeHistogram(int bins, double maxMagnitude)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bins);
if (!(maxMagnitude > 0)) throw new ArgumentOutOfRangeException(nameof(maxMagnitude));
var histogram = new int[bins];
var u = U;
var v = V;
var scale = bins / maxMagnitude;
for (var i = 0; i < u.Length; i++)
{
var m = double.Sqrt((double)u[i] * u[i] + (double)v[i] * v[i]);
histogram[int.Min(bins - 1, (int)(m * scale))]++;
}
return histogram;
}
/// <summary>Magnitude statistics; vectors with a forward–backward error above <paramref name="reliableError"/> px count as unreliable.</summary>
public MotionStatistics Statistics(double reliableError = 1.0)
{
var n = Count;
var magnitudes = ArrayPool<float>.Shared.Rent(n);
try
{
var u = U;
var v = V;
var error = Error;
double sum = 0, su = 0, sv = 0, max = 0;
var reliable = 0;
for (var i = 0; i < n; i++)
{
var m = float.Sqrt(u[i] * u[i] + v[i] * v[i]);
magnitudes[i] = m;
sum += m;
su += u[i];
sv += v[i];
max = double.Max(max, m);
if (!HasConsistency || error[i] <= reliableError) reliable++;
}
var span = magnitudes.AsSpan(0, n);
var median = PlaneOps.Median(span);
var p95 = PlaneOps.Select(span, int.Min(n - 1, (int)double.Ceiling(0.95 * n) - 1));
return new MotionStatistics(sum / n, median, p95, max, su / n, sv / n, reliable / (double)n);
}
finally
{
ArrayPool<float>.Shared.Return(magnitudes);
}
}
/// <summary>Sets every vector to (u, v).</summary>
public void Fill(float u, float v)
{
U.Fill(u);
V.Fill(v);
}
public void Dispose()
{
Return(ref _u);
Return(ref _v);
Return(ref _error);
}
private Span<float> Storage(float[]? array) => (array ?? throw new ObjectDisposedException(nameof(MotionField))).AsSpan(0, Count);
private static void Return(ref float[]? array)
{
var a = Interlocked.Exchange(ref array, null);
if (a is not null) ArrayPool<float>.Shared.Return(a);
}
}
@@ -0,0 +1,332 @@
using System.Buffers;
using Chronos.Core.Imaging;
namespace Chronos.Core.Motion;
/// <summary>Speed/quality trade-off of <see cref="OpticalFlowEngine"/>.</summary>
public enum FlowQuality
{
/// <summary>Vectors every 4 px, few iterations: previews and analysis histograms.</summary>
Draft,
/// <summary>Vectors every 2 px: motion blur and analysis.</summary>
Balanced,
/// <summary>Per-pixel vectors, more iterations and a 5×5 median: frame interpolation.</summary>
Best,
}
/// <summary>Parameters of the dense pyramidal Lucas–Kanade solver.</summary>
public sealed record OpticalFlowOptions
{
/// <summary>Upper bound on pyramid levels (the coarsest level keeps ≥ 16 px on its short side).</summary>
public int MaxLevels { get; init; } = 5;
/// <summary>Finest level solved; the output grid step is 2^FinestLevel pixels.</summary>
public int FinestLevel { get; init; } = 1;
/// <summary>Warp–solve iterations per level.</summary>
public int Iterations { get; init; } = 4;
/// <summary>Lucas–Kanade integration window radius (box of (2r+1)² samples) at every level.</summary>
public int WindowRadius { get; init; } = 3;
/// <summary>Median filter radius applied to the field after each level (0 = off).</summary>
public int MedianRadius { get; init; } = 1;
/// <summary>Tikhonov term added to the structure tensor diagonal (perceptual luminance² per px²).</summary>
public float Regularization { get; init; } = 1e-5f;
public static OpticalFlowOptions For(FlowQuality quality) => quality switch
{
FlowQuality.Draft => new OpticalFlowOptions { MaxLevels = 4, FinestLevel = 2, Iterations = 3 },
FlowQuality.Balanced => new OpticalFlowOptions(),
FlowQuality.Best => new OpticalFlowOptions { MaxLevels = 6, FinestLevel = 0, Iterations = 5, WindowRadius = 4, MedianRadius = 2 },
_ => throw new ArgumentOutOfRangeException(nameof(quality)),
};
}
/// <summary>
/// Dense optical flow by pyramidal Lucas–Kanade (Lucas &amp; Kanade 1981; Bouguet 2000) solved for a window
/// around every pixel of each level: both frames get a σ = 1 binomial blur, box-window structure tensors of
/// the first frame's gradients are inverted once per level (inverse-compositional form), and each iteration
/// warps the second frame by the current flow (bilinear) and re-solves every window with a first-order
/// correction for its neighbours' flows; the field is median filtered between levels (Sun, Roth &amp; Black
/// 2010). Chosen over Farnebäck polynomial expansion because every step is a separable box filter or a
/// per-pixel 2×2 solve that vectorises and parallelises cleanly, with equal sub-pixel accuracy on smooth
/// motion. Forward–backward consistency (Sundaram et al. 2010) marks occlusions. One engine holds reusable
/// workspaces, so it must not be shared between threads.
/// </summary>
public sealed class OpticalFlowEngine : IDisposable
{
private const float MaxUpdate = 2f;
private GrayPyramid? _first;
private GrayPyramid? _second;
private float[][] _work = [];
private int _capacity;
public OpticalFlowEngine(OpticalFlowOptions? options = null) => Options = options ?? new OpticalFlowOptions();
public OpticalFlowEngine(FlowQuality quality) : this(OpticalFlowOptions.For(quality))
{
}
public OpticalFlowOptions Options { get; }
/// <summary>Flow from <paramref name="from"/> to <paramref name="to"/> (perceptual luminance of both).</summary>
public MotionField Compute(ImageBuffer from, ImageBuffer to, CancellationToken cancellationToken = default)
{
BuildPyramids(from, to);
return Compute(_first!, _second!, cancellationToken);
}
/// <summary>Flow between two prebuilt pyramids (lets callers reuse each frame's pyramid for two pairs).</summary>
public MotionField Compute(GrayPyramid from, GrayPyramid to, CancellationToken cancellationToken = default)
{
if (from.Width != to.Width || from.Height != to.Height || from.Levels != to.Levels)
throw new ArgumentException("Pyramids differ in size or depth.", nameof(to));
var coarsest = int.Min(from.Levels, Options.MaxLevels) - 1;
var finest = int.Clamp(Options.FinestLevel, 0, coarsest);
EnsureWorkspace(from.LevelWidth(finest) * from.LevelHeight(finest));
float[] u = _work[0], v = _work[1];
for (var level = coarsest; level >= finest; level--)
{
cancellationToken.ThrowIfCancellationRequested();
var w = from.LevelWidth(level);
var h = from.LevelHeight(level);
if (level == coarsest)
{
Array.Clear(u, 0, w * h);
Array.Clear(v, 0, w * h);
}
else
{
var (nu, nv) = u == _work[0] ? (_work[2], _work[3]) : (_work[0], _work[1]);
Upsample(u, nu, from.LevelWidth(level + 1), from.LevelHeight(level + 1), w, h);
Upsample(v, nv, from.LevelWidth(level + 1), from.LevelHeight(level + 1), w, h);
(u, v) = (nu, nv);
}
SolveLevel(from.LevelArray(level), to.LevelArray(level), w, h, u, v, cancellationToken);
}
var step = 1 << finest;
var field = new MotionField(from.Width, from.Height, step);
var n = field.Count;
var fu = field.U;
var fv = field.V;
for (var i = 0; i < n; i++)
{
fu[i] = u[i] * step;
fv[i] = v[i] * step;
}
return field;
}
/// <summary>Forward and backward flow with their forward–backward consistency errors filled in.</summary>
public (MotionField Forward, MotionField Backward) ComputeBidirectional(ImageBuffer from, ImageBuffer to, CancellationToken cancellationToken = default)
{
BuildPyramids(from, to);
return ComputeBidirectional(_first!, _second!, cancellationToken);
}
/// <inheritdoc cref="ComputeBidirectional(ImageBuffer, ImageBuffer, CancellationToken)"/>
public (MotionField Forward, MotionField Backward) ComputeBidirectional(GrayPyramid from, GrayPyramid to, CancellationToken cancellationToken = default)
{
var forward = Compute(from, to, cancellationToken);
try
{
var backward = Compute(to, from, cancellationToken);
CheckConsistency(forward, backward);
return (forward, backward);
}
catch
{
forward.Dispose();
throw;
}
}
/// <summary>
/// Fills both fields' <see cref="MotionField.Error"/> with |w(p) + w'(p + w(p))|; vectors leaving the
/// frame get +∞ (unverifiable, treated as occluded).
/// </summary>
public static void CheckConsistency(MotionField forward, MotionField backward)
{
if (forward.ImageWidth != backward.ImageWidth || forward.ImageHeight != backward.ImageHeight)
throw new ArgumentException("Fields describe different image sizes.", nameof(backward));
Fill(forward, backward);
Fill(backward, forward);
forward.HasConsistency = backward.HasConsistency = true;
static void Fill(MotionField field, MotionField other)
{
var u = field.U;
var v = field.V;
var error = field.Error;
var maxX = field.ImageWidth - 0.5;
var maxY = field.ImageHeight - 0.5;
for (var j = 0; j < field.Rows; j++)
{
for (var i = 0; i < field.Columns; i++)
{
var k = j * field.Columns + i;
var x = i * field.Step + (double)u[k];
var y = j * field.Step + (double)v[k];
if (x < -0.5 || y < -0.5 || x > maxX || y > maxY)
{
error[k] = float.PositiveInfinity;
continue;
}
var (bu, bv) = other.Sample(x, y);
error[k] = float.Hypot(u[k] + bu, v[k] + bv);
}
}
}
}
public void Dispose()
{
_first?.Dispose();
_second?.Dispose();
_first = _second = null;
foreach (var a in _work) ArrayPool<float>.Shared.Return(a);
_work = [];
_capacity = 0;
}
private void BuildPyramids(ImageBuffer from, ImageBuffer to)
{
if (from.Width != to.Width || from.Height != to.Height) throw new ArgumentException("Frames differ in size.", nameof(to));
if (_first is null || _first.Width != from.Width || _first.Height != from.Height)
{
_first?.Dispose();
_second?.Dispose();
var levels = GrayPyramid.LevelsFor(from.Width, from.Height, 16, Options.MaxLevels);
_first = new GrayPyramid(from.Width, from.Height, levels);
_second = new GrayPyramid(from.Width, from.Height, levels);
}
_first.Build(from);
_second!.Build(to);
}
private void EnsureWorkspace(int length)
{
if (length <= _capacity) return;
foreach (var a in _work) ArrayPool<float>.Shared.Return(a);
// u, v, u', v', Ix, Iy, H11, H12, H22, Bx, By, scratch, smoothed first, smoothed second.
_work = new float[14][];
for (var i = 0; i < _work.Length; i++) _work[i] = ArrayPool<float>.Shared.Rent(length);
_capacity = length;
}
private void SolveLevel(float[] i0, float[] i1, int w, int h, float[] u, float[] v, CancellationToken cancellationToken)
{
var (spareU, spareV) = u == _work[0] ? (_work[2], _work[3]) : (_work[0], _work[1]);
float[] ix = _work[4], iy = _work[5], h11 = _work[6], h12 = _work[7], h22 = _work[8], bx = _work[9], by = _work[10], scratch = _work[11];
var radius = Options.WindowRadius;
var lambda = Options.Regularization;
// Central differences under-estimate high-frequency derivatives relative to how the bilinearly warped
// frame responds to a flow change (ratio 1/cos πf), which over-shoots the Gauss–Newton step beyond 2×
// above f ≈ 1/3 cycles/px and makes the iteration diverge. A σ = 1 blur of both frames removes that
// band; being the same translation-invariant filter on both, it does not bias the solution.
PlaneOps.Binomial5(i0, _work[12], scratch, w, h);
PlaneOps.Binomial5(i1, _work[13], scratch, w, h);
i0 = _work[12];
i1 = _work[13];
// Gradients of the first frame and their structure-tensor products.
PlaneOps.ForRows(h, w, y =>
{
var row = y * w;
var up = int.Max(y - 1, 0) * w;
var down = int.Min(y + 1, h - 1) * w;
for (var x = 0; x < w; x++)
{
var gx = 0.5f * (i0[row + int.Min(x + 1, w - 1)] - i0[row + int.Max(x - 1, 0)]);
var gy = 0.5f * (i0[down + x] - i0[up + x]);
ix[row + x] = gx;
iy[row + x] = gy;
h11[row + x] = gx * gx;
h12[row + x] = gx * gy;
h22[row + x] = gy * gy;
}
});
PlaneOps.BoxFilter(h11, h11, scratch, w, h, radius);
PlaneOps.BoxFilter(h12, h12, scratch, w, h, radius);
PlaneOps.BoxFilter(h22, h22, scratch, w, h, radius);
PlaneOps.ForRows(h, w, y =>
{
for (int x = 0, k = y * w; x < w; x++, k++)
{
var a = h11[k] + lambda;
var b = h12[k];
var c = h22[k] + lambda;
var r = 1f / (a * c - b * b);
h11[k] = c * r;
h12[k] = -b * r;
h22[k] = a * r;
}
});
for (var iteration = 0; iteration < Options.Iterations; iteration++)
{
cancellationToken.ThrowIfCancellationRequested();
// Each window solves for one flow v: min Σ_y (I1w(y) + g(y)·(v − u(y)) − I0(y))², i.e. the classic
// Lucas–Kanade window with a first-order correction for the neighbours' own flows. Unlike the
// per-pixel update u −= G⁻¹·box(g·It), this does not feed the current error back through
// ill-conditioned (aperture) windows, so it cannot diverge. Samples warped outside the frame
// vote for their current flow (It = 0).
PlaneOps.ForRows(h, w, y =>
{
var span = i1.AsSpan(0, w * h);
for (int x = 0, k = y * w; x < w; x++, k++)
{
var px = x + u[k];
var py = y + v[k];
var it = px >= 0 && py >= 0 && px <= w - 1 && py <= h - 1
? PlaneOps.Bilinear(span, w, h, px, py) - i0[k]
: 0f;
var r = ix[k] * u[k] + iy[k] * v[k] - it;
bx[k] = ix[k] * r;
by[k] = iy[k] * r;
}
});
PlaneOps.BoxFilter(bx, bx, scratch, w, h, radius);
PlaneOps.BoxFilter(by, by, scratch, w, h, radius);
PlaneOps.ForRows(h, w, y =>
{
for (int x = 0, k = y * w; x < w; x++, k++)
{
// (G + λI)⁻¹ (box(q) + λu): the regulariser keeps textureless windows at their current flow.
var qx = bx[k] + lambda * u[k];
var qy = by[k] + lambda * v[k];
var nu = h11[k] * qx + h12[k] * qy;
var nv = h12[k] * qx + h22[k] * qy;
u[k] += float.Clamp(nu - u[k], -MaxUpdate, MaxUpdate);
v[k] += float.Clamp(nv - v[k], -MaxUpdate, MaxUpdate);
}
});
}
if (Options.MedianRadius > 0)
{
PlaneOps.MedianFilter(u, spareU, w, h, Options.MedianRadius);
PlaneOps.MedianFilter(v, spareV, w, h, Options.MedianRadius);
Array.Copy(spareU, u, w * h);
Array.Copy(spareV, v, w * h);
}
}
/// <summary>Doubles the resolution and the magnitude of a level's flow (level-ℓ pixel k ↔ level-(ℓ−1) pixel 2k).</summary>
private static void Upsample(float[] coarse, float[] fine, int cw, int ch, int w, int h)
{
PlaneOps.ForRows(h, w, y =>
{
var span = coarse.AsSpan(0, cw * ch);
for (var x = 0; x < w; x++) fine[y * w + x] = 2 * PlaneOps.Bilinear(span, cw, ch, 0.5f * x, 0.5f * y);
});
}
}
+40
View File
@@ -0,0 +1,40 @@
namespace Chronos.Core.Motion;
/// <summary>Smoothing of per-frame series (camera paths).</summary>
internal static class PathSmoother
{
/// <summary>
/// Gaussian-weighted local linear regression (degree-1 LOESS with a Gaussian kernel truncated at 3σ):
/// each sample is replaced by the value at its own position of a line fitted to its neighbourhood.
/// Linear trends (pans) pass unchanged and the ends are not pulled toward the interior, unlike a plain
/// Gaussian average. σ ≤ 0 returns a copy.
/// </summary>
public static double[] LocalLinear(ReadOnlySpan<double> values, double sigma)
{
var n = values.Length;
var result = values.ToArray();
if (!(sigma > 0) || n < 2) return result;
var radius = (int)double.Ceiling(3 * sigma);
Span<double> kernel = radius <= 1024 ? stackalloc double[radius + 1] : new double[radius + 1];
for (var d = 0; d <= radius; d++) kernel[d] = double.Exp(-0.5 * d * d / (sigma * sigma));
for (var k = 0; k < n; k++)
{
double s0 = 0, s1 = 0, s2 = 0, t0 = 0, t1 = 0;
var lo = int.Max(0, k - radius);
var hi = int.Min(n - 1, k + radius);
for (var j = lo; j <= hi; j++)
{
var d = j - k;
var w = kernel[int.Abs(d)];
s0 += w;
s1 += w * d;
s2 += w * d * d;
t0 += w * values[j];
t1 += w * d * values[j];
}
var det = s0 * s2 - s1 * s1;
result[k] = det > 1e-12 * s0 * s0 ? (s2 * t0 - s1 * t1) / det : t0 / s0;
}
return result;
}
}
+273
View File
@@ -0,0 +1,273 @@
namespace Chronos.Core.Motion;
/// <summary>
/// Translation between two patches. <c>moving(x, y) ≈ reference(x − Dx, y − Dy)</c>: content moved by
/// (+Dx, +Dy) pixels from the reference to the moving patch. <see cref="Confidence"/> is the peak
/// sharpness ratio 1 − second/primary peak, in [0, 1]; <see cref="Peak"/> is the correlation peak height
/// (1 for a perfect translation, near 0 for unrelated content).
/// </summary>
public readonly record struct PhaseCorrelation(double Dx, double Dy, double Confidence, double Peak);
/// <summary>Tuning for <see cref="PhaseCorrelator"/>.</summary>
public sealed record PhaseCorrelatorOptions
{
/// <summary>Tukey taper fraction of the analysis window (1 = Hann). Suppresses the patch-border discontinuity.</summary>
public double WindowTaper { get; init; } = 0.5;
/// <summary>
/// Spatial σ (px) of the Gaussian low-pass applied to the normalised cross-power spectrum. It shapes the
/// correlation peak into a sampled Gaussian, which makes the log-parabola sub-pixel fit unbiased, and
/// attenuates the noisiest high frequencies.
/// </summary>
public double PeakSigma { get; init; } = 1.0;
/// <summary>Largest |shift| searched per axis (px); 0 searches the whole surface.</summary>
public int MaxShift { get; init; }
/// <summary>Default options.</summary>
public static PhaseCorrelatorOptions Default { get; } = new();
}
/// <summary>
/// Kuglin &amp; Hines (1975) phase correlation between two equally sized luminance patches: weighted-mean
/// removal, Tukey window, one complex FFT carrying both real patches (reference as real part, moving as
/// imaginary part), normalised cross-power spectrum with a relative epsilon and a Gaussian low-pass,
/// inverse FFT, integer peak search and a separable Gaussian (log-parabola) sub-pixel fit.
/// Holds its working buffers, so one instance must not be used by two threads at once.
/// </summary>
public sealed class PhaseCorrelator
{
// Relative regulariser of |cross power|: keeps empty bins from being amplified to unit magnitude.
private const double SpectrumEpsilon = 1e-6;
private readonly double[] _window;
private readonly double[] _lowPass;
private readonly double[] _re;
private readonly double[] _im;
private readonly int _maxShiftX;
private readonly int _maxShiftY;
private readonly int _exclusion;
private readonly double _windowSum;
public PhaseCorrelator(int width, int height, PhaseCorrelatorOptions? options = null)
{
ArgumentOutOfRangeException.ThrowIfLessThan(width, 4);
ArgumentOutOfRangeException.ThrowIfLessThan(height, 4);
Options = options ?? PhaseCorrelatorOptions.Default;
Width = width;
Height = height;
var n = width * height;
_re = new double[n];
_im = new double[n];
var wxArray = new double[width];
var wyArray = new double[height];
Fourier.Tukey(wxArray, Options.WindowTaper);
Fourier.Tukey(wyArray, Options.WindowTaper);
_window = new double[n];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var w = wyArray[y] * wxArray[x];
_window[y * width + x] = w;
_windowSum += w;
}
}
// Gaussian of spatial σ in the frequency domain: exp(−2π²σ²|f|²), f in cycles per pixel.
_lowPass = new double[n];
var sigma = Options.PeakSigma;
var k = -2.0 * double.Pi * double.Pi * sigma * sigma;
for (var v = 0; v < height; v++)
{
var fy = Signed(v, height) / (double)height;
for (var u = 0; u < width; u++)
{
var fx = Signed(u, width) / (double)width;
_lowPass[v * width + u] = sigma > 0 ? double.Exp(k * (fx * fx + fy * fy)) : 1.0;
}
}
_lowPass[0] = 0; // DC carries no shift information.
double sum = 0;
foreach (var g in _lowPass) sum += g;
// Normalise so that a perfect translation produces a unit peak.
var norm = n / sum;
for (var i = 0; i < n; i++) _lowPass[i] *= norm;
var limitX = width / 2 - 1;
var limitY = height / 2 - 1;
_maxShiftX = Options.MaxShift > 0 ? int.Min(Options.MaxShift, limitX) : limitX;
_maxShiftY = Options.MaxShift > 0 ? int.Min(Options.MaxShift, limitY) : limitY;
_exclusion = int.Max(2, (int)double.Ceiling(3 * double.Max(sigma, 0.5)));
}
public int Width { get; }
public int Height { get; }
public PhaseCorrelatorOptions Options { get; }
/// <summary>Correlates two row-major patches of <see cref="Width"/>×<see cref="Height"/> samples.</summary>
public PhaseCorrelation Correlate(ReadOnlySpan<float> reference, ReadOnlySpan<float> moving) =>
Correlate(reference, moving, Width, 0, 0);
/// <summary>
/// Correlates the patches at (<paramref name="x0"/>, <paramref name="y0"/>) of two equally sized planes
/// with row stride <paramref name="planeWidth"/>.
/// </summary>
public PhaseCorrelation Correlate(ReadOnlySpan<float> referencePlane, ReadOnlySpan<float> movingPlane, int planeWidth, int x0, int y0)
{
var w = Width;
var h = Height;
if (x0 < 0 || y0 < 0 || x0 + w > planeWidth) throw new ArgumentOutOfRangeException(nameof(x0), "Patch outside the plane.");
var last = (y0 + h - 1) * planeWidth + x0 + w;
if (last > referencePlane.Length || last > movingPlane.Length) throw new ArgumentOutOfRangeException(nameof(y0), "Patch outside the plane.");
// Window-weighted means, so the windowed patches have exactly zero DC.
double ma = 0, mb = 0;
for (var y = 0; y < h; y++)
{
var ra = referencePlane.Slice((y0 + y) * planeWidth + x0, w);
var rb = movingPlane.Slice((y0 + y) * planeWidth + x0, w);
var win = _window.AsSpan(y * w, w);
for (var x = 0; x < w; x++)
{
ma += win[x] * ra[x];
mb += win[x] * rb[x];
}
}
ma /= _windowSum;
mb /= _windowSum;
for (var y = 0; y < h; y++)
{
var ra = referencePlane.Slice((y0 + y) * planeWidth + x0, w);
var rb = movingPlane.Slice((y0 + y) * planeWidth + x0, w);
var o = y * w;
for (var x = 0; x < w; x++)
{
_re[o + x] = (ra[x] - ma) * _window[o + x];
_im[o + x] = (rb[x] - mb) * _window[o + x];
}
}
Fourier.Forward2D(_re, _im, w, h);
CrossPowerSpectrum();
Fourier.Inverse2D(_re, _im, w, h);
return LocatePeak();
}
/// <summary>
/// Replaces the packed spectrum Z = A + iB with the normalised, low-passed cross power conj(A)·B / |conj(A)·B|.
/// A and B are recovered from Hermitian symmetry: A_k = (Z_k + conj Z_−k)/2, B_k = (Z_k − conj Z_−k)/2i.
/// </summary>
private void CrossPowerSpectrum()
{
var w = Width;
var h = Height;
var re = _re;
var im = _im;
double magnitudeSum = 0;
for (var v = 0; v < h; v++)
{
var mv = v == 0 ? 0 : h - v;
for (var u = 0; u < w; u++)
{
var i = v * w + u;
var j = mv * w + (u == 0 ? 0 : w - u);
if (j < i) continue;
double zr = re[i], zi = im[i], yr = re[j], yi = im[j];
var ar = 0.5 * (zr + yr);
var ai = 0.5 * (zi - yi);
var br = 0.5 * (zi + yi);
var bi = -0.5 * (zr - yr);
// conj(A)·B; the mirrored bin holds its conjugate because the correlation is real.
var cr = ar * br + ai * bi;
var ci = ar * bi - ai * br;
re[i] = cr;
im[i] = ci;
re[j] = cr;
im[j] = -ci;
var mag = double.Sqrt(cr * cr + ci * ci);
magnitudeSum += i == j ? mag : 2 * mag;
}
}
var epsilon = SpectrumEpsilon * magnitudeSum / (w * h) + double.Epsilon;
var lowPass = _lowPass;
for (var i = 0; i < re.Length; i++)
{
var mag = double.Sqrt(re[i] * re[i] + im[i] * im[i]);
var f = lowPass[i] / (mag + epsilon);
re[i] *= f;
im[i] *= f;
}
}
private PhaseCorrelation LocatePeak()
{
var w = Width;
var h = Height;
var c = _re;
int px = 0, py = 0;
var best = double.NegativeInfinity;
for (var dy = -_maxShiftY; dy <= _maxShiftY; dy++)
{
var row = Wrap(dy, h) * w;
for (var dx = -_maxShiftX; dx <= _maxShiftX; dx++)
{
var value = c[row + Wrap(dx, w)];
if (value > best)
{
best = value;
px = dx;
py = dy;
}
}
}
double At(int dx, int dy) => c[Wrap(dy, h) * w + Wrap(dx, w)];
var fx = SubPixel(At(px - 1, py), best, At(px + 1, py));
var fy = SubPixel(At(px, py - 1), best, At(px, py + 1));
// Second peak: the largest value outside the main lobe (wrap-aware Chebyshev distance).
var second = double.NegativeInfinity;
for (var dy = -_maxShiftY; dy <= _maxShiftY; dy++)
{
var row = Wrap(dy, h) * w;
var nearY = int.Abs(dy - py) <= _exclusion;
for (var dx = -_maxShiftX; dx <= _maxShiftX; dx++)
{
if (nearY && int.Abs(dx - px) <= _exclusion) continue;
var value = c[row + Wrap(dx, w)];
if (value > second) second = value;
}
}
var confidence = best > 0 ? double.Clamp(1 - double.Max(second, 0) / best, 0, 1) : 0;
return new PhaseCorrelation(px + fx, py + fy, confidence, double.Max(best, 0));
}
/// <summary>Vertex of the parabola through log values (exact for a sampled Gaussian), or of the plain
/// parabola when a neighbour is not positive; clamped to ±0.5 px.</summary>
private static double SubPixel(double left, double centre, double right)
{
double offset;
if (left > 0 && centre > 0 && right > 0)
{
double l = double.Log(left), c = double.Log(centre), r = double.Log(right);
var d = l - 2 * c + r;
offset = d < 0 ? 0.5 * (l - r) / d : 0;
}
else
{
var d = left - 2 * centre + right;
offset = d < 0 ? 0.5 * (left - right) / d : 0;
}
return double.Clamp(offset, -0.5, 0.5);
}
private static int Signed(int index, int length) => index <= length / 2 ? index : index - length;
private static int Wrap(int index, int length) => index < 0 ? index + length : index;
}
+261
View File
@@ -0,0 +1,261 @@
using System.Numerics;
using System.Runtime.CompilerServices;
using Chronos.Core.Imaging;
namespace Chronos.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;
}
}
+417
View File
@@ -0,0 +1,417 @@
using System.Buffers;
using System.Numerics;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Geometry;
namespace Chronos.Core.Motion;
/// <summary>Tuning for <see cref="Stabilizer"/>.</summary>
public sealed record StabilizerOptions
{
/// <summary>Phase-correlation patch side (power of two recommended); 0 picks min(W, H)/3 rounded down to a power of two, 8..256.</summary>
public int PatchSize { get; init; }
/// <summary>
/// Texture gate: minimum gradient energy of a patch (perceptual luminance² per px², measured after a
/// 3×3 binomial blur, with the expected contribution of the estimated noise removed).
/// </summary>
public double TextureThreshold { get; init; } = 1e-5;
/// <summary>Minimum phase-correlation peak sharpness for a patch vector to be used.</summary>
public double MinimumConfidence { get; init; } = 0.3;
/// <summary>Residual (px) under which a patch vector is an inlier of a similarity hypothesis.</summary>
public double InlierThreshold { get; init; } = 1.0;
/// <summary>Largest plausible frame-to-frame rotation (radians) of a hypothesis.</summary>
public double MaxRotation { get; init; } = 0.05;
/// <summary>Largest plausible frame-to-frame |ln scale| of a hypothesis.</summary>
public double MaxScaleChange { get; init; } = 0.05;
/// <summary>σ (frames) of the Gaussian-weighted local linear regression that smooths the camera path; 0 disables.</summary>
public double SmoothingSigma { get; init; } = 12;
/// <summary>Shake (RMS px) above which stabilisation is recommended (brief §10.3).</summary>
public double RecommendThreshold { get; init; } = 0.3;
}
/// <summary>Similarity between consecutive frames: maps previous-frame pixel coordinates to current-frame ones.</summary>
public readonly record struct FrameMotion(Affine2D Transform, int ValidPatches, int Inliers)
{
/// <summary>False when no patch passed the texture and confidence gates (identity assumed).</summary>
public bool Estimated => ValidPatches > 0;
}
/// <summary>Outcome of <see cref="Stabilizer.Solve"/>; every transform uses pixel-centre coordinates.</summary>
public sealed record StabilizationResult(
IReadOnlyList<FrameMotion> Motions,
IReadOnlyList<Affine2D> CameraPath,
IReadOnlyList<Affine2D> SmoothedPath,
IReadOnlyList<Affine2D> Corrections,
double ShakeRms,
double CropScale,
bool Recommended)
{
/// <summary>Fraction of the frame area lost to the centred crop that hides every correction's borders, 1 − scale².</summary>
public double CropCost => 1 - CropScale * CropScale;
}
/// <summary>
/// Video stabilisation. Per frame: Kuglin–Hines phase correlation of nine patches on a 3×3 grid against the
/// previous frame (patches analysed in parallel), texture gating (noise-compensated gradient energy,
/// Immerkær 1996 noise estimate; a textureless frame yields no vectors and therefore no motion), then a
/// robust similarity fit (exhaustive two-point hypotheses as deterministic RANSAC, plausibility limits,
/// weighted least squares on the inliers). <see cref="Solve"/> accumulates the camera path, smooths its
/// translation, rotation and log-scale with Gaussian-weighted local linear regression (pans survive
/// unchanged), and reports per-frame corrections (smoothed ∘ raw⁻¹), shake RMS and the crop needed to hide
/// borders. Memory is two luminance planes plus one small record per frame.
/// </summary>
public sealed class Stabilizer : IDisposable
{
// Expected smoothed-gradient energy of unit-variance white noise: 2 · Σ([−1 −2 0 2 1]/8)² · Σ([1 2 1]/4)².
private const double NoiseGradientGain = 2 * (10.0 / 64) * (6.0 / 16);
private readonly PhaseCorrelator[] _correlators;
private readonly PhaseCorrelation?[] _results = new PhaseCorrelation?[9];
private readonly (int X, int Y)[] _patches;
private readonly double[] _previousEnergy;
private readonly double[] _currentEnergy;
private readonly float[][] _smooth;
private readonly Match[] _matches = new Match[9];
private readonly List<FrameMotion> _motions = [];
private float[]? _previous;
private float[]? _current;
public Stabilizer(int width, int height, StabilizerOptions? options = null)
{
ArgumentOutOfRangeException.ThrowIfLessThan(width, 16);
ArgumentOutOfRangeException.ThrowIfLessThan(height, 16);
Options = options ?? new StabilizerOptions();
Width = width;
Height = height;
PatchSize = Options.PatchSize > 0
? int.Min(Options.PatchSize, int.Min(width, height))
: int.Clamp(1 << BitOperations.Log2((uint)(int.Min(width, height) / 3)), 8, 256);
// One correlator and blur buffer per patch so the nine patches are analysed in parallel.
_correlators = new PhaseCorrelator[9];
_smooth = new float[9][];
for (var i = 0; i < 9; i++)
{
_correlators[i] = new PhaseCorrelator(PatchSize, PatchSize);
_smooth[i] = new float[PatchSize * PatchSize];
}
_patches = new (int, int)[9];
for (var j = 0; j < 3; j++)
{
for (var i = 0; i < 3; i++)
{
var x = (int)double.Round(width * (2 * i + 1) / 6.0 - PatchSize / 2.0);
var y = (int)double.Round(height * (2 * j + 1) / 6.0 - PatchSize / 2.0);
_patches[j * 3 + i] = (int.Clamp(x, 0, width - PatchSize), int.Clamp(y, 0, height - PatchSize));
}
}
_previousEnergy = new double[9];
_currentEnergy = new double[9];
_previous = ArrayPool<float>.Shared.Rent(width * height);
_current = ArrayPool<float>.Shared.Rent(width * height);
}
public int Width { get; }
public int Height { get; }
public int PatchSize { get; }
public StabilizerOptions Options { get; }
public int FrameCount => _motions.Count;
/// <summary>Adds the next frame (its perceptual luminance is analysed) and returns its motion from the previous frame.</summary>
public FrameMotion AddFrame(ImageBuffer frame)
{
if (frame.Width != Width || frame.Height != Height) throw new ArgumentException("Frame size differs.", nameof(frame));
PlaneOps.PerceptualLuminance(frame, CurrentPlane.AsSpan(0, Width * Height));
return Analyse();
}
/// <summary>Adds the next frame as a perceptual (sRGB-encoded) luminance plane.</summary>
public FrameMotion AddFrame(ReadOnlySpan<float> luminance)
{
if (luminance.Length < Width * Height) throw new ArgumentException("Plane is smaller than the frame.", nameof(luminance));
luminance[..(Width * Height)].CopyTo(CurrentPlane);
return Analyse();
}
/// <summary>Smooths the accumulated camera path and derives corrections, shake and crop.</summary>
public StabilizationResult Solve()
{
var n = _motions.Count;
if (n == 0) throw new InvalidOperationException("No frames were added.");
double cx = (Width - 1) / 2.0, cy = (Height - 1) / 2.0;
// Camera path C_k: frame-0 coordinates → frame-k coordinates, as (tx, ty, angle, ln scale) about the centre.
var path = new Affine2D[n];
var parameters = new double[4][];
for (var p = 0; p < 4; p++) parameters[p] = new double[n];
var current = Affine2D.Identity;
for (var k = 0; k < n; k++)
{
current = _motions[k].Transform * current;
path[k] = current;
var (x, y) = current.Apply(cx, cy);
var angle = current.Angle;
if (k > 0) angle += double.Round((parameters[2][k - 1] - angle) / double.Tau) * double.Tau;
parameters[0][k] = x - cx;
parameters[1][k] = y - cy;
parameters[2][k] = angle;
parameters[3][k] = double.Log(current.Scale);
}
var smoothed = new Affine2D[n];
var corrections = new Affine2D[n];
var series = new double[4][];
for (var p = 0; p < 4; p++) series[p] = PathSmoother.LocalLinear(parameters[p], Options.SmoothingSigma);
for (var k = 0; k < n; k++)
{
smoothed[k] = Affine2D.Translation(cx + series[0][k], cy + series[1][k])
* Affine2D.Similarity(double.Exp(series[3][k]), series[2][k], 0, 0)
* Affine2D.Translation(-cx, -cy);
var correction = smoothed[k] * path[k].Invert();
corrections[k] = correction.IsIdentity(1e-12) ? Affine2D.Identity : correction;
}
var shake = ShakeRms(corrections);
var crop = CropScale(corrections);
return new StabilizationResult(_motions.ToArray(), path, smoothed, corrections, shake, crop, shake > Options.RecommendThreshold);
}
public void Dispose()
{
var previous = Interlocked.Exchange(ref _previous, null);
var current = Interlocked.Exchange(ref _current, null);
if (previous is not null) ArrayPool<float>.Shared.Return(previous);
if (current is not null) ArrayPool<float>.Shared.Return(current);
}
private float[] CurrentPlane => _current ?? throw new ObjectDisposedException(nameof(Stabilizer));
private FrameMotion Analyse()
{
var current = CurrentPlane;
var first = _motions.Count == 0;
var previous = _previous!;
Parallel.For(0, 9, i =>
{
var (x0, y0) = _patches[i];
_currentEnergy[i] = TextureEnergy(current, x0, y0, _smooth[i]);
_results[i] = first || double.Min(_previousEnergy[i], _currentEnergy[i]) < Options.TextureThreshold
? null
: _correlators[i].Correlate(previous, current, Width, x0, y0);
});
// Gathered in patch order, so the fit does not depend on thread scheduling.
var count = 0;
var half = (PatchSize - 1) / 2.0;
for (var i = 0; i < 9; i++)
{
if (_results[i] is not { } r || r.Confidence < Options.MinimumConfidence) continue;
var (x0, y0) = _patches[i];
_matches[count++] = new Match(x0 + half, y0 + half, x0 + half + r.Dx, y0 + half + r.Dy, r.Confidence);
}
var motion = first ? new FrameMotion(Affine2D.Identity, 0, 0) : FitSimilarity(_matches.AsSpan(0, count));
_motions.Add(motion);
(_previous, _current) = (_current, _previous);
_currentEnergy.CopyTo(_previousEnergy, 0);
return motion;
}
/// <summary>Noise-compensated mean squared gradient of the blurred patch.</summary>
private double TextureEnergy(float[] plane, int x0, int y0, float[] smooth)
{
var p = PatchSize;
var w = Width;
double laplacian = 0;
for (var y = 1; y < p - 1; y++)
{
var row = (y0 + y) * w + x0;
for (var x = 1; x < p - 1; x++)
{
var c = row + x;
float a = plane[c - w - 1], b = plane[c - w], d = plane[c - w + 1];
float e = plane[c - 1], f = plane[c], g = plane[c + 1];
float h = plane[c + w - 1], i = plane[c + w], j = plane[c + w + 1];
smooth[y * p + x] = (a + d + h + j + 2 * (b + e + g + i) + 4 * f) * (1f / 16);
laplacian += float.Abs(a + d + h + j - 2 * (b + e + g + i) + 4 * f);
}
}
var sigma = double.Sqrt(double.Pi / 2) * laplacian / (6.0 * (p - 2) * (p - 2));
double energy = 0;
var samples = 0;
for (var y = 2; y < p - 2; y++)
{
for (var x = 2; x < p - 2; x++)
{
var k = y * p + x;
var gx = 0.5 * (smooth[k + 1] - smooth[k - 1]);
var gy = 0.5 * (smooth[k + p] - smooth[k - p]);
energy += gx * gx + gy * gy;
samples++;
}
}
return samples == 0 ? 0 : energy / samples - NoiseGradientGain * sigma * sigma;
}
private FrameMotion FitSimilarity(ReadOnlySpan<Match> matches)
{
var n = matches.Length;
if (n == 0) return new FrameMotion(Affine2D.Identity, 0, 0);
Span<bool> inliers = stackalloc bool[n];
Span<bool> best = stackalloc bool[n];
var bestCount = 0;
var bestResidual = double.PositiveInfinity;
Span<bool> pair = stackalloc bool[n];
for (var a = 0; a < n; a++)
{
for (var b = a + 1; b < n; b++)
{
pair.Clear();
pair[a] = pair[b] = true;
var model = Similarity(matches, pair);
if (double.Abs(model.Angle) > Options.MaxRotation || double.Abs(double.Log(model.Scale)) > Options.MaxScaleChange) continue;
Consider(model, matches, inliers, best, ref bestCount, ref bestResidual);
}
}
// Translation hypotheses, one per vector: covers a single valid patch and sets of implausible pairs.
if (bestCount < 2)
{
foreach (var m in matches) Consider(Affine2D.Translation(m.Qx - m.Px, m.Qy - m.Py), matches, inliers, best, ref bestCount, ref bestResidual);
return new FrameMotion(Translation(matches, best), n, bestCount);
}
return new FrameMotion(Similarity(matches, best), n, bestCount);
}
/// <summary>Scores a hypothesis and keeps it when it has more inliers (ties: smaller summed residual).</summary>
private void Consider(Affine2D model, ReadOnlySpan<Match> matches, Span<bool> inliers, Span<bool> best, ref int bestCount, ref double bestResidual)
{
var count = 0;
double residual = 0;
for (var i = 0; i < matches.Length; i++)
{
var m = matches[i];
var (x, y) = model.Apply(m.Px, m.Py);
var r = double.Hypot(x - m.Qx, y - m.Qy);
inliers[i] = r <= Options.InlierThreshold;
if (!inliers[i]) continue;
count++;
residual += r;
}
if (count < bestCount || (count == bestCount && residual >= bestResidual)) return;
bestCount = count;
bestResidual = residual;
inliers.CopyTo(best);
}
/// <summary>Weighted least-squares similarity q ≈ [a −b; b a]·p + t over the selected correspondences.</summary>
private static Affine2D Similarity(ReadOnlySpan<Match> matches, ReadOnlySpan<bool> selected)
{
double sw = 0, mpx = 0, mpy = 0, mqx = 0, mqy = 0;
for (var i = 0; i < matches.Length; i++)
{
if (!selected[i]) continue;
var m = matches[i];
sw += m.Weight;
mpx += m.Weight * m.Px;
mpy += m.Weight * m.Py;
mqx += m.Weight * m.Qx;
mqy += m.Weight * m.Qy;
}
mpx /= sw;
mpy /= sw;
mqx /= sw;
mqy /= sw;
double dot = 0, cross = 0, norm = 0;
for (var i = 0; i < matches.Length; i++)
{
if (!selected[i]) continue;
var m = matches[i];
double ax = m.Px - mpx, ay = m.Py - mpy, bx = m.Qx - mqx, by = m.Qy - mqy;
dot += m.Weight * (ax * bx + ay * by);
cross += m.Weight * (ax * by - ay * bx);
norm += m.Weight * (ax * ax + ay * ay);
}
if (norm <= 1e-12) return Affine2D.Translation(mqx - mpx, mqy - mpy);
var a = dot / norm;
var b = cross / norm;
return new Affine2D(a, -b, b, a, mqx - (a * mpx - b * mpy), mqy - (b * mpx + a * mpy));
}
private static Affine2D Translation(ReadOnlySpan<Match> matches, ReadOnlySpan<bool> selected)
{
double sw = 0, tx = 0, ty = 0;
for (var i = 0; i < matches.Length; i++)
{
if (!selected[i]) continue;
var m = matches[i];
sw += m.Weight;
tx += m.Weight * (m.Qx - m.Px);
ty += m.Weight * (m.Qy - m.Py);
}
return sw > 0 ? Affine2D.Translation(tx / sw, ty / sw) : Affine2D.Identity;
}
/// <summary>RMS displacement of the patch-grid centres under the corrections.</summary>
private double ShakeRms(Affine2D[] corrections)
{
double sum = 0;
var half = (PatchSize - 1) / 2.0;
foreach (var k in corrections)
{
foreach (var (x0, y0) in _patches)
{
var (x, y) = k.Apply(x0 + half, y0 + half);
sum += (x - x0 - half) * (x - x0 - half) + (y - y0 - half) * (y - y0 - half);
}
}
return double.Sqrt(sum / (corrections.Length * _patches.Length));
}
/// <summary>
/// Largest scale f of a centred, frame-shaped output rectangle whose corners map inside the source under
/// every inverse correction (each corner gives linear bounds on f).
/// </summary>
private double CropScale(Affine2D[] corrections)
{
double cx = (Width - 1) / 2.0, cy = (Height - 1) / 2.0;
double hx = Width / 2.0, hy = Height / 2.0;
double minX = -0.5, minY = -0.5, maxX = Width - 0.5, maxY = Height - 0.5;
var scale = 1.0;
foreach (var correction in corrections)
{
var inverse = correction.Invert();
var (ox, oy) = inverse.Apply(cx, cy);
if (ox < minX || ox > maxX || oy < minY || oy > maxY) return 0;
for (var corner = 0; corner < 4; corner++)
{
var (dx, dy) = inverse.ApplyVector((corner & 1) == 0 ? -hx : hx, (corner & 2) == 0 ? -hy : hy);
scale = Limit(scale, ox, dx, minX, maxX);
scale = Limit(scale, oy, dy, minY, maxY);
}
}
return double.Clamp(scale, 0, 1);
static double Limit(double f, double origin, double direction, double min, double max)
{
if (direction > 0) return double.Min(f, (max - origin) / direction);
if (direction < 0) return double.Min(f, (min - origin) / direction);
return f;
}
}
/// <summary>Patch centre in the previous frame (P) and where its content moved in the current one (Q).</summary>
private readonly record struct Match(double Px, double Py, double Qx, double Qy, double Weight);
}
+253
View File
@@ -0,0 +1,253 @@
using System.Numerics;
using Chronos.Core.Imaging;
namespace Chronos.Core.Motion;
/// <summary>How a <see cref="TemporalStacker"/> combines its window.</summary>
public enum StackMode
{
/// <summary>Per-pixel median: removes transients (aircraft, birds, people) present in under half the frames.</summary>
Median,
/// <summary>Per-pixel mean: noise reduction by √N for static scenes.</summary>
Mean,
}
/// <summary>
/// Sliding-window temporal stacking. <see cref="Push"/> copies frames into a ring of pooled buffers;
/// <see cref="Render"/> combines the frames currently in the window. Medians are exact: for up to
/// <see cref="NetworkLimit"/> frames an odd–even transposition sorting network runs on Vector&lt;float&gt;
/// lanes (many pixels per instruction, no branches), beyond that Hoare's selection runs per pixel.
/// Rows of every channel run in parallel.
/// </summary>
public sealed class TemporalStacker : IDisposable
{
/// <summary>Largest frame count sorted by the vectorised network (N² min/max per lane block).</summary>
public const int NetworkLimit = 32;
private readonly ImageBuffer?[] _ring;
private int _next;
public TemporalStacker(int window, StackMode mode)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(window);
Window = window;
Mode = mode;
_ring = new ImageBuffer?[window];
}
public int Window { get; }
public StackMode Mode { get; }
/// <summary>Frames currently in the window.</summary>
public int Count { get; private set; }
public bool IsFull => Count == Window;
/// <summary>Adds a copy of <paramref name="frame"/>, evicting the oldest frame once the window is full.</summary>
public void Push(ImageBuffer frame)
{
var first = _ring[0];
if (first is not null && (first.Width != frame.Width || first.Height != frame.Height || first.Channels != frame.Channels))
throw new ArgumentException("Frame differs in size or channels from the window.", nameof(frame));
var slot = _ring[_next] ??= new ImageBuffer(frame.Width, frame.Height, frame.Channels, clear: false);
frame.CopyTo(slot);
_next = (_next + 1) % Window;
Count = int.Min(Count + 1, Window);
}
/// <summary>Combines the frames in the window into <paramref name="destination"/>.</summary>
public void Render(ImageBuffer destination, CancellationToken cancellationToken = default)
{
if (Count == 0) throw new InvalidOperationException("The window is empty.");
var frames = new ImageBuffer[Count];
for (var i = 0; i < Count; i++) frames[i] = _ring[i]!;
if (Mode == StackMode.Median) Median(frames, destination, cancellationToken);
else Mean(frames, destination, cancellationToken);
}
/// <summary>Empties the window (buffers are kept for reuse).</summary>
public void Clear()
{
Count = 0;
_next = 0;
}
public void Dispose()
{
for (var i = 0; i < _ring.Length; i++)
{
_ring[i]?.Dispose();
_ring[i] = null;
}
Clear();
}
/// <summary>Exact per-pixel, per-channel median (mean of the middle pair for even counts).</summary>
public static void Median(IReadOnlyList<ImageBuffer> frames, ImageBuffer destination, CancellationToken cancellationToken = default)
{
var planes = Validate(frames, destination);
var n = frames.Count;
var dst = destination.Storage;
ForRows(destination, cancellationToken, (offset, length) =>
{
var i = 0;
if (n <= NetworkLimit && Vector.IsHardwareAccelerated)
{
Span<Vector<float>> lanes = stackalloc Vector<float>[n];
var vc = Vector<float>.Count;
for (; i <= length - vc; i += vc)
{
var at = offset + i;
for (var k = 0; k < n; k++) lanes[k] = new Vector<float>(planes[k], at);
var median = PlaneOps.MedianOfLanes(lanes);
median.CopyTo(dst, at);
}
}
Span<float> values = n <= 256 ? stackalloc float[n] : new float[n];
for (; i < length; i++)
{
var at = offset + i;
for (var k = 0; k < n; k++) values[k] = planes[k][at];
dst[at] = PlaneOps.Median(values);
}
});
}
/// <summary>Per-pixel, per-channel arithmetic mean.</summary>
public static void Mean(IReadOnlyList<ImageBuffer> frames, ImageBuffer destination, CancellationToken cancellationToken = default)
{
var planes = Validate(frames, destination);
var dst = destination.Storage;
var scale = 1f / frames.Count;
ForRows(destination, cancellationToken, (offset, length) =>
{
var span = dst.AsSpan(offset, length);
planes[0].AsSpan(offset, length).CopyTo(span);
for (var k = 1; k < planes.Length; k++) Accumulate(span, planes[k].AsSpan(offset, length));
Scale(span, scale);
});
}
private static float[][] Validate(IReadOnlyList<ImageBuffer> frames, ImageBuffer destination)
{
if (frames.Count == 0) throw new ArgumentException("At least one frame is required.", nameof(frames));
var planes = new float[frames.Count][];
for (var i = 0; i < frames.Count; i++)
{
var f = frames[i];
if (f.Width != destination.Width || f.Height != destination.Height || f.Channels != destination.Channels)
throw new ArgumentException("Frames and destination must share size and channels.", nameof(frames));
planes[i] = f.Storage;
}
return planes;
}
/// <summary>Runs <paramref name="body"/>(offset, length) over every row of every channel, in parallel when large.</summary>
private static void ForRows(ImageBuffer destination, CancellationToken cancellationToken, Action<int, int> body)
{
var rows = destination.Height * destination.Channels;
var width = destination.Width;
if ((long)rows * width < PlaneOps.ParallelThreshold)
{
for (var r = 0; r < rows; r++)
{
cancellationToken.ThrowIfCancellationRequested();
body(r * width, width);
}
}
else
{
Parallel.For(0, rows, new ParallelOptions { CancellationToken = cancellationToken }, r => body(r * width, width));
}
}
private static void Accumulate(Span<float> sum, ReadOnlySpan<float> values)
{
var i = 0;
if (Vector.IsHardwareAccelerated)
{
for (; i <= sum.Length - Vector<float>.Count; i += Vector<float>.Count)
(new Vector<float>(sum[i..]) + new Vector<float>(values[i..])).CopyTo(sum[i..]);
}
for (; i < sum.Length; i++) sum[i] += values[i];
}
private static void Scale(Span<float> values, float factor)
{
var i = 0;
if (Vector.IsHardwareAccelerated)
{
for (; i <= values.Length - Vector<float>.Count; i += Vector<float>.Count)
(new Vector<float>(values[i..]) * factor).CopyTo(values[i..]);
}
for (; i < values.Length; i++) values[i] *= factor;
}
}
/// <summary>
/// Star trails by progressive maximum with exponential decay: acc ← max(acc · decay, frame) per pixel and
/// channel. Decay 1 keeps every trail forever (the accumulator never decreases); smaller values make
/// trails fade behind the stars (see <see cref="DecayForTrailLength"/>).
/// </summary>
public sealed class StarTrailStacker : IDisposable
{
/// <summary>Relative brightness a trail point has fallen to after its trail length.</summary>
public const double TrailFloor = 0.01;
private ImageBuffer? _accumulator;
public StarTrailStacker(double decay = 1.0)
{
if (!(decay is > 0 and <= 1)) throw new ArgumentOutOfRangeException(nameof(decay), "Decay must lie in (0, 1].");
Decay = decay;
}
public double Decay { get; }
/// <summary>Frames added so far.</summary>
public int Count { get; private set; }
/// <summary>The running result (null before the first frame); owned by the stacker.</summary>
public ImageBuffer? Result => _accumulator;
/// <summary>
/// Decay that fades a trail point to <see cref="TrailFloor"/> (1 %) of its brightness after
/// <paramref name="frames"/> frames: 0.01^(1/frames). Infinite or non-positive lengths give 1 (endless trails).
/// </summary>
public static double DecayForTrailLength(double frames) =>
frames > 0 && double.IsFinite(frames) ? double.Pow(TrailFloor, 1 / frames) : 1.0;
/// <summary>Folds the next frame into the trails.</summary>
public void Add(ImageBuffer frame)
{
if (_accumulator is null)
{
_accumulator = frame.Clone();
Count = 1;
return;
}
if (frame.Width != _accumulator.Width || frame.Height != _accumulator.Height || frame.Channels != _accumulator.Channels)
throw new ArgumentException("Frame differs in size or channels.", nameof(frame));
var acc = _accumulator.Data;
var src = frame.Data;
var decay = (float)Decay;
var i = 0;
if (Vector.IsHardwareAccelerated)
{
for (; i <= acc.Length - Vector<float>.Count; i += Vector<float>.Count)
Vector.Max(new Vector<float>(acc[i..]) * decay, new Vector<float>(src[i..])).CopyTo(acc[i..]);
}
for (; i < acc.Length; i++) acc[i] = float.Max(acc[i] * decay, src[i]);
Count++;
}
public void Dispose()
{
_accumulator?.Dispose();
_accumulator = null;
Count = 0;
}
}
+87
View File
@@ -0,0 +1,87 @@
using Chronos.Core.Imaging.Geometry;
namespace Chronos.Core.Motion;
/// <summary>
/// Virtual camera pose: view centre in normalised source coordinates (0..1 across the frame), zoom ≥ 1
/// (1 shows the whole frame) and roll in degrees (positive turns the camera clockwise on screen, so the
/// content appears turned counter-clockwise).
/// </summary>
public readonly record struct CameraState(double CenterX, double CenterY, double Zoom, double Rotation);
/// <summary>A virtual camera keyframe; <see cref="Easing"/> shapes the segment from this keyframe to the next.</summary>
public readonly record struct CameraKeyframe(double Frame, double CenterX, double CenterY, double Zoom, double Rotation)
{
public BezierEasing Easing { get; init; } = BezierEasing.EaseInOut;
public CameraState State => new(CenterX, CenterY, Zoom, Rotation);
}
/// <summary>
/// Ken Burns style pan/zoom/roll: keyframes interpolated with per-segment cubic Bézier easing (centre and
/// roll linearly in the eased progress, zoom geometrically so equal steps look equally fast). The pose
/// becomes one affine that is composed with the stabiliser correction, so the frame is resampled once.
/// </summary>
public sealed class VirtualCamera
{
private readonly CameraKeyframe[] _keyframes;
public VirtualCamera(IEnumerable<CameraKeyframe> keyframes)
{
_keyframes = keyframes.OrderBy(k => k.Frame).ToArray();
if (_keyframes.Length == 0) throw new ArgumentException("At least one keyframe is required.", nameof(keyframes));
for (var i = 0; i < _keyframes.Length; i++)
{
var k = _keyframes[i];
if (!(k.Zoom >= 1) || !double.IsFinite(k.Zoom)) throw new ArgumentOutOfRangeException(nameof(keyframes), "Zoom must be ≥ 1.");
if (!double.IsFinite(k.Frame + k.CenterX + k.CenterY + k.Rotation)) throw new ArgumentOutOfRangeException(nameof(keyframes), "Keyframe values must be finite.");
if (i > 0 && k.Frame == _keyframes[i - 1].Frame) throw new ArgumentException("Two keyframes share a frame.", nameof(keyframes));
}
}
public IReadOnlyList<CameraKeyframe> Keyframes => _keyframes;
/// <summary>Pose at a (possibly fractional) output frame; held constant before the first and after the last keyframe.</summary>
public CameraState Evaluate(double frame)
{
if (frame <= _keyframes[0].Frame) return _keyframes[0].State;
if (frame >= _keyframes[^1].Frame) return _keyframes[^1].State;
var i = 0;
while (_keyframes[i + 1].Frame <= frame) i++;
var a = _keyframes[i];
if (frame == a.Frame) return a.State;
var b = _keyframes[i + 1];
var p = a.Easing.Evaluate((frame - a.Frame) / (b.Frame - a.Frame));
return new CameraState(
a.CenterX + (b.CenterX - a.CenterX) * p,
a.CenterY + (b.CenterY - a.CenterY) * p,
a.Zoom * double.Pow(b.Zoom / a.Zoom, p),
a.Rotation + (b.Rotation - a.Rotation) * p);
}
/// <summary>
/// Maps view pixel-centre coordinates (a frame-sized view) to source pixel-centre coordinates:
/// x_src = C + R(roll)·(x_view − view centre) / zoom.
/// </summary>
public static Affine2D ViewToSource(CameraState state, int sourceWidth, int sourceHeight)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceWidth);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceHeight);
var centreX = state.CenterX * sourceWidth - 0.5;
var centreY = state.CenterY * sourceHeight - 0.5;
return Affine2D.Translation(centreX, centreY)
* Affine2D.Similarity(1 / state.Zoom, state.Rotation * double.Pi / 180, 0, 0)
* Affine2D.Translation(-(sourceWidth - 1) / 2.0, -(sourceHeight - 1) / 2.0);
}
/// <summary>
/// The single view→source map for an output frame: the camera view composed with the inverse of the
/// stabiliser correction (which maps source to stabilised coordinates). Feed it to
/// <see cref="GeometrySettings.Warp"/>.
/// </summary>
public Affine2D ToSource(double frame, int sourceWidth, int sourceHeight, Affine2D? stabilization = null)
{
var view = ViewToSource(Evaluate(frame), sourceWidth, sourceHeight);
return stabilization is { } correction ? correction.Invert() * view : view;
}
}