Files
Chronos/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs
T
Claude 98e1486f83 fix(project): a hero chosen later outranks one still waiting for its photo
TranslateFramePositions read the stored pending frames, then parked the
project's own hero when the receiving copy lacked its photo (leaving no
hero chosen), and only then placed pending entries: a stale pending hero
whose photo the copy held became the hero again and the newer choice was
lost. When a hero is chosen, stored pending entries no longer carry the
hero flag (an entry left with nothing to place goes) before positions
are translated, so only the hero parked now may wait.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 17:09:19 +00:00

337 lines
17 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Titano.Core.Export;
using Titano.Core.Project;
using Titano.Core.Video;
using Titano.Testing;
namespace Titano.Core.Tests.Project;
public sealed class ProjectSettingsTests
{
[Test]
public void JsonRoundTripKeepsAutoAndManualValues()
{
var settings = new ProjectSettings
{
Exposure = new ExposureSettings
{
DeflickerWindow = new Auto<int>().WithAdvice(41, "Advisor.Reason.FlickerPeriod", "10.2"),
DeflickerStrength = new Auto<double>().WithManual(0.8),
},
Timing = new TimingSettings { FrameRate = new Auto<string>().WithAdvice("24", null) },
ExcludedFrames = [3, 7],
};
var back = ProjectSettings.FromJson(settings.ToJson());
Assert.Equal(41, back.Exposure.DeflickerWindow.Resolve(0));
Assert.True(back.Exposure.DeflickerWindow.IsAuto);
Assert.Equal("Advisor.Reason.FlickerPeriod", back.Exposure.DeflickerWindow.ReasonKey);
Assert.Equal(0.8, back.Exposure.DeflickerStrength.Resolve(1.0));
Assert.False(back.Exposure.DeflickerStrength.IsAuto);
Assert.SequenceEqual(new[] { 3, 7 }, back.ExcludedFrames);
Assert.Contains("\"deflickerWindow\"", settings.ToJson());
}
[Test]
public void ValueTypesFallBackOnlyWithoutAdvice()
{
Assert.Equal(21, new Auto<int>().Resolve(21));
Assert.Equal(FlowQualitySetting.Balanced, new Auto<FlowQualitySetting>().Resolve(FlowQualitySetting.Balanced));
Assert.Equal(0, new Auto<int>().WithAdvice(0, null).Resolve(21));
Assert.False(new Auto<bool>().WithAdvice(false, null).Resolve(true));
Assert.Equal(0.5, new Auto<double>().WithAdvice(0.8, null).WithManual(0.5).Resolve(1.0));
Assert.False(new Auto<bool>().WithManual(false).Resolve(true));
var back = ProjectSettings.FromJson(new ProjectSettings
{
Exposure = new ExposureSettings { Deflicker = new Auto<bool>().WithAdvice(false, null) },
}.ToJson());
Assert.False(back.Exposure.Deflicker.Resolve(true));
Assert.True(ProjectSettings.FromJson(new ProjectSettings().ToJson()).Exposure.Deflicker.Resolve(true));
}
[Test]
public void ResetReturnsToAdvice()
{
var a = new Auto<int>().WithAdvice(41, null).WithManual(15);
Assert.Equal(15, a.Resolve(0));
Assert.Equal(41, a.Reset().Resolve(0));
}
[Test]
public void NewerVersionIsRefused() =>
Assert.Throws<InvalidDataException>(() => ProjectSettings.FromJson("{\"version\": 99}"));
[Test]
public void MissingMembersKeepTheirDefaults()
{
var defaults = new ProjectSettings().ToJson();
Assert.Equal(defaults, ProjectSettings.FromJson("{}").ToJson());
Assert.Equal(defaults, ProjectSettings.FromJson("null").ToJson());
// An API client's partial edit: one manual value, a section given as null, keys in another casing.
var partial = ProjectSettings.FromJson(
"""{ "Exposure": { "deflicker": { "isAuto": false, "manual": false } }, "motion": null, "export": { "preset": { "isAuto": false, "manual": "4k-hevc" } } }""");
Assert.False(partial.Exposure.Deflicker.Resolve(true));
Assert.True(partial.Exposure.HolyGrail.IsAuto);
Assert.Equal(0.9, partial.Exposure.HighlightKnee);
Assert.True(partial.Motion.Stabilize.IsAuto);
Assert.Equal("4k-hevc", partial.Export.Preset.Resolve("1080p-h264"));
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);
// 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 } ] } }""");
Assert.Null(cleared.Exposure.HighlightKnee);
Assert.Equal(1, cleared.Timing.RemapCurve.Count);
}
[Test]
public void NullHighlightKneeSurvivesTheRoundTrip()
{
// "No knee, hard clip" must not come back as the default knee when the project is rewritten.
var off = new ProjectSettings { Exposure = new ExposureSettings { HighlightKnee = null } };
Assert.Contains("\"highlightKnee\": null", off.ToJson());
Assert.Null(ProjectSettings.FromJson(off.ToJson()).Exposure.HighlightKnee);
Assert.Equal(0.9, ProjectSettings.FromJson(new ProjectSettings().ToJson()).Exposure.HighlightKnee);
}
[Test]
public void NullListsAndTextsKeepTheirDefaults()
{
var project = ProjectSettings.FromJson(
"""{ "excludedFrames": null, "export": { "batch": null, "nameTemplate": null }, "timing": { "remapCurve": null }, "camera": { "keyframes": null } }""");
Assert.Count(0, project.ExcludedFrames);
Assert.Count(0, project.Export.Batch);
Assert.Equal("{date} {title} - {preset}", project.Export.NameTemplate);
Assert.Count(2, project.Timing.RemapCurve);
Assert.Count(0, project.Camera.Keyframes);
// Nullable members without a default still clear.
Assert.Null(ProjectSettings.FromJson("""{ "export": { "folder": null }, "heroFrame": null }""").HeroFrame);
}
[Test]
public void DuplicateKeysAreAJsonError()
{
Assert.Throws<System.Text.Json.JsonException>(() => ProjectSettings.FromJson("""{ "version": 1, "version": 1 }"""));
Assert.Throws<System.Text.Json.JsonException>(() => ProjectSettings.FromJson("""{ "Export": {}, "export": {} }"""));
Assert.Throws<System.Text.Json.JsonException>(() => ProjectSettings.FromJson("""{ "export": { "batch": [], "Batch": [] } }"""));
}
[Test]
public void ProjectMustBeAnObject() =>
Assert.Throws<System.Text.Json.JsonException>(() => ProjectSettings.FromJson("[1, 2]"));
[Test]
public void FramePositionsFollowInsertedFramesAndOtherMembersStay()
{
var project = new ProjectSettings
{
ExcludedFrames = [3, 7, 40],
HeroFrame = 2,
Camera = new CameraSettings { Keyframes = [new CameraKey(0, 0.5, 0.5, 1, 0), new CameraKey(7, 0.4, 0.5, 1.5, 0)] },
Exposure = new ExposureSettings { DeflickerWindow = new Auto<int>().WithManual(41) },
};
// Two frames inserted before position 3 and one before position 7; 40 is no frame of the old list and stays.
var moves = new Dictionary<int, int> { [0] = 0, [1] = 1, [2] = 4, [3] = 5, [4] = 6, [5] = 7, [6] = 8, [7] = 10 };
var moved = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.MoveFramePositions(project.ToJson(), moves)));
Assert.SequenceEqual([5, 10, 40], moved.ExcludedFrames);
Assert.Equal(4, moved.HeroFrame);
Assert.SequenceEqual([0, 10], moved.Camera.Keyframes.Select(k => k.Frame));
Assert.Equal((0.4, 1.5), (moved.Camera.Keyframes[1].CenterX, moved.Camera.Keyframes[1].Zoom));
Assert.Equal(41, moved.Exposure.DeflickerWindow.Manual);
}
[Test]
public void MovingPositionsEditsTheJsonInPlace()
{
const string project = """{ "ExcludedFrames": [1, 2], "heroFrame": null, "futureOption": { "keep": [1, 2] }, "camera": { "keyframes": [ { "frame": 1.5 } ] } }""";
var moved = Assert.NotNull(ProjectSettings.MoveFramePositions(project, new Dictionary<int, int> { [1] = 3 }));
var json = System.Text.Json.Nodes.JsonNode.Parse(moved)!;
Assert.SequenceEqual([3, 2], json["ExcludedFrames"]!.AsArray().Select(n => n!.GetValue<int>()));
Assert.Equal("""{"keep":[1,2]}""", json["futureOption"]!.ToJsonString());
Assert.Null(json["heroFrame"]);
Assert.Equal(1.5, json["camera"]!["keyframes"]![0]!["frame"]!.GetValue<double>());
}
[Test]
public void NothingToMoveGivesNoNewProject()
{
Assert.Null(ProjectSettings.MoveFramePositions(new ProjectSettings { ExcludedFrames = [1] }.ToJson(), new Dictionary<int, int>()));
Assert.Null(ProjectSettings.MoveFramePositions(new ProjectSettings { ExcludedFrames = [1] }.ToJson(), new Dictionary<int, int> { [2] = 3, [1] = 1 }));
Assert.Null(ProjectSettings.MoveFramePositions("not json", new Dictionary<int, int> { [1] = 2 }));
Assert.Null(ProjectSettings.MoveFramePositions("[1, 2]", new Dictionary<int, int> { [1] = 2 }));
Assert.Null(ProjectSettings.MoveFramePositions("""{ "heroFrame": 1, "HeroFrame": 1 }""", new Dictionary<int, int> { [1] = 2 }));
}
[Test]
public void PositionsCrossToAnotherCopyByPhotoAndWaitForPhotosItLacks()
{
// The server holds six photos; this copy only the last four, and one of its own the server lacks.
var photos = Enumerable.Range(0, 7).Select(Photo).ToList();
var server = Frames(photos[..6]);
var here = Frames([.. photos[2..6], photos[6]]);
var project = new ProjectSettings
{
ExcludedFrames = [0, 3],
HeroFrame = 1,
Camera = new CameraSettings { Keyframes = [new CameraKey(0, 0.5, 0.5, 1, 0), new CameraKey(4, 0.4, 0.5, 1.5, 0)] },
Exposure = new ExposureSettings { DeflickerWindow = new Auto<int>().WithManual(41) },
};
var taken = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(project.ToJson(), server, here)));
Assert.SequenceEqual([1], taken.ExcludedFrames);
Assert.Null(taken.HeroFrame);
Assert.SequenceEqual([2], taken.Camera.Keyframes.Select(k => k.Frame));
Assert.Equal(1.5, taken.Camera.Keyframes[0].Zoom);
Assert.Equal(41, taken.Exposure.DeflickerWindow.Manual);
var pending = Assert.NotNull(taken.PendingFrames);
Assert.Equal(2, pending.Count);
var first = Assert.Contains(pending, p => p.Sha256 == photos[0].Sha256);
Assert.True(first.Excluded && !first.Hero);
Assert.Count(1, first.Keyframes);
Assert.Equal(0.5, first.Keyframes[0].CenterX);
Assert.True(Assert.Contains(pending, p => p.Sha256 == photos[1].Sha256).Hero);
Assert.True(taken.HeroPending);
// The two photos arrive (inserted before the others): what waited takes its place, and the rest moved with its frames.
var arrived = Frames(photos);
var moved = ProjectSettings.MoveFramePositions(taken.ToJson(), new Dictionary<int, int> { [0] = 2, [1] = 3, [2] = 4, [3] = 5, [4] = 6 })!;
var placed = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(moved, null, arrived)));
Assert.SequenceEqual([0, 3], placed.ExcludedFrames);
Assert.Equal(1, placed.HeroFrame);
Assert.SequenceEqual([0, 4], placed.Camera.Keyframes.Select(k => k.Frame));
Assert.Null(placed.PendingFrames);
Assert.Null(ProjectSettings.TranslateFramePositions(placed.ToJson(), null, arrived));
}
[Test]
public void SettingsSentBackLandOnTheSamePhotos()
{
var photos = Enumerable.Range(0, 5).Select(Photo).ToList();
var server = Frames(photos[1..]);
var here = Frames(photos);
// Photo 0 is only here: its exclusion waits on the server, and comes back as a position.
var project = new ProjectSettings { ExcludedFrames = [0, 2], HeroFrame = 4 };
var sent = Assert.NotNull(ProjectSettings.TranslateFramePositions(project.ToJson(), here, server));
var back = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(sent, server, here)));
Assert.SequenceEqual([1], ProjectSettings.FromJson(sent).ExcludedFrames);
Assert.Equal(3, ProjectSettings.FromJson(sent).HeroFrame);
Assert.Equal(project.ToJson(), back.ToJson());
}
[Test]
public void AHeroOrKeyframeChosenSinceIsNewerThanTheOneThatWaited()
{
var photos = Enumerable.Range(0, 3).Select(Photo).ToList();
var waiting = new ProjectSettings
{
HeroFrame = 2,
Camera = new CameraSettings { Keyframes = [new CameraKey(0, 0.2, 0.2, 2, 0)] },
PendingFrames = [new PendingFrame { Sha256 = photos[0].Sha256, Size = photos[0].Size, Hero = true, Keyframes = [new CameraKey(9, 0.7, 0.7, 1, 0)] }],
};
var placed = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(waiting.ToJson(), null, Frames(photos))));
Assert.Equal(2, placed.HeroFrame);
Assert.Count(1, placed.Camera.Keyframes);
Assert.Equal(0.2, placed.Camera.Keyframes[0].CenterX);
Assert.Null(placed.PendingFrames);
}
[Test]
public void AHeroChosenSinceAnotherWaitedStaysTheHeroWhenItMustWaitToo()
{
// This PC chose photo 3 as the hero before the server had it, so it waits there; an editor on the server then
// chose photo 2, which this PC lacks.
var photos = Enumerable.Range(0, 4).Select(Photo).ToList();
var server = Frames(photos[..3]);
var here = Frames([photos[0], photos[1], photos[3]]);
var edited = new ProjectSettings
{
ExcludedFrames = [0],
HeroFrame = 2,
PendingFrames = [new PendingFrame { Sha256 = photos[3].Sha256, Size = photos[3].Size, CapturedAt = photos[3].CapturedAt, Hero = true }],
};
var taken = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(edited.ToJson(), server, here)));
Assert.Null(taken.HeroFrame);
Assert.SequenceEqual([0], taken.ExcludedFrames);
var waiting = Assert.NotNull(taken.PendingFrames);
Assert.Count(1, waiting);
Assert.True(waiting[0].Hero && waiting[0].Sha256 == photos[2].Sha256, "the newer hero waits for its photo");
Assert.True(taken.HeroPending);
// Its photo arrives: it is the hero again.
var arrived = Frames([photos[0], photos[1], photos[2], photos[3]]);
var moved = ProjectSettings.MoveFramePositions(taken.ToJson(), new Dictionary<int, int> { [2] = 3 }) ?? taken.ToJson();
var placed = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(moved, null, arrived)));
Assert.Equal(2, placed.HeroFrame);
Assert.Null(placed.PendingFrames);
// A hero chosen here while one waits clears the waiting one, even before its photo arrives.
var chosen = (taken with { HeroFrame = 1 }).ToJson();
var cleared = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(chosen, null, here)));
Assert.Equal(1, cleared.HeroFrame);
Assert.Null(cleared.PendingFrames);
}
[Test]
public void AProjectNamingNoFrameCrossesAsItIs()
{
var json = new ProjectSettings { Exposure = new ExposureSettings { DeflickerWindow = new Auto<int>().WithManual(41) } }.ToJson();
Assert.False(ProjectSettings.NamesFrames(json));
Assert.False(json.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase), "an old project reads and writes as it did");
Assert.False(ProjectSettings.NamesFrames("not json"));
Assert.True(ProjectSettings.NamesFrames("""{ "HeroFrame": 0 }"""));
Assert.Null(ProjectSettings.TranslateFramePositions(json, Frames([Photo(1)]), Frames([Photo(2)])));
Assert.Null(ProjectSettings.TranslateFramePositions("[1]", null, Frames([])));
}
[Test]
public void PhotosMatchByHashElseBySizeAndCaptureTime()
{
var time = new DateTime(2026, 9, 28, 18, 0, 0, 123);
var hashed = new FramePhoto(new string('a', 64), 100, time);
Assert.True(hashed.Matches(new FramePhoto(new string('A', 64), 1, null)));
Assert.False(hashed.Matches(new FramePhoto(new string('b', 64), 100, time)));
Assert.True(hashed.Matches(new FramePhoto("", 100, time.AddTicks(9_999))));
Assert.False(hashed.Matches(new FramePhoto(null, 100, time.AddMilliseconds(1))));
Assert.False(new FramePhoto(null, 100, null).Matches(new FramePhoto(null, 100, null)));
var frames = Frames([new FramePhoto(null, 100, time), hashed]);
Assert.Equal(1, frames.IndexOf(new FramePhoto(new string('a', 64), 100, null)));
Assert.Equal(0, frames.IndexOf(new FramePhoto(null, 100, time)));
Assert.Null(frames.IndexOf(new FramePhoto(null, 101, time)));
}
private static FramePhoto Photo(int seed) =>
new(Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData([(byte)seed])), 1000 + seed, new DateTime(2026, 9, 28, 18, 0, 0).AddSeconds(10 * seed));
private static FramePhotos Frames(IEnumerable<FramePhoto> photos) => new(photos.Select((p, i) => (i, p)));
[Test]
public void BuiltInPresetIdsAreUnique() =>
Assert.Equal(ExportPresets.BuiltIn.Count, ExportPresets.BuiltIn.Select(p => p.Id).Distinct().Count());
[Test]
public void BitRateFollowsBitsPerPixel()
{
var p = Assert.NotNull(ExportPresets.Find("4k-hevc10-archive"));
// 0.30 × 3840 × 2160 × 24 ≈ 59.7 Mb/s (archive budget); share presets use the codec default.
Assert.Equal(59_719_680L, p.EffectiveBitRate(3840, 2160, new Rational(24, 1)));
Assert.Equal(19_906_560L, ExportPresets.Find("4k-h264")!.EffectiveBitRate(3840, 2160, new Rational(24, 1)));
var s = p.ToEncodeSettings("out.mp4", 3840, 2160);
Assert.Equal(24, s.GopLength);
Assert.Equal(10, s.BitDepth);
}
}