refactor!: rename Titano to Chronos and move CI and releases to Gitea
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s

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. 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) and
  pe-check.

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-23 11:34:48 +02:00
1 parent c99842cc86
commit 5f27a86406
1799 files changed
+11728 -10668

No files matched your search

@@ -0,0 +1,57 @@
using Chronos.Core.Imaging;
using Chronos.Core.Video;
namespace Chronos.Core.Tests.Render;
/// <summary>One encode recorded by <see cref="CapturingEncoderProvider"/>.</summary>
internal sealed class CapturedEncode(EncodeSettings settings)
{
public EncodeSettings Settings { get; } = settings;
public List<ImageBuffer> Frames { get; } = [];
public List<long> Durations { get; } = [];
public bool Completed { get; set; }
public bool Disposed { get; set; }
}
/// <summary>Test encoder: keeps a copy of every frame, can pretend to be hardware or to fail at a given frame.</summary>
internal sealed class CapturingEncoderProvider(string name, params EncoderCapability[] capabilities) : IVideoEncoderProvider
{
public string Name => name;
public IReadOnlyList<EncoderCapability> Capabilities => capabilities;
public List<CapturedEncode> Encodes { get; } = [];
/// <summary>When set, WriteFrame throws this for the frame with that zero-based index.</summary>
public (int Frame, Exception Error)? FailAt { get; set; }
public bool CanEncode(EncodeSettings settings) => capabilities.Any(c =>
c.Codec == settings.Codec && settings.Width <= c.MaxWidth && settings.Height <= c.MaxHeight && (settings.BitDepth == 8 || c.SupportsTenBit));
public IVideoEncoderSession Open(EncodeSettings settings)
{
var encode = new CapturedEncode(settings);
Encodes.Add(encode);
var capability = capabilities.First(c => c.Codec == settings.Codec);
return new Session(this, encode, capability);
}
private sealed class Session(CapturingEncoderProvider owner, CapturedEncode encode, EncoderCapability capability) : IVideoEncoderSession
{
public string EncoderName => capability.Name;
public bool IsHardware => capability.Hardware;
public void WriteFrame(ImageBuffer frame, long duration90k)
{
if (owner.FailAt is { } fail && fail.Frame == encode.Frames.Count) throw fail.Error;
if (frame.Width != encode.Settings.Width || frame.Height != encode.Settings.Height) throw new ArgumentException("size");
encode.Frames.Add(frame.Clone());
encode.Durations.Add(duration90k);
}
public void Complete() => encode.Completed = true;
public void Dispose() => encode.Disposed = true;
}
}
@@ -0,0 +1,83 @@
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Render.Diagnostics;
using Chronos.Core.Video;
using Chronos.Core.Video.Managed;
namespace Chronos.Core.Tests.Render;
/// <summary>Small synthetic renders shared by the render tests.</summary>
internal static class RenderFixture
{
/// <summary>No module and no knee: the output equals the source.</summary>
public static ProjectSettings Plain { get; } = new() { Exposure = new ExposureSettings { HighlightKnee = null } };
public static SyntheticFrameSource Source(int frames = 12, double flickerEv = 0, Func<int, (double X, double Y)>? motion = null, int width = 96, int height = 64,
Func<SyntheticSequenceOptions, SyntheticSequenceOptions>? configure = null)
{
var options = new SyntheticSequenceOptions
{
Width = width,
Height = height,
FrameCount = frames,
StartEv = 0,
EndEv = 1,
FlickerEv = flickerEv,
Seed = 5,
};
return new SyntheticFrameSource(SyntheticSequence.Create(configure is null ? options : configure(options)), motion);
}
/// <summary>Renders into a capturing encoder (PNG-sequence capability) and returns the captured frames.</summary>
public static async Task<(CapturedEncode Encode, RenderResult Result)> CaptureAsync(RenderInput input, ResolvedExport? export = null, RenderOptions? options = null,
CancellationToken cancellationToken = default)
{
var capture = new CapturingEncoderProvider("capture", new EncoderCapability(VideoCodec.PngSequence, "Capture", false, 8192, 8192, true));
var target = new RenderTarget(export ?? Preset("png-sequence"), Path.Combine(Path.GetTempPath(), "chronos-capture-" + Guid.NewGuid().ToString("N")));
var result = await Pipeline(capture).RenderAsync(input, target, options, cancellationToken: cancellationToken);
return (capture.Encodes.Single(), result);
}
public static RenderInput Input(SyntheticFrameSource source, ProjectSettings? project = null) =>
new() { Source = source, Frames = source.Metadata(), Project = project ?? Plain };
/// <summary>A built-in preset's values at an explicit size (0×0 = source size).</summary>
public static ResolvedExport Preset(string presetId, int width = 96, int height = 64) =>
ExportResolver.FromPreset(ExportPresets.Find(presetId)!) with { Width = width, Height = height };
public static RenderTarget Target(string folder, ResolvedExport export, string name = "out") =>
new(export, Path.Combine(folder, name + (export.Container == ContainerFormat.ImageSequence ? string.Empty : VideoCodecInfo.FileExtension(export.Codec))));
public static RenderPipeline Pipeline(params IVideoEncoderProvider[] extra) =>
new([.. extra, new ManagedEncoderProvider()]);
/// <summary>Peak signal-to-noise ratio of the 8-bit sRGB encodings.</summary>
public static double Psnr(ImageBuffer expected, ImageBuffer actual)
{
var a = PixelConvert.ToInterleaved8(expected, 3);
var b = PixelConvert.ToInterleaved8(actual, 3);
double sum = 0;
for (var i = 0; i < a.Length; i++) sum += (a[i] - b[i]) * (a[i] - b[i]);
return sum == 0 ? double.PositiveInfinity : 10 * Math.Log10(255.0 * 255 / (sum / a.Length));
}
/// <summary>Synchronous progress sink (Progress&lt;T&gt; would post to the thread pool).</summary>
public sealed class Sink<T>(Action<T> report) : IProgress<T>
{
public void Report(T value) => report(value);
}
/// <summary>Throws an <see cref="IOException"/> for one frame, as an unreadable file would.</summary>
public sealed class FailingSource(IRenderFrameSource inner, int failAt) : IRenderFrameSource
{
public int FrameCount => inner.FrameCount;
public int Width => inner.Width;
public int Height => inner.Height;
public ValueTask<ImageBuffer> GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) =>
index == failAt ? throw new IOException($"frame {index} is unreadable") : inner.GetFrameAsync(index, maxLongEdge, purpose, cancellationToken);
}
}
@@ -0,0 +1,72 @@
using Chronos.Core.Render;
using Chronos.Core.Video;
using Chronos.Testing;
using static Chronos.Core.Tests.Render.RenderFixture;
namespace Chronos.Core.Tests.Render;
/// <summary>Process-wide observations (unobserved task exceptions, managed heap) that must not overlap other tests.</summary>
[Serial]
public sealed class RenderIsolationTests
{
private readonly TestContext _context;
public RenderIsolationTests(TestContext context) => _context = context;
[Test]
public async Task FailuresLeaveNoUnobservedTaskExceptions()
{
// Faulted tasks the earlier tests left for the finalizer are reported now, before this test starts counting.
GC.Collect();
GC.WaitForPendingFinalizers();
var unobserved = 0;
void Handler(object? sender, UnobservedTaskExceptionEventArgs e) => Interlocked.Increment(ref unobserved);
TaskScheduler.UnobservedTaskException += Handler;
try
{
var dir = _context.CreateTempDirectory();
var capture = new CapturingEncoderProvider("capture", new EncoderCapability(VideoCodec.PngSequence, "Capture", false, 4096, 4096, true))
{
FailAt = (2, new InvalidDataException("encoder broke")),
};
for (var i = 0; i < 3; i++)
{
await Assert.ThrowsAsync<InvalidDataException>(() => Pipeline(capture).RenderAsync(Input(Source()), Target(dir, Preset("png-sequence"))));
var input = Input(Source()) with { Source = new FailingSource(Source(), failAt: 3 + i) };
await Assert.ThrowsAsync<IOException>(() => Pipeline().RenderAsync(input, Target(dir, Preset("gif-preview"))));
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.Equal(0, unobserved);
Assert.Empty(Directory.GetFileSystemEntries(dir));
}
finally
{
TaskScheduler.UnobservedTaskException -= Handler;
}
}
/// <summary>BRIEF §20.4: peak memory does not depend on the sequence length (live managed heap sampled while rendering).</summary>
[Test]
public async Task MemoryDoesNotGrowWithSequenceLength()
{
async Task<long> PeakAsync(int frames)
{
var dir = _context.CreateTempDirectory();
long peak = 0;
var progress = new Sink<RenderProgress>(p =>
{
if (p.Stage == RenderStage.Rendering && p.Done % 8 == 0) peak = Math.Max(peak, GC.GetTotalMemory(forceFullCollection: true));
});
var project = Plain with { Exposure = new Chronos.Core.Project.ExposureSettings { Deflicker = new Chronos.Core.Project.Auto<bool>().WithManual(true) } };
await Pipeline().RenderAsync(Input(Source(frames), project), Target(dir, Preset("mjpeg-avi")), progress: progress, cancellationToken: _context.Cancellation);
return peak;
}
await PeakAsync(16);
var shortPeak = await PeakAsync(48);
var longPeak = await PeakAsync(192);
_context.Log($"peak live heap: 48 frames {shortPeak / 1024} KiB, 192 frames {longPeak / 1024} KiB");
Assert.Less(longPeak - shortPeak, 2 << 20);
}
}
@@ -0,0 +1,208 @@
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Codecs.Png;
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Render.Diagnostics;
using Chronos.Core.Video;
using Chronos.Core.Video.Managed;
using Chronos.Testing;
using static Chronos.Core.Tests.Render.RenderFixture;
namespace Chronos.Core.Tests.Render;
public sealed class RenderPipelineTests
{
private readonly TestContext _context;
public RenderPipelineTests(TestContext context) => _context = context;
[Theory]
[Case("mjpeg-avi", 8)]
[Case("jpeg-sequence", 8)]
[Case("png-sequence", 8)]
[Case("png-sequence", 16)]
[Case("tiff16-sequence", 16)]
[Case("dng-sequence", 16)]
[Case("gif-preview", 8)]
[Case("apng", 8)]
public async Task RendersEveryManagedFormat(string presetId, int bitDepth)
{
var dir = _context.CreateTempDirectory();
var source = Source();
var export = Preset(presetId) with { BitDepth = bitDepth };
var target = Target(dir, export);
var result = await Pipeline().RenderAsync(Input(source), target, cancellationToken: _context.Cancellation);
Assert.Equal(target.OutputPath, result.OutputPath);
Assert.SequenceEqual(new[] { Path.GetFileName(target.OutputPath) }, Directory.GetFileSystemEntries(dir).Select(Path.GetFileName));
Assert.Equal((96, 64), (result.Width, result.Height));
Assert.Equal(12, result.FrameCount);
Assert.Equal(RenderResultBytes(target.OutputPath), result.Bytes);
Assert.False(result.Hardware);
Assert.Approximately(12 / export.FrameRate.Value, result.DurationSeconds, 1e-4);
using var expected = source.Sequence.Render(5);
using var decoded = DecodeFrame(export.Codec, target.OutputPath, 5, out var count);
Assert.Equal(12, count);
var psnr = Psnr(expected, decoded);
_context.Log($"{presetId} {bitDepth}-bit: {result.Bytes} bytes, PSNR {psnr:F1} dB");
Assert.Greater(psnr, export.Codec switch { VideoCodec.Gif => 25, VideoCodec.Mjpeg or VideoCodec.JpegSequence => 35, _ => 60 });
}
[Test]
public async Task LosslessOutputsAreByteIdenticalAcrossRuns()
{
var dir = _context.CreateTempDirectory();
var project = Plain with
{
Exposure = new ExposureSettings { Deflicker = new Auto<bool>().WithManual(true), HighlightKnee = 0.9 },
Timing = new TimingSettings { Mode = new Auto<TimingMode>().WithManual(TimingMode.Interpolated), FrameRate = new Auto<string>().WithManual("15") },
};
var first = await Pipeline().RenderAsync(Input(Source(flickerEv: 0.2), project), Target(dir, Preset("png-sequence"), "a"), cancellationToken: _context.Cancellation);
var second = await Pipeline().RenderAsync(Input(Source(flickerEv: 0.2), project), Target(dir, Preset("png-sequence"), "b"), cancellationToken: _context.Cancellation);
var a = Directory.GetFiles(first.OutputPath).Order(StringComparer.Ordinal).ToArray();
var b = Directory.GetFiles(second.OutputPath).Order(StringComparer.Ordinal).ToArray();
Assert.Equal(a.Length, b.Length);
Assert.Greater(first.FrameCount, 12);
for (var i = 0; i < a.Length; i++) Assert.BytesEqual(File.ReadAllBytes(a[i]), File.ReadAllBytes(b[i]));
var apngA = await Pipeline().RenderAsync(Input(Source(), project), Target(dir, Preset("apng"), "c"), cancellationToken: _context.Cancellation);
var apngB = await Pipeline().RenderAsync(Input(Source(), project), Target(dir, Preset("apng"), "d"), cancellationToken: _context.Cancellation);
Assert.BytesEqual(File.ReadAllBytes(apngA.OutputPath), File.ReadAllBytes(apngB.OutputPath));
}
[Theory]
[Case("mjpeg-avi")]
[Case("png-sequence")]
[Case("gif-preview")]
public async Task CancellationLeavesNoOutput(string presetId)
{
var dir = _context.CreateTempDirectory();
using var cts = CancellationTokenSource.CreateLinkedTokenSource(_context.Cancellation);
var progress = new Sink<RenderProgress>(p =>
{
if (p.Stage == RenderStage.Rendering && p.Done == 5) cts.Cancel();
});
await Assert.ThrowsAsync<OperationCanceledException>(() => Pipeline().RenderAsync(Input(Source(24)), Target(dir, Preset(presetId)), progress: progress, cancellationToken: cts.Token));
Assert.Empty(Directory.GetFileSystemEntries(dir));
}
[Test]
public async Task SourceFailurePropagatesOnceAndLeavesNoOutput()
{
var dir = _context.CreateTempDirectory();
var input = Input(Source()) with { Source = new FailingSource(Source(), failAt: 7) };
var error = await Assert.ThrowsAsync<IOException>(() => Pipeline().RenderAsync(input, Target(dir, Preset("mjpeg-avi"))));
Assert.Equal("frame 7 is unreadable", error.Message);
Assert.Empty(Directory.GetFileSystemEntries(dir));
}
[Test]
public async Task EncoderFailurePropagatesAndDisposesTheSession()
{
var capture = new CapturingEncoderProvider("capture", new EncoderCapability(VideoCodec.PngSequence, "Capture", false, 4096, 4096, true))
{
FailAt = (4, new InvalidDataException("encoder broke")),
};
var error = await Assert.ThrowsAsync<InvalidDataException>(() => Pipeline(capture).RenderAsync(Input(Source()), Target(_context.CreateTempDirectory(), Preset("png-sequence"))));
Assert.Equal("encoder broke", error.Message);
var encode = capture.Encodes.Single();
Assert.True(encode.Disposed);
Assert.False(encode.Completed);
Assert.Equal(4, encode.Frames.Count);
}
[Test]
public async Task ProgressReportsEveryFrameAndPreviews()
{
var reports = new List<RenderProgress>();
var options = new RenderOptions { PreviewInterval = 5, PreviewLongEdge = 32 };
var project = Plain with { Exposure = new ExposureSettings { Deflicker = new Auto<bool>().WithManual(true), HighlightKnee = null } };
await Pipeline().RenderAsync(Input(Source(), project), Target(_context.CreateTempDirectory(), Preset("jpeg-sequence")), options,
new Sink<RenderProgress>(reports.Add), _context.Cancellation);
var preparing = reports.Where(r => r.Stage == RenderStage.Preparing).ToList();
var rendering = reports.Where(r => r.Stage == RenderStage.Rendering).ToList();
Assert.Equal(12, preparing.Count);
Assert.SequenceEqual(Enumerable.Range(1, 12), rendering.Select(r => r.Done));
Assert.True(rendering.All(r => r.Total == 12 && r.FramesPerSecond > 0 && r.Remaining >= TimeSpan.Zero));
Assert.SequenceEqual(new[] { 1, 6, 11 }, rendering.Where(r => r.Preview is not null).Select(r => r.Done));
Assert.Equal(32, rendering[0].Preview!.Width);
Assert.Equal(RenderStage.Finishing, reports[^1].Stage);
foreach (var r in rendering) r.Preview?.Dispose();
}
[Test]
public async Task BatchRendersEachTargetAndReportsFailures()
{
var dir = _context.CreateTempDirectory();
var server = new RenderPipeline([new ManagedEncoderProvider()], EncoderHost.Server);
var targets = new[]
{
Target(dir, Preset("png-sequence"), "png"),
Target(dir, Preset("1080p-h264"), "h264"),
Target(dir, Preset("gif-preview"), "gif"),
};
var results = await server.RenderBatchAsync(Input(Source()), targets, cancellationToken: _context.Cancellation);
Assert.Equal(3, results.Count);
Assert.True(results[0].Succeeded && results[2].Succeeded);
var error = Assert.NotNull(results[1].Error as RenderException);
Assert.Equal(EncoderNotices.NeedsRenderNode, error.ReasonKey);
Assert.SequenceEqual(new[] { "gif.gif", "png" }, Directory.GetFileSystemEntries(dir).Select(Path.GetFileName).Order(StringComparer.Ordinal));
}
[Test]
public async Task EverythingExcludedIsARenderError()
{
var project = Plain with { ExcludedFrames = [.. Enumerable.Range(0, 12)] };
var error = await Assert.ThrowsAsync<RenderException>(() => Pipeline().RenderAsync(Input(Source(), project), Target(_context.CreateTempDirectory(), Preset("png-sequence"))));
Assert.Equal("Export.Render.NoFrames", error.ReasonKey);
}
[Test]
public async Task ResultBecomesARenderHistoryEntity()
{
var result = await Pipeline().RenderAsync(Input(Source()), Target(_context.CreateTempDirectory(), Preset("apng")), cancellationToken: _context.Cancellation);
var sequence = Guid.CreateVersion7();
var entity = result.ToEntity(sequence, "APNG", "{}", "test");
Assert.Equal(sequence, entity.SequenceId);
Assert.Equal(result.OutputPath, entity.OutputPath);
Assert.Equal("Apng", entity.Codec);
Assert.Equal(result.Bytes, entity.Bytes);
Assert.Approximately(15, entity.Fps, 1e-12);
Assert.Equal("Managed APNG", result.EncoderName);
}
private static long RenderResultBytes(string path) => File.Exists(path)
? new FileInfo(path).Length
: new DirectoryInfo(path).EnumerateFiles().Sum(f => f.Length);
/// <summary>Decodes output picture <paramref name="index"/> and counts the pictures of the output.</summary>
private static ImageBuffer DecodeFrame(VideoCodec codec, string path, int index, out int count)
{
switch (codec)
{
case VideoCodec.Mjpeg:
var avi = AviReader.Read(File.ReadAllBytes(path));
count = avi.Frames.Count;
return JpegDecoder.DecodeToLinear(avi.Frames[index]);
case VideoCodec.Gif or VideoCodec.Apng:
var bytes = File.ReadAllBytes(path);
var animation = codec == VideoCodec.Gif ? GifReader.Decode(bytes) : ApngReader.Decode(bytes);
count = animation.Frames.Count;
return animation.ToLinear(index);
default:
var files = Directory.GetFiles(path).Order(StringComparer.Ordinal).ToArray();
count = files.Length;
var data = File.ReadAllBytes(files[index]);
return codec switch
{
VideoCodec.JpegSequence => JpegDecoder.DecodeToLinear(data),
VideoCodec.PngSequence => PngDecoder.DecodeToLinear(data),
_ => TiffImageReader.Decode(data),
};
}
}
}
@@ -0,0 +1,202 @@
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Video;
using Chronos.Testing;
namespace Chronos.Core.Tests.Render;
public sealed class RenderPlanTests
{
private static readonly DateTime Start = new(2024, 6, 21, 19, 0, 0);
private static DateTime?[] Regular(int count, double interval = 10) =>
Enumerable.Range(0, count).Select(i => (DateTime?)Start.AddSeconds(i * interval)).ToArray();
private static ProjectSettings Timing(TimingMode mode, string? playback = null, double? fit = null, IReadOnlyList<CurvePoint>? curve = null, int[]? excluded = null) => new()
{
Timing = new TimingSettings
{
Mode = new Auto<TimingMode>().WithManual(mode),
FrameRate = playback is null ? new Auto<string>() : new Auto<string>().WithManual(playback),
FitToSeconds = fit,
RemapCurve = curve ?? [new(0, 0), new(1, 1)],
},
ExcludedFrames = excluded ?? [],
};
private static void AssertExactDurations(RenderPlan plan)
{
Assert.Equal(plan.Duration90k, plan.Frames.Sum(f => f.Duration90k));
Assert.Equal(RenderPlan.TicksAt(plan.FrameRate, plan.SlotCount), plan.Duration90k);
long t = 0;
var slot = 0;
foreach (var f in plan.Frames)
{
Assert.Equal(t, f.Start90k);
Assert.Equal(slot, f.StartSlot);
Assert.Greater(f.Duration90k, 0);
t += f.Duration90k;
slot += f.Slots;
}
Assert.Equal(plan.SlotCount, slot);
Assert.Monotonic(plan.Frames.Select(f => f.SourcePosition));
}
[Test]
public void ConstantShowsEveryFrameOnceAtTheOutputRate()
{
var plan = RenderPlan.Build(Regular(100), Timing(TimingMode.Constant), new Rational(24, 1));
Assert.Equal(100, plan.Frames.Count);
Assert.SequenceEqual(Enumerable.Range(0, 100).Select(i => (double)i), plan.Frames.Select(f => f.SourcePosition));
Assert.True(plan.Frames.All(f => f.Duration90k == 3750 && f.Flags == PlannedFrameFlags.None && f.Speed == 1));
Assert.Equal(375_000L, plan.Duration90k);
AssertExactDurations(plan);
}
[Test]
public void ExcludedFramesAreSkipped()
{
var plan = RenderPlan.Build(Regular(20), Timing(TimingMode.Constant, excluded: [3, 7, 99]), new Rational(25, 1));
Assert.Equal(18, plan.Frames.Count);
Assert.DoesNotContain(3, plan.Frames.Select(f => f.From));
Assert.DoesNotContain(7, plan.Frames.Select(f => f.To));
Assert.Equal(2, plan.Statistics.ExcludedFrames);
Assert.Equal(2.0, plan.Frames.Single(f => f.From == 2).Speed);
AssertExactDurations(plan);
}
[Test]
public void NtscDurationsAccumulateWithoutDrift()
{
var plan = RenderPlan.Build(Regular(1001), Timing(TimingMode.Constant), Rational.Fps2997);
Assert.Equal(1001 * 3003L, plan.Duration90k);
Assert.True(plan.Frames.All(f => f.Duration90k == 3003));
var fps23 = RenderPlan.Build(Regular(7), Timing(TimingMode.Constant), Rational.Fps23976);
Assert.SequenceEqual(new long[] { 3754, 3754, 3753, 3754, 3754, 3754, 3753 }, fps23.Frames.Select(f => f.Duration90k));
Assert.Equal(26_276L, fps23.Duration90k);
AssertExactDurations(fps23);
}
[Test]
public void SlowerPlaybackHoldsFramesInConstantAndSynthesisesInInterpolated()
{
var held = RenderPlan.Build(Regular(10), Timing(TimingMode.Constant, playback: "12"), new Rational(24, 1));
Assert.Equal(10, held.Frames.Count);
Assert.True(held.Frames.All(f => f.Slots == 2 && f.IsHeld && f.Duration90k == 7500));
AssertExactDurations(held);
var smooth = RenderPlan.Build(Regular(10), Timing(TimingMode.Interpolated, playback: "12"), new Rational(24, 1));
Assert.Equal(19, smooth.Frames.Count);
Assert.Equal(9, smooth.Statistics.InterpolatedFrames);
Assert.Equal(0.5, smooth.Frames[1].SourcePosition);
Assert.Equal(0.5, smooth.Frames[1].Fraction);
Assert.Equal(9.0, smooth.Frames[^1].SourcePosition);
Assert.True(smooth.Frames[^1].IsHeld, "the last frame has no successor to blend towards");
AssertExactDurations(smooth);
}
[Test]
public void FitToSecondsScalesThePlan()
{
var shorter = RenderPlan.Build(Regular(100), Timing(TimingMode.Constant, fit: 2), new Rational(25, 1));
Assert.Equal(50, shorter.SlotCount);
Assert.Equal(180_000L, shorter.Duration90k);
Assert.True(shorter.Frames.All(f => f.Fraction == 0 && f.SourcePosition % 2 == 0));
Assert.Equal(50, shorter.Statistics.SkippedFrames);
Assert.Approximately(2.0, shorter.Statistics.MaximumSpeed, 1e-9);
var longer = RenderPlan.Build(Regular(100), Timing(TimingMode.Interpolated, fit: 7.96), new Rational(25, 1));
Assert.Equal(199, longer.SlotCount);
Assert.Equal(716_400L, longer.Duration90k);
Assert.Greater(longer.Statistics.InterpolatedFrames, 90);
AssertExactDurations(longer);
}
[Test]
public void AdaptiveFollowsCaptureTimeAndShortensPauses()
{
var times = Regular(40);
for (var i = 11; i < 40; i++) times[i] = times[i]!.Value.AddSeconds(10); // 2× interval into frame 11
for (var i = 21; i < 40; i++) times[i] = times[i]!.Value.AddSeconds(60); // 7× gap into frame 21
for (var i = 31; i < 40; i++) times[i] = times[i]!.Value.AddHours(1); // deliberate pause into frame 31
var plan = RenderPlan.Build(times, Timing(TimingMode.Adaptive), new Rational(24, 1));
Assert.Equal(40, plan.Frames.Count);
Assert.Equal(2, plan.Frames[10].Slots);
Assert.Equal(4, plan.Frames[20].Slots); // 3 + log2(7/3) = 4.22 periods, rounded on the grid
Assert.Equal(5, plan.Frames[30].Slots); // 0.2 s × 24 fps = 4.8 periods
Assert.True(plan.Frames.Where((_, i) => i is not (10 or 20 or 30)).All(f => f.Slots == 1));
Assert.False(plan.IsCutBefore(11));
Assert.True(plan.IsCutBefore(21));
Assert.True(plan.IsCutBefore(31));
Assert.Equal(-1, plan.NextContinuous(30));
Assert.Equal(29, plan.PreviousContinuous(30));
Assert.Equal(2, plan.Statistics.Cuts);
Assert.Approximately(10.0, plan.Statistics.MedianIntervalSeconds!.Value, 1e-9);
AssertExactDurations(plan);
}
[Test]
public void InterpolatedFillsMissingAndExcludedFrames()
{
var times = Regular(40);
for (var i = 20; i < 40; i++) times[i] = times[i]!.Value.AddSeconds(10); // one capture missing before frame 20
for (var i = 35; i < 40; i++) times[i] = times[i]!.Value.AddSeconds(600); // too long to synthesise
var plan = RenderPlan.Build(times, Timing(TimingMode.Interpolated, excluded: [30]), new Rational(30, 1));
var gap = plan.Frames.Single(f => f.From == 19 && f.IsInterpolated);
Assert.Equal(19.5, gap.SourcePosition);
Assert.Equal(20, gap.To);
var excluded = plan.Frames.Single(f => f.From == 29 && f.IsInterpolated);
Assert.Equal(30.0, excluded.SourcePosition);
Assert.Equal(31, excluded.To);
Assert.Equal(0.5, excluded.Fraction);
Assert.True(plan.IsCutBefore(35));
Assert.False(plan.Frames.Any(f => f.From == 34 && f.IsInterpolated));
Assert.Equal(41, plan.Frames.Count);
AssertExactDurations(plan);
}
[Test]
public void RemapIsMonotoneEvenForBadCurves()
{
var ease = RenderPlan.Build(Regular(120), Timing(TimingMode.Remapped, curve: [new(0, 0), new(0.5, 0.2), new(1, 1)]), new Rational(24, 1));
AssertExactDurations(ease);
Assert.Equal(120, ease.SlotCount);
Assert.Equal(0.0, ease.Frames[0].SourcePosition);
Assert.Greater(ease.Frames[^1].SourcePosition, 115);
Assert.Less(ease.Frames[^1].Speed * ease.Frames[^1].Slots, 3.5);
Assert.Less(ease.Frames[10].Speed, 0.5);
Assert.Empty(ease.Warnings);
var bad = RenderPlan.Build(Regular(60), Timing(TimingMode.Remapped, curve: [new(1, 1), new(0, 0.1), new(0.4, 0.8), new(0.6, 0.3)]), new Rational(24, 1));
Assert.Contains("Export.Plan.RemapNotMonotonic", bad.Warnings);
AssertExactDurations(bad);
Assert.Approximately(0.1 * 60, bad.Frames[0].SourcePosition, 1e-9);
}
[Test]
public void AnUnreadablePlaybackRateFallsBackToTheOutputRate()
{
var plan = RenderPlan.Build(Regular(10), Timing(TimingMode.Constant, playback: "fast"), new Rational(25, 1));
Assert.Contains("Export.Plan.FrameRateIgnored", plan.Warnings);
Assert.Equal(10, plan.SlotCount);
Assert.Equal(25.0, plan.PlaybackRate);
}
[Test]
public void EverythingExcludedGivesAnEmptyPlan()
{
var plan = RenderPlan.Build(Regular(3), Timing(TimingMode.Constant, excluded: [0, 1, 2]), new Rational(30, 1));
Assert.Empty(plan.Frames);
Assert.Equal(0L, plan.Duration90k);
Assert.Contains("Export.Plan.NoFrames", plan.Warnings);
}
[Test]
public void AdaptiveWithoutCaptureTimesFallsBackToConstantPacing()
{
var plan = RenderPlan.Build(new DateTime?[12], Timing(TimingMode.Adaptive), new Rational(30, 1));
Assert.Equal(12, plan.Frames.Count);
Assert.Contains("Export.Plan.NoCaptureTimes", plan.Warnings);
AssertExactDurations(plan);
}
}
@@ -0,0 +1,371 @@
using Chronos.Core.Analysis;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Geometry;
using Chronos.Core.Motion;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Render.Diagnostics;
using Chronos.Testing;
using static Chronos.Core.Tests.Render.RenderFixture;
namespace Chronos.Core.Tests.Render;
public sealed class RenderProcessingTests
{
private readonly TestContext _context;
public RenderProcessingTests(TestContext context) => _context = context;
private static ProjectSettings With(ExposureSettings? exposure = null, MotionSettings? motion = null, CameraSettings? camera = null, StackSettings? stack = null,
TimingSettings? timing = null) => Plain with
{
Exposure = exposure ?? Plain.Exposure,
Motion = motion ?? new MotionSettings(),
Camera = camera ?? new CameraSettings(),
Stack = stack ?? new StackSettings(),
Timing = timing ?? new TimingSettings(),
};
private static Auto<T> On<T>(T value) => new Auto<T>().WithManual(value);
private static double[] LogLuminance(IEnumerable<ImageBuffer> frames) => [.. frames.Select(f => FrameStatistics.MeasureLogLuminance(f))];
private static double Rms(IEnumerable<double> values)
{
var v = values.ToArray();
var mean = v.Average();
return Math.Sqrt(v.Sum(x => (x - mean) * (x - mean)) / v.Length);
}
/// <summary>The §20.4 deflicker gate measured on rendered frames (same recipe as the analysis gate).</summary>
[Test]
public async Task DeflickerRemovesFlickerAndKeepsTheRamp()
{
var source = Source(200, configure: o => o with { Seed = 3, StartEv = -2, EndEv = 1, FlickerEv = 0.1 });
var project = With(new ExposureSettings { Deflicker = On(true), DeflickerWindow = On(21), HighlightKnee = null });
var (encode, _) = await CaptureAsync(Input(source, project), cancellationToken: _context.Cancellation);
var truth = source.Sequence.SceneEv;
var measured = Analysis.AnalysisFixtures.MeasureSeries(source.Sequence);
var output = LogLuminance(encode.Frames);
var before = Analysis.AnalysisFixtures.FrameToFrameResidualRms(measured, truth);
var after = Analysis.AnalysisFixtures.FrameToFrameResidualRms(output, truth);
var rampError = Analysis.AnalysisFixtures.MaxDeviation(output, truth);
_context.Log($"flicker {before:F4} → {after:F4} EV ({1 - after / before:P0}); max ramp deviation {rampError:F4} EV");
Assert.GreaterOrEqual(1 - after / before, 0.6);
Assert.LessOrEqual(rampError, 0.05);
}
[Test]
public async Task HolyGrailTurnsExposureStepsIntoRamps()
{
var source = Source(80, configure: o => o with { ExposureSteps = [new SyntheticExposureStep(40, 1.0)], StartEv = 0, EndEv = 0 });
var project = With(new ExposureSettings { HolyGrail = On(true), Deflicker = On(true), HighlightKnee = null });
var (encode, _) = await CaptureAsync(Input(source, project), cancellationToken: _context.Cancellation);
var output = LogLuminance(encode.Frames);
var steps = output.Zip(output.Skip(1), (a, b) => Math.Abs(b - a)).ToArray();
_context.Log($"largest output step {steps.Max():F3} EV");
Assert.LessOrEqual(steps.Max(), 0.3 + 0.02);
Assert.Approximately(-1.0, output[^1] - output[0], 0.1, "the step is kept, only spread out");
}
[Test]
public async Task ExcludedFramesDoNotCreateExposureSteps()
{
// Frame 10 is a test shot one stop darker; excluding it must leave no holy-grail step behind.
var source = Source(30, configure: o => o with { ExposureSteps = [new SyntheticExposureStep(10, 1.0), new SyntheticExposureStep(11, -1.0)], StartEv = 0, EndEv = 0 });
var project = With(new ExposureSettings { HolyGrail = On(true), HighlightKnee = null });
var all = await RenderPreparation.PrepareAsync(Input(source, project), cancellationToken: _context.Cancellation);
var excluded = await RenderPreparation.PrepareAsync(Input(source, project with { ExcludedFrames = [10] }), cancellationToken: _context.Cancellation);
Assert.Count(2, all.Report.Transitions);
Assert.Empty(excluded.Report.Transitions);
Assert.True(double.IsNaN(excluded.MeasuredLogLuminance[10]));
}
[Test]
public async Task WhiteBalanceSmoothingRemovesColourJitter()
{
var source = Source(48, configure: o => o with { WhiteBalanceJitter = 0.1 });
var (encode, _) = await CaptureAsync(Input(source, With(new ExposureSettings { WhiteBalanceSmoothing = On(true), HighlightKnee = null })), cancellationToken: _context.Cancellation);
double Ratio(ImageBuffer f)
{
var stats = FrameStatistics.Measure(f);
return Math.Log2(stats.MeanRed / stats.MeanGreen);
}
var before = Enumerable.Range(0, 48).Select(i =>
{
using var f = source.Sequence.Render(i);
return Ratio(f);
}).ToArray();
var after = encode.Frames.Select(Ratio).ToArray();
double Jitter(double[] r) => Rms(r.Zip(r.Skip(1), (a, b) => b - a));
_context.Log($"R/G jitter {Jitter(before):F4} → {Jitter(after):F4}");
Assert.Less(Jitter(after), 0.3 * Jitter(before));
}
[Test]
public async Task RegionDeflickerCorrectsSkyAndLandSeparately()
{
var source = Source(48, configure: o => o with { SkyFlickerEv = 0.3, LandFlickerEv = 0.3, StartEv = 0, EndEv = 0 });
var landMask = new float[96 * 64];
for (var y = 0; y < 64; y++)
{
for (var x = 0; x < 96; x++) landMask[y * 96 + x] = source.Sequence.IsSky(x, y) ? 0 : 1;
}
double LandResidual(List<ImageBuffer> frames) => Rms(frames.Select(f => FrameStatistics.MeasureLogLuminance(f, landMask)));
var global = await CaptureAsync(Input(source, With(new ExposureSettings { Deflicker = On(true), HighlightKnee = null })), cancellationToken: _context.Cancellation);
var regions = await CaptureAsync(Input(source, With(new ExposureSettings { Deflicker = On(true), Regions = On(RegionMode.Horizon), HighlightKnee = null })),
cancellationToken: _context.Cancellation);
var g = LandResidual(global.Encode.Frames);
var r = LandResidual(regions.Encode.Frames);
_context.Log($"land residual global {g:F3} EV, regions {r:F3} EV");
Assert.Less(r, 0.5 * g);
var prepared = await RenderPreparation.PrepareAsync(Input(source, With(new ExposureSettings { Deflicker = On(true), Regions = On(RegionMode.Horizon) })),
cancellationToken: _context.Cancellation);
Assert.Equal(RegionMethod.Horizon, prepared.Report.RegionMethod);
Assert.NotNull(prepared.SkyEv);
}
[Test]
public async Task ExportAspectCropsTheCentreAndCameraCropMovesIt()
{
var source = Source(4);
using var reference = source.Sequence.Render(2);
var (square, _) = await CaptureAsync(Input(source), Preset("png-sequence", 64, 64), cancellationToken: _context.Cancellation);
using (var expected = GeometryStage.Apply(reference, new GeometrySettings { Crop = new RectD(16, 0, 64, 64), OutputWidth = 64, OutputHeight = 64 }))
Assert.Greater(Psnr(expected, square.Frames[2]), 60);
var quarter = With(camera: new CameraSettings { Crop = [0.5, 0.5, 0.5, 0.5] });
var (corner, result) = await CaptureAsync(Input(source, quarter), Preset("png-sequence", 0, 0), cancellationToken: _context.Cancellation);
Assert.Equal((48, 32), (result.Width, result.Height));
using (var expected = GeometryStage.Apply(reference, new GeometrySettings { Crop = new RectD(48, 32, 48, 32) }))
Assert.Greater(Psnr(expected, corner.Frames[2]), 60);
}
[Test]
public async Task VirtualCameraZoomsAndTheDecodeSizeFollowsTheNeed()
{
var plain = Source(4, width: 480, height: 320);
await CaptureAsync(Input(plain), Preset("png-sequence", 96, 64), cancellationToken: _context.Cancellation);
Assert.Equal(96, plain.LargestRenderRequest);
var zoomed = Source(4, width: 480, height: 320);
var camera = With(camera: new CameraSettings { Keyframes = [new CameraKey(0, 0.5, 0.5, 2, 0), new CameraKey(3, 0.5, 0.5, 2, 0)] });
var (encode, _) = await CaptureAsync(Input(zoomed, camera), Preset("png-sequence", 96, 64), cancellationToken: _context.Cancellation);
Assert.Equal(192, zoomed.LargestRenderRequest);
var capped = Source(4, width: 480, height: 320);
await CaptureAsync(Input(capped, camera), Preset("png-sequence", 96, 64), new RenderOptions { MaxWorkingLongEdge = 120 }, _context.Cancellation);
Assert.Equal(120, capped.LargestRenderRequest);
using var full = zoomed.Sequence.Render(1);
using var expected = GeometryStage.Apply(full, new GeometrySettings { Crop = new RectD(120, 80, 240, 160), OutputWidth = 96, OutputHeight = 64 });
var psnr = Psnr(expected, encode.Frames[1]);
_context.Log($"zoom ×2 vs direct crop: {psnr:F1} dB");
Assert.Greater(psnr, 28);
}
[Test]
public async Task ExposureOffsetAndKneeAreApplied()
{
var source = Source(3, configure: o => o with { StartEv = 2, EndEv = 2 });
var (raw, _) = await CaptureAsync(Input(source), cancellationToken: _context.Cancellation);
var (brighter, _) = await CaptureAsync(Input(source, With(new ExposureSettings { ExposureOffsetEv = 1, HighlightKnee = null })), cancellationToken: _context.Cancellation);
for (var i = 0; i < raw.Frames[0].Data.Length; i += 13) Assert.Approximately(2 * raw.Frames[0].Data[i], brighter.Frames[0].Data[i], 1e-5);
Assert.Greater(raw.Frames[0].Data.ToArray().Max(), 1f);
var (kneed, _) = await CaptureAsync(Input(source, With(new ExposureSettings { HighlightKnee = 0.8 })), cancellationToken: _context.Cancellation);
Assert.Less(kneed.Frames[0].Data.ToArray().Max(), 1f);
for (var i = 0; i < raw.Frames[0].Data.Length; i += 13)
{
if (raw.Frames[0].Data[i] < 0.5f) Assert.Approximately(raw.Frames[0].Data[i], kneed.Frames[0].Data[i], 1e-6);
}
}
[Test]
public async Task InterpolatedFramesFollowTheMotion()
{
Func<int, (double, double)> pan = i => (2.0 * i, 0);
var source = Source(6, motion: pan, configure: o => o with { StartEv = 0, EndEv = 0 });
var timing = new TimingSettings { Mode = On(TimingMode.Interpolated), FrameRate = new Auto<string>().WithManual("15") };
var export = Preset("png-sequence") with { FrameRate = new Chronos.Core.Video.Rational(30, 1) };
var (encode, result) = await CaptureAsync(Input(source, With(timing: timing)), export, cancellationToken: _context.Cancellation);
Assert.Equal(11, result.FrameCount);
Assert.Equal(12, encode.Durations.Sum() / 3000);
var truth = Source(6, motion: i => (2.0 * i + 1, 0), configure: o => o with { StartEv = 0, EndEv = 0 });
using var shifted = await truth.GetFrameAsync(2, 0, DecodePurpose.Render, _context.Cancellation);
double Interior(ImageBuffer a, ImageBuffer b)
{
using var ca = GeometryStage.Apply(a, new GeometrySettings { Crop = new RectD(12, 4, 72, 56) });
using var cb = GeometryStage.Apply(b, new GeometrySettings { Crop = new RectD(12, 4, 72, 56) });
return Psnr(ca, cb);
}
var synthesised = Interior(shifted, encode.Frames[5]);
var nearest = Interior(shifted, encode.Frames[4]);
_context.Log($"synthesised frame {synthesised:F1} dB vs nearest whole frame {nearest:F1} dB");
Assert.Greater(synthesised, 30);
Assert.Greater(synthesised, nearest + 5);
}
[Test]
public async Task MotionBlurSmearsAlongTheMotionOnly()
{
var blur = new MotionSettings { MotionBlur = On(true), TargetShutterAngle = On(360.0) };
var moving = Source(6, motion: i => (3.0 * i, 0), configure: o => o with { StartEv = 0, EndEv = 0 });
var sharp = await CaptureAsync(Input(moving), cancellationToken: _context.Cancellation);
var blurred = await CaptureAsync(Input(moving, With(motion: blur)), cancellationToken: _context.Cancellation);
double Gradient(ImageBuffer f, int dx, int dy)
{
double sum = 0;
var g = f.Plane(1);
for (var y = 8; y < f.Height - 8; y++)
{
for (var x = 8; x < f.Width - 8; x++) sum += Math.Abs(g[y * f.Width + x] - g[(y + dy) * f.Width + x + dx]);
}
return sum;
}
var horizontal = Gradient(blurred.Encode.Frames[3], 1, 0) / Gradient(sharp.Encode.Frames[3], 1, 0);
var vertical = Gradient(blurred.Encode.Frames[3], 0, 1) / Gradient(sharp.Encode.Frames[3], 0, 1);
_context.Log($"gradient ratios: horizontal {horizontal:F3}, vertical {vertical:F3}");
Assert.Less(horizontal, 0.75);
Assert.Greater(vertical, horizontal + 0.1);
var still = Source(6, configure: o => o with { StartEv = 0, EndEv = 0 });
var a = await CaptureAsync(Input(still), cancellationToken: _context.Cancellation);
var b = await CaptureAsync(Input(still, With(motion: blur)), cancellationToken: _context.Cancellation);
Assert.Greater(Psnr(a.Encode.Frames[3], b.Encode.Frames[3]), 40);
}
[Test]
public async Task StabilisationRemovesShake()
{
var random = new Random(11);
var shake = Enumerable.Range(0, 24).Select(_ => (X: random.NextDouble() * 6 - 3, Y: random.NextDouble() * 6 - 3)).ToArray();
var source = new PatternFrameSource(320, 192, 24, i => shake[i]);
var project = With(motion: new MotionSettings { Stabilize = On(true), StabilizeSmoothing = On(12.0) });
var input = new RenderInput { Source = source, Frames = source.Metadata(), Project = project };
static double Steps(IReadOnlyList<(double X, double Y)> p) =>
Math.Sqrt(Enumerable.Range(1, p.Count - 1).Average(k => Math.Pow(p[k].X - p[k - 1].X, 2) + Math.Pow(p[k].Y - p[k - 1].Y, 2)));
var prepared = await RenderPreparation.PrepareAsync(input, cancellationToken: _context.Cancellation);
var residual = Enumerable.Range(0, 24).Select(k =>
{
var (x, y) = prepared.Stabilization![k].Apply(159.5, 95.5);
return (shake[k].X + x - 159.5, shake[k].Y + y - 95.5);
}).ToArray();
_context.Log($"camera path steps {Steps(shake):F2} px → {Steps(residual):F3} px after correction; zoom {prepared.StabilizationZoom:F3}");
Assert.Less(Steps(residual), 0.1 * Steps(shake));
Assert.InRange(prepared.StabilizationZoom, 1.01, 1.2);
var (encode, result) = await CaptureAsync(input, Preset("png-sequence", 0, 0), cancellationToken: _context.Cancellation);
Assert.Equal((320, 192), (result.Width, result.Height));
using var stabilizer = new Stabilizer(320, 192);
var output = encode.Frames.Select(f => stabilizer.AddFrame(f).Transform).Skip(1).ToArray();
var after = Math.Sqrt(output.Average(m => m.Tx * m.Tx + m.Ty * m.Ty));
_context.Log($"rendered frame-to-frame shift {after:F3} px");
Assert.Less(after, 0.1 * Steps(shake) * prepared.StabilizationZoom);
}
[Test]
public async Task MedianStackRemovesTransientsAndStarTrailsNeverDarken()
{
var source = Source(9, configure: o => o with { StartEv = 0, EndEv = 0 });
var input = Input(source, With(stack: new StackSettings { Mode = StackSetting.Median, Length = 5 })) with { Source = new TransientSource(source, 4) };
var (median, _) = await CaptureAsync(input, cancellationToken: _context.Cancellation);
Assert.Equal(9, median.Frames.Count);
using var clean = source.Sequence.Render(4);
Assert.Greater(Psnr(clean, median.Frames[4]), 45);
var stars = Source(12, motion: i => (1.0 * i, 0), configure: o => o with { StarField = true, StartEv = 0, EndEv = 0, StarCount = 60 });
var (trails, _) = await CaptureAsync(Input(stars, With(stack: new StackSettings { Mode = StackSetting.StarTrails, Length = 0 })), cancellationToken: _context.Cancellation);
var luminance = LogLuminance(trails.Frames);
Assert.Monotonic(luminance);
for (var k = 1; k < trails.Frames.Count; k++)
{
var previous = trails.Frames[k - 1].Data;
var current = trails.Frames[k].Data;
for (var i = 0; i < current.Length; i++) Assert.True(current[i] >= previous[i] - 1e-6f, $"pixel {i} darkened at frame {k}");
}
}
[Test]
public async Task PrecomputedAnalysisSkipsTheMeasuringPass()
{
var source = Source(30, flickerEv: 0.2);
var project = With(new ExposureSettings { Deflicker = On(true), HighlightKnee = null });
var measured = await RenderPreparation.PrepareAsync(Input(source, project), cancellationToken: _context.Cancellation);
Assert.Equal(30, measured.Report.MeasuredFrames);
var cached = new PrecomputedAnalysis { LogLuminance = measured.MeasuredLogLuminance };
var decodes = source.Decodes;
var reused = await RenderPreparation.PrepareAsync(Input(source, project) with { Analysis = cached }, cancellationToken: _context.Cancellation);
Assert.Equal(0, reused.Report.MeasuredFrames);
Assert.Equal(decodes, source.Decodes);
Assert.SequenceEqual(measured.ExposureEv, reused.ExposureEv);
var target = measured.TargetLogLuminance();
Assert.Approximately(measured.MeasuredLogLuminance[7] + measured.ExposureEv[7], target[7], 1e-12);
static double[] Steps(double[] v) => [.. v.Zip(v.Skip(1), (a, b) => b - a)];
Assert.Less(Rms(Steps(target)), 0.5 * Rms(Steps(measured.MeasuredLogLuminance)));
var wrongLength = await RenderPreparation.PrepareAsync(Input(source, project) with { Analysis = new PrecomputedAnalysis { LogLuminance = new double[3] } },
cancellationToken: _context.Cancellation);
Assert.Equal(30, wrongLength.Report.MeasuredFrames);
Assert.SequenceEqual(measured.ExposureEv, wrongLength.ExposureEv);
var nothing = await RenderPreparation.PrepareAsync(Input(source), cancellationToken: _context.Cancellation);
Assert.Equal(0, nothing.Report.MeasuredFrames);
Assert.True(nothing.ExposureEv.All(e => e == 0));
}
[Test]
public async Task HeldFramesKeepTheirDurationOnConstantRateOutputs()
{
var source = Source(10, configure: o => o with { TimeShifts = [new SyntheticTimeShift(5, 20)] });
var project = With(timing: new TimingSettings { Mode = On(TimingMode.Adaptive) });
var export = Preset("mjpeg-avi");
var dir = _context.CreateTempDirectory();
var result = await Pipeline().RenderAsync(Input(source, project), Target(dir, export), cancellationToken: _context.Cancellation);
var avi = AviReader.Read(File.ReadAllBytes(result.OutputPath));
Assert.Equal(10, result.FrameCount);
Assert.Equal(12, avi.Frames.Count); // frame 4 lasts three periods (30 s ÷ 10 s)
Assert.Approximately(12 / 25.0, result.DurationSeconds, 1e-9);
}
[Test]
public void SetupReportsGeometryEncoderPlanAndEstimates()
{
var source = Source(48, width: 480, height: 320);
var input = Input(source, With(new ExposureSettings { Deflicker = On(true) }, motion: new MotionSettings { MotionBlur = On(true) }));
var setup = Pipeline().Setup(input, Target("/exports", Preset("gif-preview", 480, 270)));
Assert.True(setup.Encoder.IsReady);
Assert.Equal((480, 270), (setup.Geometry.OutputWidth, setup.Geometry.OutputHeight));
Assert.Equal(48, setup.Plan.Frames.Count);
Assert.True(setup.NeedsPreparation);
var workload = setup.Workload();
Assert.Equal(48, workload.FlowFrames);
Assert.Equal(48, workload.AnalysisFrames);
Assert.Equal(480L * 320, workload.WorkingPixels);
var estimate = setup.Estimate();
Assert.Greater(estimate.Bytes, 0);
Assert.Greater(estimate.Time.TotalSeconds, 0);
}
/// <summary>Adds a bright square to one frame (a passing aircraft light).</summary>
private sealed class TransientSource(IRenderFrameSource inner, int frame) : IRenderFrameSource
{
public int FrameCount => inner.FrameCount;
public int Width => inner.Width;
public int Height => inner.Height;
public async ValueTask<ImageBuffer> GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
{
var image = await inner.GetFrameAsync(index, maxLongEdge, purpose, cancellationToken);
if (index != frame) return image;
for (var c = 0; c < 3; c++)
{
for (var y = 20; y < 30; y++)
{
for (var x = 40; x < 50; x++) image[c, x, y] = 1;
}
}
return image;
}
}
}
@@ -0,0 +1,68 @@
using Chronos.Core.Render.Diagnostics;
using Chronos.Core.Video;
using Chronos.Testing;
namespace Chronos.Core.Tests.Render;
public sealed class SelfTestTests
{
private static readonly string[] Groups = ["plan", "export", "select", "codec", "render", "proc", "robust"];
private readonly TestContext _context;
public SelfTestTests(TestContext context) => _context = context;
[Test]
public void ChecksAreUniqueAndGrouped()
{
Assert.GreaterOrEqual(SelfTest.Checks.Count, 60);
Assert.Equal(SelfTest.Checks.Count, SelfTest.Checks.Select(c => c.Id).Distinct().Count());
Assert.True(SelfTest.Checks.All(c => Groups.Contains(c.Group) && c.Id.StartsWith(c.Group + ".", StringComparison.Ordinal) && c.Description.Length > 0));
Assert.True(Groups.All(g => SelfTest.Checks.Any(c => c.Group == g)));
}
[Test]
public async Task FastGroupsPassAndCleanUp()
{
var work = _context.CreateTempDirectory();
var reported = new List<SelfTestResult>();
var results = await SelfTest.RunAsync(new SelfTestOptions { WorkDirectory = work, Filters = ["plan.", "export.", "select.", "codec."] },
new RenderFixture.Sink<SelfTestResult>(reported.Add), _context.Cancellation);
foreach (var r in results.Where(r => r.Outcome != SelfTestOutcome.Passed)) _context.Log($"{r.Id}: {r.Outcome} {r.Detail}");
Assert.Equal(SelfTest.Checks.Count(c => c.Group is "plan" or "export" or "select" or "codec"), results.Count);
Assert.True(results.All(r => r.Outcome == SelfTestOutcome.Passed));
Assert.SequenceEqual(results.Select(r => r.Id), reported.Select(r => r.Id));
Assert.Empty(Directory.GetFileSystemEntries(work));
}
[Test]
public async Task RenderGroupPassesWithManagedEncoders()
{
var results = await SelfTest.RunAsync(new SelfTestOptions { WorkDirectory = _context.CreateTempDirectory(), Filters = ["render."] }, cancellationToken: _context.Cancellation);
foreach (var r in results) _context.Log($"{r.Id}: {r.Outcome} {r.Detail}");
Assert.Equal(SelfTestOutcome.Skipped, results.Single(r => r.Id == "render.mp4").Outcome);
Assert.True(results.Where(r => r.Id != "render.mp4").All(r => r.Outcome == SelfTestOutcome.Passed));
}
[Test]
public async Task FailuresAreReportedNotThrown()
{
// An "MP4 encoder" that writes nothing: the inspection of its missing file must fail the check, not the run.
var fake = new CapturingEncoderProvider("fake", new EncoderCapability(VideoCodec.H264, "Fake H.264", true, 4096, 4096, false));
var results = await SelfTest.RunAsync(new SelfTestOptions { WorkDirectory = _context.CreateTempDirectory(), Filters = ["render.mp4"], PlatformEncoders = [fake] },
cancellationToken: _context.Cancellation);
var result = results.Single();
Assert.Equal(SelfTestOutcome.Failed, result.Outcome);
Assert.Contains("FileNotFoundException", result.Detail);
}
[Test]
public async Task CancellationStopsTheRunAndCleansUp()
{
var work = _context.CreateTempDirectory();
using var cts = CancellationTokenSource.CreateLinkedTokenSource(_context.Cancellation);
var progress = new RenderFixture.Sink<SelfTestResult>(_ => cts.Cancel());
await Assert.ThrowsAsync<OperationCanceledException>(() => SelfTest.RunAsync(new SelfTestOptions { WorkDirectory = work, Filters = ["plan."] }, progress, cts.Token));
Assert.Empty(Directory.GetFileSystemEntries(work));
}
}