feat(render): preparation pass, render geometry and pipeline

RenderPreparation measures (or reuses cached) luminance, colour, region
and camera-path series and turns them into per-frame corrections.
RenderPipeline renders planned frames through exposure, one geometry
resample, flow synthesis, motion blur, stacking and the knee, overlapping
encoding with processing; cancellation and failures leave no output and
no unobserved exceptions. Batch renders share one preparation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 11:09:02 +00:00
1 parent 222d9ec4ad
commit 3780105f36
16 files changed
+2451 -1

No files matched your search

@@ -0,0 +1,83 @@
using Titano.Core.Diagnostics.Synthetic;
using Titano.Core.Export;
using Titano.Core.Imaging;
using Titano.Core.Project;
using Titano.Core.Render;
using Titano.Core.Render.Diagnostics;
using Titano.Core.Video;
using Titano.Core.Video.Managed;
namespace Titano.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(), "titano-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,69 @@
using Titano.Core.Render;
using Titano.Core.Video;
using Titano.Testing;
using static Titano.Core.Tests.Render.RenderFixture;
namespace Titano.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()
{
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 Titano.Core.Project.ExposureSettings { Deflicker = new Titano.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 Titano.Core.Codecs.Jpeg;
using Titano.Core.Codecs.Png;
using Titano.Core.Codecs.Tiff;
using Titano.Core.Export;
using Titano.Core.Imaging;
using Titano.Core.Project;
using Titano.Core.Render;
using Titano.Core.Render.Diagnostics;
using Titano.Core.Video;
using Titano.Core.Video.Managed;
using Titano.Testing;
using static Titano.Core.Tests.Render.RenderFixture;
namespace Titano.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("Render.Error.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,351 @@
using Titano.Core.Analysis;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Geometry;
using Titano.Core.Motion;
using Titano.Core.Project;
using Titano.Core.Render;
using Titano.Core.Render.Diagnostics;
using Titano.Testing;
using static Titano.Core.Tests.Render.RenderFixture;
namespace Titano.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 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);
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 Titano.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 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;
}
}
}