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

@@ -0,0 +1,311 @@
using System.Globalization;
using Chronos.App.Editor;
using Chronos.Core.Imaging.Geometry;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Testing;
namespace Chronos.App.Tests.Editor;
/// <summary>
/// The Camera step's rows (owner review 1, R5/R6) and the Exposure step's Look group on an open session of the 96 × 64
/// synthetic sunset: the crop box locked to the aspect through Crop size, X and Y, the orientation controls, Straighten,
/// the look written only when it is not the identity, and every row's label and tooltip in English and Italian.
/// </summary>
[Serial]
public sealed class CameraTabTests
{
private static (EditorSession Session, FakeSequenceSource Source) Open(ProjectSettings? project = null)
{
var content = EditorFixture.Content(EditorFixture.Sunset, project);
var source = new FakeSequenceSource(EditorFixture.Sunset, content);
return (new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)), source);
}
private static ProjectSettings WithAspect(string aspect, string? preset = null)
{
var project = new ProjectSettings();
project = project with { Camera = project.Camera with { Aspect = project.Camera.Aspect.WithManual(aspect) } };
return preset is null ? project : project with { Export = project.Export with { Preset = project.Export.Preset.WithManual(preset) } };
}
private static T Row<T>(IReadOnlyList<SettingRow> rows, string headerKey)
where T : SettingRow => (T)rows.Single(r => r.Header == Loc.L(headerKey));
private static void Refresh(IReadOnlyList<SettingRow> rows)
{
foreach (var row in rows) row.Refresh();
}
[Test]
public void TheRotationRowCountsTheTurnsAsShown()
{
var camera = new CameraSettings();
foreach (var op in new[] { OrientationOp.Mirror, OrientationOp.RotateRight, OrientationOp.RotateRight, OrientationOp.Flip, OrientationOp.RotateRight })
{
var before = CameraTab.ShownTurns(camera);
camera = OrientationEdit.Apply(camera, op);
var expected = op == OrientationOp.RotateRight ? (before + 1) % 4 : (4 - before) % 4;
Assert.Equal(expected, CameraTab.ShownTurns(camera), $"after {op}");
}
Assert.Equal(3, CameraTab.ShownTurns(new CameraSettings { Rotate = 90, Mirror = true }));
Assert.Equal(1, CameraTab.ShownTurns(new CameraSettings { Rotate = 90, Mirror = true, Flip = true }));
}
[Test]
public async Task CropSizeAndPlaceMoveTheBoxLockedToTheAspect()
{
var (session, _) = Open(WithAspect("9:16"));
await using (session)
{
var rows = CameraTab.FramingRows(session);
var size = Row<NumberRow>(rows, "Editor.Camera.CropSize");
var x = Row<NumberRow>(rows, "Editor.Camera.CropX");
var y = Row<NumberRow>(rows, "Editor.Camera.CropY");
Assert.Equal(1.0, size.Value, "no crop: the largest box");
Assert.Equal(0.0, x.Value);
Assert.True(x.IsApplicable, "a 9:16 box can move across a 3:2 frame");
Assert.False(y.IsApplicable, "but not up or down");
Assert.Equal(Loc.L("Tooltips.Editor.NotApplicable.NoSlack"), y.NotApplicableReason);
var ratio = session.CropLockRatio(session.Project);
x.Value = 1;
var box = CropFrame.Of(session.Project.Camera.Crop);
Assert.Approximately(1, box.Right, 1e-9, "Crop X +1 puts the box at the right edge");
Assert.Approximately(ratio, box.Width / box.Height, 1e-9, "locked to the aspect");
Refresh(rows);
size.Value = 0.5;
box = CropFrame.Of(session.Project.Camera.Crop);
Assert.Approximately(0.5, box.Height, 1e-9, "half the largest box");
Assert.Approximately(1, box.Right, 1e-9, "still at the right edge");
Assert.Approximately(ratio, box.Width / box.Height, 1e-9);
Refresh(rows);
Assert.True(y.IsApplicable, "a smaller box can move up and down");
Assert.Equal(1.0, x.Value);
Assert.Equal("+1.00", x.DisplayValue);
Assert.Equal("50 %", size.DisplayValue);
y.Value = -1;
Assert.Approximately(0, CropFrame.Of(session.Project.Camera.Crop).Y, 1e-9, "Crop Y −1 is the top");
Refresh(rows);
size.Value = 0.02;
Assert.Approximately(CropFrame.MinimumShare, CropFrame.Of(session.Project.Camera.Crop).Height, 1e-9, "never below a tenth of the largest box");
Assert.True(session.Project.Camera is { OffsetX: 0, OffsetY: 0 });
}
}
[Test]
public async Task TheWholeFrameAtItsOwnProportionsIsNoCrop()
{
var (session, _) = Open(WithAspect("source", "png-sequence"));
await using (session)
{
var rows = CameraTab.FramingRows(session);
var size = Row<NumberRow>(rows, "Editor.Camera.CropSize");
size.Value = 0.6;
Assert.NotNull(session.Project.Camera.Crop);
Refresh(rows);
size.Value = 1;
Assert.Null(session.Project.Camera.Crop, "the largest box is the whole view: nothing is stored");
Assert.Equal(ProjectSettings.BaseVersion, session.Project.RequiredFormat);
}
}
[Test]
public async Task ALegacyCropPlacedByOffsetsIsBakedInAtItsFirstEdit()
{
var legacy = WithAspect("1:1");
legacy = legacy with { Camera = legacy.Camera with { OffsetX = 1 } };
var (session, _) = Open(legacy);
await using (session)
{
var rows = CameraTab.FramingRows(session);
var before = CameraTab.LockedBox(session, session.Project);
Assert.Approximately(1, before.Right, 1e-9, "the render puts the square at the right");
Assert.Equal(1.0, Row<NumberRow>(rows, "Editor.Camera.CropX").Value, "the rows show it where it renders");
Row<NumberRow>(rows, "Editor.Camera.CropSize").Value = 0.8;
var after = CropFrame.Of(session.Project.Camera.Crop);
Assert.True(session.Project.Camera is { OffsetX: 0, OffsetY: 0 }, "the offsets are baked into the box");
Assert.Approximately(1, after.Right, 1e-9);
Assert.Approximately(0.8 * before.Height, after.Height, 1e-9);
}
}
[Test]
public async Task TheRotationButtonsTurnAndTheRowShowsTheStoredAngle()
{
var (session, _) = Open(WithAspect("16:9"));
await using (session)
{
var rows = CameraTab.FramingRows(session);
var rotation = Row<IconActionsRow>(rows, "Editor.Camera.Rotation");
Assert.Equal("0°", rotation.Value);
Assert.SequenceEqual([Loc.L("Editor.Camera.RotateLeft"), Loc.L("Editor.Camera.RotateRight")], rotation.Actions.Select(a => a.Name));
Assert.SequenceEqual(["Icon.RotateLeft", "Icon.RotateRight"], rotation.Actions.Select(a => a.GlyphKey));
rotation.Actions[1].Command.Execute(null);
Refresh(rows);
Assert.Equal("90°", rotation.Value);
rotation.Actions[0].Command.Execute(null);
rotation.Actions[0].Command.Execute(null);
Refresh(rows);
Assert.Equal("270°", rotation.Value);
Assert.Equal("9:16", session.Project.Camera.Aspect.Manual, "three quarter turns: portrait");
}
}
[Test]
public async Task MirrorAndFlipAreSwitchesThatMoveTheCropWithThePicture()
{
var project = WithAspect("16:9");
project = project with { Camera = project.Camera with { Crop = [0.1, 0.2, 0.3, 0.4] } };
var (session, _) = Open(project);
await using (session)
{
var rows = CameraTab.FramingRows(session);
var mirror = Row<SwitchRow>(rows, "Editor.Camera.Mirror");
var flip = Row<SwitchRow>(rows, "Editor.Camera.Flip");
Assert.False(mirror.IsOn);
mirror.IsOn = true;
Assert.True(session.Project.Camera.Mirror);
Assert.SequenceEqual([0.6, 0.2, 0.3, 0.4], session.Project.Camera.Crop!, "x becomes 1 − x − w");
flip.IsOn = true;
Assert.True(session.Project.Camera.Flip);
Assert.SequenceEqual([0.6, 0.4, 0.3, 0.4], session.Project.Camera.Crop!, "y becomes 1 − y − h");
Assert.True(session.Undo());
Refresh(rows);
Assert.False(flip.IsOn, "the switch follows undo");
Assert.True(mirror.IsOn);
}
}
[Test]
public async Task ASwitchTheProjectDoesNotTakeSpringsBack()
{
var (session, source) = Open();
await using (session)
{
var mirror = Row<SwitchRow>(CameraTab.FramingRows(session), "Editor.Camera.Mirror");
source.IsReadOnly = true;
mirror.IsOn = true;
Assert.False(mirror.IsOn);
Assert.False(session.Project.Camera.Mirror);
}
}
[Test]
public async Task StraightenStoresTenthsOfADegreeAndShowsTheGrid()
{
var (session, _) = Open();
await using (session)
{
var straighten = Row<NumberRow>(CameraTab.FramingRows(session), "Editor.Camera.Straighten");
Assert.True(straighten.ShowsGrid, "using it shows the preview's grid");
Assert.Equal((-15.0, 15.0), (straighten.Minimum, straighten.Maximum));
straighten.Value = -1.23;
Assert.Equal(-1.2, session.Project.Camera.Straighten);
Assert.Equal("−1.2°", straighten.DisplayValue);
Assert.Equal(ProjectSettings.CurrentVersion, session.Project.RequiredFormat, "a straighten needs format 2");
straighten.Value = 0.02;
Assert.Equal(0.0, session.Project.Camera.Straighten);
Assert.False(double.IsNegative(session.Project.Camera.Straighten), "never −0");
Assert.Equal(ProjectSettings.BaseVersion, session.Project.RequiredFormat, "level again: format 1");
Assert.True(CameraTab.FramingRows(session).OfType<NumberRow>().Count(r => r.ShowsGrid) == 1, "only Straighten");
}
}
[Test]
public async Task TheLookIsWrittenOnlyWhenAFilterIsChosen()
{
var (session, _) = Open();
await using (session)
{
var before = session.Project.ToJson();
var rows = ExposureTab.LookRows(session);
Assert.True(rows[0] is GroupRow, "the group starts with its name");
var filter = Row<ChoiceRow>(rows, "Editor.Look.Filter");
var strength = Row<NumberRow>(rows, "Editor.Look.Strength");
Assert.Equal("none", filter.Selected?.Value);
Assert.False(strength.IsApplicable, "no filter: Strength is n/a");
Assert.Equal(Loc.L("Tooltips.Editor.NotApplicable.NoLook"), strength.NotApplicableReason);
Assert.SequenceEqual(["None", "Mono", "Sepia", "Warm", "Cool", "Vivid", "Muted", "Fade"], filter.Options.Select(o => o.Label));
filter.Selected = filter.Options.Single(o => Equals(o.Value, "sepia"));
Assert.Equal(new LookSettings { Filter = "sepia" }.Filter, session.Project.Look?.Filter);
Assert.Null(session.Project.Look!.Strength, "100 % is the default");
Assert.Equal(ProjectSettings.CurrentVersion, session.Project.RequiredFormat);
Refresh(rows);
Assert.True(strength.IsApplicable);
Assert.Equal(1.0, strength.Value);
strength.Value = 0.6;
Assert.Equal(0.6, session.Project.Look!.Strength);
Assert.Equal("60 %", strength.DisplayValue);
strength.Value = 1;
Assert.Null(session.Project.Look!.Strength);
// 0 % would be a look that changes nothing yet changes the text: None is the one way there.
Assert.Equal(ExposureTab.MinimumStrength, strength.Minimum);
Assert.Null(ExposureTab.WithLook(session.Project, "sepia", 0).Look, "the identity is written as no look");
Refresh(rows);
filter.Selected = filter.Options.Single(o => Equals(o.Value, "none"));
Assert.Null(session.Project.Look, "the identity is no look");
Assert.Equal(ProjectSettings.BaseVersion, session.Project.RequiredFormat);
Assert.Equal(before, session.Project.ToJson(), "and the text is the one before the look");
}
}
[Test]
public void ALookOfANewerChronosKeepsWhatItDoesNotKnow()
{
var extra = ProjectSettings.FromJson("""{"look":{"filter":"warm","strength":0.4,"grain":0.2}}""");
var changed = ExposureTab.WithLook(extra, "cool", 0.4);
Assert.Equal("cool", changed.Look?.Filter);
Assert.Contains("\"grain\":0.2", changed.ToJson().Replace(" ", string.Empty, StringComparison.Ordinal));
}
[Test]
public async Task EveryRowHasATooltipAndALabelOfAtMostThreeWordsInEnglishAndItalian()
{
var (session, _) = Open(WithAspect("9:16"));
await using (session)
{
var missing = new List<string>();
void OnMissing(string key) => missing.Add(key);
Loc.MissingKey += OnMissing;
try
{
foreach (var culture in new[] { "en", "it" })
{
Loc.SetCulture(CultureInfo.GetCultureInfo(culture));
var rows = CameraTab.FramingRows(session).Concat(ExposureTab.LookRows(session)).ToList();
var labels = new List<string>();
foreach (var row in rows)
{
labels.Add(row.Header);
Assert.False(string.IsNullOrWhiteSpace(row.ToolTip), $"{culture}: {row.Header} has a tooltip");
Assert.NotEqual(row.Header, row.ToolTip, $"{culture}: the tooltip explains, it does not repeat the label");
if (row is IconActionsRow icons)
{
foreach (var action in icons.Actions)
{
labels.Add(action.Name);
Assert.False(string.IsNullOrWhiteSpace(action.ToolTip), $"{culture}: {action.Name} has a tooltip");
}
}
if (row is ChoiceRow choices) labels.AddRange(choices.Options.Select(o => o.Label));
}
labels.AddRange(new[] { "Editor.Camera.ResetFraming", "Editor.Export.OutputSize" }.Select(k => Loc.L(k)));
foreach (var key in new[] { "Tooltips.Editor.Camera.ResetFraming", "Tooltips.Editor.Camera.ResetFramingNone", "Tooltips.Editor.Export.OutputSize" })
Assert.False(string.IsNullOrWhiteSpace(Loc.L(key)), key);
foreach (var label in labels)
Assert.LessOrEqual(label.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length, 3, $"{culture}: \"{label}\" is at most three words");
}
}
finally
{
Loc.MissingKey -= OnMissing;
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
Assert.Empty(missing);
}
}
}
@@ -206,6 +206,26 @@ public sealed class EditPathTests
"a crop of the whole frame is no crop");
}
[Test]
public void TheOrientationAndTheLookReadEdited()
{
var content = EditorFixture.Content(EditorFixture.Sunset);
var project = new ProjectSettings();
foreach (var (camera, what) in new[]
{
(new CameraSettings { Rotate = 90 }, "a quarter turn"), (new CameraSettings { Mirror = true }, "a mirror"),
(new CameraSettings { Flip = true }, "a flip"), (new CameraSettings { Straighten = -1.2 }, "a straighten"),
})
Assert.Equal(Loc.L("Editor.Step.Edited"), State(EditPath.Camera, content, project: project with { Camera = camera }).Text, what);
Assert.Equal(Loc.L("Editor.Step.Edited"), State(EditPath.Exposure, content, project: project with { Look = new LookSettings { Filter = "sepia" } }).Text,
"a look");
Assert.Equal(Loc.L("Common.Auto"), State(EditPath.Exposure, content, project: project with { Look = null }).Text, "no look");
Assert.Equal(Loc.L("Common.Auto"), State(EditPath.Exposure, content, project: project with { Look = new LookSettings { Filter = "sepia", Strength = 0 } }).Text,
"a look at 0 % changes no pixel");
Assert.Equal(Loc.L("Common.Auto"), State(EditPath.Exposure, content, project: project with { Look = new LookSettings { Filter = "grain" } }).Text,
"a filter this Chronos does not know renders as none");
}
[Test]
public void AMissingValueOfASettingThatDoesNotApplyAsksNothing()
{
@@ -3,6 +3,7 @@ using System.Text.Json;
using Chronos.App.Editor;
using Chronos.Core.Advice;
using Chronos.Core.Analysis;
using Chronos.Core.Imaging.Geometry;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Protocol;
@@ -416,4 +417,196 @@ public sealed class EditorSessionTests
Assert.Equal(2, session.Project.HeroFrame);
}
}
// ---- Orientation and framing (owner review 1, R5/R6) ----
/// <summary>A project with a manual aspect (the advice never decides it) and a crop.</summary>
private static ProjectSettings WithAspect(string aspect, double[]? crop = null)
{
var project = new ProjectSettings();
return project with { Camera = project.Camera with { Aspect = project.Camera.Aspect.WithManual(aspect), Crop = crop } };
}
[Test]
public async Task EachOrientationPressIsOneUndoStepAndTurnsTheCropWithThePicture()
{
var (session, _) = Open(WithAspect("16:9", [0.1, 0.2, 0.4, 0.3]));
await using (session)
{
Assert.True(session.Orient(OrientationOp.RotateRight));
Assert.Equal(90, session.Project.Camera.Rotate);
Assert.Equal("9:16", session.Project.Camera.Aspect.Manual, "the proportions turn with the picture");
Assert.SequenceEqual([0.5, 0.1, 0.3, 0.4], session.Project.Camera.Crop!, "the crop keeps the content");
Assert.True(session.Orient(OrientationOp.Mirror));
Assert.True(session.Project.Camera.Mirror);
Assert.SequenceEqual([0.2, 0.1, 0.3, 0.4], session.Project.Camera.Crop!, "mirror maps x to 1 − x − w");
Assert.True(session.Undo());
Assert.False(session.Project.Camera.Mirror, "one press, one step");
Assert.Equal(90, session.Project.Camera.Rotate);
Assert.True(session.Undo());
Assert.Equal(0, session.Project.Camera.Rotate);
Assert.SequenceEqual([0.1, 0.2, 0.4, 0.3], session.Project.Camera.Crop!);
}
}
[Test]
public async Task OptimiseAfterATurnAdvisesTheAspectOfTheTurnedView()
{
var (session, _) = Open();
await using (session)
{
session.Edit(p => Advisor.Apply(p, session.Advice));
var advised = EditorSettings.Aspect.Effective(session.Project, null);
Assert.True(advised is "16:9" or "9:16", "the analysis advises a video aspect");
Assert.True(session.Orient(OrientationOp.RotateRight));
var turned = EditorSettings.Aspect.Effective(session.Project, null);
Assert.NotEqual(advised, turned, "the turn transposes the advised aspect");
session.Optimise(AdvisorSection.Camera);
Assert.Equal(turned, EditorSettings.Aspect.Effective(session.Project, null), "the advice is worked out on the turned view");
}
}
[Test]
public async Task ATurnSeenThroughAMirrorTurnsThePictureTheWayTheUserPressed()
{
var (session, _) = Open(WithAspect("16:9"));
await using (session)
{
session.Orient(OrientationOp.RotateRight);
Assert.Equal(90, session.Project.Camera.Rotate, "clockwise as stored");
session.Orient(OrientationOp.Mirror);
session.Orient(OrientationOp.RotateRight);
Assert.Equal(0, session.Project.Camera.Rotate, "through one mirror, a clockwise press is an anticlockwise stored turn");
session.Orient(OrientationOp.Flip);
session.Orient(OrientationOp.RotateRight);
Assert.Equal(90, session.Project.Camera.Rotate, "mirror and flip together are a half turn: the sense is kept");
Assert.True(session.Project.Camera is { Mirror: true, Flip: true });
}
}
[Test]
public async Task FourRightTurnsGiveBackTheSameCanonicalText()
{
var keyed = WithAspect("16:9", [0.1, 0.2, 0.4, 0.3]);
keyed = keyed with { Camera = keyed.Camera with { Keyframes = [new CameraKey(4, 0.3, 0.6, 1.5, 2)], Straighten = 1.5 } };
var (session, _) = Open(keyed);
await using (session)
{
var before = session.Project.ToJson();
for (var i = 0; i < 4; i++) Assert.True(session.Orient(OrientationOp.RotateRight));
Assert.Equal(before, session.Project.ToJson());
Assert.Equal(ProjectSettings.CurrentVersion, session.Project.RequiredFormat, "a straighten needs format 2");
}
}
[Test]
public async Task AnAspectChangeRefitsALockedCropAroundItsCentre()
{
var (session, _) = Open(WithAspect("16:9"));
await using (session)
{
var ratio = session.CropLockRatio(session.Project);
var box = CropFrame.Clamp(new RectD(0.2, 0.2, 0.5, 0.5 / ratio), ratio);
Assert.True(session.Edit(p => p with { Camera = p.Camera with { Crop = CropFrame.ToCrop(box) } }));
Assert.True(session.Edit(p => EditorSettings.Aspect.WithManual(p, "9:16")));
var refitted = CropFrame.Of(session.Project.Camera.Crop);
Assert.Approximately(session.CropLockRatio(session.Project), refitted.Width / refitted.Height, 1e-9, "locked to the new proportions");
Assert.Approximately(box.CenterX, refitted.CenterX, 1e-9, "the same centre");
Assert.Approximately(box.CenterY, refitted.CenterY, 1e-9);
Assert.Approximately(box.Width * box.Height, refitted.Width * refitted.Height, 1e-9, "the same area");
Assert.True(session.Undo());
Assert.SequenceEqual(CropFrame.ToCrop(box)!, session.Project.Camera.Crop!, "the aspect and the refit are one step");
}
}
[Test]
public async Task ALegacyCropPlacedByOffsetsIsLeftForTheRenderToFit()
{
var legacy = WithAspect("16:9", [0, 0, 1, 0.8]);
legacy = legacy with { Camera = legacy.Camera with { OffsetX = 0.5 } };
var (session, _) = Open(legacy);
await using (session)
{
Assert.True(session.Edit(p => EditorSettings.Aspect.WithManual(p, "1:1")));
Assert.SequenceEqual([0.0, 0, 1, 0.8], session.Project.Camera.Crop!);
Assert.Equal(0.5, session.Project.Camera.OffsetX);
}
}
[Test]
public async Task ResetFramingClearsTheCropAndTheOrientationAndKeepsTheKeyframesOnTheirContent()
{
var framed = WithAspect("9:16", [0.2, 0, 0.3, 1]);
var key = new CameraKey(3, 0.4, 0.5, 2, 0);
framed = framed with
{
Camera = framed.Camera with { OffsetX = 0.2, OffsetY = -0.1, Rotate = 270, Mirror = true, Flip = true, Straighten = -3.5, Keyframes = [key] },
Look = new LookSettings { Filter = "sepia" },
};
var (session, _) = Open(framed);
await using (session)
{
Assert.True(EditorSession.HasFraming(session.Project.Camera));
Assert.True(session.ResetFraming());
var camera = session.Project.Camera;
Assert.Null(camera.Crop);
Assert.True(camera is { OffsetX: 0, OffsetY: 0, Rotate: 0, Mirror: false, Flip: false, Straighten: 0 });
var back = OrientationEdit.Apply(OrientationEdit.Apply(OrientationEdit.Apply(OrientationEdit.Apply(OrientationEdit.Apply(framed,
OrientationOp.Flip), OrientationOp.Mirror), OrientationOp.RotateLeft), OrientationOp.RotateLeft), OrientationOp.RotateLeft);
Assert.SequenceEqual(back.Camera.Keyframes, camera.Keyframes, "keyframes stay on the content they framed");
Assert.Equal(1, camera.Keyframes.Count);
Assert.Equal("16:9", camera.Aspect.Manual, "the aspect turns back with the picture");
Assert.Equal("sepia", session.Project.Look?.Filter, "nor the look");
Assert.False(EditorSession.HasFraming(camera));
Assert.False(session.ResetFraming(), "nothing left to clear");
Assert.True(session.Undo());
Assert.Equal(270, session.Project.Camera.Rotate, "one step");
}
}
[Test]
public void ResetFramingTurnsAKeyframeBackWithThePicture()
{
var turned = new ProjectSettings();
turned = turned with { Camera = turned.Camera with { Rotate = 90, Aspect = turned.Camera.Aspect.WithManual("9:16"), Keyframes = [new CameraKey(2, 0.2, 0.3, 1.5, 0)] } };
var reset = EditorSession.WithoutFraming(turned);
var (x, y) = OrientationEdit.MapPoint(0.2, 0.3, OrientationOp.RotateLeft);
Assert.True(reset.Camera.Keyframes[0] is { CenterX: var cx, CenterY: var cy } && cx == x && cy == y, "moved as the picture turns back");
Assert.True((x, y) != (0.2, 0.3));
Assert.Equal("16:9", reset.Camera.Aspect.Manual);
var again = OrientationEdit.Apply(reset, OrientationOp.RotateRight);
Assert.True(again.Camera is { Rotate: 90 } && again.Camera.Keyframes[0] is { CenterX: 0.2, CenterY: 0.3 }, "turning again puts it where it was");
Assert.Equal("9:16", again.Camera.Aspect.Manual);
}
[Test]
public async Task ASequencePresetKeepsTheOrientationAndTheLook()
{
var turned = new ProjectSettings() with { Look = new LookSettings { Filter = "mono", Strength = 0.5 } };
turned = turned with { Camera = turned.Camera with { Rotate = 90, Mirror = true, Straighten = 2 } };
var (session, _) = Open(turned);
await using (session)
{
Assert.True(session.ApplyPreset(session.Presets.First(p => p.Id == "social-vertical")));
Assert.True(session.Project.Camera is { Rotate: 90, Mirror: true, Straighten: 2 });
Assert.Equal("mono", session.Project.Look?.Filter);
Assert.Equal(0.5, session.Project.Look?.Strength);
}
}
[Test]
public async Task AReadOnlyProjectIsNeitherTurnedNorReset()
{
var (session, source) = Open(WithAspect("16:9", [0.1, 0.2, 0.4, 0.3]));
await using (session)
{
source.IsReadOnly = true;
Assert.False(session.Orient(OrientationOp.RotateLeft));
Assert.False(session.ResetFraming());
Assert.Equal(0, session.Project.Camera.Rotate);
Assert.NotNull(session.Project.Camera.Crop);
}
}
}
@@ -4,6 +4,7 @@ using System.IO;
using System.Net.Http;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
@@ -19,6 +20,7 @@ using Chronos.Core.Export;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Testing;
using Chronos.Ui.Controls;
using Chronos.Ui.Theming;
@@ -424,6 +426,129 @@ public sealed class EditorSmokeTests
}
});
/// <summary>
/// The Camera step edits the crop box on the preview (owner review 1, R5): its mask is on by default and shows the box the
/// render fits, a drag on the picture is one undo step, a run of key presses another, the box is locked to the output
/// proportions with the offsets at 0, and a quarter turn shows the turned view frame.
/// </summary>
[Test]
public Task TheCameraStepEditsTheCropBoxOnThePreview() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
app.Window.Width = 1200;
app.Window.Height = 788;
var id = await app.Sample.FillEditorAsync();
app.Shell.OpenSequence(id);
await app.Shell.Sequence.OpenAsync(id);
var editor = Assert.NotNull(app.Shell.Sequence.Editor);
try
{
editor.SelectedTab = editor.Exposure;
Assert.False(editor.ShowCropMask, "the other steps keep their mask off");
Assert.False(editor.CropEditable);
Assert.Equal(Loc.L("Tooltips.Editor.Preview.View"), editor.PreviewToolTip);
editor.SelectedTab = editor.Tabs.OfType<CameraTab>().Single();
Assert.True(editor.ShowCropMask, "on by default on the Camera step");
Assert.True(editor.CropEditable);
Assert.Equal(Loc.L("Tooltips.Editor.Preview.CropEdit"), editor.PreviewToolTip);
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
await SettleAsync(app.Window);
var (width, height) = (editor.Session.Content.SourceWidth, editor.Session.Content.SourceHeight);
RenderGeometry Geometry() => RenderGeometry.Create(editor.Session.Project.Camera, ExportResolver.Resolve(editor.Session.Project.Export), width, height);
static Rect RectOf(Chronos.Core.Imaging.Geometry.RectD r) => new(r.X, r.Y, r.Width, r.Height);
Assert.Equal(RectOf(Geometry().EditableCrop), editor.EditCrop, "the mask is the box the render fits");
Assert.Equal(editor.EditCrop, editor.CropRect);
var viewport = Find<PreviewViewport>(app.Window).Single(v => v.IsVisible);
Assert.True(viewport.CropEditable);
Assert.Equal(editor.EditCrop, viewport.EditCrop);
Assert.Equal(editor.CropLockRatio, viewport.CropLockRatio);
Assert.Equal(editor.PreviewToolTip, viewport.ToolTip);
// The bottom-right handle dragged in: one undo step, the box locked, the offsets at 0.
Point At(double nx, double ny)
{
var (x, y) = viewport.View.ToView(nx * viewport.ImageSize.Width, ny * viewport.ImageSize.Height);
return new Point(x, y);
}
var before = editor.Session.Project.Camera;
var box = viewport.EditCrop;
viewport.Press(At(box.Right, box.Bottom));
viewport.DragTo(At(box.X + box.Width * 0.7, box.Y + box.Height * 0.7), aboutCentre: false);
Assert.Same(before, editor.Session.Project.Camera, "nothing changes while dragging");
viewport.EndDrag(commit: true);
var cropped = editor.Session.Project.Camera;
var crop = Assert.NotNull(cropped.Crop);
Assert.Approximately(0, cropped.OffsetX, 0);
Assert.Approximately(0, cropped.OffsetY, 0);
Assert.Approximately(editor.CropLockRatio, crop[2] / crop[3], 1e-9, "locked to the proportions");
Assert.Less(crop[3], box.Height);
Assert.Approximately(box.X, crop[0], 1e-9, "anchored at the opposite corner");
Assert.Equal(new Rect(crop[0], crop[1], crop[2], crop[3]), editor.EditCrop);
// Two nudges are one more step.
Assert.True(viewport.IsCropSelected, "the press took the box");
Assert.True(viewport.Nudge(Key.Right, ModifierKeys.None));
Assert.True(viewport.Nudge(Key.Down, ModifierKeys.None));
editor.Session.EndEditRun();
var nudged = Assert.NotNull(editor.Session.Project.Camera.Crop);
Assert.Approximately(crop[0] + 0.01, nudged[0], 1e-9);
Assert.Approximately(crop[1] + 0.01, nudged[1], 1e-9);
editor.UndoCommand.Execute(null);
Assert.SequenceEqual(crop, editor.Session.Project.Camera.Crop!, "one undo takes both nudges back");
editor.UndoCommand.Execute(null);
Assert.SequenceEqual(before.Crop ?? [], editor.Session.Project.Camera.Crop ?? [], "and one more the drag");
editor.RedoCommand.Execute(null);
Assert.SequenceEqual(crop, editor.Session.Project.Camera.Crop!);
// The straighten grid shows while the slider is used, on the Camera step only.
editor.IsStraightening = true;
await SettleAsync(app.Window);
Assert.True(viewport.ShowGrid);
editor.IsStraightening = false;
Assert.False(viewport.ShowGrid);
// A quarter turn: the box waits for the turned picture, then maps onto it.
var ratio = editor.CropLockRatio;
editor.Session.Edit(p => p with { Camera = p.Camera with { Rotate = 90, Crop = null } });
Assert.Equal(ratio, editor.CropLockRatio, "the box of the picture on screen until the turned one comes");
Assert.False(editor.CropEditable, "and it cannot be dragged meanwhile: it would land in the turned frame");
Assert.False(editor.CommitCropCommand.CanExecute(editor.EditCrop));
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
Assert.True(editor.CropEditable, "the turned picture is on screen");
var picture = (System.Windows.Media.Imaging.BitmapSource)editor.PreviewImage!;
Assert.Less(picture.PixelWidth, picture.PixelHeight, "the landscape source shows turned");
Assert.Equal(Geometry().LockRatio, editor.CropLockRatio);
Assert.Equal(RectOf(Geometry().EditableCrop), editor.EditCrop);
editor.UndoCommand.Execute(null);
await editor.Session.FlushAsync();
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
// Read-only and newer-format projects are drawn, never edited.
var content = EditorFixture.Content(EditorFixture.Sunset);
foreach (var (source, reason) in new[]
{
(new FakeSequenceSource(EditorFixture.Sunset, content) { IsReadOnly = true }, "read-only"),
(new FakeSequenceSource(EditorFixture.Sunset, content with { Project = content.Project with { Version = ProjectSettings.CurrentVersion + 1 } }), "newer format"),
})
{
var locked = new EditorViewModel(app.Shell, new EditorSession(source, source.Content, []), [], EncoderHost.Client);
await using (locked)
{
locked.SelectedTab = locked.Tabs.OfType<CameraTab>().Single();
Assert.True(locked.ShowCropMask, reason);
Assert.False(locked.CropEditable, reason);
Assert.False(locked.CommitCropCommand.CanExecute(new Rect(0.1, 0.1, 0.5, 0.5)), reason);
Assert.Equal(Loc.L("Tooltips.Editor.Preview.View"), locked.PreviewToolTip);
}
}
}
finally
{
await app.Shell.Sequence.CloseAsync();
}
});
/// <summary>
/// At the 1200 px minimum beside the 200 px rail (owner review 1, R1), a server sequence's job keeps its Cancel whole in every
/// language, also read-only (the longest place line): the title and the summary give way first (BRIEF §11.5, cancel always stays).
@@ -8,7 +8,7 @@ using Chronos.Testing;
namespace Chronos.App.Tests.Editor;
/// <summary>Composed texts of the editor (the conflict prompt among them), crop margins and the waveform monitor.</summary>
/// <summary>Composed texts of the editor (the conflict prompt among them, the Camera step's values) and the waveform monitor.</summary>
public sealed class EditorTextTests
{
static EditorTextTests() => _ = EditorFixture.Sunset;
@@ -38,22 +38,15 @@ public sealed class EditorTextTests
}
[Test]
public void CropMarginsKeepAtLeastATenthOfTheFrame()
public void TheCameraRowsShowAnglesAndPlacementsAsTheMockupDoes()
{
Assert.SequenceEqual([0.0, 0, 0, 0], CropMargins.Of(null));
var crop = CropMargins.With(null, CropSide.Left, 0.2);
Assert.SequenceEqual([0.2, 0, 0.8, 1], crop!);
crop = CropMargins.With(crop, CropSide.Top, 0.6);
Assert.Approximately(CropMargins.MaxMargin, crop![1], 1e-12, "no margin beyond the maximum");
crop = CropMargins.With(crop, CropSide.Left, 0.45);
crop = CropMargins.With(crop, CropSide.Right, 0.45);
Assert.Approximately(CropMargins.MinSize, crop![2], 1e-12, "opposite margins leave a tenth of the width");
var margins = CropMargins.Of(crop);
Assert.Approximately(0.45, margins[0], 1e-12);
Assert.Approximately(0.45, margins[1], 1e-12);
Assert.Null(CropMargins.With(CropMargins.With(CropMargins.With(crop, CropSide.Left, 0), CropSide.Right, 0), CropSide.Top, 0),
"no margin left is the whole frame");
Assert.SequenceEqual([0.0, 0, 0, 0], CropMargins.Of([double.NaN, 0, 1, 1]), "an invalid crop is ignored, as the render does");
Assert.Equal("−1.2°", CameraTab.Degrees(-1.2), "a minus sign, one decimal");
Assert.Equal("15.0°", CameraTab.Degrees(15));
Assert.Equal("0°", CameraTab.Degrees(0), "level reads as a whole number");
Assert.Equal("0°", CameraTab.Degrees(-0.0), "never a negative zero");
Assert.Equal("+0.40", EditorText.Placement(0.4));
Assert.Equal("−0.60", EditorText.Placement(-0.6));
Assert.Equal("Centred", EditorText.Placement(0));
}
[Test]
@@ -1,6 +1,7 @@
using Chronos.App.Editor;
using Chronos.Core.Advice;
using Chronos.Core.Export;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Core.Video;
using Chronos.Core.Video.Managed;
@@ -90,4 +91,57 @@ public sealed class ExportPlannerTests
Assert.Equal("Custom", plan.PresetName);
Assert.Equal(48, plan.Setup.Encoder.Settings.Width);
}
/// <summary>An H.264 encoder that takes at most <paramref name="maxWidth"/>×<paramref name="maxHeight"/> (either way round).</summary>
private sealed class H264Provider(int maxWidth, int maxHeight) : IVideoEncoderProvider
{
public string Name => "h264";
public IReadOnlyList<EncoderCapability> Capabilities { get; } = [new(VideoCodec.H264, "Test H.264", false, maxWidth, maxHeight, false)];
public bool CanEncode(EncodeSettings settings) => settings.Codec == VideoCodec.H264;
public IVideoEncoderSession Open(EncodeSettings settings) => throw new NotSupportedException("Planning never encodes.");
}
private static ProjectSettings FourKAt(string aspect)
{
var project = new ProjectSettings();
return project with
{
Camera = project.Camera with { Aspect = project.Camera.Aspect.WithManual(aspect) },
Export = project.Export with { Preset = project.Export.Preset.WithManual("4k-h264") },
};
}
[Test]
public void TheChosenProportionsWinAndThePresetKeepsItsName()
{
var planner = new ExportPlanner(Content, [new H264Provider(4096, 2304)], EncoderHost.Client);
var plan = planner.Plan(FourKAt("9:16"))!;
Assert.Equal((2160, 3840), plan.OutputSize, "4K at 9:16");
Assert.Equal((2160, 3840), plan.EncodedSize, "the encoder takes it turned");
Assert.False(plan.IsCapped);
Assert.Equal("2160 × 3840", ExportTab.OutputSizeOf(plan));
Assert.Equal(Loc.L("Tooltips.Editor.Export.OutputSize"), ExportTab.OutputSizeToolTipOf(plan));
Assert.Equal(Loc.L("Export.Preset.4kH264"), plan.PresetName, "the preset is not made Custom");
Assert.False(plan.Export.IsCustom);
Assert.Equal((3840, 2160), (plan.Export.Width, plan.Export.Height), "Width × Height stay the preset's box");
var workload = plan.Setup.Workload();
Assert.Equal((2160, 3840), (workload.Width, workload.Height), "the estimate is of the adapted size");
var source = planner.Plan(FourKAt("source"))!;
Assert.Equal((3840, 2160), source.OutputSize, "source keeps the preset's ratio");
}
[Test]
public void AnOutputTheEncoderShrinksIsMarkedCapped()
{
var plan = new ExportPlanner(Content, [new H264Provider(1920, 1080)], EncoderHost.Client).Plan(FourKAt("9:16"))!;
Assert.Equal((2160, 3840), plan.OutputSize);
Assert.Equal((1080, 1920), plan.EncodedSize);
Assert.True(plan.IsCapped);
Assert.Equal(Loc.L("Editor.Export.Capped", "1080 × 1920"), ExportTab.OutputSizeOf(plan));
Assert.Equal(Loc.L("Tooltips.Editor.Export.OutputCapped", "1080 × 1920"), ExportTab.OutputSizeToolTipOf(plan), "the largest size it takes, turned");
}
}
@@ -1,6 +1,12 @@
using System.IO;
using Chronos.App.Editor;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Render.Diagnostics;
using Chronos.Core.Video;
using Chronos.Core.Video.Managed;
using Chronos.Testing;
namespace Chronos.App.Tests.Editor;
@@ -71,6 +77,11 @@ public sealed class PreviewRendererTests
using var last = await renderer.RenderAsync(new PreviewRequest(EditorFixture.Sunset.Count - 1, new ProjectSettings(), 96, PreviewFraming.Source, true),
null, CancellationToken.None);
Assert.Empty(last!.Vectors);
// The flow sees the frames as the render's does, before the look (owner review 1, phase 4): the same vectors with Vivid.
var vivid = new ProjectSettings { Look = new LookSettings { Filter = "vivid" } };
using var looked = await renderer.RenderAsync(new PreviewRequest(10, vivid, 96, PreviewFraming.Source, Vectors: true), null, CancellationToken.None);
Assert.SequenceEqual(frame.Vectors, looked!.Vectors);
}
[Test]
@@ -183,6 +194,133 @@ public sealed class PreviewRendererTests
Assert.True(waveform.Density.Any(d => d > 0));
}
[Test]
public async Task OutputFramingFollowsChosenPortraitProportions()
{
// The chosen proportions win (owner review 1, R5): the square preset's box takes a 9:16 picture.
var (renderer, _) = Create();
var project = new ProjectSettings();
project = project with
{
Export = project.Export with { Preset = project.Export.Preset.WithManual("square-1440") },
Camera = project.Camera with { Aspect = project.Camera.Aspect.WithManual("9:16") },
};
using var output = await renderer.RenderAsync(new PreviewRequest(0, project, 80, PreviewFraming.Output), null, CancellationToken.None);
Assert.Equal(45, output!.Corrected.Width, "810 × 1440 at the preview's long edge");
Assert.Equal(80, output.Corrected.Height);
using var source = await renderer.RenderAsync(new PreviewRequest(0, project, 96, PreviewFraming.Source), null, CancellationToken.None);
Assert.Equal(96, source!.Corrected.Width, "the whole frame");
Assert.Approximately(9.0 / 16 * 64 / 96, source.LockRatio, 1e-12, "the box's ratio in normalised units");
Assert.Approximately(1, source.EditCrop.Height, 1e-9, "the largest 9:16 box of the 3:2 frame");
Assert.Approximately(source.LockRatio, source.EditCrop.Width, 1e-9);
Assert.Approximately(source.EditCrop.Width, source.Crop.Width, 0.02, "the output's footprint is the box");
Assert.Approximately(source.EditCrop.X, source.Crop.X, 0.02);
}
[Test]
public async Task SourceFramingShowsTheTurnedViewFrame()
{
var (renderer, _) = Create();
var plain = new ProjectSettings();
var turned = plain with { Camera = plain.Camera with { Rotate = 90 } };
using var frame = await renderer.RenderAsync(new PreviewRequest(5, plain, 96, PreviewFraming.Source), null, CancellationToken.None);
using var view = await renderer.RenderAsync(new PreviewRequest(5, turned, 96, PreviewFraming.Source), null, CancellationToken.None);
Assert.Equal((96, 64), (frame!.Corrected.Width, frame.Corrected.Height));
Assert.Equal((64, 96), (view!.Corrected.Width, view.Corrected.Height), "a quarter turn swaps the size");
Assert.Equal((64, 96), (view.Original.Width, view.Original.Height));
Assert.Equal((64, 96), view.ViewSize);
Assert.Equal((96, 64), frame.ViewSize);
// Turned a quarter clockwise, exactly: the view's (x, y) is the frame's (y, H − 1 − x).
for (var c = 0; c < 3; c++)
{
var a = frame.Original.Plane(c);
var b = view.Original.Plane(c);
for (var y = 0; y < 96; y += 7)
{
for (var x = 0; x < 64; x += 5) Assert.Approximately(a[(63 - x) * 96 + y], b[y * 64 + x], 1e-6, $"channel {c} at ({x}, {y})");
}
}
}
[Test]
public async Task TheMaskIsTheEditableCropOfTheViewFrame()
{
var (renderer, _) = Create();
var project = new ProjectSettings();
project = project with
{
Camera = project.Camera with
{
Aspect = project.Camera.Aspect.WithManual("1:1"),
Crop = [0.1, 0.05, 0.6, 0.8],
OffsetX = 0.5,
Rotate = 270,
Straighten = 4,
},
};
using var frame = await renderer.RenderAsync(new PreviewRequest(2, project, 96, PreviewFraming.Source), null, CancellationToken.None);
var geometry = RenderGeometry.Create(project.Camera, ExportResolver.Resolve(project.Export), EditorFixture.Sunset.Options.Width, EditorFixture.Sunset.Options.Height);
Assert.Equal(geometry.EditableCrop, frame!.EditCrop, "the box the render fits, the same on every frame");
Assert.Equal(geometry.LockRatio, frame.LockRatio);
Assert.Approximately(frame.EditCrop.Width / frame.EditCrop.Height * frame.Corrected.Width / frame.Corrected.Height, 1, 0.03, "square on the picture");
Assert.Approximately(frame.EditCrop.X, frame.Crop.X, 0.02, "without stabilisation or pose, the output's footprint is the box");
Assert.Approximately(frame.EditCrop.Width, frame.Crop.Width, 0.02);
Assert.Approximately(frame.EditCrop.Height, frame.Crop.Height, 0.02);
Assert.Equal((64, 96), (frame.Corrected.Width, frame.Corrected.Height));
}
[Test]
public async Task ALookChangesOnlyTheCorrectedPicture()
{
var (renderer, _) = Create();
var plain = Deflickered() with { Exposure = new ProjectSettings().Exposure with { HighlightKnee = null } };
var look = new LookSettings { Filter = "sepia", Strength = 0.6 };
foreach (var framing in new[] { PreviewFraming.Output, PreviewFraming.Source })
{
using var before = await renderer.RenderAsync(new PreviewRequest(4, plain, 64, framing), null, CancellationToken.None);
using var after = await renderer.RenderAsync(new PreviewRequest(4, plain with { Look = look }, 64, framing), null, CancellationToken.None);
Assert.True(before!.Original.Data.SequenceEqual(after!.Original.Data), $"{framing}: the original side has no look");
Assert.False(before.Corrected.Data.SequenceEqual(after.Corrected.Data), $"{framing}: the corrected side has it");
FrameFinish.Apply(before.Corrected, look, null);
Assert.True(before.Corrected.Data.SequenceEqual(after.Corrected.Data), $"{framing}: the render's finish");
}
}
[Test]
public async Task OutputFramingMatchesTheRenderTurnedStraightenedAndWithALook()
{
var project = new ProjectSettings();
project = project with
{
Exposure = project.Exposure with { HighlightKnee = null },
Export = project.Export with { Preset = project.Export.Preset.WithManual("png-sequence") },
Camera = project.Camera with { Rotate = 90, Straighten = 3 },
Look = new LookSettings { Filter = "sepia", Strength = 0.6 },
};
var (renderer, _) = Create();
using var preview = await renderer.RenderAsync(new PreviewRequest(0, project, 96, PreviewFraming.Output), null, CancellationToken.None);
Assert.Equal((64, 96), (preview!.Corrected.Width, preview.Corrected.Height), "the turned frame at the source's size");
var capture = new CapturingEncoder();
var pixels = new SyntheticFrameSource(EditorFixture.Sunset);
var folder = Path.Combine(Path.GetTempPath(), "chronos-preview-" + Guid.NewGuid().ToString("N"));
try
{
var input = new RenderInput { Source = pixels, Frames = pixels.Metadata(), Project = project };
await new RenderPipeline([capture, new ManagedEncoderProvider()]).RenderAsync(input, new RenderTarget(ExportResolver.Resolve(project.Export), folder));
}
finally
{
if (Directory.Exists(folder)) Directory.Delete(folder, recursive: true);
}
var rendered = capture.Frames[0];
Assert.Equal((preview.Corrected.Width, preview.Corrected.Height), (rendered.Width, rendered.Height));
Assert.Greater(Psnr(rendered, preview.Corrected), 40, "the preview is the render's frame");
foreach (var frame in capture.Frames) frame.Dispose();
}
/// <summary>A sunset project as the advisor leaves it: deflicker, holy grail, white balance and stabilisation on.</summary>
private static ProjectSettings Sunset()
{
@@ -207,6 +345,49 @@ public sealed class PreviewRendererTests
return Math.Log2(sum / n);
}
/// <summary>Peak signal-to-noise ratio of the 8-bit sRGB encodings.</summary>
private 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>A PNG-sequence encoder that keeps a copy of every frame instead of writing it.</summary>
private sealed class CapturingEncoder : IVideoEncoderProvider
{
private static readonly EncoderCapability Capability = new(VideoCodec.PngSequence, "Capture", false, 8192, 8192, true);
public string Name => "capture";
public IReadOnlyList<EncoderCapability> Capabilities { get; } = [Capability];
public List<ImageBuffer> Frames { get; } = [];
public bool CanEncode(EncodeSettings settings) => settings.Codec == VideoCodec.PngSequence;
public IVideoEncoderSession Open(EncodeSettings settings) => new Session(this);
private sealed class Session(CapturingEncoder owner) : IVideoEncoderSession
{
public string EncoderName => Capability.Name;
public bool IsHardware => false;
public void WriteFrame(ImageBuffer frame, long duration90k) => owner.Frames.Add(frame.Clone());
public void Complete()
{
}
public void Dispose()
{
}
}
}
/// <summary>Standard deviation of the frame-to-frame differences (flicker, not the slow ramp).</summary>
private static double Spread(List<double> values)
{
@@ -117,7 +117,7 @@ public sealed class ProjectHistoryTests
[Test]
public void SettingsOfANewerChronosAdoptedDropTheStepsInsteadOfMergingThem()
{
var newer = ProjectSettings.FromJson("""{ "version": 2, "exposure": { "exposureOffsetEv": 1.5 }, "grade": { "look": "film" } }""", allowNewer: true);
var newer = ProjectSettings.FromJson("""{ "version": 3, "exposure": { "exposureOffsetEv": 1.5 }, "grade": { "look": "film" } }""", allowNewer: true);
// The workspace's merge throws as ProjectMerge does where both sides changed and one is a newer Chronos's.
foreach (var merge in new Func<ProjectSettings, ProjectSettings, ProjectSettings, ProjectSettings>?[]
{ null, (basis, ours, theirs) => ProjectMerge.MergeWithConflicts(basis, ours, theirs).Merged })
@@ -65,6 +65,30 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
}
}
/// <summary>
/// Owner review 1, phase 4: an older server (format 1) stores whatever settings it is sent and then fails every render of
/// them, so a turn or a look is never sent to it; an edit of the base format still is.
/// </summary>
[Test]
public async Task SettingsAnOlderServerCannotReadAreNotSent()
{
var (source, api, _) = Open(serverFormat: ProjectSettings.BaseVersion);
await using (source)
{
var content = await source.LoadAsync(context.Cancellation);
var turned = content.Project with { Camera = content.Project.Camera with { Rotate = 90 } };
var refused = await Assert.ThrowsAsync<EditorException>(() => source.SaveProjectAsync(turned, content.Project, context.Cancellation));
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), refused.Message);
var look = content.Project with { Look = new LookSettings { Filter = "sepia" } };
await Assert.ThrowsAsync<EditorException>(() => source.SaveProjectAsync(look, content.Project, context.Cancellation));
Assert.Empty(api.Edits);
var brighter = content.Project with { Exposure = content.Project.Exposure with { ExposureOffsetEv = 0.5 } };
await source.SaveProjectAsync(brighter, content.Project, context.Cancellation);
Assert.Count(1, api.Edits);
}
}
[Test]
public async Task SavesSendTheVersionTheyWereMadeFrom()
{
@@ -574,12 +598,12 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
}
private (RemoteSequenceSource Source, FakeRemoteSequenceApi Api, RemoteSequence Remote) Open(int frames = 6, int cached = int.MaxValue,
bool readOnly = false) =>
Open(EditorFixture.Sequence(frames), cached, readOnly);
bool readOnly = false, int serverFormat = ProjectSettings.CurrentVersion) =>
Open(EditorFixture.Sequence(frames), cached, readOnly, serverFormat);
/// <summary>A server sequence whose first <paramref name="cached"/> proxies are on this PC (synthetic JPEGs).</summary>
private (RemoteSequenceSource Source, FakeRemoteSequenceApi Api, RemoteSequence Remote) Open(SyntheticSequence sunset, int cached = int.MaxValue,
bool readOnly = false)
bool readOnly = false, int serverFormat = ProjectSettings.CurrentVersion)
{
var folder = context.CreateTempDirectory("proxies");
var sequence = new Sequence
@@ -603,7 +627,7 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
}
var remote = new RemoteSequence(Server, sequence, frames, files);
var api = new FakeRemoteSequenceApi(sequence, [.. frames.Select(f => f.Id)]) { SettingsJson = new ProjectSettings().ToJson() };
return (new RemoteSequenceSource(remote, api, DecoderFactory.CreateClient(null), readOnly), api, remote);
return (new RemoteSequenceSource(remote, api, DecoderFactory.CreateClient(null), readOnly, serverFormat), api, remote);
}
/// <summary>Someone on the server sets the exposure offset to 0.3 and moves the framing.</summary>
@@ -0,0 +1,81 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Chronos.App.Editor;
using Chronos.App.Shell;
using Chronos.Core.Localization;
using Chronos.Testing;
namespace Chronos.App.Tests.Editor;
/// <summary>
/// The Camera step's Straighten slider reports its use to the editor (owner review 1, R6): the NumberRow template of
/// <c>Editor/EditorPanels.xaml</c> turns <see cref="SliderActivity"/> on for the row that shows the grid, and binds its
/// <see cref="SliderActivity.IsActiveProperty"/> one way to the source <c>Editor.IsStraightening</c> of the step. Built off
/// screen on the test dispatcher (no window): the slider's activity is set as <see cref="SliderActivity"/> sets it when the
/// slider takes the focus or the mouse capture.
/// </summary>
[WindowsOnly]
[Serial]
public sealed class StraightenGridBindingTests
{
[Test]
public async Task UsingTheStraightenSliderTellsTheEditor()
{
var content = EditorFixture.Content(EditorFixture.Sunset);
var session = new EditorSession(new FakeSequenceSource(EditorFixture.Sunset, content), content, [], TimeSpan.FromMilliseconds(20));
await using (session)
{
var rows = CameraTab.FramingRows(session);
Windows.WpfApplication.Dispatcher.Invoke(() =>
{
AppResources.Merge(Application.Current);
var step = new FakeStep();
var items = new ItemsControl { ItemsSource = rows, DataContext = step };
items.Resources.MergedDictionaries.Add(new ResourceDictionary
{
Source = new Uri("pack://application:,,,/Chronos;component/Editor/EditorPanels.xaml", UriKind.Absolute),
});
var host = new Border { Child = items };
host.Measure(new Size(320, 2000));
host.Arrange(new Rect(0, 0, 320, 2000));
host.UpdateLayout();
var sliders = Descendants<Slider>(host).ToList();
Assert.Equal(rows.OfType<NumberRow>().Count(), sliders.Count);
var straighten = Assert.NotNull(sliders.SingleOrDefault(s => s.DataContext is NumberRow { ShowsGrid: true }));
Assert.Equal(Loc.L("Editor.Camera.Straighten"), ((NumberRow)straighten.DataContext).Header);
Assert.True(SliderActivity.GetTracks(straighten), "the Straighten slider is tracked");
Assert.False(sliders.Where(s => !ReferenceEquals(s, straighten)).Any(SliderActivity.GetTracks), "no other slider is");
Assert.False(step.Editor.IsStraightening);
straighten.SetCurrentValue(SliderActivity.IsActiveProperty, true);
Assert.True(step.Editor.IsStraightening, "focused or dragged: the editor shows the grid");
straighten.SetCurrentValue(SliderActivity.IsActiveProperty, false);
Assert.False(step.Editor.IsStraightening, "let go: the grid goes");
});
}
}
private static IEnumerable<T> Descendants<T>(DependencyObject root)
where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
{
var child = VisualTreeHelper.GetChild(root, i);
if (child is T match) yield return match;
foreach (var nested in Descendants<T>(child)) yield return nested;
}
}
/// <summary>The step's data context as the template reads it: <c>Editor.IsStraightening</c>.</summary>
public sealed class FakeStep
{
public FakeEditor Editor { get; } = new();
}
public sealed class FakeEditor
{
public bool IsStraightening { get; set; }
}
}
@@ -0,0 +1,52 @@
using System.Text.Json;
using Chronos.App.Library;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.App.Tests.Library;
/// <summary>
/// The Library's Render on a remote card is held to the editor's rule (owner review 1, phase 4): settings or proportions a
/// server of an older settings format would render otherwise are not posted to it.
/// </summary>
public sealed class LibraryRenderGateTests
{
private static ExportSettings Uhd() => new() { Preset = new Auto<string>().WithManual("4k-h264") };
[Test]
public void AnOlderServerIsNotSentARenderItWouldGetWrong()
{
var plain = new ProjectSettings { Export = Uhd() };
var turned = plain with { Camera = new CameraSettings { Rotate = 90 } };
var portrait = plain with { Camera = new CameraSettings { Aspect = new Auto<string>().WithManual("9:16") } };
var newer = Loc.L("Tooltips.Server.NeedsNewerServer");
Assert.Null(LibraryActions.ServerCannotRender(plain, plain.Export, 6000, 4000, ProjectSettings.BaseVersion));
Assert.Equal(newer, LibraryActions.ServerCannotRender(turned, turned.Export, 6000, 4000, ProjectSettings.BaseVersion));
Assert.Equal(newer, LibraryActions.ServerCannotRender(portrait, portrait.Export, 6000, 4000, ProjectSettings.BaseVersion), "the proportions win only on a newer server");
Assert.Null(LibraryActions.ServerCannotRender(turned, turned.Export, 6000, 4000, ProjectSettings.CurrentVersion));
Assert.Null(LibraryActions.ServerCannotRender(portrait, portrait.Export, 6000, 4000, ProjectSettings.CurrentVersion));
}
/// <summary>
/// The remote card's render is sized on the project just read (the card's copy may be older: here 16:9 against 9:16) and
/// does not embed it, so the server renders the sequence's settings as they are when a node takes the job.
/// </summary>
[Test]
public void ARemoteRenderIsSizedOnTheProjectReadAndRendersTheServersSettings()
{
var project = new ProjectSettings { Export = Uhd(), Camera = new CameraSettings { Aspect = new Auto<string>().WithManual("9:16") } };
var card = new Sequence { Id = Guid.NewGuid(), ArchiveId = Guid.NewGuid(), Folder = "harbour", SettingsJson = new ProjectSettings { Export = Uhd() }.ToJson() };
var request = LibraryActions.ServerRender(card, project, project.Export, 6000, 4000);
Assert.Equal(card.Id, request.Target.Single());
var parameters = JsonSerializer.Deserialize(request.ParametersJson!, ProtocolJson.Default.RenderJobParameters)!;
Assert.Equal((2160, 3840), (parameters.Width, parameters.Height));
Assert.Null(parameters.SettingsJson);
Assert.Equal(2, parameters.RequiredSettingsFormat);
}
}
@@ -1,3 +1,4 @@
using Chronos.Core.Imaging.Geometry;
using Chronos.Testing;
using Chronos.Ui.Visuals;
@@ -69,4 +70,75 @@ public sealed class ViewportMathTests
Assert.Approximately(Math.Round(10.4 * 1.5), t.OffsetX * 1.5, 1e-9);
Assert.Approximately(Math.Round(-3.1 * 1.5), t.OffsetY * 1.5, 1e-9);
}
[Test]
public void ACropPressTakesAHandleWithinTheGripThenTheInsideAtEveryZoom()
{
// A 400×300 image with the box [0.25, 0.2, 0.5, 0.6]: the grip is 6 view units whatever the zoom.
var crop = new RectD(0.25, 0.2, 0.5, 0.6);
foreach (var view in new[] { new ViewTransform(0.25, 40, 10), new ViewTransform(1, -30, 5), new ViewTransform(4, -500, -300) })
{
CropHandle Hit(double nx, double ny, double dx, double dy)
{
var (x, y) = view.ToView(nx * 400, ny * 300);
return ViewportMath.HitCrop(view, 400, 300, crop, x + dx, y + dy, 6);
}
var zoom = $"scale {view.Scale}";
Assert.Equal(CropHandle.TopLeft, Hit(0.25, 0.2, -5, 4), zoom);
Assert.Equal(CropHandle.BottomRight, Hit(0.75, 0.8, 6, -6), zoom);
Assert.Equal(CropHandle.Top, Hit(0.5, 0.2, 3, -2), zoom);
Assert.Equal(CropHandle.Left, Hit(0.25, 0.5, 2, 0), zoom);
Assert.Equal(CropHandle.Inside, Hit(0.25, 0.5, 0, 7), "beside a handle, inside the box: a move");
Assert.Equal(CropHandle.None, Hit(0.25, 0.5, -7, 0), "outside the box and the grip: a pan");
Assert.Equal(CropHandle.Inside, Hit(0.5, 0.5, 0, 0), zoom);
Assert.Equal(CropHandle.None, Hit(0.1, 0.1, 0, 0), zoom);
}
Assert.Equal(CropHandle.None, ViewportMath.HitCrop(new ViewTransform(0, 0, 0), 400, 300, crop, 0, 0, 6), "no view yet");
}
[Test]
public void TheNearestHandleWinsOnATinyBox()
{
// At 1/4 zoom a box of 40×30 image pixels is 10×7.5 view units: every handle is within the grip of the centre.
var view = new ViewTransform(0.25, 0, 0);
var crop = new RectD(0.45, 0.45, 0.1, 0.1);
var (x, y) = view.ToView(0.55 * 400, 0.55 * 300);
Assert.Equal(CropHandle.BottomRight, ViewportMath.HitCrop(view, 400, 300, crop, x - 1, y - 1, 6));
var (cx, cy) = view.ToView(0.5 * 400, 0.45 * 300);
Assert.Equal(CropHandle.Top, ViewportMath.HitCrop(view, 400, 300, crop, cx, cy + 0.5, 6));
}
[Test]
public void TheHandlesSitOnTheCornersAndTheEdgeMidpoints()
{
var crop = new RectD(0.1, 0.2, 0.4, 0.6);
Assert.Count(8, ViewportMath.CropHandles);
Assert.Within(0.1, 0.2, ViewportMath.HandleAt(crop, CropHandle.TopLeft).X, ViewportMath.HandleAt(crop, CropHandle.TopLeft).Y, 1e-12);
Assert.Within(0.3, 0.8, ViewportMath.HandleAt(crop, CropHandle.Bottom).X, ViewportMath.HandleAt(crop, CropHandle.Bottom).Y, 1e-12);
Assert.Within(0.5, 0.5, ViewportMath.HandleAt(crop, CropHandle.Right).X, ViewportMath.HandleAt(crop, CropHandle.Right).Y, 1e-12);
Assert.Within(0.3, 0.5, ViewportMath.HandleAt(crop, CropHandle.Inside).X, ViewportMath.HandleAt(crop, CropHandle.Inside).Y, 1e-12);
}
[Test]
public void PlusAndMinusResizeAboutTheCentreLockedAndWithinTheLimits()
{
const double ratio = 0.5;
var largest = CropFrame.Largest(ratio);
var box = CropFrame.FromRows(0.5, 0, 0, ratio);
var grown = ViewportMath.ResizeCrop(box, 0.02, ratio);
Assert.Approximately(box.Height + 0.02 * largest.Height, grown.Height, 1e-12);
Assert.Approximately(ratio, grown.Width / grown.Height, 1e-12);
Assert.Within(box.CenterX, box.CenterY, grown.CenterX, grown.CenterY, 1e-12);
var smallest = CropFrame.FromRows(CropFrame.MinimumShare, 0, 0, ratio);
Assert.Approximately(smallest.Height, ViewportMath.ResizeCrop(smallest, -0.02, ratio).Height, 1e-12, "not below the minimum");
var whole = ViewportMath.ResizeCrop(largest, 0.02, ratio);
Assert.Approximately(largest.Height, whole.Height, 1e-12, "not beyond the largest box");
// At an edge the grown box moves back inside the view.
var corner = CropFrame.FromRows(0.9, 1, 1, ratio);
var pushed = ViewportMath.ResizeCrop(corner, 0.08, ratio);
Assert.LessOrEqual(pushed.Right, 1 + 1e-12);
Assert.LessOrEqual(pushed.Bottom, 1 + 1e-12);
}
}
@@ -278,6 +278,230 @@ public sealed class VisualsSmokeTests
}
});
[Test]
public void ACropDragMovesThenResizesLockedAndIsReportedOncePerDrag() => WpfHost.Run(() =>
{
var preview = CropPreview(new Rect(0.3, 0.2, 0.3, 0.6), ratio: 0.5);
Render(preview, 800, 450);
var edits = new List<CropEditEventArgs>();
preview.CropEditCompleted += (_, e) => edits.Add(e);
// Inside the box: a move; only the overlay follows the pointer until the button is released.
preview.Press(At(preview, 0.45, 0.5));
Assert.Equal(PreviewViewport.DragMode.MoveCrop, preview.Dragging);
preview.DragTo(At(preview, 0.55, 0.55), aboutCentre: false);
Assert.Empty(edits, "nothing is reported while dragging");
Assert.Approximately(0.4, preview.ShownCrop.X, 1e-6, "the overlay follows");
Assert.Approximately(0.3, preview.EditCrop.X, 0, "the box itself waits for the release");
preview.EndDrag(commit: true);
var moved = Assert.Contains(edits, _ => true).Crop;
Assert.Within(0.4, 0.25, moved.X, moved.Y, 1e-6);
Assert.False(edits[0].IsNudge);
Assert.Equal(moved, preview.EditCrop, "the finished box is the edited one");
// The bottom-right handle, dragged far outside: anchored at the top-left corner, locked, clamped to the view.
preview.Press(At(preview, 0.7, 0.85));
Assert.Equal(PreviewViewport.DragMode.ResizeCrop, preview.Dragging);
preview.DragTo(At(preview, 1.5, 1.5), aboutCentre: false);
preview.EndDrag(commit: true);
Assert.Count(2, edits);
var resized = edits[1].Crop;
Assert.Within(0.4, 0.25, resized.X, resized.Y, 1e-9, "anchored at the opposite corner");
Assert.Approximately(0.5, resized.Width / resized.Height, 1e-9, "the ratio stays locked");
Assert.Approximately(1, resized.Bottom, 1e-9, "as large as the view lets it be");
Assert.LessOrEqual(resized.Right, 1);
// Alt resizes about the centre.
preview.Press(At(preview, resized.Right, resized.Bottom));
preview.DragTo(At(preview, resized.Right - 0.05, resized.Bottom - 0.1), aboutCentre: true);
preview.EndDrag(commit: true);
var centred = edits[2].Crop;
Assert.Within(resized.X + resized.Width / 2, resized.Y + resized.Height / 2, centred.X + centred.Width / 2, centred.Y + centred.Height / 2, 1e-9);
Assert.Approximately(0.5, centred.Width / centred.Height, 1e-9);
// A press released where it started, and a pan outside the box, report nothing.
preview.Press(At(preview, centred.X + centred.Width / 2, centred.Y + centred.Height / 2));
preview.EndDrag(commit: true);
preview.Press(At(preview, 0.05, 0.05));
Assert.Equal(PreviewViewport.DragMode.Pan, preview.Dragging);
preview.DragTo(At(preview, 0.1, 0.1), aboutCentre: false);
preview.EndDrag(commit: true);
Assert.Count(3, edits);
});
[Test]
public void APressTakesAHandleThenTheDividerThenTheBoxThenPansAtEveryZoom() => WpfHost.Run(() =>
{
var preview = CropPreview(new Rect(0.4, 0.4, 0.2, 0.2), ratio: 1);
preview.OriginalSource = Bitmap(2000, 1500);
preview.IsCompareEnabled = true;
preview.WipePosition = 0.5;
Render(preview, 800, 450);
var surface = Assert.NotNull(FindChild<PreviewSurface>(preview));
foreach (var zoom in new double?[] { null, 1, 2 })
{
if (zoom is { } z) preview.Zoom = z;
var label = zoom is null ? "fit" : $"zoom {zoom}";
// The image column under the divider, and a box of 0.06 × 0.12 around it (corner handles well away).
var divider = surface.ActualWidth / 2;
var nx = preview.View.ToImage(divider, 0).X / 2000;
var y = At(preview, 0, 0.5).Y;
PreviewViewport.DragMode Take(Rect box, double x)
{
preview.EditCrop = box;
preview.Press(new Point(x, y));
var mode = preview.Dragging;
preview.EndDrag(commit: false);
return mode;
}
Assert.Equal(PreviewViewport.DragMode.ResizeCrop, Take(new Rect(nx, 0.44, 0.06, 0.12), divider), $"{label}: a handle on the divider");
Assert.Equal(PreviewViewport.DragMode.Wipe, Take(new Rect(nx - 0.03, 0.44, 0.06, 0.12), divider), $"{label}: the divider inside the box");
Assert.Equal(PreviewViewport.DragMode.MoveCrop, Take(new Rect(nx - 0.03, 0.44, 0.06, 0.12), At(preview, nx + 0.012, 0.5).X), $"{label}: inside");
Assert.Equal(PreviewViewport.DragMode.Pan, Take(new Rect(nx - 0.03, 0.44, 0.06, 0.12), At(preview, nx + 0.06, 0.5).X), $"{label}: outside");
}
// A box that spans the view both ways (no crop) cannot move: zoomed in, a press inside pans; the middle button pans
// anywhere, inside a box that can move too.
preview.IsCompareEnabled = false;
preview.Zoom = 2;
preview.EditCrop = new Rect(0, 0, 1, 1);
preview.Press(At(preview, 0.5, 0.5));
Assert.Equal(PreviewViewport.DragMode.Pan, preview.Dragging, "zoomed, the whole view: pan");
preview.EndDrag(commit: false);
preview.EditCrop = new Rect(0.4, 0.4, 0.2, 0.2);
preview.PressPan(At(preview, 0.5, 0.5));
Assert.Equal(PreviewViewport.DragMode.Pan, preview.Dragging, "middle button inside a box");
preview.EndDrag(commit: false);
// Not editable: no handle and no box to take, the divider and pan only.
preview.CropEditable = false;
preview.EditCrop = new Rect(0.4, 0.4, 0.2, 0.2);
preview.Press(At(preview, 0.4, 0.4));
Assert.Equal(PreviewViewport.DragMode.Pan, preview.Dragging);
preview.EndDrag(commit: false);
});
[Test]
public void EscCancelsADragAndTheKeysNudgeTheBoxOnceItIsTaken() => WpfHost.Run(() =>
{
var preview = CropPreview(new Rect(0.3, 0.2, 0.3, 0.6), ratio: 0.5);
var window = OffScreen(preview, 800, 450);
try
{
var edits = new List<CropEditEventArgs>();
preview.CropEditCompleted += (_, e) => edits.Add(e);
Assert.False(Press(preview, Key.Right), "until the box is taken, the arrows step frames");
// Esc cancels a drag: the box stays, nothing is reported.
preview.Press(At(preview, 0.45, 0.5));
preview.DragTo(At(preview, 0.6, 0.6), aboutCentre: false);
Assert.True(Press(preview, Key.Escape));
Assert.Equal(PreviewViewport.DragMode.None, preview.Dragging);
Assert.Equal(new Rect(0.3, 0.2, 0.3, 0.6), preview.EditCrop);
Assert.Equal(new Rect(0.3, 0.2, 0.3, 0.6), preview.ShownCrop);
Assert.Empty(edits);
// The press took the box: the arrows move it 1 %, + and − resize it about its centre, each reported as a nudge.
Assert.True(preview.IsCropSelected);
Assert.True(Press(preview, Key.Right));
Assert.Count(1, edits);
Assert.True(edits[0].IsNudge);
Assert.Approximately(0.31, preview.EditCrop.X, 1e-9);
Assert.True(preview.Nudge(Key.Down, ModifierKeys.Shift), "Shift moves 10 %");
Assert.Approximately(0.3, preview.EditCrop.Y, 1e-9);
var before = preview.EditCrop;
Assert.True(Press(preview, Key.OemMinus));
var shrunk = preview.EditCrop;
Assert.Less(shrunk.Height, before.Height);
Assert.Approximately(0.5, shrunk.Width / shrunk.Height, 1e-9);
Assert.Within(before.X + before.Width / 2, before.Y + before.Height / 2, shrunk.X + shrunk.Width / 2, shrunk.Y + shrunk.Height / 2, 1e-9);
Assert.Count(3, edits);
// Esc gives the arrows back; Enter takes the box from the keyboard.
Assert.True(Press(preview, Key.Escape));
Assert.False(preview.IsCropSelected);
Assert.False(Press(preview, Key.Left));
Assert.True(Press(preview, Key.Enter));
Assert.True(Press(preview, Key.Left));
Assert.Count(4, edits);
// A box that can no longer change gives the keys back.
preview.CropEditable = false;
Assert.False(preview.IsCropSelected);
Assert.False(Press(preview, Key.Right));
}
finally
{
window.Close();
}
});
[Test]
public void TheEditableBoxDrawsItsHandlesAndScreenReadersReadIt() => WpfHost.Run(() =>
{
var card = ColorOf("Brush.Card");
var preview = CropPreview(new Rect(0.25, 0.2, 0.5, 0.6), ratio: 0.5 / 0.6);
Render(preview, 800, 450);
var surface = Assert.NotNull(FindChild<PreviewSurface>(preview));
Color HandlePixel(double nx, double ny)
{
var bitmap = Render(preview, 800, 450);
var (x, y) = preview.View.ToView(nx * 2000, ny * 1500);
var p = surface.TranslatePoint(new Point(x, y), preview);
return PixelAt(bitmap, (int)Math.Round(p.X), (int)Math.Round(p.Y));
}
foreach (var (nx, ny) in new[] { (0.25, 0.2), (0.75, 0.8), (0.5, 0.2), (0.75, 0.5) })
Assert.True(Near(HandlePixel(nx, ny), card, 8), $"a Card handle at ({nx}, {ny})");
preview.CropMaskMode = CropMaskMode.ShowResult;
Assert.True(Near(HandlePixel(0.25, 0.8), card, 8), "the handles draw in either mask mode");
var peer = UIElementAutomationPeer.CreatePeerForElement(preview);
var value = Assert.NotNull(peer.GetPattern(PatternInterface.Value) as System.Windows.Automation.Provider.IValueProvider);
Assert.Equal(Loc.L("Editor.Preview.CropValue", Loc.L("Common.Percent", 25), Loc.L("Common.Percent", 20), Loc.L("Common.Percent", 60)), value.Value);
Assert.True(value.IsReadOnly);
preview.CropMaskMode = CropMaskMode.ShowLoss;
preview.CropEditable = false;
Assert.False(Near(HandlePixel(0.25, 0.2), card, 8), "no handles while the box cannot change");
Assert.Null(peer.GetPattern(PatternInterface.Value), "and no value to read");
});
private static PreviewViewport CropPreview(Rect crop, double ratio) => new()
{
Source = Bitmap(2000, 1500),
ShowCropMask = true,
CropEditable = true,
CropLockRatio = ratio,
EditCrop = crop,
};
/// <summary>The surface point of the normalised image point (<paramref name="nx"/>, <paramref name="ny"/>) of a 2000 × 1500 preview.</summary>
private static Point At(PreviewViewport preview, double nx, double ny)
{
var (x, y) = preview.View.ToView(nx * 2000, ny * 1500);
return new Point(x, y);
}
/// <summary>A window off screen around <paramref name="element"/>, so it has a presentation source for key events.</summary>
private static Window OffScreen(FrameworkElement element, double width, double height)
{
var window = new Window
{
Content = new Border { Child = element },
Width = width,
Height = height,
WindowStyle = WindowStyle.None,
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
ShowActivated = false,
ShowInTaskbar = false,
};
window.Show();
window.UpdateLayout();
return window;
}
private static IEnumerable<(string Name, FrameworkElement Element, double Width, double Height)> Samples()
{
var n = 120_000;
@@ -342,6 +566,15 @@ public sealed class VisualsSmokeTests
ShowCropMask = true,
CropRect = new Rect(0.1, 0.1, 0.8, 0.8),
}, 800, 450);
yield return ("PreviewViewport.CropEdit", new PreviewViewport
{
Source = Bitmap(2000, 1500),
ShowCropMask = true,
CropEditable = true,
CropLockRatio = 0.5,
EditCrop = new Rect(0.3, 0.2, 0.3, 0.6),
ShowGrid = true,
}, 800, 450);
yield return ("SequenceCard", SampleCard(), 236, 208);
yield return ("SegmentedControl", SampleSegments(), 120, 32);
@@ -438,8 +671,13 @@ public sealed class VisualsSmokeTests
return false;
}
private static void Press(UIElement target, Key key) =>
target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(target)!, 0, key) { RoutedEvent = Keyboard.KeyDownEvent });
/// <summary>Raises a key press on <paramref name="target"/>; true when something handled it.</summary>
private static bool Press(UIElement target, Key key)
{
var args = new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(target)!, 0, key) { RoutedEvent = Keyboard.KeyDownEvent };
target.RaiseEvent(args);
return args.Handled;
}
private static RenderTargetBitmap Render(FrameworkElement element, double width, double height)
{
@@ -244,6 +244,71 @@ public sealed class ServerHomeTests(TestContext context)
}
}
[Test]
public async Task AServerThatReadsAnOlderFormatIsNotSentSettingsItCannotRead()
{
Assert.Null(ServerJobs.NeedsNewerServer(ProjectSettings.BaseVersion, ProjectSettings.BaseVersion));
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), ServerJobs.NeedsNewerServer(2, ProjectSettings.BaseVersion));
// A server that says no format reads the base one; a session-less home too.
Assert.Equal(ProjectSettings.BaseVersion, Chronos.App.Server.SyncHost.SettingsFormatOf(new ServerInfo("Studio NAS", "1.3.0", 1, [], null, [], new ServerLimits(0, 0))));
Assert.Equal(ProjectSettings.BaseVersion, Chronos.App.Server.SyncHost.SettingsFormatOf(null));
Assert.Equal(ProjectSettings.CurrentVersion, Chronos.App.Server.SyncHost.SettingsFormatOf(
new ServerInfo("Studio NAS", "1.4.0", 1, [], null, [], new ServerLimits(0, 0), SettingsFormat: ProjectSettings.CurrentVersion)));
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
var server = new FakeServer(bed) { SettingsFormat = ProjectSettings.BaseVersion };
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome(() => null, () => null));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
var ui = new RecordingUi();
await using (session)
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
{
await menu.RefreshAsync();
// A change of the base format goes to the older server as before.
Assert.True(session.SetHero(2));
Assert.Null(menu.PushBlockedReason);
Assert.True(menu.SyncCommand.CanExecute(null));
// A turn needs format 2: Sync is disabled saying why, and a render of it is held.
Assert.True(session.Edit(p => p with { Camera = p.Camera with { Rotate = 90 } }));
Assert.True(await session.FlushAsync());
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), menu.PushBlockedReason);
Assert.Equal(menu.PushBlockedReason, menu.SyncToolTip);
Assert.False(menu.SyncCommand.CanExecute(null));
Assert.False(await menu.ReadyToRenderAsync(), "the server cannot read it");
Assert.Equal((Loc.L("Editor.Workspace.RenderHeld"), true), (ui.Toasts[^1].Title, ui.Toasts[^1].IsError));
var before = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId;
await menu.SyncAsync();
Assert.Equal(before, host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
// Saved as a version with the turn, then turned back: the working state is of the base format, but the version
// waiting to be sent is not. Sync stays disabled, and the workspace itself never sends it (Send first, Delete,
// Resolve reach the host without the menu's gate), saying why.
await host.SaveVersionAsync(projectId, null, bed.Ct);
Assert.True(session.Edit(p => p with { Camera = p.Camera with { Rotate = 0 } }));
Assert.True(await session.FlushAsync());
await menu.RefreshAsync();
Assert.Equal(ProjectSettings.BaseVersion, session.Project.WrittenFormat);
Assert.Equal(2, menu.Status!.UnpushedFormat);
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), menu.PushBlockedReason);
Assert.False(menu.SyncCommand.CanExecute(null));
var refused = await Assert.ThrowsAsync<WorkspaceSyncException>(() => host.SyncAsync(projectId, bed.Ct));
Assert.True(refused.HomeReadsOlderFormat);
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), WorkspaceText.Failure(refused, server: true));
Assert.Equal(before, host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
// A server of this format takes it.
server.SettingsFormat = ProjectSettings.CurrentVersion;
Assert.Null(menu.PushBlockedReason);
Assert.True(menu.SyncCommand.CanExecute(null));
}
}
/// <summary>The home a workspace project of the test sequence names on <see cref="Server"/>.</summary>
private static BundleHome ServerHome(WorkspaceTestBed bed) => new(BundleHome.ServerKind, bed.SequenceId, null, Server);
@@ -276,6 +341,9 @@ public sealed class ServerHomeTests(TestContext context)
public HashSet<Guid> Deleted { get; } = [];
/// <summary>The settings format the server reads, as its info says.</summary>
public int SettingsFormat { get; set; } = ProjectSettings.CurrentVersion;
public async Task<HomeSequence> SequenceAsync(CancellationToken cancellationToken)
{
var sequence = await Reach(() => Inner.SequenceAsync(cancellationToken));
@@ -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()
{
@@ -1,3 +1,4 @@
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Video;
using Chronos.Core.Windows.MediaFoundation;
@@ -143,6 +144,62 @@ public sealed class MediaFoundationEncoderTests(TestContext context)
Assert.Equal(60, report.FrameCount);
}
/// <summary>
/// Owner review 1, phase 4: 4K at 9:16 is 2160×3840. Each H.264 encoder of this machine is asked for portrait UHD and
/// its landscape twin: none takes one and refuses the other, so the announced limits are a long edge × short edge
/// (<see cref="EncoderSelector.Takes"/>), and portrait UHD is announced wherever landscape UHD is. Encoders that refuse
/// both (Microsoft's DX12 encoder on some GPUs) are left to the provider, which then opens the next one.
/// </summary>
[Test]
[WindowsOnly]
[Timeout(180_000)]
public void PortraitUhdH264EncodesWhereLandscapeDoes()
{
RequireMediaFoundation();
var provider = new MediaFoundationEncoderProvider();
var h264 = provider.Capabilities.Where(c => c.Codec == VideoCodec.H264).ToList();
if (h264.Count == 0) TestContext.Skip("No H.264 encoder on this machine");
foreach (var capability in h264)
{
var (portrait, landscape) = (Accepts(capability, 2160, 3840), Accepts(capability, 3840, 2160));
Assert.Equal(landscape, portrait, $"{capability.Name} takes portrait UHD as it takes landscape UHD");
Assert.True(EncoderSelector.Takes(capability, 2160, 3840), $"{capability.Name} announces portrait UHD");
if (!capability.Hardware) Assert.False(EncoderSelector.Takes(capability, 2400, 3840), $"{capability.Name}: the short edge is over the software limit");
}
var request = Settings(Path.Combine(context.CreateTempDirectory(), "portrait.mp4"), VideoCodec.H264, 8);
Assert.Equal(provider.CanEncode(request with { Width = 3840, Height = 2160 }), provider.CanEncode(request with { Width = 2160, Height = 3840 }));
bool Accepts(EncoderCapability capability, int width, int height)
{
var settings = Settings(Path.Combine(context.CreateTempDirectory(), $"{width}x{height}.mp4"), VideoCodec.H264, 8) with
{
Width = width,
Height = height,
EncoderName = capability.Name,
PreferHardware = capability.Hardware,
BitRate = 20_000_000,
};
try
{
using (var session = provider.Open(settings))
{
using var frame = new ImageBuffer(width, height);
for (var c = 0; c < 3; c++) frame.Plane(c).Fill(0.25f);
for (var f = 0; f < 3; f++) session.WriteFrame(frame, Frame30);
session.Complete();
}
var report = Mp4Inspector.Inspect(settings.OutputPath);
context.Log($"{capability.Name} {width}×{height}: {report}");
return report.IsValid && (report.Width, report.Height) == (width, height);
}
catch (NotSupportedException ex)
{
context.Log($"{capability.Name} {width}×{height}: refused ({ex.InnerException?.Message ?? ex.Message})");
return false;
}
}
}
[Test]
[WindowsOnly]
[Timeout(60_000)]
@@ -39,6 +39,23 @@ public sealed class AnalysisJobTests(TestContext context)
Longitude = 12.3,
});
[Test]
public async Task LightAnalysisAdvisesTheAspectOfTheTurnedView()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering());
var turned = new ProjectSettings { Camera = new CameraSettings { Rotate = 90 } };
await fx.Db.Sequences.EditAsync(sequence.Id, new SequenceEdit { SettingsJson = turned.ToJson() }, null, fx.Ct);
await fx.StartEngineAsync();
var job = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id], sequence.DisplayTitle));
await fx.WaitForAsync(job.Id, JobState.Done);
var project = ProjectSettings.FromJson(await File.ReadAllTextAsync(fx.Folder(sequence).ProjectPath, fx.Ct));
Assert.Equal(90, project.Camera.Rotate);
Assert.Equal("9:16", project.Camera.Aspect.AutoValue);
}
[Test]
public async Task LightAnalysisFillsAutoValuesAndKeepsManualOnes()
{
@@ -0,0 +1,54 @@
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Processing;
using Chronos.Testing;
namespace Chronos.Data.Tests.Processing;
/// <summary>
/// The project of a sequence as the engine reads and writes it (owner review 1, phase 4): a format-1 project stays format 1
/// through every edit that uses nothing newer, a transform raises it to 2 and its removal brings it back, and settings of
/// a newer Chronos are refused saying so in the user's language.
/// </summary>
[Category("processing")]
public sealed class ProjectStoreTests(TestContext context)
{
[Test]
public async Task AnEditNeverRaisesTheFormatOfAProjectThatUsesNothingNewer()
{
await using var fixture = await ProcessingFixture.CreateAsync(context);
var sequence = await fixture.AddAsync(SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 64, Height = 48, FrameCount = 4 }));
var store = new ProjectStore(fixture.Db, new SequenceWriter(new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) }));
async Task<int> StoredFormatAsync()
{
var row = (await fixture.Db.Sequences.GetAsync(sequence.Id, fixture.Ct))!;
var file = await File.ReadAllTextAsync(fixture.Folder(sequence).ProjectPath, fixture.Ct);
Assert.Equal(row.SettingsJson, file, "the index and project.json hold the same text");
return ProjectContent.FormatOf(file);
}
Assert.True(await store.UpdateAsync(fixture.Archive.Paths, sequence, p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.5 } }, fixture.Ct));
Assert.Equal(ProjectSettings.BaseVersion, await StoredFormatAsync());
// A read project of the base format is never stamped higher, even when it says the highest this Chronos reads.
Assert.True(await store.UpdateAsync(fixture.Archive.Paths, sequence, p => p with { Version = ProjectSettings.CurrentVersion, HeroFrame = 2 }, fixture.Ct));
Assert.Equal(ProjectSettings.BaseVersion, await StoredFormatAsync());
Assert.True(await store.UpdateAsync(fixture.Archive.Paths, sequence, p => p with { Camera = p.Camera with { Rotate = 90 } }, fixture.Ct));
Assert.Equal(2, await StoredFormatAsync());
Assert.True(await store.UpdateAsync(fixture.Archive.Paths, sequence, p => p with { Camera = p.Camera with { Rotate = 0 } }, fixture.Ct));
Assert.Equal(ProjectSettings.BaseVersion, await StoredFormatAsync());
Assert.False(await store.UpdateAsync(fixture.Archive.Paths, sequence, p => p with { Version = ProjectSettings.BaseVersion }, fixture.Ct), "nothing changed");
}
[Test]
public void SettingsOfANewerChronosAreRefusedSayingSo()
{
var refused = Assert.Throws<InvalidDataException>(() => ProjectStore.Parse("""{"version":3,"camera":{"rotate":90}}"""));
Assert.Equal(Loc.L("Errors.Render.NewerSettings"), refused.Message);
Assert.Equal(90, ProjectStore.Parse("""{"version":2,"camera":{"rotate":90}}""").Camera.Rotate);
// Text that is not a project keeps its own reason.
Assert.NotEqual(Loc.L("Errors.Render.NewerSettings"), Assert.Throws<InvalidDataException>(() => ProjectStore.Parse("[1]")).Message);
}
}
@@ -599,6 +599,105 @@ public sealed class RenderJobTests(TestContext context)
Assert.SequenceEqual(["mjpeg", "gif"], ProcessingJobs.Split(posted, 96, 64).Select(p => p.Codec));
}
/// <summary>
/// Owner review 1, phase 4: a render job carries the output size its settings give it (the chosen proportions win over a
/// fixed-size preset, a quarter turn swaps a source-sized output) and the settings format its render needs, so a render
/// node is matched to what it will write; a job posted by an older client gets both from the server (<see cref="ProcessingJobs.Split"/>).
/// </summary>
[Test]
public void RenderJobsCarryTheSizeAndFormatOfTheirSettings()
{
var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "Synthetic", Title = "Roof" };
var uhd = new ExportSettings { Preset = new Auto<string>().WithManual("4k-h264") };
var portrait = new ProjectSettings { Camera = new CameraSettings { Aspect = new Auto<string>().WithManual("9:16") } };
static Chronos.Protocol.RenderJobParameters Read(Chronos.Data.Archiving.Jobs.ArchiveJobRequest request) => ProcessingJobs.ReadRender(request.ParametersJson).Parameters;
var adapted = Read(ProcessingJobs.Render(sequence, uhd, 6000, 4000, portrait));
Assert.Equal((2160, 3840, 2), (adapted.Width, adapted.Height, adapted.RequiredSettingsFormat));
var source = Read(ProcessingJobs.Render(sequence, uhd, 6000, 4000, new ProjectSettings()));
Assert.Equal((3840, 2160, 1), (source.Width, source.Height, source.RequiredSettingsFormat));
// A source-sized output turns with the picture; the turn needs format 2.
var png = new ExportSettings { Preset = new Auto<string>().WithManual("png-sequence") };
var turned = Read(ProcessingJobs.Render(sequence, png, 6000, 4000, new ProjectSettings { Camera = new CameraSettings { Rotate = 90 } }));
Assert.Equal((4000, 6000, 2), (turned.Width, turned.Height, turned.RequiredSettingsFormat));
// The sequence's own settings when the job embeds none.
var own = Read(ProcessingJobs.Render(sequence with { SettingsJson = portrait.ToJson() }, uhd, 6000, 4000));
Assert.Equal((2160, 3840, 2), (own.Width, own.Height, own.RequiredSettingsFormat));
// Posted by an older client (the preset's size, no format) with a batch: the server sizes each job for the settings.
var posted = Read(ProcessingJobs.Render(sequence, uhd with { Batch = ["1080p-h264"] }, 6000, 4000)) with { SettingsJson = portrait.ToJson() };
Assert.Equal((3840, 2160, 1), (posted.Width, posted.Height, posted.RequiredSettingsFormat));
var split = ProcessingJobs.Split(posted, 6000, 4000, portrait);
Assert.SequenceEqual([(2160, 3840, 2), (1080, 1920, 2)], split.Select(p => (p.Width, p.Height, p.RequiredSettingsFormat)));
Assert.Equal(split[0], ProcessingJobs.Routed(split[0], portrait, 6000, 4000), "a size already adapted stays");
// The sequence's settings change between posting and routing: the size comes from the preset again, never from the
// size a newer client already adapted (2160×2160 for 1:1 would adapt to 2160×1215 for 16:9).
var square = new ProjectSettings { Camera = new CameraSettings { Aspect = new Auto<string>().WithManual("1:1") } };
var wide = new ProjectSettings { Camera = new CameraSettings { Aspect = new Auto<string>().WithManual("16:9") } };
var squared = Read(ProcessingJobs.Render(sequence, uhd, 6000, 4000, square));
Assert.Equal((2160, 2160), (squared.Width, squared.Height));
var rerouted = ProcessingJobs.Routed(squared, wide, 6000, 4000);
Assert.Equal((3840, 2160), (rerouted.Width, rerouted.Height), "the preset's box adapted to the new aspect");
var tall = Read(ProcessingJobs.Render(sequence, uhd, 6000, 4000, new ProjectSettings { Camera = new CameraSettings { Aspect = new Auto<string>().WithManual("4:5") } }));
Assert.Equal((2160, 2700), (tall.Width, tall.Height));
Assert.Equal((3840, 2160), (ProcessingJobs.Routed(tall, wide, 6000, 4000).Width, ProcessingJobs.Routed(tall, wide, 6000, 4000).Height));
Assert.Equal((3840, 2160, 1), ProcessingJobs.Split(posted, 6000, 4000).Select(p => (p.Width, p.Height, p.RequiredSettingsFormat)).First(),
"settings that cannot be read keep the size the job was posted with");
// What the desktop asks of a server before a render: the highest format of the export and its batch.
Assert.Equal(1, ProcessingJobs.RequiredFormat(portrait, png, 6000, 4000), "a source-sized output keeps the proportions");
Assert.Equal(2, ProcessingJobs.RequiredFormat(portrait, png with { Batch = ["4k-h264"] }, 6000, 4000));
}
/// <summary>
/// Owner review 1, phase 4, end to end: a turned, portrait project with a look renders each output at the size its job
/// was routed with (the fixed box adapted to 9:16, the source-sized output on the turned view) and records it so.
/// </summary>
[Test]
public async Task ATurnedPortraitProjectRendersAtTheSizeItsJobWasRoutedWith()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
await fx.StartEngineAsync();
var settings = new ProjectSettings
{
Camera = new CameraSettings { Aspect = new Auto<string>().WithManual("9:16"), Rotate = 90, Straighten = 2 },
Look = new LookSettings { Filter = "sepia", Strength = 0.6 },
};
var request = ProcessingJobs.Render(sequence, Mjpeg with { Batch = ["png-sequence"] }, 96, 64, settings);
var routed = ProcessingJobs.ReadRender(request.ParametersJson).Parameters;
Assert.Equal((54, 96, 2), (routed.Width, routed.Height, routed.RequiredSettingsFormat));
await fx.WaitForAsync((await fx.EnqueueAsync(request)).Id, JobState.Done);
var renders = (await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct)).OrderBy(r => r.OutputPath, StringComparer.Ordinal).ToList();
Assert.SequenceEqual([(54, 96), (54, 96)], renders.Select(r => (r.Width, r.Height)));
var pngs = Directory.GetFiles(Path.Combine(fx.Folder(sequence).Exports, "clip-PNG")).Order().ToList();
Assert.Equal(Frames, pngs.Count);
using var decoded = DecoderFactory.CreateServer().Decode(new DecodeRequest(pngs[^1]));
Assert.Equal((54, 96), (Assert.NotNull(decoded).Pixels.Width, decoded.Pixels.Height));
}
/// <summary>Settings of a newer Chronos fail the render with the reason in the user's language, never as an English message.</summary>
[Test]
public async Task AnOverFormatRenderFailsSayingANewerChronosIsNeeded()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
await fx.StartEngineAsync();
var parameters = ProcessingJobs.ReadRender(ProcessingJobs.Render(sequence, Mjpeg, 96, 64).ParametersJson).Parameters with
{
SettingsJson = """{"version":3,"camera":{"rotate":90},"grade":{"lut":"teal"}}""",
};
var request = new Chronos.Data.Archiving.Jobs.ArchiveJobRequest(JobKind.Render, [sequence.Id], "newer",
System.Text.Json.JsonSerializer.Serialize(parameters, Chronos.Protocol.ProtocolJson.Default.RenderJobParameters), JobPriority.User);
Assert.Equal(3, ProcessingJobs.ReadRender(ProcessingJobs.Render(sequence, Mjpeg, 96, 64,
ProjectSettings.FromJson(parameters.SettingsJson, allowNewer: true)).ParametersJson).Parameters.RequiredSettingsFormat, "routed to none older");
var failed = await fx.WaitForAsync((await fx.EnqueueAsync(request)).Id, JobState.Failed);
Assert.Equal(Loc.L("Errors.Render.NewerSettings"), failed.Error);
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
}
/// <summary>MJPEG job parameters whose preset JSON is <paramref name="presetJson"/>.</summary>
private static string WithPreset(string presetJson) => System.Text.Json.JsonSerializer.Serialize(
new Chronos.Protocol.RenderJobParameters("MJPEG", presetJson, "mjpeg", 96, 64, false, null), Chronos.Protocol.ProtocolJson.Default.RenderJobParameters);
@@ -21,6 +21,102 @@ public sealed class ProjectMergeTests
private static PendingFrame Waiting(FramePhoto photo, bool excluded = false, bool hero = false) =>
new() { Sha256 = photo.Sha256, Size = photo.Size, CapturedAt = photo.CapturedAt, Excluded = excluded, Hero = hero };
[Test]
public void ATurnOnOneSideAndALookOnTheOtherMergeIntoFormatTwo()
{
var basis = new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = 0.2 } };
var ours = basis with { Camera = basis.Camera with { Rotate = 90, Straighten = 1.5 } };
var theirs = basis with { Look = new LookSettings { Filter = "sepia", Strength = 0.6 } };
var result = ProjectMerge.MergeWithConflicts(basis, ours, theirs);
Assert.False(result.HasConflicts);
Assert.Equal((90, 1.5), (result.Merged.Camera.Rotate, result.Merged.Camera.Straighten));
Assert.Equal("sepia", result.Merged.Look?.Filter);
Assert.Equal(2, result.Merged.Version);
Assert.Contains("\"version\": 2", result.Merged.ToJson());
// One side takes the turn away while the other keeps the look: the format the members need, not the one taken.
var undone = ProjectMerge.MergeWithConflicts(result.Merged, result.Merged with { Camera = basis.Camera }, result.Merged with { Look = null }).Merged;
Assert.Equal(1, ProjectContent.FormatOf(undone.ToJson()));
Assert.Equal(basis.ToJson(), undone.ToJson());
}
[Test]
public void BothSidesCroppingGiveOneCropConflict()
{
var basis = new ProjectSettings { Camera = new CameraSettings { Aspect = new Auto<string>().WithManual("9:16") } };
var ours = basis with { Camera = basis.Camera with { Crop = [0.1, 0, 0.3, 0.9] } };
var theirs = basis with { Camera = basis.Camera with { Crop = [0.5, 0.05, 0.2, 0.6] } };
var result = ProjectMerge.MergeWithConflicts(basis, ours, theirs);
// The box is one value: never the x of one side and the width of the other.
Assert.SequenceEqual(["camera.crop"], result.Conflicts.Select(c => c.Path));
Assert.SequenceEqual([0.1, 0, 0.3, 0.9], Assert.NotNull(result.Merged.Camera.Crop));
Assert.SequenceEqual([0.5, 0.05, 0.2, 0.6], Assert.NotNull(
ProjectMerge.MergeWithConflicts(basis, ours, theirs, new HashSet<string> { "camera.crop" }).Merged.Camera.Crop));
// With a mirror on their side too, the crop and the mirror are one conflict: their crop is in the mirrored frame.
var mirrored = theirs with { Camera = theirs.Camera with { Mirror = true } };
var coupled = ProjectMerge.MergeWithConflicts(basis, ours, mirrored);
Assert.SequenceEqual(["camera.mirror"], coupled.Conflicts.Select(c => c.Path));
Assert.SequenceEqual([0.1, 0, 0.3, 0.9], Assert.NotNull(coupled.Merged.Camera.Crop), "ours: our crop");
Assert.False(coupled.Merged.Camera.Mirror, "and unmirrored");
var taken = ProjectMerge.MergeWithConflicts(basis, ours, mirrored, new HashSet<string> { "camera.mirror" }).Merged;
Assert.SequenceEqual([0.5, 0.05, 0.2, 0.6], Assert.NotNull(taken.Camera.Crop));
Assert.True(taken.Camera.Mirror);
}
/// <summary>
/// A turn of a project without a crop changes only the orientation and the aspect (nothing else to move), so member by
/// member a crop or keyframes the other side placed in the unturned frame would apply to the turned one: one conflict.
/// </summary>
[Test]
public void ATurnOnOneSideAndAFramingOnTheOtherAreOneConflict()
{
var basis = new ProjectSettings { Camera = new CameraSettings { Aspect = new Auto<string>().WithManual("16:9") } };
var turned = basis with { Camera = Chronos.Core.Imaging.Geometry.OrientationEdit.Apply(basis.Camera, Chronos.Core.Imaging.Geometry.OrientationOp.RotateRight) };
Assert.Null(turned.Camera.Crop);
var cropped = basis with { Camera = basis.Camera with { Crop = [0.1, 0.2, 0.6, 0.3375] } };
foreach (var (ours, theirs) in new[] { (turned, cropped), (cropped, turned) })
{
var result = ProjectMerge.MergeWithConflicts(basis, ours, theirs);
Assert.SequenceEqual(["camera.rotate"], result.Conflicts.Select(c => c.Path));
Assert.Equal(ours.ToJson(), result.Merged.ToJson(), "ours whole: the orientation and the framing of one side");
var other = ProjectMerge.MergeWithConflicts(basis, ours, theirs, new HashSet<string> { "camera.rotate" }).Merged;
Assert.Equal(theirs.ToJson(), other.ToJson());
}
// Keyframes placed in the unturned frame, on the camera and on a photo that waits.
var keyed = basis with
{
Camera = basis.Camera with { Keyframes = [new CameraKey(0, 0.8, 0.5, 2, 0)] },
};
Assert.SequenceEqual(["camera.rotate"], ProjectMerge.MergeWithConflicts(basis, turned, keyed).Conflicts.Select(c => c.Path));
var photo = Photo(1);
var waiting = basis with { PendingFrames = [Waiting(photo) with { Keyframes = [new CameraKey(0, 0.8, 0.5, 2, 0)] }] };
Assert.SequenceEqual(["camera.rotate"], ProjectMerge.MergeWithConflicts(basis, waiting, turned).Conflicts.Select(c => c.Path));
// Anything else on the other side merges with the turn as before.
var brighter = basis with { Exposure = basis.Exposure with { ExposureOffsetEv = 0.3 } };
var merged = ProjectMerge.MergeWithConflicts(basis, turned, brighter);
Assert.False(merged.HasConflicts);
Assert.Equal((90, 0.3), (merged.Merged.Camera.Rotate, merged.Merged.Exposure.ExposureOffsetEv));
}
[Test]
public void AFormatThreeSideIsNeverMerged()
{
var basis = new ProjectSettings { Camera = new CameraSettings { Rotate = 90 } };
var newer = ProjectSettings.FromJson("""{ "version": 3, "camera": { "rotate": 180 }, "look": { "filter": "film" } }""", allowNewer: true);
var mine = basis with { Look = new LookSettings { Filter = "warm" } };
Assert.Throws<NewerSettingsException>(() => ProjectMerge.MergeWithConflicts(basis, mine, newer));
Assert.Throws<NewerSettingsException>(() => ProjectMerge.MergeWithConflicts(basis, newer, mine));
Assert.Equal(3, ProjectMerge.MergeWithConflicts(basis, basis, newer).Merged.Version);
}
[Test]
public void EntriesOfOnePhotoMergeAsOneWithThePositionsOfBoth()
{
@@ -69,7 +165,7 @@ public sealed class ProjectMergeTests
public void SettingsOfANewerChronosAreNeverMergedWithThisOnes()
{
var basis = new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = 0.1 } };
var newer = ProjectSettings.FromJson("""{ "version": 2, "exposure": { "exposureOffsetEv": 0.5 }, "grade": { "look": "film" } }""", allowNewer: true);
var newer = ProjectSettings.FromJson("""{ "version": 3, "exposure": { "exposureOffsetEv": 0.5 }, "grade": { "look": "film" } }""", allowNewer: true);
var mine = basis with { Stack = new StackSettings { Mode = StackSetting.Median } };
// Both changed: refused, whichever side the newer one is, in a replay too.
@@ -327,7 +327,7 @@ public abstract class ProjectRecoveryTests(TestContext context) : DatabaseTest(c
var folder = fx.Paths.Sequence(sequence.Folder);
// A newer Chronos on another PC sharing the archive pushes version 2 in its settings format, and mirrors it.
var settings = """{ "version": 2, "exposure": { "exposureOffsetEv": 0.5 }, "futureThing": true }""";
var settings = """{ "version": 3, "exposure": { "exposureOffsetEv": 0.5 }, "futureThing": true }""";
var now = DateTimeOffset.UtcNow;
var future = new ProjectVersion
{
@@ -339,7 +339,7 @@ public abstract class ProjectRecoveryTests(TestContext context) : DatabaseTest(c
ClientName = "newer",
SettingsJson = settings,
ContentHash = ProjectContent.Hash(settings),
SettingsFormat = 2,
SettingsFormat = 3,
FramesVersion = head.FramesVersion,
CreatedAt = now,
StoredAt = now,
@@ -91,6 +91,21 @@ public abstract class ProjectServiceTests(TestContext context) : DatabaseTest(co
};
}
/// <summary>
/// <paramref name="version"/> as a build on the other OS wrote it before every build wrote LF: its text with the other
/// line ends (CRLF for LF, LF for CRLF), hashed as such. Flipped, not made CRLF, so a test means the same on every OS.
/// </summary>
internal static ProjectVersion Foreign(ProjectVersion version)
{
var text = Foreign(version.SettingsJson);
return version with { SettingsJson = text, ContentHash = ProjectContent.Hash(text) };
}
/// <summary><paramref name="text"/> with the other line ends: LF where it has CRLF, CRLF where it has LF.</summary>
internal static string Foreign(string text) => text.Contains("\r\n", StringComparison.Ordinal)
? text.Replace("\r\n", "\n", StringComparison.Ordinal)
: text.Replace("\n", "\r\n", StringComparison.Ordinal);
[Test]
public async Task MainIsMadeFromTheSequenceSettingsWithItsPositionsParkedByPhoto()
{
@@ -195,6 +210,33 @@ public abstract class ProjectServiceTests(TestContext context) : DatabaseTest(co
Assert.Equal(2, (await projects.HeadAsync(main.Id, fx.Ct)).Number);
}
[Test]
public async Task PushesFromAnotherOsAreNoOutsideChange()
{
var fx = await FixtureAsync();
// Hashed photos: only line ends tell the texts apart (no photo named anew to compare by).
var (sequence, frames) = await UploadedAsync(fx, 4);
Assert.True(frames.All(f => f.Sha256 is { Length: 64 }));
var projects = fx.Service.Projects;
var main = await projects.MainAsync(sequence.Id, fx.Ct);
var first = await projects.HeadAsync(main.Id, fx.Ct);
// A Windows desktop of a build before pushes to this home: CRLF versions on a home writing LF (and the reverse on Linux).
var second = Foreign(Draft(first, new ProjectSettings { ExcludedFrames = [1], HeroFrame = 2 }, frames));
Assert.Equal(PushOutcome.Stored, (await projects.PushAsync(main.Id, second, fx.Ct)).Outcome);
var third = Foreign(Draft(second, new ProjectSettings { ExcludedFrames = [1, 3], Exposure = new ExposureSettings { ExposureOffsetEv = 0.4 } }, frames));
Assert.Equal(PushOutcome.Stored, (await projects.PushAsync(main.Id, third, fx.Ct)).Outcome);
Assert.Equal(PushOutcome.AlreadyStored, (await projects.PushAsync(main.Id, third, fx.Ct)).Outcome);
// The editor's old path writes the same settings again: the mirror of the third version, no outside change.
await WriteSettingsAsync(fx, sequence.Id, ProjectSettings.FromJson(ProjectContent.Place(third.SettingsJson, Photos(frames))));
var head = await projects.HeadAsync(main.Id, fx.Ct);
Assert.Equal((third.Id, 3), (head.Id, head.Number));
Assert.Equal(third.ContentHash, head.ContentHash);
Assert.SequenceEqual([ProjectVersionKind.Commit, ProjectVersionKind.Commit, ProjectVersionKind.Imported],
(await projects.HistoryAsync(main.Id, cancellationToken: fx.Ct)).Select(v => v.Kind));
}
[Test]
public async Task SettingsAnotherPathWritesBecomeAnExternalVersionOfMain()
{
@@ -54,6 +54,11 @@ internal sealed class FakeSyncRemote : ISyncRemote
/// <summary>Edits the server accepted, in order.</summary>
public List<UpdateSequenceRequest> Updates { get; } = [];
/// <summary>The settings format the server announces (an older server's 1).</summary>
public int SettingsFormat { get; set; } = Chronos.Core.Project.ProjectSettings.CurrentVersion;
public Task<int> SettingsFormatAsync(CancellationToken cancellationToken) => Task.FromResult(SettingsFormat);
public FakeSequence Add(string? title, IEnumerable<byte[]> originals, string? settingsJson = null,
SequenceStatus status = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt)
{
@@ -243,6 +243,20 @@ public sealed class SyncRulesTests
Assert.Empty(SyncRules.Differences(SyncFixture.Window33, SyncFixture.Window33));
}
/// <summary>
/// Owner review 1, phase 4: the "version" member follows the content (format 2 only while a turn or a look is set), so a
/// rotation alone is one difference, the rotation's; a newer Chronos's format still differs.
/// </summary>
[Test]
public void TheDerivedFormatIsNoDifferenceOfItsOwn()
{
var plain = new ProjectSettings().ToJson();
var turned = new ProjectSettings { Camera = new CameraSettings { Rotate = 90 } }.ToJson();
Assert.Contains("\"version\": 2", turned);
Assert.SequenceEqual(["camera.rotate"], SyncRules.Differences(turned, plain).Select(d => d.Path));
Assert.Contains(SyncRules.Differences("""{"version":3,"camera":{"rotate":90}}""", turned, max: 5), d => d.Path == "version");
}
[Test]
public void PayloadDifferencesListTheSequenceFieldsBeforeTheSettings()
{
@@ -701,6 +701,35 @@ public sealed class SyncServiceTests(TestContext context)
Assert.Equal(SyncStatus.InSync, recovered.Status);
}
/// <summary>
/// Owner review 1, phase 4: settings an older server cannot read (a turn needs format 2) stay on this PC, the sync row
/// saying why; it would store them and then fail every render of them. Settings of the base format are sent as before.
/// </summary>
[Test]
public async Task SettingsAnOlderServerCannotReadStayHere()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(1);
var local = await f.LocalAsync("Harbour", photos);
var remote = f.Remote.Add("Harbour", photos);
f.Remote.SettingsFormat = ProjectSettings.BaseVersion;
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
await f.EditLocalSettingsAsync(local.Id, new ProjectSettings { Camera = new CameraSettings { Rotate = 90 } }.ToJson());
await f.RefreshAsync();
Assert.Null(remote.SettingsJson);
Assert.Empty(f.Remote.Updates);
var entry = await f.EntryAsync("Harbour");
Assert.Equal(SyncStatus.LocalAhead, entry.Status);
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), entry.Link!.Error);
await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
await f.RefreshAsync();
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson), "the base format is sent");
Assert.Null((await f.EntryAsync("Harbour")).Link!.Error);
}
[Test]
public async Task WithoutTheEditRightThisPcsEditsWaitInsteadOfFailing()
{
@@ -118,6 +118,58 @@ public abstract class WorkspaceMergeTests(TestContext context) : DatabaseTest(co
Assert.Null(await sync.CommitAsync(id, cancellationToken: fx.Ct));
}
[Test]
public async Task ABaseSavedWithTheOtherOsLineEndsReadsAsTheWorkingState()
{
var fx = await FixtureAsync();
Assert.True(fx.Frames.All(f => f.Sha256 is { Length: 64 }));
var projects = fx.Archive.Service.Projects;
var main = await projects.MainAsync(fx.Sequence.Id, fx.Ct);
// The head a build before stored on the other OS (CRLF where this build writes LF, and the reverse on Linux).
var foreign = ProjectServiceTests.Foreign(ProjectServiceTests.Draft(await projects.HeadAsync(main.Id, fx.Ct),
new ProjectSettings { ExcludedFrames = [1], HeroFrame = 3 }, fx.Frames));
Assert.Equal(PushOutcome.Stored, (await projects.PushAsync(main.Id, foreign, fx.Ct)).Outcome);
var (_, sync) = fx.Workspace();
var project = await fx.CheckoutAsync(sync);
var id = project.ProjectId;
Assert.Equal(foreign.ContentHash, project.ReadBundle().Workspace!.Base!.ContentHash);
Assert.SequenceEqual([1], (await sync.OpenAsync(id, fx.Ct)).Working.ExcludedFrames);
// Nothing edited here: in step with its base, and nothing to save.
Assert.Equal(WorkspaceState.InSync, (await sync.StatusAsync(id, fx.Home, fx.Ct)).State);
Assert.Null(await sync.CommitAsync(id, cancellationToken: fx.Ct));
Assert.Equal(foreign.Id, (await fx.Home.HeadAsync(id, fx.Ct)).Id);
}
[Test]
public async Task ARestoreOfAVersionTheBaseHoldsWithOtherLineEndsIsNoRestore()
{
var fx = await FixtureAsync();
var projects = fx.Archive.Service.Projects;
var main = await projects.MainAsync(fx.Sequence.Id, fx.Ct);
var choices = new ProjectSettings { ExcludedFrames = [1], HeroFrame = 3 };
// A version an older build stored on the other OS, then the same choices as this build writes them (the base).
var foreign = ProjectServiceTests.Foreign(ProjectServiceTests.Draft(await projects.HeadAsync(main.Id, fx.Ct), choices, fx.Frames));
Assert.Equal(PushOutcome.Stored, (await projects.PushAsync(main.Id, foreign, fx.Ct)).Outcome);
var same = ProjectServiceTests.Draft(foreign, choices, fx.Frames);
Assert.NotEqual(foreign.SettingsJson, same.SettingsJson);
Assert.Equal(PushOutcome.Stored, (await projects.PushAsync(main.Id, same, fx.Ct)).Outcome);
var (_, sync) = fx.Workspace();
var project = await fx.CheckoutAsync(sync);
var id = project.ProjectId;
Assert.Equal(same.Id, project.ReadBundle().Workspace!.Base!.VersionId);
// The foreign version restored before a pull moved the base onto the same choices: the restore stays recorded.
await sync.RestoreAsync(id, foreign.Id, fx.Home, fx.Ct);
project.WriteSync(project.ReadSync() with { RestoredFrom = foreign.Id });
// Edited further and saved: the parent already holds the restored version, so the new version is a plain one.
await EditAsync(sync, id, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = 0.4 } }, fx.Ct);
var next = Assert.NotNull(await sync.CommitAsync(id, cancellationToken: fx.Ct));
Assert.Equal((ProjectVersionKind.Commit, (Guid?)null), (next.Kind, next.RestoredFrom));
}
[Test]
public async Task ABaseNamingAPhotoByItsHashReadsAsTheWorkingStateOnMediaThatHaveNotLearntIt()
{
@@ -332,7 +384,7 @@ public abstract class WorkspaceMergeTests(TestContext context) : DatabaseTest(co
Assert.Equal(local.Id, sync.Unpushed(id).Single().Id);
Assert.Equal(local.SettingsJson, sync.Unpushed(id).Single().SettingsJson);
var working = (await sync.OpenAsync(id, fx.Ct)).Working;
Assert.Equal((ProjectSettings.CurrentVersion, 0.3), (working.Version, working.Exposure.ExposureOffsetEv));
Assert.Equal((ProjectSettings.BaseVersion, 0.3), (working.Version, working.Exposure.ExposureOffsetEv));
Assert.SequenceEqual([1], working.ExcludedFrames);
Assert.Equal(WorkspaceState.Conflict, (await sync.PullAsync(id, fx.Home, fx.Ct)).Status.State);
@@ -455,7 +455,7 @@ public abstract class WorkspaceTests(TestContext context) : DatabaseTest(context
var (_, sync) = fx.Workspace();
var project = await fx.CheckoutAsync(sync);
var bundle = project.ReadBundle();
File.WriteAllText(project.BundlePath, bundle.ToJson().Replace("\"version\": 1", "\"version\": 2", StringComparison.Ordinal));
File.WriteAllText(project.BundlePath, bundle.ToJson().Replace("\"version\": 1", "\"version\": 3", StringComparison.Ordinal));
var session = await sync.OpenAsync(project.ProjectId, fx.Ct);
Assert.True(session.IsReadOnly);
@@ -498,6 +498,42 @@ public sealed class ProjectTests(TestContext context)
Assert.Contains(ServerCapabilities.Projects, (await client.GetInfoAsync(context.Cancellation)).Capabilities);
}
/// <summary>
/// Owner review 1, phase 4: the server announces the settings format it reads, and takes the versions of the formats it
/// reads (1, and 2 with a turn or a look), refusing a newer one with 422 <c>newer_format</c>, nothing stored.
/// </summary>
[Test]
public async Task TheServerTakesTheSettingsFormatsItAnnounces()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
using (var anonymous = new ChronosClient(server.HttpBase, new CertificatePinning([]), "tests"))
Assert.Equal(ProjectSettings.CurrentVersion, (await anonymous.GetInfoAsync(context.Cancellation)).SettingsFormat);
Assert.Equal(2, ProjectSettings.CurrentVersion);
var (http, _, token) = await server.UserAsync("alberto", "editor");
using var alberto = Client(server, token);
var sid = await SequenceAsync(server, token, 2);
var main = (await alberto.ListProjectsAsync(sid)).Single(p => p.IsMain);
var head = await alberto.GetProjectHeadAsync(sid, main.Id);
var home = ProjectWire.ToHomeFrames(await alberto.GetProjectFramesAsync(sid));
var plain = Version(head, new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = 0.3 } }, home);
Assert.Equal(1, plain.SettingsFormat);
var v2 = Assert.NotNull((await alberto.PushProjectVersionAsync(sid, main.Id, plain)).Version);
var turned = Version(v2, new ProjectSettings { Camera = new CameraSettings { Rotate = 90, Mirror = true }, Look = new LookSettings { Filter = "sepia" } }, home);
Assert.Equal(2, turned.SettingsFormat);
var v3 = Assert.NotNull((await alberto.PushProjectVersionAsync(sid, main.Id, turned)).Version);
Assert.Equal(2, ProjectContent.FormatOf(v3.SettingsJson));
var mirrored = ProjectSettings.FromJson(Assert.NotNull((await server.Database.Sequences.GetAsync(sid))!.SettingsJson));
Assert.Equal((90, true, "sepia"), (mirrored.Camera.Rotate, mirrored.Camera.Mirror, mirrored.Look?.Filter), "Main's head is the sequence's settings");
const string future = """{"version":3,"camera":{"rotate":90}}""";
var newer = Version(v3, new ProjectSettings(), home) with { SettingsJson = future, ContentHash = ProjectContent.Hash(future), SettingsFormat = 3 };
using (var raw = await http.PostAsJsonAsync($"/api/v1/sequences/{sid}/projects/{main.Id}/versions", newer, ProtocolJson.Default.ProjectVersionDto))
await raw.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, ProjectErrors.NewerFormat);
Assert.Equal(3, (await alberto.GetProjectAsync(sid, main.Id)).HeadNumber);
}
[Test]
public async Task TheFramesOfAHomeAreOfOneFramesVersionWithTheAliasesOfItsConversions()
{
@@ -132,6 +132,9 @@ public sealed class RenderNodeClientTests(TestContext context)
Assert.SequenceEqual(["apng", "gif", "mjpeg"], registered.Encoders.Select(e => e.Codec).Order(StringComparer.Ordinal));
// Each encoder announces its own largest output, so the server matches job sizes per codec.
Assert.True(registered.Encoders.All(e => (e.MaxWidth, e.MaxHeight) == (65535, 65535)), "per-encoder limits");
// And the settings format it renders (owner review 1, phase 4), so the server gives it only jobs it renders as asked.
var stored = Assert.NotNull(Chronos.Server.Api.Dto.Capabilities(Assert.NotNull(await server.Database.RenderNodes.GetAsync(id))));
Assert.Equal(ProjectSettings.CurrentVersion, stored.SettingsFormat);
}
[Test]
@@ -3,10 +3,14 @@ using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Archiving;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Processing;
using Chronos.Data.Repositories;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Server.Api;
using Chronos.Server.Jobs;
using Chronos.Server.Storage;
using Chronos.Testing;
@@ -94,6 +98,110 @@ public sealed class RenderNodeTests(TestContext context)
Assert.Equal(uhd.Id, (await claim.ReadAsync(ProtocolJson.Default.ClaimedJob)).Job.Id);
}
/// <summary>
/// Owner review 1, phase 4: a node that does not announce its settings format (an older Chronos) reads format 1, and is
/// never given a job it would render otherwise than asked: settings of format 2 (a turn), the chosen proportions in a
/// fixed-size preset (4K at 9:16 = 2160×3840), or a sequence's settings changed to format 2 after the job was queued. A
/// node of format 2 takes them, a portrait UHD frame on an encoder announced as 4096×2304 included.
/// </summary>
[Test]
public async Task OnlyNodesThatReadTheSettingsFormatTakeTheJobsThatNeedIt()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor", renderNode: true);
using var old = await editor.PostAsync("/api/v1/nodes/register", new StringContent(
"""{"clientName":"old-pc","encoders":[{"codec":"h264","name":"H.264 Encoder MFT","hardware":false,"tenBit":false}],"maxWidth":4096,"maxHeight":4096}""",
System.Text.Encoding.UTF8, "application/json"));
var older = await old.ReadAsync(ProtocolJson.Default.RenderNodeDto);
var stored = Assert.NotNull(Dto.Capabilities(Assert.NotNull(await server.Database.RenderNodes.GetAsync(older.Id))));
Assert.Equal(1, stored.SettingsFormat);
var sequence = await JobApiTests.CreateSequenceAsync(editor);
var turned = new ProjectSettings { Camera = new CameraSettings { Rotate = 90 } }.ToJson();
var portrait = new ProjectSettings { Camera = new CameraSettings { Aspect = new Auto<string>().WithManual("9:16") } }.ToJson();
var v2 = await JobApiTests.CreateAsync(editor, "render", sequence, WithSettings(H264Job(3840, 2160), turned));
var proportions = await JobApiTests.CreateAsync(editor, "render", sequence, WithSettings(H264Job(3840, 2160), portrait));
var routed = ProcessingJobs.ReadRender((await server.Database.Jobs.GetAsync(proportions.Id))!.ParametersJson).Parameters;
Assert.Equal((2160, 3840, 2), (routed.Width, routed.Height, routed.RequiredSettingsFormat), "the server sized the job posted at the preset's size");
// Queued as format 1, then the sequence's own settings took a turn.
var plain = await JobApiTests.CreateAsync(editor, "render", sequence, H264Job(3840, 2160));
Assert.Equal(1, ProcessingJobs.ReadRender((await server.Database.Jobs.GetAsync(plain.Id))!.ParametersJson).Parameters.RequiredSettingsFormat);
var row = (await server.Database.Sequences.GetAsync(sequence))!;
await server.Database.Sequences.EditAsync(sequence, new SequenceEdit { SettingsJson = turned }, row.SettingsVersion);
using (var none = await editor.PostAsync($"/api/v1/nodes/{older.Id}/claim", null)) await none.ExpectAsync(HttpStatusCode.NoContent);
// The software H.264 encoder takes portrait UHD as a long edge × short edge, on a node that knows it.
using var registered = await editor.PostAsJsonAsync("/api/v1/nodes/register", new RegisterNodeRequest("studio-pc",
[new NodeEncoder("h264", "H.264 Encoder MFT", false, false, 4096, 2304)], 4096, 2304, SettingsFormat: 2), ProtocolJson.Default.RegisterNodeRequest);
var newer = await registered.ReadAsync(ProtocolJson.Default.RenderNodeDto);
var claimed = new List<Guid>();
for (var i = 0; i < 3; i++)
{
using var claim = await editor.PostAsync($"/api/v1/nodes/{newer.Id}/claim", null);
claimed.Add((await claim.ReadAsync(ProtocolJson.Default.ClaimedJob)).Job.Id);
}
Assert.SequenceEqual(new[] { v2.Id, proportions.Id, plain.Id }.Order(), claimed.Order());
}
/// <summary>
/// An encoder's limit is a long edge × short edge on a node of format 2 (its encoders take portrait UHD within 4096×2304);
/// an older node shrinks a frame to the limit as announced, so it is held to that.
/// </summary>
[Test]
public void APortraitFrameFitsALandscapeLimitOnlyOnANodeThatKnowsIt()
{
var job = new RenderJobParameters("4K", "{}", "h264", 2160, 3840, UseProxies: false, null, RequiredSettingsFormat: 2);
NodeEncoder[] software = [new("h264", "H.264 Encoder MFT", false, false, 4096, 2304)];
var older = new RegisterNodeRequest("old-pc", software, 4096, 2304);
var newer = older with { ClientName = "studio-pc", SettingsFormat = 2 };
Assert.False(RenderNodeService.CanEncode(older, job));
Assert.True(RenderNodeService.CanEncode(newer, job));
Assert.True(RenderNodeService.Renders(newer, job));
Assert.False(RenderNodeService.Renders(older, job with { Width = 1080, Height = 1920 }), "format 2 is never sent to a format-1 node");
Assert.True(RenderNodeService.Renders(older, job with { Width = 3840, Height = 2160, RequiredSettingsFormat = 1 }));
Assert.False(RenderNodeService.CanEncode(newer, job with { Width = 2400 }), "both edges above the short limit");
}
/// <summary>A job waits for a node only while one online could render it: one of an older settings format cannot.</summary>
[Test]
public async Task AJobDoesNotWaitForNodesThatCannotReadItsSettings()
{
await using var server = await TestServer.StartAsync(context, o => o.NodeTimeoutSeconds = 60);
var (editor, _, _) = await server.UserAsync("alberto", "editor", renderNode: true);
await RegisterAsync(editor, "old-pc", "h264", 4096);
var sequence = await JobApiTests.CreateSequenceAsync(editor);
var turned = new ProjectSettings { Camera = new CameraSettings { Rotate = 90 } }.ToJson();
var created = await JobApiTests.CreateAsync(editor, "render", sequence, WithSettings(H264Job(1920, 1080), turned));
var queued = (await server.Database.Jobs.GetAsync(created.Id))!;
var parameters = ProcessingJobs.ReadRender(queued.ParametersJson).Parameters;
Assert.Equal(2, parameters.RequiredSettingsFormat);
// Waited longer than a node may stay silent: only an online node that renders it keeps it waiting.
var job = queued with { Created = DateTimeOffset.UtcNow - TimeSpan.FromSeconds(61) };
RenderNodeAvailability Availability() => new(server.Database, server.Options, TimeProvider.System);
Assert.True(await Availability().AwaitsNodeAsync(queued with { Created = DateTimeOffset.UtcNow }, parameters, context.Cancellation), "a node may be reconnecting");
Assert.False(await Availability().AwaitsNodeAsync(job, parameters, context.Cancellation), "only a node of format 1 is online");
Assert.True(await Availability().AwaitsNodeAsync(job, parameters with { RequiredSettingsFormat = 1, SettingsJson = null }, context.Cancellation),
"it renders a job of format 1");
Assert.False(await Availability().AwaitsNodeAsync(job, parameters with { RequiredSettingsFormat = 1 }, context.Cancellation),
"a job queued as format 1 whose settings route it to format 2 is never claimed by that node, so it does not wait for it");
// Queued as format 1 on the sequence's own settings, which then took a turn: the claim skips the older node, and so
// does the wait, so the server's own engine takes the job.
var plain = (await server.Database.Jobs.GetAsync((await JobApiTests.CreateAsync(editor, "render", sequence, H264Job(1920, 1080))).Id))!;
var plainParameters = ProcessingJobs.ReadRender(plain.ParametersJson).Parameters;
var waited = plain with { Created = DateTimeOffset.UtcNow - TimeSpan.FromSeconds(61) };
Assert.Equal(1, plainParameters.RequiredSettingsFormat);
Assert.True(await Availability().AwaitsNodeAsync(waited, plainParameters, context.Cancellation), "plain settings: the older node renders it");
var row = (await server.Database.Sequences.GetAsync(sequence))!;
await server.Database.Sequences.EditAsync(sequence, new SequenceEdit { SettingsJson = turned }, row.SettingsVersion);
Assert.False(await Availability().AwaitsNodeAsync(waited, plainParameters, context.Cancellation), "the turn needs a node of format 2");
using (var registered = await editor.PostAsJsonAsync("/api/v1/nodes/register", new RegisterNodeRequest("studio-pc", [new NodeEncoder("h264", "NVENC", true, false)],
4096, 4096, SettingsFormat: 2), ProtocolJson.Default.RegisterNodeRequest))
await registered.ExpectAsync(HttpStatusCode.OK);
Assert.True(await Availability().AwaitsNodeAsync(job, parameters, context.Cancellation), "a node of format 2 is online");
}
[Test]
public async Task TheOutputUploadBecomesARenderAndFinishesTheJob()
{
@@ -241,9 +349,14 @@ public sealed class RenderNodeTests(TestContext context)
}
private static string H264Job(int width, int height) => JsonSerializer.Serialize(
new RenderJobParameters("H.264", """{"preset":{"isAuto":false,"manual":"4k-h264"}}""", "h264", width, height, UseProxies: false, null),
new RenderJobParameters("H.264", $$$"""{"preset":{"isAuto":false,"manual":"4k-h264"},"overrides":{"width":{{{width}}},"height":{{{height}}}}}""", "h264", width, height,
UseProxies: false, null),
ProtocolJson.Default.RenderJobParameters);
/// <summary>Render job parameters <paramref name="parametersJson"/> with <paramref name="settingsJson"/> embedded.</summary>
private static string WithSettings(string parametersJson, string settingsJson) => JsonSerializer.Serialize(
JsonSerializer.Deserialize(parametersJson, ProtocolJson.Default.RenderJobParameters)! with { SettingsJson = settingsJson }, ProtocolJson.Default.RenderJobParameters);
internal static async Task<RenderNodeDto> RegisterAsync(HttpClient client, string name, string codec, int maxWidth)
{
using var response = await client.PostAsJsonAsync("/api/v1/nodes/register",
@@ -168,7 +168,8 @@ public sealed class ProcessingModuleTests(TestContext context)
var done = await JobApiTests.WaitForAsync(editor, job.Id, "done");
Assert.Equal(JobEngineHost.WorkerId, done.NodeId?.Split('#')[0]);
var render = (await server.Database.Renders.ListBySequenceAsync(sequence.Id)).Single();
Assert.Equal(($"{sequence.Folder}/exports/clip-MJPEG.avi", "Mjpeg", 96, 64), (render.OutputPath, render.Codec, render.Width, render.Height));
// The analysis advises 16:9, and the chosen proportions win over the 96×64 box (owner review 1, phase 4): 96×54.
Assert.Equal(($"{sequence.Folder}/exports/clip-MJPEG.avi", "Mjpeg", 96, 54), (render.OutputPath, render.Codec, render.Width, render.Height));
Assert.Contains(Loc.L("Export.Log.NoRenderNode", Loc.L("Export.Preset.Custom"), "HEVC", "MJPEG"), done.LogTail);
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 173 KiB

After

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 168 KiB

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 236 KiB

After

Width:  |  Height:  |  Size: 276 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 229 KiB

After

Width:  |  Height:  |  Size: 270 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

After

Width:  |  Height:  |  Size: 215 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 208 KiB

After

Width:  |  Height:  |  Size: 213 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 211 KiB

After

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 208 KiB

After

Width:  |  Height:  |  Size: 207 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 275 KiB

After

Width:  |  Height:  |  Size: 275 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 270 KiB

After

Width:  |  Height:  |  Size: 271 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 271 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 267 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 420 KiB

After

Width:  |  Height:  |  Size: 425 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 400 KiB

After

Width:  |  Height:  |  Size: 404 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 272 KiB

After

Width:  |  Height:  |  Size: 272 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 316 KiB

After

Width:  |  Height:  |  Size: 317 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 309 KiB

After

Width:  |  Height:  |  Size: 310 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 266 KiB

After

Width:  |  Height:  |  Size: 267 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 259 KiB

After

Width:  |  Height:  |  Size: 261 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 114 KiB

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 116 KiB

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 111 KiB

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 KiB

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 116 KiB

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 112 KiB

After

Width:  |  Height:  |  Size: 112 KiB