feat(editor): visual crop, rotate/mirror/flip/straighten, colour looks (owner review 1 phase 4) (#26)
CI / Build and test (push) Successful in 8m19s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 12m9s
CI / PostgreSQL 16 integration (push) Successful in 7m49s
CI / PostgreSQL 17 integration (push) Successful in 7m19s
CI / Docker image (push) Successful in 46s
Release / Server image (push) Successful in 1m14s

Owner review 1 R5 + R6. Camera rotation, mirror, flip, straighten and crop handles locked to the output; an Exposure Look group; Export output size ("proportions win"); settings format 2 with older-node gates. Also fixes project text and hashes differing between Windows and Linux.

Closes #19
Closes #20

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 #26.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-05 01:09:09 +01:00
1 parent db389a54f2
commit 188b2c2e55
355 files changed
+10549 -1061

No files matched your search

@@ -2,6 +2,7 @@ using Chronos.Core.Advice;
using Chronos.Core.Analysis;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Imaging.Geometry;
using Chronos.Core.Mathematics;
using Chronos.Core.Project;
using Chronos.Core.Tests.Analysis.Deep;
@@ -326,6 +327,51 @@ public sealed class AdvisorTests(TestContext context)
Assert.Equal("3840x2160", Value(wide, AdvisorParameters.Resolution));
}
[Test]
public void TheAspectIsAdvisedOnTheTurnedView()
{
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.HolyGrail()));
var turned = sequence.ForCamera(new CameraSettings { Rotate = 90 });
Assert.Equal(90, turned.Rotate);
var portrait = Advisor.Recommend(light, null, turned);
Assert.Equal("9:16", Value(portrait, AdvisorParameters.Aspect));
Assert.Equal(AdvisorKeys.AspectPortrait, portrait.Find(AdvisorParameters.Aspect)!.ReasonKey);
Assert.Equal("16:9", Value(Advisor.Recommend(light, null, sequence with { Rotate = 180 }), AdvisorParameters.Aspect));
// A portrait source turned a quarter is landscape again, its reason naming the view's size.
var landscape = Advisor.Recommend(light, null, sequence with { SourceWidth = 4000, SourceHeight = 6000, Rotate = 270 });
Assert.Equal("16:9", Value(landscape, AdvisorParameters.Aspect));
Assert.SequenceEqual([6000.0, 4000.0, 84.0], landscape.Find(AdvisorParameters.Aspect)!.ReasonArgs.Select(Convert.ToDouble));
// Applied to a turned project, the advice matches what a turn of the advised aspect gives.
var project = Advisor.Apply(new ProjectSettings { Camera = new CameraSettings { Rotate = 90 } }, portrait);
Assert.Equal("9:16", project.Camera.Aspect.AutoValue);
}
/// <summary>
/// The horizon framing places the decoded frame's horizon in the view as shown, as the preview draws it: a half turn or a
/// flip shows it upside down, a straighten turns it about the centre and magnifies it by its cover zoom (10° on 3:2
/// moves a horizon at 0.70 to about 0.745, which the framing must put on the third).
/// </summary>
[Test]
public void TheHorizonIsPlacedInTheViewAsShown()
{
double[] horizon = [0.70, 0.70, 0.70, 0.70, 0.70];
Assert.Approximately(0.70, AdvisorRules.ViewRow(FrameOrientation.Identity(6000, 4000), horizon), 1e-12);
Assert.Approximately(0.30, AdvisorRules.ViewRow(FrameOrientation.Of(0, false, true, 0, 6000, 4000), horizon), 1e-9);
Assert.Approximately(0.30, AdvisorRules.ViewRow(FrameOrientation.Of(180, false, false, 0, 6000, 4000), horizon), 1e-9);
Assert.Approximately(0.70, AdvisorRules.ViewRow(FrameOrientation.Of(0, true, false, 0, 6000, 4000), horizon), 1e-9);
var straightened = FrameOrientation.Of(0, false, false, 10, 6000, 4000);
var centre = (4000 - 1) / 2.0;
var expected = (centre + straightened.CoverZoom * double.Cos(10 * double.Pi / 180) * (0.70 * 4000 - 0.5 - centre) + 0.5) / 4000;
Assert.Approximately(expected, AdvisorRules.ViewRow(straightened, horizon), 1e-9);
Assert.InRange(expected, 0.74, 0.75);
// The context carries the straighten, so the advice is worked out again for it.
Assert.Equal(10.0, new SequenceContext().ForCamera(new CameraSettings { Straighten = 10 }).Straighten);
}
[Test]
public async Task RecommendationsAreDeterministic()
{
@@ -128,6 +128,22 @@ public sealed class EncoderSelectorTests
Assert.Equal((1080, 606), (odd.Settings.Width, odd.Settings.Height));
}
[Test]
public void APortraitFrameReadsTheLimitTurned()
{
// An encoder announced as 4096×2304 takes 4K at 9:16: its limit is long edge × short edge.
var portrait = EncoderSelector.Select(Request(VideoCodec.H264, 2160, 3840), Client(SoftwareH264), EncoderHost.Client);
Assert.Equal((2160, 3840), (portrait.Settings.Width, portrait.Settings.Height));
Assert.False(portrait.Notices.Any(n => n.Key is EncoderNotices.ResolutionCappedByEncoder or EncoderNotices.ResolutionCappedByLevel), "not capped");
var capped = EncoderSelector.Select(Request(VideoCodec.H264, 4320, 7680), Client(SoftwareH264), EncoderHost.Client);
Assert.Equal((2304, 4096), (capped.Settings.Width, capped.Settings.Height));
Assert.True(capped.Notices.Any(n => n.Key == EncoderNotices.ResolutionCappedByEncoder));
Assert.True(EncoderSelector.Takes(SoftwareH264, 2304, 4096));
Assert.False(EncoderSelector.Takes(SoftwareH264, 2400, 3840), "the short edge is over the limit");
}
[Test]
public void BitRateIsCappedByTheHighestLevel()
{
@@ -45,6 +45,18 @@ public sealed class Affine2DTests
Assert.Within(double.Cos(0.7), double.Sin(0.7), vx, vy, 1e-15);
}
[Test]
public void AQuarterTurnRotationIsNotExact()
{
// Why FrameOrientation writes its quarter turns as integer matrices: cos(π/2) is about 6e-17, not 0.
var rotation = Affine2D.Rotation(double.Pi / 2);
Assert.NotEqual(0.0, rotation.M11);
Assert.Approximately(0, rotation.M11, 1e-16);
var turn = new Affine2D(0, -1, 1, 0, 0, 0);
Assert.Equal(Affine2D.Identity, turn * turn * turn * turn);
Assert.Equal(new Affine2D(0, 1, -1, 0, 0, 0), turn.Invert());
}
[Test]
public void SimilarityDecomposes()
{
@@ -0,0 +1,174 @@
using Chronos.Core.Imaging.Geometry;
using Chronos.Testing;
namespace Chronos.Core.Tests.Geometry;
public sealed class CropFrameTests
{
/// <summary>9:16 on a 6000×4000 view, in normalised units: 0.5625 × 4000 / 6000.</summary>
private const double Portrait = 0.375;
[Test]
public void TheLargestBoxIsCentredAndLocked()
{
AssertBox(new RectD(0.3125, 0, 0.375, 1), CropFrame.Largest(Portrait));
AssertBox(new RectD(0, 0, 1, 1), CropFrame.Largest(1));
AssertBox(new RectD(0, 0.25, 1, 0.5), CropFrame.Largest(2));
Assert.Throws<ArgumentOutOfRangeException>(() => CropFrame.Largest(0));
Assert.Throws<ArgumentOutOfRangeException>(() => CropFrame.Largest(double.NaN));
}
[Test]
public void StoredCropsReadAsTheRenderReadsThem()
{
AssertBox(new RectD(0, 0, 1, 1), CropFrame.Of(null));
AssertBox(new RectD(0, 0, 1, 1), CropFrame.Of([0.1, 0.2]));
AssertBox(new RectD(0, 0, 1, 1), CropFrame.Of([0.1, double.NaN, 0.3, 0.3]));
AssertBox(new RectD(0, 0, 1, 1), CropFrame.Of([0.5, 0.5, 0.0001, 0.5]));
AssertBox(new RectD(0.5, 0, 0.5, 0.25), CropFrame.Of([0.5, -1, 0.8, 0.25]));
Assert.True(CropFrame.IsWhole(null));
Assert.True(CropFrame.IsWhole([0, 0, 1, 1]));
Assert.False(CropFrame.IsWhole([0, 0, 0.9, 1]));
Assert.Null(CropFrame.ToCrop(new RectD(0, 0, 1, 1)));
Assert.SequenceEqual([0.25, 0.125, 0.5, 0.5], CropFrame.ToCrop(new RectD(0.25, 0.125, 0.5, 0.5))!);
// Written on a 12-decimal grid, never −0.
Assert.SequenceEqual([0.333333333333, 0, 0.5, 0.5], CropFrame.ToCrop(new RectD(1 / 3.0, -0.0, 0.5, 0.5))!);
Assert.False(double.IsNegative(CropFrame.ToCrop(new RectD(-0.0, 0.2, 0.5, 0.5))![0]));
}
[Test]
public void LockedBakesTheOffsetsOfALegacyCrop()
{
// A free crop of the whole view with the box pushed right: the render's FitCrop, normalised.
AssertBox(new RectD(0.625, 0, 0.375, 1), CropFrame.Locked(null, Portrait, offsetX: 1));
AssertBox(new RectD(0.3125, 0, 0.375, 1), CropFrame.Locked(null, Portrait, double.NaN, double.NaN));
var box = CropFrame.Locked([0.2, 0.1, 0.4, 0.8], Portrait, -1, 0);
AssertBox(new RectD(0.2, 0.1, 0.3, 0.8), box);
// A box the editor wrote comes back unchanged.
AssertBox(box, CropFrame.Locked(CropFrame.ToCrop(box), Portrait));
}
[Test]
public void MovingStaysInsideAndKeepsTheSize()
{
var box = new RectD(0.3, 0.2, 0.3, 0.4);
AssertBox(new RectD(0.4, 0.15, 0.3, 0.4), CropFrame.Move(box, 0.1, -0.05));
AssertBox(new RectD(0.7, 0, 0.3, 0.4), CropFrame.Move(box, 2, -1));
AssertBox(new RectD(0, 0.6, 0.3, 0.4), CropFrame.Move(box, -5, 5));
}
[Theory]
[Case(CropHandle.BottomRight, 0.9, 0.95, false)]
[Case(CropHandle.TopLeft, 0.0, 0.0, false)]
[Case(CropHandle.TopRight, 2.0, -3.0, false)]
[Case(CropHandle.Left, 0.31, 0.5, false)]
[Case(CropHandle.Top, 0.5, -1.0, false)]
[Case(CropHandle.Right, 0.4, 0.5, false)]
[Case(CropHandle.Bottom, 0.5, 0.3, false)]
[Case(CropHandle.BottomLeft, 0.1, 0.9, true)]
[Case(CropHandle.Right, 5.0, 0.5, true)]
[Case(CropHandle.TopLeft, 0.45, 0.45, true)]
public void ResizingKeepsTheRatioTheMinimumAndTheFrame(CropHandle handle, double x, double y, bool aboutCentre)
{
var start = new RectD(0.35, 0.3, 0.15, 0.4);
var box = CropFrame.ResizeFrom(start, handle, x, y, Portrait, aboutCentre);
Assert.Approximately(Portrait, box.Width / box.Height, 1e-12, "the ratio stays locked");
Assert.True(box.X >= -1e-12 && box.Y >= -1e-12 && box.Right <= 1 + 1e-12 && box.Bottom <= 1 + 1e-12, $"{box} lies inside the view");
Assert.GreaterOrEqual(box.Height, CropFrame.Largest(Portrait).Height * CropFrame.MinimumShare - 1e-12);
if (aboutCentre)
{
Assert.Approximately(start.CenterX, box.CenterX, 1e-12);
Assert.Approximately(start.CenterY, box.CenterY, 1e-12);
return;
}
// The opposite corner or edge stays where it was; an edge handle keeps the box centred on the other axis.
switch (handle)
{
case CropHandle.BottomRight:
Assert.Within(start.X, start.Y, box.X, box.Y, 1e-12);
break;
case CropHandle.TopLeft:
Assert.Within(start.Right, start.Bottom, box.Right, box.Bottom, 1e-12);
break;
case CropHandle.TopRight:
Assert.Within(start.X, start.Bottom, box.X, box.Bottom, 1e-12);
break;
case CropHandle.Left:
Assert.Within(start.Right, start.CenterY, box.Right, box.CenterY, 1e-12);
break;
case CropHandle.Right:
Assert.Within(start.X, start.CenterY, box.X, box.CenterY, 1e-12);
break;
case CropHandle.Top:
Assert.Within(start.CenterX, start.Bottom, box.CenterX, box.Bottom, 1e-12);
break;
case CropHandle.Bottom:
Assert.Within(start.CenterX, start.Y, box.CenterX, box.Y, 1e-12);
break;
}
}
[Test]
public void ResizingFollowsThePointer()
{
var start = new RectD(0.35, 0.3, 0.15, 0.4);
// Bottom-right to (0.5375, 0.8): both axes ask for a height of 0.5 (0.1875 / 0.375 and 0.8 − 0.3).
AssertBox(new RectD(0.35, 0.3, 0.1875, 0.5), CropFrame.ResizeFrom(start, CropHandle.BottomRight, 0.5375, 0.8, Portrait));
// Dragged past the anchor: the minimum box.
var least = CropFrame.ResizeFrom(start, CropHandle.BottomRight, 0, 0, Portrait);
Assert.Approximately(0.1, least.Height, 1e-12);
// Far out: as large as fits from the anchor (0.7 of height below it).
Assert.Approximately(0.7, CropFrame.ResizeFrom(start, CropHandle.BottomRight, 1, 1, Portrait).Height, 1e-12);
// The inside and no handle leave the box.
Assert.Equal(start, CropFrame.ResizeFrom(start, CropHandle.Inside, 0.9, 0.9, Portrait));
Assert.Equal(start, CropFrame.ResizeFrom(start, CropHandle.None, 0.9, 0.9, Portrait));
}
[Test]
public void ClampAndRefitKeepTheCentre()
{
// A 16:9 box (in units of a square view) refitted to 1:1 keeps its centre and its area.
var wide = new RectD(0.2, 0.3, 0.64, 0.36);
var square = CropFrame.Refit(wide, 1);
Assert.Approximately(square.Width, square.Height, 1e-12);
Assert.Within(wide.CenterX, wide.CenterY, square.CenterX, square.CenterY, 1e-12);
Assert.Approximately(wide.Width * wide.Height, square.Width * square.Height, 1e-12);
// Near an edge the refitted box moves inside rather than leaving the view.
var edge = CropFrame.Refit(new RectD(0.8, 0.1, 0.2, 0.8), 1);
Assert.Approximately(1, edge.Right, 1e-12);
Assert.Approximately(edge.Width, edge.Height, 1e-12);
// Too large or too small: the largest box, the minimum.
AssertBox(CropFrame.Largest(Portrait), CropFrame.Clamp(new RectD(-1, -1, 3, 3), Portrait));
Assert.Approximately(0.1, CropFrame.Clamp(new RectD(0.5, 0.5, 0.001, 0.001), Portrait).Height, 1e-12);
AssertBox(CropFrame.Largest(Portrait), CropFrame.Clamp(new RectD(double.NaN, 0, 0, 0), Portrait));
}
[Test]
public void RowsRoundTrip()
{
foreach (var (size, x, y) in new[] { (1.0, 0.0, 0.0), (0.5, -1.0, 1.0), (0.8, 0.25, -0.5), (0.1, 1.0, 0.3) })
{
var box = CropFrame.FromRows(size, x, y, Portrait);
Assert.Approximately(Portrait, box.Width / box.Height, 1e-12);
var rows = CropFrame.ToRows(box, Portrait);
Assert.Approximately(size, rows.Size, 1e-12);
Assert.Approximately(x, rows.X, 1e-12);
// The largest portrait box fills the height: no vertical slack, so y reads 0.
Assert.Approximately(size == 1 ? 0 : y, rows.Y, 1e-12);
AssertBox(box, CropFrame.FromRows(rows.Size, rows.X, rows.Y, Portrait));
}
AssertBox(CropFrame.Largest(Portrait), CropFrame.FromRows(double.NaN, double.NaN, 0, Portrait));
Assert.True(CropFrame.HasSlack(CropFrame.Largest(Portrait), horizontal: true));
Assert.False(CropFrame.HasSlack(CropFrame.Largest(Portrait), horizontal: false));
}
private static void AssertBox(RectD expected, RectD actual)
{
Assert.Approximately(expected.X, actual.X, 1e-12, $"x of {actual}");
Assert.Approximately(expected.Y, actual.Y, 1e-12, $"y of {actual}");
Assert.Approximately(expected.Width, actual.Width, 1e-12, $"width of {actual}");
Assert.Approximately(expected.Height, actual.Height, 1e-12, $"height of {actual}");
}
}
@@ -0,0 +1,237 @@
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Geometry;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Tests.Render;
using Chronos.Testing;
namespace Chronos.Core.Tests.Geometry;
public sealed class FrameOrientationTests
{
private const int Width = 48;
private const int Height = 32;
[Theory]
[Case(90, false, false)]
[Case(180, false, false)]
[Case(270, false, false)]
[Case(-90, false, false)]
[Case(0, true, false)]
[Case(0, false, true)]
[Case(90, true, false)]
[Case(270, false, true)]
[Case(180, true, true)]
public void TurnsMirrorsAndFlipsPermuteThePixelsExactly(int rotate, bool mirror, bool flip)
{
using var frame = Texture(Width, Height, seed: 7);
var camera = new CameraSettings { Rotate = rotate, Mirror = mirror, Flip = flip };
var geometry = RenderGeometry.Create(camera, RenderFixture.Preset("png-sequence", 0, 0), Width, Height);
var turns = FrameOrientation.TurnsOf(rotate);
Assert.Equal(turns % 2 == 1 ? (Height, Width) : (Width, Height), (geometry.OutputWidth, geometry.OutputHeight));
Assert.Equal((geometry.OutputWidth, geometry.OutputHeight), (geometry.ViewWidth, geometry.ViewHeight));
Assert.Empty(geometry.Warnings);
using var view = GeometryStage.Apply(frame, geometry.For(Width, Height, 0, Affine2D.Identity));
using var expected = Permuted(frame, turns, mirror, flip);
Assert.Equal((expected.Width, expected.Height), (view.Width, view.Height));
Assert.True(expected.Data.SequenceEqual(view.Data), "the view is an exact permutation of the frame");
// The editor's Source framing (the whole view frame) is the same permutation.
using var whole = GeometryStage.Apply(frame, geometry.ViewFor(Width, Height, view.Width, view.Height));
Assert.True(expected.Data.SequenceEqual(whole.Data));
}
[Test]
public void QuarterTurnsAreExactIntegerMaps()
{
Assert.Equal(new Affine2D(0, -1, 1, 0, Height - 1, 0), FrameOrientation.Of(90, false, false, 0, Width, Height).FrameToView);
Assert.Equal(new Affine2D(-1, 0, 0, -1, Width - 1, Height - 1), FrameOrientation.Of(180, false, false, 0, Width, Height).FrameToView);
Assert.Equal(new Affine2D(0, 1, -1, 0, 0, Width - 1), FrameOrientation.Of(270, false, false, 0, Width, Height).FrameToView);
foreach (var rotate in new[] { 0, 90, 180, 270 })
{
foreach (var (mirror, flip) in new[] { (false, false), (true, false), (false, true), (true, true) })
{
var o = FrameOrientation.Of(rotate, mirror, flip, 0, Width, Height);
Assert.Equal(Affine2D.Identity, o.ViewToFrame * o.FrameToView);
Assert.Equal(Affine2D.Identity, o.FrameToView * o.ViewToFrame);
}
}
}
[Test]
public void OrientationAlgebraHolds()
{
// mirror² = flip² = I.
var mirror = FrameOrientation.Of(0, true, false, 0, Width, Height).FrameToView;
var flip = FrameOrientation.Of(0, false, true, 0, Width, Height).FrameToView;
Assert.Equal(Affine2D.Identity, mirror * mirror);
Assert.Equal(Affine2D.Identity, flip * flip);
// turn⁴ = I: each quarter turn takes the previous view (its size swapped) as its frame.
var turn = Affine2D.Identity;
var (w, h) = (Width, Height);
for (var k = 0; k < 4; k++)
{
turn = FrameOrientation.Of(90, false, false, 0, w, h).FrameToView * turn;
(w, h) = (h, w);
if (k < 3) Assert.NotEqual(Affine2D.Identity, turn);
}
Assert.Equal(Affine2D.Identity, turn);
// Parity: a turn right then a mirror is a turn left then a flip, the transpose; mirror and flip together are a half turn.
var transpose = new Affine2D(0, 1, 1, 0, 0, 0);
Assert.Equal(transpose, FrameOrientation.Of(90, true, false, 0, Width, Height).FrameToView);
Assert.Equal(transpose, FrameOrientation.Of(270, false, true, 0, Width, Height).FrameToView);
Assert.Equal(FrameOrientation.Of(180, false, false, 0, Width, Height).FrameToView, FrameOrientation.Of(0, true, true, 0, Width, Height).FrameToView);
Assert.True(FrameOrientation.Of(360, false, false, 0, Width, Height).IsIdentity);
}
[Theory]
[Case(7.5, 0)]
[Case(-12.0, 0)]
[Case(15.0, 90)]
public void StraightenMatchesTheAnalyticRamp(double degrees, int rotate)
{
using var ramp = new ImageBuffer(96, 64, 1);
for (var y = 0; y < 64; y++)
for (var x = 0; x < 96; x++)
ramp[0, x, y] = 0.1f + 0.01f * x + 0.005f * y;
var orientation = FrameOrientation.Of(rotate, false, false, degrees, 96, 64);
using var view = GeometryStage.Apply(ramp, new GeometrySettings
{
Crop = RectD.FromSize(orientation.ViewWidth, orientation.ViewHeight),
OutputWidth = orientation.ViewWidth,
OutputHeight = orientation.ViewHeight,
Warp = orientation.ViewToFrame,
});
Assert.Equal((orientation.ViewWidth, orientation.ViewHeight), (view.Width, view.Height));
var checkedPixels = 0;
for (var v = 0; v < view.Height; v++)
{
for (var u = 0; u < view.Width; u++)
{
var (sx, sy) = orientation.ViewToFrame.Apply(u, v);
// Every sample lies inside the frame's pixel centres (the cover zoom), within rounding.
Assert.True(sx >= -1e-9 && sx <= 95 + 1e-9 && sy >= -1e-9 && sy <= 63 + 1e-9, $"view ({u}, {v}) samples ({sx}, {sy})");
if (sx < 1 || sx >= 93 || sy < 1 || sy >= 61) continue; // all 4×4 taps inside: the ramp is reproduced exactly
Assert.Approximately(0.1 + 0.01 * sx + 0.005 * sy, view[0, u, v], 2e-6);
checkedPixels++;
}
}
Assert.Greater(checkedPixels, view.Width * view.Height / 2);
}
[Theory]
[Case(15.0, 0)]
[Case(-15.0, 0)]
[Case(15.0, 90)]
[Case(-15.0, 270)]
[Case(0.3, 0)]
public void StraightenNeverShowsABorder(double degrees, int rotate)
{
using var frame = Texture(96, 64, seed: 3);
var camera = new CameraSettings { Rotate = rotate, Straighten = degrees };
var geometry = RenderGeometry.Create(camera, RenderFixture.Preset("png-sequence", 0, 0), 96, 64);
var settings = geometry.For(96, 64, 0, Affine2D.Identity) with { Border = BorderMode.Transparent };
using var view = GeometryStage.Apply(frame, settings);
var alpha = view.Plane(3).ToArray();
Assert.GreaterOrEqual(alpha.Min(), 1 - 1e-6, "every output pixel is fully covered");
}
[Test]
public void CoverZoomFollowsTheFormula()
{
Assert.Equal(1.0, FrameOrientation.CoverZoomOf(0, 1920, 1080));
var (sin, cos) = double.SinCos(15 * double.Pi / 180);
Assert.Approximately(cos + 16 / 9.0 * sin, FrameOrientation.CoverZoomOf(15, 1920, 1080), 1e-12);
Assert.Approximately(cos + 16 / 9.0 * sin, FrameOrientation.CoverZoomOf(-15, 1080, 1920), 1e-12);
// On the pixel-centre extents of the view.
var o = FrameOrientation.Of(0, false, false, 15, 1920, 1080);
Assert.Approximately(cos + 1919 / 1079.0 * sin, o.CoverZoom, 1e-12);
Assert.Equal(o.CoverZoom, FrameOrientation.Of(90, false, false, 15, 1080, 1920).CoverZoom);
Assert.Equal(1.0, FrameOrientation.Of(90, true, false, 0, 1920, 1080).CoverZoom);
}
[Test]
public void ValuesAreNormalisedAndResizedKeepsThem()
{
Assert.Equal(3, FrameOrientation.TurnsOf(-90));
Assert.Equal(1, FrameOrientation.TurnsOf(450));
Assert.Equal(0, FrameOrientation.TurnsOf(45));
Assert.Equal(15.0, FrameOrientation.StraightenOf(40));
Assert.Equal(-15.0, FrameOrientation.StraightenOf(-15.5));
Assert.Equal(0.0, FrameOrientation.StraightenOf(double.NaN));
Assert.False(FrameOrientation.IsValidStraighten(double.PositiveInfinity));
var full = FrameOrientation.Of(-90, true, false, 4, 6000, 4000);
var small = full.Resized(600, 400);
Assert.Equal((3, true, false, 4.0), (small.Turns, small.Mirror, small.Flip, small.Straighten));
Assert.Equal((400, 600), (small.ViewWidth, small.ViewHeight));
Assert.Same(full, full.Resized(6000, 4000));
Assert.True(FrameOrientation.Identity(10, 10).IsIdentity);
}
[Test]
public void InvalidValuesRenderAsNoneWithAWarning()
{
var export = RenderFixture.Preset("png-sequence", 0, 0);
var skewed = RenderGeometry.Create(new CameraSettings { Rotate = 45 }, export, 96, 64);
Assert.True(skewed.Orientation.IsIdentity);
Assert.Equal((96, 64), (skewed.OutputWidth, skewed.OutputHeight));
Assert.Equal("Export.Render.RotationIgnored", skewed.Warnings.Single().Key);
Assert.SequenceEqual(["45"], skewed.Warnings.Single().Args);
var steep = RenderGeometry.Create(new CameraSettings { Straighten = 20 }, export, 96, 64);
Assert.Equal(15.0, steep.Orientation.Straighten);
Assert.Equal("Export.Render.StraightenClamped", steep.Warnings.Single().Key);
Assert.SequenceEqual(["20", "15"], steep.Warnings.Single().Args);
var broken = RenderGeometry.Create(new CameraSettings { Straighten = double.NaN }, export, 96, 64);
Assert.True(broken.Orientation.IsIdentity);
Assert.SequenceEqual(["NaN", "0"], broken.Warnings.Single().Args);
}
/// <summary>A seeded RGB texture.</summary>
internal static ImageBuffer Texture(int width, int height, int seed)
{
var random = new Random(seed);
var image = new ImageBuffer(width, height, 3);
for (var i = 0; i < image.Data.Length; i++) image.Data[i] = (float)random.NextDouble();
return image;
}
/// <summary>The frame turned right <paramref name="turns"/> times, then mirrored and flipped, by moving pixels.</summary>
internal static ImageBuffer Permuted(ImageBuffer frame, int turns, bool mirror, bool flip)
{
var image = frame.Clone();
for (var k = 0; k < turns; k++) image = Replace(image, Move(image, image.Height, image.Width, (src, u, v) => (v, src.Height - 1 - u)));
if (mirror) image = Replace(image, Move(image, image.Width, image.Height, (src, u, v) => (src.Width - 1 - u, v)));
if (flip) image = Replace(image, Move(image, image.Width, image.Height, (src, u, v) => (u, src.Height - 1 - v)));
return image;
}
private static ImageBuffer Replace(ImageBuffer old, ImageBuffer next)
{
old.Dispose();
return next;
}
/// <summary>A new image whose pixel (u, v) is the source pixel <paramref name="from"/>(u, v).</summary>
private static ImageBuffer Move(ImageBuffer src, int width, int height, Func<ImageBuffer, int, int, (int X, int Y)> from)
{
var dst = new ImageBuffer(width, height, src.Channels);
for (var c = 0; c < src.Channels; c++)
{
for (var v = 0; v < height; v++)
{
for (var u = 0; u < width; u++)
{
var (x, y) = from(src, u, v);
dst[c, u, v] = src[c, x, y];
}
}
}
return dst;
}
}
@@ -119,6 +119,19 @@ public sealed class GeometryStageTests
Assert.Approximately(0.5, small[0, x, y], 0.02);
}
[Test]
public void IntegerMapsMovePixelsExactly()
{
// A transpose (a quarter turn with a mirror) samples every output pixel at a source pixel centre.
using var source = Texture(sigma: 1.0);
using var output = new ImageBuffer(Size, Size, 3);
GeometryStage.Warp(source, output, new Affine2D(0, 1, 1, 0, 0, 0));
for (var c = 0; c < 3; c++)
for (var y = 0; y < Size; y++)
for (var x = 0; x < Size; x++)
Assert.Equal(source[c, y, x], output[c, x, y]);
}
[Test]
public void CancellationStopsTheWarp()
{
@@ -0,0 +1,246 @@
using Chronos.Core.Imaging.Geometry;
using Chronos.Core.Project;
using Chronos.Testing;
namespace Chronos.Core.Tests.Geometry;
public sealed class OrientationEditTests
{
private static readonly OrientationOp[] Ops = [OrientationOp.RotateLeft, OrientationOp.RotateRight, OrientationOp.Mirror, OrientationOp.Flip];
private static ProjectSettings Framed { get; } = new()
{
Camera = new CameraSettings
{
Crop = CropFrame.ToCrop(CropFrame.FromRows(0.7, 1 / 3.0, -0.2, 16 / 9.0 * 4000 / 6000)),
Aspect = new Auto<string>().WithManual("16:9").WithAdvice("3:2", null),
OffsetX = 0.25,
OffsetY = -0.5,
Keyframes = [new CameraKey(0, 0.25, 0.4, 1.5, 3), new CameraKey(9, 0.6, 0.125, 2, -1.5, "Linear")],
Straighten = 2.5,
},
PendingFrames = [new PendingFrame { Sha256 = "ab", Keyframes = [new CameraKey(4, 0.75, 0.5, 1, 2)] }],
};
[Test]
public void FourRightTurnsGiveBackTheText()
{
var text = Framed.ToJson();
var settings = Framed;
for (var k = 0; k < 4; k++)
{
settings = OrientationEdit.Apply(settings, OrientationOp.RotateRight);
Assert.Equal((k + 1) % 4 * 90, settings.Camera.Rotate);
if (k < 3) Assert.NotEqual(text, settings.ToJson());
}
Assert.Equal(text, settings.ToJson());
// Without a straighten, the turns leave nothing of format 2 behind.
var plain = new ProjectSettings { Camera = new CameraSettings { Crop = [0.1, 0.2, 0.3, 0.4] } };
var turned = plain;
for (var k = 0; k < 4; k++) turned = OrientationEdit.Apply(turned, OrientationOp.RotateRight);
Assert.Equal(plain.ToJson(), turned.ToJson());
Assert.Equal(ProjectSettings.BaseVersion, turned.WrittenFormat);
}
[Test]
public void EveryPressIsUndoneByItsOpposite()
{
var text = Framed.ToJson();
foreach (var start in new[] { Framed, OrientationEdit.Apply(Framed, OrientationOp.Mirror), OrientationEdit.Apply(Framed, OrientationOp.RotateLeft) })
{
var before = start.ToJson();
Assert.Equal(before, OrientationEdit.Apply(OrientationEdit.Apply(start, OrientationOp.RotateRight), OrientationOp.RotateLeft).ToJson());
Assert.Equal(before, OrientationEdit.Apply(OrientationEdit.Apply(start, OrientationOp.Mirror), OrientationOp.Mirror).ToJson());
Assert.Equal(before, OrientationEdit.Apply(OrientationEdit.Apply(start, OrientationOp.Flip), OrientationOp.Flip).ToJson());
}
Assert.Equal(text, Framed.ToJson());
}
/// <summary>
/// Values off the 12-decimal grid (a crop or keyframe centre an older Chronos, a hand or another program wrote) cannot
/// come back bit for bit, as 1 − v drops bits of a v below ½: they land on the grid at the first press, no visible change,
/// and from then on every net-zero sequence of presses gives back the same text.
/// </summary>
[Test]
public void ValuesOffTheGridLandOnItOnceAndThenStay()
{
var legacy = new ProjectSettings
{
Camera = new CameraSettings { Crop = [1 / 3.0, 0.2, 0.25, 0.3], Keyframes = [new CameraKey(0, 0.47368421052631576, 1 / 7.0, 1.5, 0)] },
};
var once = legacy;
for (var k = 0; k < 4; k++) once = OrientationEdit.Apply(once, OrientationOp.RotateRight);
Assert.Approximately(1 / 3.0, once.Camera.Crop![0], 1e-12);
Assert.Approximately(0.47368421052631576, once.Camera.Keyframes[0].CenterX, 1e-12);
Assert.Approximately(1 / 7.0, once.Camera.Keyframes[0].CenterY, 1e-12);
var text = once.ToJson();
var turned = once;
for (var k = 0; k < 4; k++) turned = OrientationEdit.Apply(turned, OrientationOp.RotateRight);
Assert.Equal(text, turned.ToJson(), "four turns of gridded values");
var mirrored = OrientationEdit.Apply(OrientationEdit.Apply(once, OrientationOp.Mirror), OrientationOp.Mirror);
Assert.Equal(text, mirrored.ToJson(), "two mirrors of gridded values");
foreach (var op in Ops)
{
var opposite = op switch
{
OrientationOp.RotateLeft => OrientationOp.RotateRight,
OrientationOp.RotateRight => OrientationOp.RotateLeft,
_ => op,
};
Assert.Equal(text, OrientationEdit.Apply(OrientationEdit.Apply(once, op), opposite).ToJson(), $"{op} undone");
}
// What the editor writes itself is on the grid already.
Assert.Equal(0.473684210526, CropFrame.Grid(0.47368421052631576));
}
/// <summary>A crop out of range turns with the content it shows (as it renders, clamped), not with its stored numbers.</summary>
[Test]
public void AnOutOfRangeCropTurnsWithTheContentItShows()
{
var camera = new CameraSettings { Crop = [0.5, 0, 0.7, 1] };
Assert.Equal(new RectD(0.5, 0, 0.5, 1), CropFrame.Of(camera.Crop));
var mirrored = OrientationEdit.Apply(camera, OrientationOp.Mirror);
Assert.Equal(new RectD(0, 0, 0.5, 1), CropFrame.Of(mirrored.Crop), "the left half: the right half mirrored");
var turned = OrientationEdit.Apply(camera, OrientationOp.RotateRight);
Assert.Equal(new RectD(0, 0.5, 1, 0.5), CropFrame.Of(turned.Crop), "the right half turned clockwise is the bottom half");
// A crop in range stays as stored.
Assert.SequenceEqual([0.6, 0.2, 0.3, 0.4], OrientationEdit.Apply(new CameraSettings { Crop = [0.1, 0.2, 0.3, 0.4] }, OrientationOp.Mirror).Crop!);
}
/// <summary>A turn transposes the aspect text as written, never reduced: turning back gives the stored text (21:9, not 7:3).</summary>
[Test]
public void TurningBackGivesTheStoredAspectText()
{
foreach (var aspect in new[] { "21:9", "1920:1080", "16:9", "4/5" })
{
var project = new ProjectSettings { Camera = new CameraSettings { Aspect = new Auto<string>().WithManual(aspect) } };
var right = OrientationEdit.Apply(project, OrientationOp.RotateRight);
Assert.True(AspectRatio.TryParse(right.Camera.Aspect.Manual, out var transposed));
Assert.True(AspectRatio.TryParse(aspect, out var stored));
Assert.Equal((stored.Height, stored.Width), (transposed.Width, transposed.Height));
Assert.Equal(project.ToJson(), OrientationEdit.Apply(right, OrientationOp.RotateLeft).ToJson(), aspect);
}
Assert.Equal("9:21", OrientationEdit.Transposed(new Auto<string>().WithManual("21:9")).Manual);
}
[Test]
public void MirrorMovesTheCropAndNegatesTheAngles()
{
var camera = new CameraSettings
{
Crop = [0.1, 0.2, 0.3, 0.4],
OffsetX = 0.5,
OffsetY = 0.25,
Keyframes = [new CameraKey(0, 0.2, 0.7, 2, 5)],
Straighten = 3,
};
var mirrored = OrientationEdit.Apply(camera, OrientationOp.Mirror);
Assert.True(mirrored.Mirror);
Assert.SequenceEqual([0.6, 0.2, 0.3, 0.4], mirrored.Crop!);
Assert.Equal((-0.5, 0.25), (mirrored.OffsetX, mirrored.OffsetY));
Assert.Equal(new CameraKey(0, 0.8, 0.7, 2, -5), mirrored.Keyframes.Single());
Assert.Equal(-3.0, mirrored.Straighten);
Assert.Equal(camera.Aspect, mirrored.Aspect);
var flipped = OrientationEdit.Apply(camera, OrientationOp.Flip);
Assert.True(flipped.Flip);
Assert.SequenceEqual([0.1, 0.4, 0.3, 0.4], flipped.Crop!);
Assert.Equal((0.5, -0.25), (flipped.OffsetX, flipped.OffsetY));
Assert.Equal(new CameraKey(0, 0.2, 0.3, 2, -5), flipped.Keyframes.Single());
// A zero stays a zero (JSON would write −0 as "-0").
Assert.False(double.IsNegative(OrientationEdit.Apply(new CameraSettings(), OrientationOp.Mirror).Straighten));
}
[Test]
public void AQuarterTurnTransposesTheCropAndTheAspect()
{
var camera = new CameraSettings
{
Crop = [0.1, 0.2, 0.3, 0.4],
Aspect = new Auto<string>().WithManual("16:9").WithAdvice("4:3", null),
OffsetX = 0.5,
OffsetY = 0.25,
Keyframes = [new CameraKey(0, 0.2, 0.7, 2, 5)],
Straighten = 3,
};
var right = OrientationEdit.Apply(camera, OrientationOp.RotateRight);
Assert.Equal(90, right.Rotate);
Assert.SequenceEqual([0.4, 0.1, 0.4, 0.3], right.Crop!);
Assert.Equal((-0.25, 0.5), (right.OffsetX, right.OffsetY));
Assert.Equal(new CameraKey(0, 0.3, 0.2, 2, 5), right.Keyframes.Single());
Assert.Equal("9:16", right.Aspect.Manual);
Assert.Equal("3:4", right.Aspect.AutoValue);
Assert.Equal(3.0, right.Straighten);
var left = OrientationEdit.Apply(camera, OrientationOp.RotateLeft);
Assert.Equal(270, left.Rotate);
Assert.SequenceEqual([0.2, 0.6, 0.4, 0.3], left.Crop!);
// "source", a square and text that cannot be read stay as they are.
foreach (var aspect in new[] { "source", "1:1", "wide" })
Assert.Equal(aspect, OrientationEdit.Transposed(new Auto<string>().WithManual(aspect)).Manual);
Assert.Null(OrientationEdit.Transposed(new Auto<string>()).Manual);
}
[Test]
public void ATurnSeenThroughOneMirrorIsStoredTheOtherWay()
{
Assert.Equal(270, OrientationEdit.Apply(new CameraSettings { Mirror = true }, OrientationOp.RotateRight).Rotate);
Assert.Equal(90, OrientationEdit.Apply(new CameraSettings { Flip = true }, OrientationOp.RotateLeft).Rotate);
Assert.Equal(90, OrientationEdit.Apply(new CameraSettings { Mirror = true, Flip = true }, OrientationOp.RotateRight).Rotate);
Assert.Equal(0, OrientationEdit.Apply(new CameraSettings { Rotate = 90 }, OrientationOp.RotateLeft).Rotate);
Assert.Equal(0, OrientationEdit.Apply(new CameraSettings { Rotate = -90 }, OrientationOp.RotateRight).Rotate);
}
/// <summary>
/// Each press moves the view as the user sees it: a frame point shown at normalised (x, y) before the press is shown
/// at <see cref="OrientationEdit.MapPoint"/>(x, y) after it, whatever the stored turn, mirror, flip and straighten.
/// </summary>
[Test]
public void PressesMoveThePictureAsShown()
{
const int width = 60, height = 40;
foreach (var rotate in new[] { 0, 90, 180, 270 })
{
foreach (var (mirror, flip) in new[] { (false, false), (true, false), (false, true), (true, true) })
{
foreach (var straighten in new[] { 0.0, 6.5 })
{
var camera = new CameraSettings { Rotate = rotate, Mirror = mirror, Flip = flip, Straighten = straighten };
var before = FrameOrientation.Of(camera, width, height);
foreach (var op in Ops)
{
var after = FrameOrientation.Of(OrientationEdit.Apply(camera, op), width, height);
foreach (var (px, py) in new[] { (0.0, 0.0), (59.0, 0.0), (12.5, 30.0), (30.0, 20.0), (44.0, 7.25) })
{
var (bx, by) = Normalised(before, px, py);
var (ax, ay) = Normalised(after, px, py);
var (ex, ey) = OrientationEdit.MapPoint(bx, by, op);
Assert.Within(ex, ey, ax, ay, 1e-9, $"{op} on rotate {rotate}, mirror {mirror}, flip {flip}, straighten {straighten} at ({px}, {py})");
}
}
}
}
}
}
[Test]
public void ParkedKeyframesMoveWithTheProject()
{
var turned = OrientationEdit.Apply(Framed, OrientationOp.RotateRight);
Assert.Equal(new CameraKey(4, 0.5, 0.75, 1, 2), turned.PendingFrames!.Single().Keyframes!.Single());
Assert.Equal("ab", turned.PendingFrames!.Single().Sha256);
var mirrored = OrientationEdit.Apply(Framed, OrientationOp.Mirror);
Assert.Equal(new CameraKey(4, 0.25, 0.5, 1, -2), mirrored.PendingFrames!.Single().Keyframes!.Single());
Assert.Null(OrientationEdit.Apply(new ProjectSettings(), OrientationOp.Flip).PendingFrames);
}
/// <summary>A frame pixel centre in normalised edge coordinates of the view.</summary>
private static (double X, double Y) Normalised(FrameOrientation orientation, double x, double y)
{
var (vx, vy) = orientation.FrameToView.Apply(x, y);
return ((vx + 0.5) / orientation.ViewWidth, (vy + 0.5) / orientation.ViewHeight);
}
}
@@ -0,0 +1,230 @@
using System.Numerics;
using Chronos.Core.Analysis;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Color;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Testing;
namespace Chronos.Core.Tests.Imaging;
public sealed class LookFilterTests
{
/// <summary>Flat linear patches: black, shadows, mid grey, white, highlights above 1, saturated colours and a negative channel.</summary>
private static readonly (float R, float G, float B)[] Patches =
[
(0, 0, 0), (0.001f, 0.002f, 0.0005f), (0.05f, 0.04f, 0.03f), (0.18f, 0.18f, 0.18f), (0.5f, 0.25f, 0.1f), (1, 1, 1), (1.4f, 1.2f, 0.9f),
(0.9f, 0.1f, 0.05f), (0.05f, 0.6f, 0.1f), (0.1f, 0.2f, 0.8f), (0.3f, -0.01f, 0.2f), (2.5f, 0.3f, 0.02f),
];
/// <summary>One row of every patch, repeated so the row is not a whole number of vectors (the padded tail runs too).</summary>
private static ImageBuffer PatchImage(int channels = 3, int repeats = 3)
{
var width = Patches.Length * repeats + 1;
Assert.NotEqual(0, width % Vector<float>.Count);
var image = new ImageBuffer(width, 2, channels);
for (var y = 0; y < 2; y++)
{
for (var x = 0; x < width; x++)
{
var (r, g, b) = Patches[x % Patches.Length];
(image[0, x, y], image[1, x, y], image[2, x, y]) = (r, g, b);
if (channels == 4) image[3, x, y] = 0.25f + x * 0.01f;
}
}
return image;
}
/// <summary>The closed form of a look: m = M·c, p = 0.18·(m / 0.18)^γ above 0, q = lift + (1 − lift)·p, c + s·(q − c).</summary>
private static double[] ClosedForm(string name, double strength, double r, double g, double b)
{
var look = LookFilter.Definition(name)!;
var m = look.Matrix;
double[] c = [r, g, b];
var result = new double[3];
for (var i = 0; i < 3; i++)
{
var v = m[3 * i] * r + m[3 * i + 1] * g + m[3 * i + 2] * b;
if (v > 0) v = 0.18 * Math.Pow(v / 0.18, look.Contrast);
v = look.Lift + (1 - look.Lift) * v;
result[i] = c[i] + strength * (v - c[i]);
}
return result;
}
private static void Near(double expected, double actual, string message) =>
Assert.Approximately(expected, actual, 1e-6 * Math.Max(1, Math.Abs(expected)), message);
private static IEnumerable<string> Looks => LookFilter.Names.Where(n => n != LookFilter.None);
[Test]
public void NamesAreKnownOrdinallyAndEachLookIsDefined()
{
Assert.Equal(8, LookFilter.Names.Count);
Assert.True(LookFilter.IsKnown(null));
Assert.True(LookFilter.Names.All(LookFilter.IsKnown));
Assert.False(LookFilter.IsKnown("Mono"));
Assert.False(LookFilter.IsKnown("technicolor"));
Assert.Null(LookFilter.Definition(LookFilter.None));
foreach (var name in Looks)
{
var look = LookFilter.Definition(name);
Assert.NotNull(look);
Assert.Equal(9, look!.Matrix.Count);
Assert.True(look.Matrix.All(double.IsFinite) && look.Contrast > 0 && look.Lift is >= 0 and < 0.1, name);
}
}
[Test]
public void TheIdentityANullLookAndStrengthZeroLeaveThePictureByteEqual()
{
using var original = PatchImage(channels: 4);
foreach (var (filter, strength) in new (string?, double)[] { (null, 1), (LookFilter.None, 1), ("vivid", 0), ("vivid", -1), ("vivid", double.NaN), ("technicolor", 1) })
{
using var image = original.Clone();
LookFilter.Apply(image, filter, strength);
Assert.True(image.Data.SequenceEqual(original.Data), $"{filter} at {strength}");
Assert.Equal((0.5f, 0.25f, 0.1f), LookFilter.Apply(filter, strength, 0.5f, 0.25f, 0.1f));
}
LookSettings?[] identities = [null, new LookSettings(), new LookSettings { Filter = LookFilter.None }, new LookSettings { Filter = "sepia", Strength = 0 },
new LookSettings { Filter = "technicolor" }];
foreach (var look in identities)
{
using var image = original.Clone();
FrameFinish.Apply(image, look, null);
Assert.True(image.Data.SequenceEqual(original.Data), look?.ToString());
Assert.True(FrameFinish.IsIdentity(look, null), look?.ToString());
}
}
[Theory]
[Case("mono")]
[Case("sepia")]
[Case("warm")]
[Case("cool")]
[Case("vivid")]
[Case("muted")]
[Case("fade")]
public void EachLookMatchesItsClosedFormScalarAndVectorised(string name)
{
foreach (var strength in new[] { 1, 0.5, 0.3 })
{
using var image = PatchImage();
LookFilter.Apply(image, name, strength);
for (var x = 0; x < image.Width; x++)
{
var (r, g, b) = Patches[x % Patches.Length];
var expected = ClosedForm(name, strength, r, g, b);
var scalar = LookFilter.Apply(name, strength, r, g, b);
double[] reference = [scalar.R, scalar.G, scalar.B];
for (var c = 0; c < 3; c++)
{
var label = $"{name} at {strength}, patch {x % Patches.Length}, channel {c}";
Near(expected[c], reference[c], "scalar " + label);
Near(expected[c], image[c, x, 1], "vectorised " + label);
}
}
}
}
[Test]
public void MonoIsTheRec709Luminance()
{
using var image = PatchImage();
LookFilter.Apply(image, "mono", 1);
for (var x = 0; x < image.Width; x++)
{
var (r, g, b) = Patches[x % Patches.Length];
Assert.Equal(image[0, x, 0], image[1, x, 0]);
Assert.Equal(image[1, x, 0], image[2, x, 0]);
Near(ColorSpace.Luminance(r, g, b), image[0, x, 0], $"patch {x % Patches.Length}");
}
}
[Test]
public void HalfStrengthIsTheMidpoint()
{
foreach (var name in Looks)
{
using var full = PatchImage();
using var half = PatchImage();
using var original = PatchImage();
LookFilter.Apply(full, name, 1);
LookFilter.Apply(half, name, 0.5);
for (var i = 0; i < original.Data.Length; i++)
Near((original.Data[i] + (double)full.Data[i]) / 2, half.Data[i], $"{name} sample {i}");
}
}
[Test]
public void AStrengthAboveOneIsOne()
{
using var one = PatchImage();
using var more = PatchImage();
LookFilter.Apply(one, "fade", 1);
LookFilter.Apply(more, "fade", 3);
Assert.True(one.Data.SequenceEqual(more.Data));
}
[Test]
public void AlphaAndSingleChannelPicturesAreLeftAlone()
{
using var original = PatchImage(channels: 4);
using var image = original.Clone();
LookFilter.Apply(image, "sepia", 1);
Assert.True(image.Plane(3).SequenceEqual(original.Plane(3)));
Assert.False(image.Plane(0).SequenceEqual(original.Plane(0)));
using var grey = new ImageBuffer(5, 1, 1);
grey.Data.Fill(0.4f);
LookFilter.Apply(grey, "fade", 1);
Assert.True(grey.Data.ToArray().All(v => v == 0.4f));
}
[Test]
public void ValuesAboveOneAreKeptThenTheKneeIsApplied()
{
using var looked = PatchImage();
LookFilter.Apply(looked, "vivid", 1);
Assert.Greater(looked.Data.ToArray().Max(), 1.5);
var look = new LookSettings { Filter = "vivid" };
using var finished = PatchImage();
FrameFinish.Apply(finished, look, 0.8);
using var expected = looked.Clone();
ExposureProcessor.Apply(expected, 0, null, 0.8);
Assert.True(finished.Data.SequenceEqual(expected.Data));
Assert.Less(finished.Data.ToArray().Max(), 1);
}
[Test]
public void APixelsResultDoesNotDependOnWhereItLies()
{
// Over 2^20 pixels the planes are split across cores; the row of a small picture must come out the same.
using var small = PatchImage(repeats: 1);
using var large = new ImageBuffer(small.Width, (1 << 20) / small.Width + 3);
for (var c = 0; c < 3; c++)
{
for (var y = 0; y < large.Height; y++) small.Row(c, 0).CopyTo(large.Row(c, y));
}
LookFilter.Apply(small, "fade", 0.7);
LookFilter.Apply(large, "fade", 0.7);
for (var c = 0; c < 3; c++)
{
for (var y = 0; y < large.Height; y += 997) Assert.True(large.Row(c, y).SequenceEqual(small.Row(c, 0)), $"channel {c}, row {y}");
Assert.True(large.Row(c, large.Height - 1).SequenceEqual(small.Row(c, 0)), $"channel {c}, last row");
}
}
[Test]
public void AnUnknownLookIsIgnoredWithAWarning()
{
var warnings = new List<RenderWarning>();
Assert.Null(FrameFinish.Look(new LookSettings { Filter = "technicolor", Strength = 0.5 }, warnings));
Assert.Equal("Export.Render.LookIgnored(technicolor)", warnings.Single().ToString());
warnings.Clear();
Assert.Null(FrameFinish.Look(new LookSettings { Filter = LookFilter.None }, warnings));
Assert.NotNull(FrameFinish.Look(new LookSettings { Filter = "warm" }, warnings));
Assert.Empty(warnings);
}
}
@@ -96,13 +96,13 @@ public sealed class ProjectBundleTests(TestContext context)
{
var workspace = new BundleWorkspace(Guid.CreateVersion7(), "Main", true, new BundleHome(BundleHome.ArchiveKind, SequenceId, ArchiveId), null,
new BundleMedia(BundleMedia.Proxies, 0));
var json = (Sample() with { Workspace = workspace }).ToJson().Replace("\"version\": 1", "\"version\": 2", StringComparison.Ordinal);
var json = (Sample() with { Workspace = workspace }).ToJson().Replace("\"version\": 1", "\"version\": 3", StringComparison.Ordinal);
var bundle = ProjectBundle.Parse(json);
Assert.True(bundle.IsReadOnly);
Assert.True(bundle.Project.IsNewerFormat);
Assert.Equal(0.8, bundle.Project.Exposure.DeflickerStrength.Resolve(1.0));
var plain = Sample().ToJson().Replace("\"version\": 1", "\"version\": 2", StringComparison.Ordinal);
var plain = Sample().ToJson().Replace("\"version\": 1", "\"version\": 3", StringComparison.Ordinal);
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse(plain));
}
@@ -131,7 +131,7 @@ public sealed class ProjectContentTests
Assert.Equal(saved, ProjectContent.Rebind(saved, Frames(Photo(7))));
Assert.False(ProjectContent.SameChoices(saved, current, Frames(Photo(7))));
// A newer Chronos's settings are its own to rename.
var newer = """{ "version": 2, "pendingFrames": [ { "size": 1001, "capturedAt": "2026-09-28T18:00:10", "excluded": true } ] }""";
var newer = """{ "version": 3, "pendingFrames": [ { "size": 1001, "capturedAt": "2026-09-28T18:00:10", "excluded": true } ] }""";
Assert.Equal(newer, ProjectContent.Rebind(newer, now));
}
@@ -329,12 +329,12 @@ public sealed class ProjectContentTests
[Test]
public void SettingsOfANewerFormatAreReadOnlyAndKeptAsTheyAre()
{
var newer = """{ "version": 2, "excludedFrames": [1], "exposure": { "exposureOffsetEv": 1.5 }, "grade": { "look": "film" } }""";
var newer = """{ "version": 3, "excludedFrames": [1], "exposure": { "exposureOffsetEv": 1.5 }, "grade": { "look": "film" } }""";
Assert.Throws<InvalidDataException>(() => ProjectSettings.FromJson(newer));
var read = ProjectSettings.FromJson(newer, allowNewer: true);
Assert.True(read.IsNewerFormat);
Assert.Equal(1.5, read.Exposure.ExposureOffsetEv);
Assert.Equal(2, ProjectContent.FormatOf(newer));
Assert.Equal(3, ProjectContent.FormatOf(newer));
Assert.Equal(1, ProjectContent.FormatOf("""{ "exposure": {} }"""));
// Its positions are a newer Chronos's to translate: only the text is made canonical.
@@ -344,6 +344,42 @@ public sealed class ProjectContentTests
Assert.Equal(portable, ProjectContent.Place(portable, Frames(Photo(2))));
}
[Test]
public void TheTextAndItsHashAreTheSameOnEveryOs()
{
// Built with explicit "\r\n", not Environment.NewLine, so the test fails without the fix on Linux too.
var frames = Frames(Photo(1), Photo(2), Photo(3));
var lf = ProjectContent.ToPortable(Positions([1], 2, 0), frames);
var crlf = lf.Replace("\n", "\r\n", StringComparison.Ordinal);
// Every writer of project text names LF itself: on Linux Environment.NewLine is LF already, so only these fail there.
Assert.Equal("\n", ProjectJson.Default.Options.NewLine);
Assert.Equal("\n", ProjectSettings.IndentedJson.NewLine);
Assert.False(lf.Contains('\r', StringComparison.Ordinal), "portable");
Assert.False(new ProjectSettings().ToJson().Contains('\r', StringComparison.Ordinal), "ToJson");
Assert.Equal(lf, ProjectContent.Canonical(crlf));
Assert.Equal(lf, ProjectContent.ToPortable(crlf, NoFrames()));
// A version stored by a Windows build before (CRLF text, CRLF hash) holds what the LF text holds.
foreach (var photos in new[] { frames, NoFrames() })
{
Assert.True(ProjectContent.SameChoices(crlf, lf, photos));
Assert.True(ProjectContent.SameChoices(lf, crlf, photos));
}
Assert.True(ProjectContent.MatchesHash(lf, ProjectContent.Hash(crlf)));
Assert.True(ProjectContent.MatchesHash(crlf, ProjectContent.Hash(lf)));
Assert.True(ProjectContent.MatchesHash(lf, ProjectContent.Hash(lf).ToUpperInvariant()));
Assert.False(ProjectContent.MatchesHash(lf, ProjectContent.Hash(ProjectContent.ToPortable(Positions([2], 2, 0), frames))));
Assert.False(ProjectContent.MatchesHash(lf, null));
Assert.False(ProjectContent.MatchesHash(lf, "abc"));
// The integrity check stays exact.
Assert.True(ProjectContent.Verifies(crlf, ProjectContent.Hash(crlf)));
Assert.False(ProjectContent.Verifies(lf, ProjectContent.Hash(crlf)));
// Other choices are still other choices.
Assert.False(ProjectContent.SameChoices(crlf, ProjectContent.ToPortable(Positions([2], 2, 0), frames), frames));
}
private static FramePhotos NoFrames() => new([]);
[Test]
public void TextThatIsNoProjectIsRefused()
{
@@ -77,7 +77,7 @@ public sealed class ProjectSettingsTests
Assert.Equal("{date} {title} - {preset}", partial.Export.NameTemplate);
Assert.SequenceEqual(new[] { 0.0, 1.0 }, partial.Timing.RemapCurve.Select(p => p.X));
Assert.Equal(9, partial.Stack.Length);
Assert.Equal(ProjectSettings.CurrentVersion, partial.Version);
Assert.Equal(ProjectSettings.BaseVersion, partial.Version);
// An explicit null clears a nullable value; arrays are replaced, not merged.
var cleared = ProjectSettings.FromJson("""{ "exposure": { "highlightKnee": null }, "timing": { "remapCurve": [ { "x": 0, "y": 0.5 } ] } }""");
@@ -470,4 +470,171 @@ public sealed class ProjectSettingsTests
Assert.Equal(24, s.GopLength);
Assert.Equal(10, s.BitDepth);
}
/// <summary>
/// SHA-256 of the default project's canonical text, as format-1 builds write it: none of phase 4's members, version 1.
/// Builds before wrote it indented with the OS's line ends (CRLF on Windows, LF on Linux); this pin is of the CRLF text,
/// the hash such a Windows build stored.
/// </summary>
private const string DefaultProjectHash = "df0b0f50b113475ece3753a80df0be05cc281cdaa1fa08a73a438ea9161358e0";
/// <summary>SHA-256 of the same text with LF, as every build writes it now on every OS.</summary>
private const string DefaultProjectLfHash = "24e4c2d0379bfda6e42533d4687d69cca95bab72f2a49bd70e2fba267b66a3d1";
[Test]
public void ProjectsWithoutTheNewMembersKeepTheirTextAndHash()
{
var defaults = new ProjectSettings().ToJson();
Assert.False(defaults.Contains('\r', StringComparison.Ordinal), "line ends");
Assert.Equal(DefaultProjectLfHash, ProjectContent.Hash(ProjectContent.Canonical(defaults)));
// A version a Windows build stored before still names this text.
Assert.True(ProjectContent.MatchesHash(ProjectContent.Canonical(defaults), DefaultProjectHash));
Assert.Equal(DefaultProjectHash, ProjectContent.Hash(ProjectContent.Canonical(defaults).Replace("\n", "\r\n", StringComparison.Ordinal)));
// The old build wrote the OS's line ends (OldJson leaves NewLine unset): the same text but for those.
Assert.Equal(OldBuild.Write(new OldProject()).ReplaceLineEndings("\n"), defaults);
Assert.Contains("\"version\": 1", defaults);
foreach (var member in new[] { "rotate", "mirror", "flip", "straighten", "\"look\"" })
Assert.False(defaults.Contains(member, StringComparison.Ordinal), member);
// A project written by a format-1 build reads and writes back the same, byte for byte but for line ends.
var older = new ProjectSettings
{
Camera = new CameraSettings { Crop = [0.1, 0.2, 0.5, 0.6], Aspect = new Auto<string>().WithManual("9:16"), Keyframes = [new CameraKey(3, 0.4, 0.5, 1.5, 2)] },
Exposure = new ExposureSettings { ExposureOffsetEv = 0.3 },
}.ToJson();
Assert.Equal(older, ProjectContent.Canonical(older));
Assert.Equal(older, OldBuild.Write(OldBuild.Read(older)).ReplaceLineEndings("\n"));
Assert.Equal(older, ProjectContent.Canonical(older.Replace("\n", "\r\n", StringComparison.Ordinal)));
Assert.Equal(ProjectSettings.BaseVersion, ProjectContent.FormatOf(older));
}
[Test]
public void TheNewMembersRoundTripAndRaiseTheFormatOnlyWhileUsed()
{
var plain = new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = 0.5 } };
Assert.Equal(ProjectSettings.BaseVersion, plain.RequiredFormat);
var turned = plain with { Camera = plain.Camera with { Rotate = 90, Mirror = true, Flip = true, Straighten = -3.5 } };
var looked = plain with { Look = new LookSettings { Filter = "sepia", Strength = 0.6 } };
foreach (var settings in new[] { turned, looked, plain with { Camera = new CameraSettings { Straighten = 1 } }, plain with { Camera = new CameraSettings { Flip = true } } })
{
Assert.Equal(2, settings.RequiredFormat);
var json = settings.ToJson();
Assert.Contains("\"version\": 2", json);
var back = ProjectSettings.FromJson(json);
Assert.Equal(2, back.Version);
Assert.False(back.IsNewerFormat);
Assert.Equal(json, back.ToJson());
}
var read = ProjectSettings.FromJson(turned.ToJson());
Assert.Equal((90, true, true, -3.5), (read.Camera.Rotate, read.Camera.Mirror, read.Camera.Flip, read.Camera.Straighten));
Assert.Equal((1, true), (read.Camera.Turns, read.Camera.IsOriented));
var look = Assert.NotNull(ProjectSettings.FromJson(looked.ToJson()).Look);
Assert.Equal(("sepia", (double?)0.6), (look.Filter, look.Strength));
// Taken away again, the project is format 1 with the text it had before.
var undone = ProjectSettings.FromJson(turned.ToJson()) with { Camera = plain.Camera };
Assert.Equal(ProjectSettings.BaseVersion, undone.RequiredFormat);
Assert.Equal(plain.ToJson(), undone.ToJson());
Assert.Equal(plain.ToJson(), (ProjectSettings.FromJson(looked.ToJson()) with { Look = null }).ToJson());
// An identity look and a whole turn need nothing newer; an unknown look does (it is a newer Chronos's).
Assert.Equal(1, (plain with { Look = new LookSettings { Filter = "none" } }).RequiredFormat);
Assert.Equal(1, (plain with { Look = new LookSettings { Filter = "mono", Strength = 0 } }).RequiredFormat);
Assert.Equal(1, (plain with { Camera = new CameraSettings { Rotate = 360 } }).RequiredFormat);
Assert.Equal(2, (plain with { Look = new LookSettings { Filter = "film" } }).RequiredFormat);
Assert.Equal(3, new CameraSettings { Rotate = -90 }.Turns);
}
[Test]
public void TheNewMembersComeAfterTheOldOnesSoAnOlderBuildWritesThemBackInPlace()
{
var settings = new ProjectSettings
{
Camera = new CameraSettings { Crop = [0.2, 0, 0.6, 1], Keyframes = [new CameraKey(1, 0.5, 0.5, 2, 0)], Rotate = 270, Straighten = 2.25 },
HeroFrame = 4,
Look = new LookSettings { Filter = "warm" },
};
var canonical = ProjectContent.Canonical(settings.ToJson());
// A format-1 build keeps them as members it does not know, and writes them where they were.
var old = OldBuild.Read(canonical);
Assert.True(old.Camera.Extra!.ContainsKey("rotate") && old.Extra!.ContainsKey("look"));
// In the OS's line ends (CRLF on Windows): the same text and content hash but for those.
Assert.Equal(canonical, OldBuild.Write(old).ReplaceLineEndings("\n"));
Assert.True(ProjectContent.MatchesHash(OldBuild.Write(old), ProjectContent.Hash(canonical)));
Assert.True(ProjectContent.SameChoices(OldBuild.Write(old), canonical, new FramePhotos([])));
var camera = System.Text.Json.Nodes.JsonNode.Parse(canonical)!["camera"]!.AsObject().Select(p => p.Key).ToList();
Assert.SequenceEqual(["crop", "aspect", "offsetX", "offsetY", "keyframes", "rotate", "straighten"], camera);
}
[Test]
public void ANewerFormatStaysReadOnlyAndKeepsItsNumber()
{
const string newer = """{ "version": 3, "camera": { "rotate": 90 }, "look": { "filter": "film", "grain": 0.2 } }""";
Assert.Throws<InvalidDataException>(() => ProjectSettings.FromJson(newer));
var read = ProjectSettings.FromJson(newer, allowNewer: true);
Assert.True(read.IsNewerFormat);
Assert.Equal(3, read.WrittenFormat);
var canonical = ProjectContent.Canonical(newer);
Assert.Equal(3, ProjectContent.FormatOf(canonical));
Assert.Contains("\"grain\": 0.2", canonical);
Assert.Equal(canonical, ProjectContent.Canonical(canonical));
// A format-2 project is this Chronos's own (written as the format it needs); text without a version is format 1.
Assert.False(ProjectSettings.FromJson("""{ "version": 2 }""").IsNewerFormat);
Assert.Equal(1, ProjectSettings.FromJson("""{ "version": 2 }""").WrittenFormat);
Assert.Equal(1, ProjectContent.FormatOf("""{ "camera": {} }"""));
Assert.Equal(1, ProjectContent.FormatOf(null));
}
/// <summary>
/// The settings as a format-1 build reads and writes them: its camera without phase 4's members and its project without
/// the look, with the same serialiser options. What it does not know lands in <c>Extra</c>.
/// </summary>
private static class OldBuild
{
public static OldProject Read(string json) => System.Text.Json.JsonSerializer.Deserialize(json, OldJson.Default.OldProject)!;
public static string Write(OldProject project) => System.Text.Json.JsonSerializer.Serialize(project, OldJson.Default.OldProject);
}
}
/// <summary>A format-1 build's camera (before owner review 1, phase 4).</summary>
internal sealed record OldCamera
{
public double[]? Crop { get; init; }
public Auto<string> Aspect { get; init; } = new();
public double OffsetX { get; init; }
public double OffsetY { get; init; }
public IReadOnlyList<CameraKey> Keyframes { get; init; } = [];
[System.Text.Json.Serialization.JsonExtensionData]
public Dictionary<string, System.Text.Json.JsonElement>? Extra { get; set; }
}
/// <summary>A format-1 build's project (before owner review 1, phase 4).</summary>
internal sealed record OldProject
{
public int Version { get; init; } = 1;
public TimingSettings Timing { get; init; } = new();
public ExposureSettings Exposure { get; init; } = new();
public MotionSettings Motion { get; init; } = new();
public OldCamera Camera { get; init; } = new();
public StackSettings Stack { get; init; } = new();
public ExportSettings Export { get; init; } = new();
public IReadOnlyList<int> ExcludedFrames { get; init; } = [];
public int? HeroFrame { get; init; }
public IReadOnlyList<PendingFrame>? PendingFrames { get; init; }
[System.Text.Json.Serialization.JsonExtensionData]
public Dictionary<string, System.Text.Json.JsonElement>? Extra { get; set; }
}
[System.Text.Json.Serialization.JsonSourceGenerationOptions(
WriteIndented = true,
PropertyNamingPolicy = System.Text.Json.Serialization.JsonKnownNamingPolicy.CamelCase,
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true,
PropertyNameCaseInsensitive = true)]
[System.Text.Json.Serialization.JsonSerializable(typeof(OldProject))]
internal sealed partial class OldJson : System.Text.Json.Serialization.JsonSerializerContext;
@@ -1,3 +1,4 @@
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Video;
@@ -26,7 +27,7 @@ internal sealed class CapturingEncoderProvider(string name, params EncoderCapabi
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));
c.Codec == settings.Codec && EncoderSelector.Takes(c, settings.Width, settings.Height) && (settings.BitDepth == 8 || c.SupportsTenBit));
public IVideoEncoderSession Open(EncodeSettings settings)
{
@@ -0,0 +1,82 @@
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Color;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Testing;
using static Chronos.Core.Tests.Render.RenderFixture;
namespace Chronos.Core.Tests.Render;
/// <summary>The colour look in renders (owner review 1, R6): once per output frame, after stacking, before the knee.</summary>
public sealed class LookRenderTests(TestContext context)
{
private static ProjectSettings With(LookSettings? look, double? knee = null, StackSettings? stack = null) =>
Plain with { Look = look, Exposure = new ExposureSettings { HighlightKnee = knee }, Stack = stack ?? new StackSettings() };
private static void SameFrames(IReadOnlyList<ImageBuffer> expected, IReadOnlyList<ImageBuffer> actual)
{
Assert.Equal(expected.Count, actual.Count);
for (var i = 0; i < expected.Count; i++) Assert.True(expected[i].Data.SequenceEqual(actual[i].Data), $"frame {i}");
}
[Test]
public async Task TheIdentityLooksRenderTheSameBytesAsNoLook()
{
var (plain, _) = await CaptureAsync(Input(Source(4), With(null)), cancellationToken: context.Cancellation);
foreach (var look in new[] { new LookSettings { Filter = LookFilter.None }, new LookSettings { Filter = "vivid", Strength = 0 } })
{
var (encode, result) = await CaptureAsync(Input(Source(4), With(look)), cancellationToken: context.Cancellation);
SameFrames(plain.Frames, encode.Frames);
Assert.Empty(result.Warnings);
}
}
[Test]
public async Task AnUnknownLookRendersAsNoneWithAWarning()
{
var (plain, _) = await CaptureAsync(Input(Source(4), With(null)), cancellationToken: context.Cancellation);
var (encode, result) = await CaptureAsync(Input(Source(4), With(new LookSettings { Filter = "technicolor" })), cancellationToken: context.Cancellation);
SameFrames(plain.Frames, encode.Frames);
Assert.Contains(result.Warnings, w => w.Key == "Export.Render.LookIgnored" && w.Args.SequenceEqual(["technicolor"]));
}
[Test]
public async Task ACaptureWithALookIsTheFinishOfThePlainCapture()
{
// The look comes before the knee: the plain render has no knee, so the finish adds both in its own order.
var look = new LookSettings { Filter = "sepia", Strength = 0.7 };
var source = Source(6, configure: o => o with { StartEv = 1, EndEv = 2 });
var (plain, _) = await CaptureAsync(Input(source, With(null)), cancellationToken: context.Cancellation);
var (encode, result) = await CaptureAsync(Input(source, With(look, knee: 0.85)), cancellationToken: context.Cancellation);
Assert.Empty(result.Warnings);
foreach (var frame in plain.Frames) FrameFinish.Apply(frame, look, 0.85);
SameFrames(plain.Frames, encode.Frames);
Assert.Less(encode.Frames.Max(f => f.Data.ToArray().Max()), 1);
}
[Test]
public async Task AMedianStackWithMonoIsMonoOfTheMedian()
{
var stack = new StackSettings { Mode = StackSetting.Median, Length = 5 };
var source = Source(9, motion: i => (0.5 * i, 0));
var (median, _) = await CaptureAsync(Input(source, With(null, stack: stack)), cancellationToken: context.Cancellation);
var (mono, _) = await CaptureAsync(Input(source, With(new LookSettings { Filter = "mono" }, stack: stack)), cancellationToken: context.Cancellation);
foreach (var frame in median.Frames) LookFilter.Apply(frame, "mono", 1);
SameFrames(median.Frames, mono.Frames);
Assert.True(mono.Frames.All(f => f.Plane(0).SequenceEqual(f.Plane(1)) && f.Plane(1).SequenceEqual(f.Plane(2))));
}
[Test]
public async Task PngOutputWithALookIsByteIdenticalAcrossRuns()
{
var dir = context.CreateTempDirectory();
var project = With(new LookSettings { Filter = "fade", Strength = 0.8 }, knee: 0.9);
var first = await Pipeline().RenderAsync(Input(Source(5), project), Target(dir, Preset("png-sequence") with { BitDepth = 16 }, "a"), cancellationToken: context.Cancellation);
var second = await Pipeline().RenderAsync(Input(Source(5), project), Target(dir, Preset("png-sequence") with { BitDepth = 16 }, "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(5, a.Length);
Assert.Equal(a.Length, b.Length);
for (var i = 0; i < a.Length; i++) Assert.BytesEqual(File.ReadAllBytes(a[i]), File.ReadAllBytes(b[i]));
}
}
@@ -0,0 +1,138 @@
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Geometry;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Tests.Geometry;
using Chronos.Testing;
namespace Chronos.Core.Tests.Render;
public sealed class RenderGeometryTests
{
[Test]
public void TheChosenProportionsWinOverAFixedPreset()
{
var portrait = RenderGeometry.Create(Camera("9:16"), Export("4k-h264"), 6000, 4000);
Assert.Equal((2160, 3840), (portrait.OutputWidth, portrait.OutputHeight));
Assert.Approximately(9 / 16.0, portrait.OutputRatio, 1e-12);
Assert.Empty(portrait.Warnings);
var source = RenderGeometry.Create(new CameraSettings(), Export("4k-h264"), 6000, 4000);
Assert.Equal((3840, 2160), (source.OutputWidth, source.OutputHeight));
Assert.Approximately(16 / 9.0, source.OutputRatio, 1e-12);
// Every case agrees with RenderSize, which the server routes jobs with.
foreach (var aspect in new[] { "source", "9:16", "1:1", "4:5", "21:9" })
{
foreach (var camera in new[] { Camera(aspect), Camera(aspect) with { Rotate = 90 } })
{
foreach (var preset in new[] { "4k-h264", "1080p-h264", "vertical-1080x1920", "png-sequence" })
{
var geometry = RenderGeometry.Create(camera, Export(preset), 6000, 4000);
Assert.Equal(RenderSize.Of(camera, Export(preset), 6000, 4000), (geometry.OutputWidth, geometry.OutputHeight), $"{aspect} {preset} {camera.Rotate}");
}
}
}
}
[Test]
public void AQuarterTurnSwapsTheViewAndLocksTheCropInIt()
{
var turned = RenderGeometry.Create(new CameraSettings { Rotate = 90 }, Export("png-sequence"), 6000, 4000);
Assert.Equal((4000, 6000), (turned.ViewWidth, turned.ViewHeight));
Assert.Equal((4000, 6000), (turned.OutputWidth, turned.OutputHeight));
Assert.Equal((6000, 4000), (turned.SourceWidth, turned.SourceHeight));
// 1:1 on the turned view: the box is as wide as the view and 4000/6000 of its height, in normalised units.
var square = RenderGeometry.Create(Camera("1:1") with { Rotate = 90 }, Export("png-sequence"), 6000, 4000);
Assert.Approximately(1.5, square.LockRatio, 1e-12);
var crop = square.EditableCrop;
Assert.Approximately(1, crop.Width, 1e-12);
Assert.Approximately(2 / 3.0, crop.Height, 1e-12);
Assert.Approximately(1 / 6.0, crop.Y, 1e-12);
Assert.Equal((4000, 4000), (square.OutputWidth, square.OutputHeight));
}
[Test]
public void TheEditableCropIsTheRenderedCrop()
{
var camera = Camera("4:5") with { Crop = [0.1, 0.2, 0.5, 0.6], OffsetX = 1, OffsetY = -1, Rotate = 270, Mirror = true };
var geometry = RenderGeometry.Create(camera, Export("png-sequence"), 96, 64);
// The Export step's footprint of a frame without pose or stabilisation is the Camera step's box.
foreach (var (w, h) in new[] { (96, 64), (48, 32) })
{
var plan = GeometryStage.Plan(w, h, geometry.For(w, h, 0, Affine2D.Identity));
var footprint = geometry.FootprintInView(plan, w, h);
var box = geometry.EditableCrop;
Assert.Approximately(box.X, footprint.X, 1e-9);
Assert.Approximately(box.Y, footprint.Y, 1e-9);
Assert.Approximately(box.Width, footprint.Width, 1e-9);
Assert.Approximately(box.Height, footprint.Height, 1e-9);
}
Assert.Equal(new RectD(0, 0, 1, 1), geometry.FootprintInView(null, 96, 64));
// The box the editor would write for it renders the same.
var written = Camera("4:5") with { Crop = CropFrame.ToCrop(geometry.EditableCrop), Rotate = 270, Mirror = true };
var again = RenderGeometry.Create(written, Export("png-sequence"), 96, 64);
Assert.Equal((geometry.OutputWidth, geometry.OutputHeight), (again.OutputWidth, again.OutputHeight));
Assert.Approximately(geometry.EditableCrop.X, again.EditableCrop.X, 1e-12);
Assert.Approximately(geometry.EditableCrop.Y, again.EditableCrop.Y, 1e-12);
}
[Test]
public void ViewToFrameMapsTheViewOntoTheDecodedFrame()
{
var geometry = RenderGeometry.Create(new CameraSettings { Rotate = 180, Flip = true, Straighten = -4 }, Export("png-sequence"), 6000, 4000);
var small = geometry.ViewToFrame(600, 400);
Assert.Equal(FrameOrientation.Of(180, false, true, -4, 600, 400).ViewToFrame, small);
Assert.Equal(geometry.Orientation.ViewToFrame, geometry.ViewToFrame(6000, 4000));
Assert.Equal(Affine2D.Identity, RenderGeometry.Create(new CameraSettings(), Export("png-sequence"), 60, 40).ViewToFrame(60, 40));
// The Source framing shows the whole view at the size asked, and only an identity camera skips the warp.
var view = geometry.ViewFor(600, 400, 300, 200);
var plan = GeometryStage.Plan(600, 400, view);
Assert.Equal((300, 200), (plan.OutputWidth, plan.OutputHeight));
Assert.Equal(new RectD(0, 0, 600, 400), plan.Crop);
}
[Test]
public void TheDecodeGrowsWithTheCoverZoom()
{
var plain = RenderGeometry.Create(new CameraSettings(), Export("png-sequence", 96, 64), 480, 320);
Assert.Equal(96, plain.WorkingLongEdge);
foreach (var degrees in new[] { 2.0, 10.0, -15.0 })
{
var straightened = RenderGeometry.Create(new CameraSettings { Straighten = degrees }, Export("png-sequence", 96, 64), 480, 320);
var zoom = straightened.Orientation.CoverZoom;
Assert.Greater(zoom, 1);
Assert.Equal((int)double.Ceiling(96 * zoom), straightened.WorkingLongEdge);
}
// Quarter turns do not change the long edge.
Assert.Equal(96, RenderGeometry.Create(new CameraSettings { Rotate = 90 }, Export("png-sequence", 64, 96), 480, 320).WorkingLongEdge);
}
[Test]
public void StabilisationComposesInRawFrameSpace()
{
// stab⁻¹ · O⁻¹ · V: the correction is undone in the decoded frame, after the view is mapped back into it.
var geometry = RenderGeometry.Create(new CameraSettings { Rotate = 90 }, Export("png-sequence"), 96, 64);
var shift = Affine2D.Translation(3, -2);
var settings = geometry.For(96, 64, 0, shift);
var plain = geometry.For(96, 64, 0, Affine2D.Identity);
var (x, y) = settings.Warp.Apply(10, 20);
var (px, py) = plain.Warp.Apply(10, 20);
Assert.Within(px - 3, py + 2, x, y, 1e-12);
using var frame = FrameOrientationTests.Texture(96, 64, seed: 11);
using var view = GeometryStage.Apply(frame, plain);
Assert.Equal((64, 96), (view.Width, view.Height));
}
private static CameraSettings Camera(string aspect) => new() { Aspect = new Auto<string>().WithManual(aspect) };
private static ResolvedExport Export(string preset, int width = -1, int height = -1)
{
var export = ExportResolver.Resolve(new ExportSettings { Preset = new Auto<string>().WithManual(preset) });
return width < 0 ? export : export with { Width = width, Height = height };
}
}
@@ -74,6 +74,33 @@ public sealed class RenderPipelineTests
Assert.BytesEqual(File.ReadAllBytes(apngA.OutputPath), File.ReadAllBytes(apngB.OutputPath));
}
[Test]
public async Task TransformedOutputsAreByteIdenticalAcrossRuns()
{
var dir = _context.CreateTempDirectory();
var project = Plain with
{
Camera = new CameraSettings
{
Rotate = 90,
Mirror = true,
Straighten = 3.5,
Aspect = new Auto<string>().WithManual("4:5"),
Crop = [0.1, 0.05, 0.8, 0.8],
Keyframes = [new CameraKey(0, 0.45, 0.5, 1.2, 2), new CameraKey(11, 0.55, 0.5, 1.4, -2)],
},
};
var export = Preset("png-sequence", 64, 64);
var first = await Pipeline().RenderAsync(Input(Source(), project), Target(dir, export, "a"), cancellationToken: _context.Cancellation);
var second = await Pipeline().RenderAsync(Input(Source(), project), Target(dir, export, "b"), cancellationToken: _context.Cancellation);
Assert.Equal((51, 64), (first.Width, first.Height));
var a = Directory.GetFiles(first.OutputPath).Order(StringComparer.Ordinal).ToArray();
var b = Directory.GetFiles(second.OutputPath).Order(StringComparer.Ordinal).ToArray();
Assert.Equal(12, a.Length);
Assert.Equal(a.Length, b.Length);
for (var i = 0; i < a.Length; i++) Assert.BytesEqual(File.ReadAllBytes(a[i]), File.ReadAllBytes(b[i]));
}
[Theory]
[Case("mjpeg-avi")]
[Case("png-sequence")]
@@ -142,6 +142,61 @@ public sealed class RenderProcessingTests
Assert.Greater(Psnr(expected, corner.Frames[2]), 60);
}
/// <summary>
/// A crop in the view frame keeps its content through every orientation press: the capture after the press is the
/// plain capture turned, mirrored or flipped the same way.
/// </summary>
[Theory]
[Case(OrientationOp.RotateRight, 1, false, false)]
[Case(OrientationOp.RotateLeft, 3, false, false)]
[Case(OrientationOp.Mirror, 0, true, false)]
[Case(OrientationOp.Flip, 0, false, true)]
public async Task OrientationPressesKeepTheCroppedContent(OrientationOp op, int turns, bool mirror, bool flip)
{
var source = Source(4);
var framed = With(camera: new CameraSettings { Crop = [0.5, 0.25, 0.5, 0.5], Aspect = On("3:2") });
var (plain, before) = await CaptureAsync(Input(source, framed), Preset("png-sequence", 0, 0), cancellationToken: _context.Cancellation);
Assert.Equal((48, 32), (before.Width, before.Height));
var pressed = OrientationEdit.Apply(framed, op);
var (moved, after) = await CaptureAsync(Input(source, pressed), Preset("png-sequence", 0, 0), cancellationToken: _context.Cancellation);
Assert.Empty(after.Warnings);
using var expected = Geometry.FrameOrientationTests.Permuted(plain.Frames[2], turns, mirror, flip);
Assert.Equal((expected.Width, expected.Height), (after.Width, after.Height));
var psnr = Psnr(expected, moved.Frames[2]);
_context.Log($"{op}: {psnr:F1} dB");
Assert.Greater(psnr, 60);
Assert.True(expected.Data.SequenceEqual(moved.Frames[2].Data), "a quarter turn, a mirror and a flip move whole pixels");
}
[Test]
public async Task APortraitAspectTurnsAFixedPresetToPortrait()
{
var source = Source(4);
using var reference = source.Sequence.Render(2);
var project = With(camera: new CameraSettings { Aspect = On("9:16") });
var (encode, result) = await CaptureAsync(Input(source, project), Preset("png-sequence", 96, 64), cancellationToken: _context.Cancellation);
Assert.Equal((54, 96), (result.Width, result.Height));
Assert.Empty(result.Warnings);
using var expected = GeometryStage.Apply(reference, new GeometrySettings { Crop = new RectD(30, 0, 36, 64), OutputWidth = 54, OutputHeight = 96 });
Assert.Greater(Psnr(expected, encode.Frames[2]), 60);
}
[Test]
public async Task StraightenLevelsTheViewAndDecodesLarger()
{
var source = Source(4, width: 480, height: 320);
var project = With(camera: new CameraSettings { Straighten = -6 });
var (encode, result) = await CaptureAsync(Input(source, project), Preset("png-sequence", 96, 64), cancellationToken: _context.Cancellation);
var orientation = FrameOrientation.Of(project.Camera, 480, 320);
Assert.Equal((int)double.Ceiling(96 * orientation.CoverZoom), source.LargestRenderRequest);
Assert.Empty(result.Warnings);
using var full = source.Sequence.Render(1);
using var expected = GeometryStage.Apply(full, new GeometrySettings { OutputWidth = 96, OutputHeight = 64, Warp = orientation.ViewToFrame });
var psnr = Psnr(expected, encode.Frames[1]);
_context.Log($"straighten −6° vs a direct warp: {psnr:F1} dB, cover zoom {orientation.CoverZoom:F4}");
Assert.Greater(psnr, 28);
}
[Test]
public async Task VirtualCameraZoomsAndTheDecodeSizeFollowsTheNeed()
{
@@ -0,0 +1,30 @@
using Chronos.Core.Export;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Testing;
namespace Chronos.Core.Tests.Render;
public sealed class RenderRulesTests
{
[Test]
public void AMismatchedFixedPresetNeedsFormatTwo()
{
var project = new ProjectSettings { Camera = Camera("9:16") };
Assert.Equal(2, RenderRules.RequiredFormat(project, Export("4k-h264"), 6000, 4000));
// The same proportions as the preset, "source" or a free-size preset change nothing an older build would render.
Assert.Equal(1, RenderRules.RequiredFormat(project with { Camera = Camera("16:9") }, Export("4k-h264"), 6000, 4000));
Assert.Equal(1, RenderRules.RequiredFormat(new ProjectSettings(), Export("4k-h264"), 6000, 4000));
Assert.Equal(1, RenderRules.RequiredFormat(project, Export("png-sequence"), 6000, 4000));
// The settings' own format counts too.
var turned = new ProjectSettings { Camera = new CameraSettings { Rotate = 90 } };
Assert.Equal(2, RenderRules.RequiredFormat(turned, Export("png-sequence"), 6000, 4000));
var newer = ProjectSettings.FromJson("""{ "version": 3 }""", allowNewer: true);
Assert.Equal(3, RenderRules.RequiredFormat(newer, Export("4k-h264"), 6000, 4000));
}
private static CameraSettings Camera(string aspect) => new() { Aspect = new Auto<string>().WithManual(aspect) };
private static ResolvedExport Export(string preset, ExportOverrides? overrides = null) =>
ExportResolver.Resolve(new ExportSettings { Preset = new Auto<string>().WithManual(preset), Overrides = overrides ?? new ExportOverrides() });
}
@@ -0,0 +1,83 @@
using Chronos.Core.Export;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Testing;
namespace Chronos.Core.Tests.Render;
public sealed class RenderSizeTests
{
[Theory]
[Case("4k-h264", "9:16", 2160, 3840)]
[Case("4k-h264", "1:1", 2160, 2160)]
[Case("4k-h264", "4:5", 2160, 2700)]
[Case("4k-h264", "21:9", 3840, 1646)]
[Case("4k-h264", "16:9", 3840, 2160)]
[Case("1080p-h264", "9:16", 1080, 1920)]
[Case("vertical-1080x1920", "16:9", 1920, 1080)]
[Case("vertical-1080x1920", "9:16", 1080, 1920)]
public void TheChosenProportionsWinOverAFixedPreset(string preset, string aspect, int width, int height) =>
Assert.Equal((width, height), RenderSize.Of(Camera(aspect), Export(preset), 6000, 4000));
[Test]
public void SourceKeepsThePresetsSize()
{
Assert.Equal((3840, 2160), RenderSize.Of(new CameraSettings(), Export("4k-h264"), 3000, 4000));
Assert.Equal((1080, 1920), RenderSize.Of(Camera("source"), Export("vertical-1080x1920"), 6000, 4000));
// An aspect that cannot be read renders as source.
Assert.Equal((3840, 2160), RenderSize.Of(Camera("wide"), Export("4k-h264"), 6000, 4000));
// The Auto's advised value counts like a manual one.
var advised = new CameraSettings { Aspect = new Auto<string>().WithAdvice("9:16", null) };
Assert.Equal((2160, 3840), RenderSize.Of(advised, Export("4k-h264"), 6000, 4000));
}
[Test]
public void SizesAreEvenOnlyForCodecsThatNeedIt()
{
var png = Export("png-sequence", new ExportOverrides { Width = 1001, Height = 1001 });
Assert.Equal((563, 1001), RenderSize.Of(Camera("9:16"), png, 6000, 4000));
var h264 = Export("1080p-h264", new ExportOverrides { Width = 1001, Height = 1001 });
Assert.Equal((562, 1000), RenderSize.Of(Camera("9:16"), h264, 6000, 4000));
}
[Test]
public void FreeSizePresetsAreUnchanged()
{
// No side given: the aspect-fitted crop of the view, capped by the decode size.
var png = Export("png-sequence");
Assert.Equal((6000, 4000), RenderSize.Of(new CameraSettings(), png, 6000, 4000));
Assert.Equal((2250, 4000), RenderSize.Of(Camera("9:16"), png, 6000, 4000));
Assert.Equal((1500, 1000), RenderSize.Of(new CameraSettings(), png, 6000, 4000, maxWorkingLongEdge: 1500));
Assert.Equal((3000, 2000), RenderSize.Of(new CameraSettings { Crop = [0.25, 0.25, 0.5, 0.5] }, png, 6000, 4000));
// One side given: the other from the ratio.
Assert.Equal((1200, 800), RenderSize.Of(new CameraSettings(), Export("png-sequence", new ExportOverrides { Width = 1200 }), 6000, 4000));
Assert.Equal((450, 800), RenderSize.Of(Camera("9:16"), Export("png-sequence", new ExportOverrides { Height = 800 }), 6000, 4000));
}
[Test]
public void AQuarterTurnTurnsTheSourceRatio()
{
var turned = new CameraSettings { Rotate = 90 };
Assert.Equal((4000, 6000), RenderSize.Of(turned, Export("png-sequence"), 6000, 4000));
Assert.Equal((4000, 6000), RenderSize.ViewSize(turned, 6000, 4000));
Assert.Equal((6000, 4000), RenderSize.ViewSize(turned with { Rotate = 180 }, 6000, 4000));
// A fixed preset with "source" keeps its own size whatever the turn.
Assert.Equal((3840, 2160), RenderSize.Of(turned, Export("4k-h264"), 6000, 4000));
Assert.Approximately(2 / 3.0, RenderSize.Ratio(turned, Export("png-sequence"), 6000, 4000), 1e-12);
}
[Test]
public void AdaptTurnsTheBoxToTheRatiosOrientation()
{
Assert.Equal((2160, 3840), RenderSize.Adapt(3840, 2160, 9 / 16.0));
Assert.Equal((2160, 3840), RenderSize.Adapt(2160, 3840, 9 / 16.0));
Assert.Equal((1920, 1080), RenderSize.Adapt(1080, 1920, 16 / 9.0));
Assert.Equal((1080, 1080), RenderSize.Adapt(1080, 1920, 1));
Assert.Throws<ArgumentOutOfRangeException>(() => RenderSize.Adapt(1920, 1080, 0));
}
private static CameraSettings Camera(string aspect) => new() { Aspect = new Auto<string>().WithManual(aspect) };
private static ResolvedExport Export(string preset, ExportOverrides? overrides = null) =>
ExportResolver.Resolve(new ExportSettings { Preset = new Auto<string>().WithManual(preset), Overrides = overrides ?? new ExportOverrides() });
}
@@ -44,6 +44,16 @@ public sealed class SelfTestTests
Assert.True(results.Where(r => r.Id != "render.mp4").All(r => r.Outcome == SelfTestOutcome.Passed));
}
[Test]
public async Task GeometryChecksPass()
{
string[] ids = ["proc.orient", "proc.straighten", "proc.portrait", "proc.aspect", "proc.crop", "proc.look"];
var results = await SelfTest.RunAsync(new SelfTestOptions { WorkDirectory = _context.CreateTempDirectory(), Filters = ids }, cancellationToken: _context.Cancellation);
foreach (var r in results) _context.Log($"{r.Id}: {r.Outcome} {r.Detail}");
Assert.SequenceEqual(ids.Order(StringComparer.Ordinal), results.Select(r => r.Id).Order(StringComparer.Ordinal));
Assert.True(results.All(r => r.Outcome == SelfTestOutcome.Passed));
}
[Test]
public async Task FailuresAreReportedNotThrown()
{