feat: export panel and Render menu, playback options, videos library (owner review 1 phase 5) (#27)
CI / Build and test (push) Successful in 9m41s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 9s
Release / Build, test and publish (push) Successful in 14m49s
CI / PostgreSQL 16 integration (push) Successful in 8m51s
CI / PostgreSQL 17 integration (push) Successful in 9m48s
CI / Docker image (push) Successful in 54s
Release / Server image (push) Successful in 1m39s

Owner review 1 R3, R8, R9. A grouped Export step and Render menu; encoding, playback (reverse, boomerang, loops, fades, hold) and still frames; one videos library on the desktop and the server with a verified trash and copies to a videos folder.

Closes #21

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 #27.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-05 09:18:40 +01:00
1 parent 188b2c2e55
commit 728ffa35cb
729 files changed
+26954 -1652

No files matched your search

@@ -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\": 3", StringComparison.Ordinal);
var json = (Sample() with { Workspace = workspace }).ToJson().Replace("\"version\": 1", "\"version\": 4", 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\": 3", StringComparison.Ordinal);
var plain = Sample().ToJson().Replace("\"version\": 1", "\"version\": 4", 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": 3, "pendingFrames": [ { "size": 1001, "capturedAt": "2026-09-28T18:00:10", "excluded": true } ] }""";
var newer = """{ "version": 4, "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": 3, "excludedFrames": [1], "exposure": { "exposureOffsetEv": 1.5 }, "grade": { "look": "film" } }""";
var newer = """{ "version": 4, "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(3, ProjectContent.FormatOf(newer));
Assert.Equal(4, ProjectContent.FormatOf(newer));
Assert.Equal(1, ProjectContent.FormatOf("""{ "exposure": {} }"""));
// Its positions are a newer Chronos's to translate: only the text is made canonical.
@@ -570,23 +570,130 @@ public sealed class ProjectSettingsTests
[Test]
public void ANewerFormatStaysReadOnlyAndKeepsItsNumber()
{
const string newer = """{ "version": 3, "camera": { "rotate": 90 }, "look": { "filter": "film", "grain": 0.2 } }""";
const string newer = """{ "version": 4, "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);
Assert.Equal(4, read.WrittenFormat);
var canonical = ProjectContent.Canonical(newer);
Assert.Equal(3, ProjectContent.FormatOf(canonical));
Assert.Equal(4, 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.
// Format-2 and format-3 projects are this Chronos's own (written as the format they need); text without a version
// is format 1.
Assert.False(ProjectSettings.FromJson("""{ "version": 2 }""").IsNewerFormat);
Assert.Equal(1, ProjectSettings.FromJson("""{ "version": 2 }""").WrittenFormat);
Assert.False(ProjectSettings.FromJson("""{ "version": 3 }""").IsNewerFormat);
Assert.Equal(1, ProjectSettings.FromJson("""{ "version": 3 }""").WrittenFormat);
Assert.Equal(1, ProjectContent.FormatOf("""{ "camera": {} }"""));
Assert.Equal(1, ProjectContent.FormatOf(null));
}
[Test]
public void APlaybackAtItsDefaultIsWrittenAsNone()
{
var plain = new ProjectSettings().ToJson();
foreach (var playback in new[]
{
new PlaybackSettings(),
new PlaybackSettings { Direction = "Forward", Loops = 1, FadeIn = 0, FadeOut = 0, HoldEnd = 0 },
new PlaybackSettings { Loops = 0, FadeIn = double.NaN, HoldEnd = -2 },
})
{
Assert.True(playback.IsDefault);
var settings = new ProjectSettings { Export = new ExportSettings { Playback = playback } };
Assert.Equal(ProjectSettings.BaseVersion, settings.RequiredFormat);
Assert.Equal(plain, settings.ToJson());
}
Assert.False(plain.Contains("playback", StringComparison.Ordinal));
Assert.Null(ProjectSettings.FromJson(plain).Export.Playback);
}
[Test]
public void ThePlaybackRaisesTheFormatToThreeAndLeavesOutItsDefaults()
{
var plain = new ProjectSettings();
var turned = plain with { Camera = new CameraSettings { Rotate = 90 } };
var reversed = new PlaybackSettings { Direction = PlaybackDirection.Reverse, Loops = 1, FadeIn = 0 };
Assert.Equal((1, 2), (plain.RequiredFormat, turned.RequiredFormat));
foreach (var settings in new[]
{
plain with { Export = plain.Export with { Playback = reversed } },
turned with { Export = plain.Export with { Playback = new PlaybackSettings { FadeOut = 2.5 } } },
plain with { Export = plain.Export with { Playback = new PlaybackSettings { Loops = 3, HoldEnd = 1 } } },
})
{
Assert.Equal(ProjectSettings.PlaybackVersion, settings.RequiredFormat);
Assert.Equal(3, ProjectSettings.CurrentVersion);
var json = settings.ToJson();
Assert.Contains("\"version\": 3", json);
var back = ProjectSettings.FromJson(json);
Assert.Equal(3, back.Version);
Assert.False(back.IsNewerFormat);
Assert.Equal(json, back.ToJson());
Assert.Equal(json, ProjectContent.Canonical(json));
}
// Each member at its default is left out of the text.
var text = (plain with { Export = plain.Export with { Playback = reversed } }).ToJson();
var written = System.Text.Json.Nodes.JsonNode.Parse(text)!["export"]!["playback"]!.AsObject().Select(p => p.Key).ToList();
Assert.SequenceEqual(["direction"], written);
// Every member reads back; the effective values clamp what is out of range.
var full = ProjectSettings.FromJson("""{ "export": { "playback": { "direction": "boomerang", "loops": 40, "fadeIn": 1.5, "fadeOut": 99, "holdEnd": 3 } } }""");
var playback = Assert.NotNull(full.Export.Playback);
Assert.Equal(("boomerang", (int?)40, (double?)1.5, (double?)99.0, (double?)3.0), (playback.Direction, playback.Loops, playback.FadeIn, playback.FadeOut, playback.HoldEnd));
Assert.Equal((PlaybackSettings.MaxLoops, PlaybackSettings.MaxFadeSeconds), (playback.EffectiveLoops, playback.EffectiveFadeOut));
Assert.Equal(3, full.RequiredFormat);
// A direction this Chronos does not know renders forward but is kept, and keeps the format.
var unknown = ProjectSettings.FromJson("""{ "export": { "playback": { "direction": "pingpong", "speed": 2 } } }""");
var kept = Assert.NotNull(unknown.Export.Playback);
Assert.Equal(PlaybackDirection.Forward, kept.EffectiveDirection);
Assert.False(kept.IsDefault);
Assert.Equal(3, unknown.RequiredFormat);
Assert.Contains("\"speed\": 2", unknown.ToJson());
// Taken away again, the project is format 1 with the text it had before.
var undone = ProjectSettings.FromJson(text) with { Export = plain.Export };
Assert.Equal(plain.ToJson(), undone.ToJson());
}
[Test]
public void AFormatThreeFileReadByAFormatTwoBuildKeepsItsPlayback()
{
var path = Path.Combine(TestContext.FixturesDirectory, "settings", "format3-playback.json");
var fixture = File.ReadAllText(path);
var settings = ProjectSettings.FromJson(fixture);
Assert.Equal(3, settings.Version);
var playback = Assert.NotNull(settings.Export.Playback);
Assert.Equal((PlaybackDirection.Boomerang, 2, 1.5, 2.0, 3.0), (playback.EffectiveDirection, playback.EffectiveLoops, playback.EffectiveFadeIn, playback.EffectiveFadeOut, playback.EffectiveHoldEnd));
Assert.Equal((3, 90), (settings.RequiredFormat, settings.Camera.Rotate));
var canonical = ProjectContent.Canonical(settings.ToJson());
Assert.Equal(3, ProjectContent.FormatOf(canonical));
// A format-2 build knows no playback: it lands in the export's Extra and is written back where it was.
var old = Format2Build.Read(canonical);
Assert.True(old.Export.Extra!.ContainsKey("playback"));
Assert.Equal(3, old.Version);
Assert.Equal(canonical, Format2Build.Write(old).ReplaceLineEndings("\n"));
Assert.True(ProjectContent.MatchesHash(Format2Build.Write(old), ProjectContent.Hash(canonical)));
var export = System.Text.Json.Nodes.JsonNode.Parse(canonical)!["export"]!.AsObject().Select(p => p.Key).ToList();
Assert.Equal("playback", export[^1]);
}
/// <summary>
/// The settings as a format-2 build reads and writes them: its export without the playback (owner review 1, phase 5),
/// with the same serialiser options. What it does not know lands in <c>Extra</c>.
/// </summary>
private static class Format2Build
{
public static Format2Project Read(string json) => System.Text.Json.JsonSerializer.Deserialize(json, OldJson.Default.Format2Project)!;
public static string Write(Format2Project project) => System.Text.Json.JsonSerializer.Serialize(project, OldJson.Default.Format2Project);
}
/// <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>.
@@ -630,6 +737,39 @@ internal sealed record OldProject
public Dictionary<string, System.Text.Json.JsonElement>? Extra { get; set; }
}
/// <summary>A format-2 build's export (before owner review 1, phase 5): no playback.</summary>
internal sealed record Format2Export
{
public Auto<string> Preset { get; init; } = new();
public ExportOverrides Overrides { get; init; } = new();
public string NameTemplate { get; init; } = "{date} {title} - {preset}";
public string? Folder { get; init; }
public IReadOnlyList<string> Batch { get; init; } = [];
public bool SyncToServer { get; init; }
[System.Text.Json.Serialization.JsonExtensionData]
public Dictionary<string, System.Text.Json.JsonElement>? Extra { get; set; }
}
/// <summary>A format-2 build's project (owner review 1, phase 4): phase 4's camera and look, the export without playback.</summary>
internal sealed record Format2Project
{
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 CameraSettings Camera { get; init; } = new();
public StackSettings Stack { get; init; } = new();
public Format2Export Export { get; init; } = new();
public IReadOnlyList<int> ExcludedFrames { get; init; } = [];
public int? HeroFrame { get; init; }
public IReadOnlyList<PendingFrame>? PendingFrames { get; init; }
public LookSettings? Look { 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,
@@ -637,4 +777,5 @@ internal sealed record OldProject
UseStringEnumConverter = true,
PropertyNameCaseInsensitive = true)]
[System.Text.Json.Serialization.JsonSerializable(typeof(OldProject))]
[System.Text.Json.Serialization.JsonSerializable(typeof(Format2Project))]
internal sealed partial class OldJson : System.Text.Json.Serialization.JsonSerializerContext;
@@ -26,6 +26,9 @@ internal sealed class CapturingEncoderProvider(string name, params EncoderCapabi
/// <summary>When set, WriteFrame throws this for the frame with that zero-based index.</summary>
public (int Frame, Exception Error)? FailAt { get; set; }
/// <summary>The settings each session says it did not take (<see cref="IVideoEncoderSession.Ignored"/>).</summary>
public IReadOnlyList<EncoderSetting> Ignores { get; set; } = [];
public bool CanEncode(EncodeSettings settings) => capabilities.Any(c =>
c.Codec == settings.Codec && EncoderSelector.Takes(c, settings.Width, settings.Height) && (settings.BitDepth == 8 || c.SupportsTenBit));
@@ -54,5 +57,7 @@ internal sealed class CapturingEncoderProvider(string name, params EncoderCapabi
public void Complete() => encode.Completed = true;
public void Dispose() => encode.Disposed = true;
public IReadOnlyList<EncoderSetting> Ignored => owner.Ignores;
}
}
@@ -0,0 +1,145 @@
using Chronos.Core.Imaging;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Video;
using Chronos.Testing;
namespace Chronos.Core.Tests.Render;
/// <summary>The output program of the playback settings (owner review 1, R8): order, loops, hold and fades.</summary>
public sealed class OutputProgramPlaybackTests
{
private static readonly Rational Fps25 = new(25, 1);
[Theory]
[Case("forward", 1, new[] { 0, 1, 2, 3 })]
[Case("forward", 2, new[] { 0, 1, 2, 3, 0, 1, 2, 3 })]
[Case("forward", 3, new[] { 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3 })]
[Case("reverse", 1, new[] { 3, 2, 1, 0 })]
[Case("reverse", 2, new[] { 3, 2, 1, 0, 3, 2, 1, 0 })]
[Case("reverse", 3, new[] { 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0 })]
[Case("boomerang", 1, new[] { 0, 1, 2, 3, 2, 1, 0 })]
[Case("boomerang", 2, new[] { 0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0 })]
[Case("boomerang", 3, new[] { 0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0 })]
public void DirectionsAndLoopsGiveThePlanIndicesInOrder(string direction, int loops, int[] expected)
{
var frames = Frames(3600, 3600, 3600, 7200);
var program = OutputProgram.Build(frames, new PlaybackSettings { Direction = direction, Loops = loops }, Fps25);
Assert.SequenceEqual(expected, program.Entries.Select(e => e.PlanIndex));
// No frame is emitted twice in a row: neither the turn of a boomerang nor the joint of two passes.
for (var i = 1; i < program.Count; i++) Assert.NotEqual(program.Entries[i - 1].PlanIndex, program.Entries[i].PlanIndex);
Assert.True(program.Entries.All(e => e.Gain == 1 && e.Duration90k == frames[e.PlanIndex].Duration90k));
Assert.Equal(expected.Sum(i => frames[i].Duration90k), program.Duration90k);
Assert.Equal(0, program.Warnings.Count);
}
[Test]
public void ASingleFrameBoomerangPlaysOncePerLoop()
{
var program = OutputProgram.Build(Frames(3600), new PlaybackSettings { Direction = PlaybackDirection.Boomerang, Loops = 3 }, Fps25);
Assert.SequenceEqual([0, 0, 0], program.Entries.Select(e => e.PlanIndex));
}
[Test]
public void ValuesOutOfRangeAreClamped()
{
var program = OutputProgram.Build(Frames(3600, 3600), new PlaybackSettings { Loops = 50 }, Fps25);
Assert.Equal(2 * PlaybackSettings.MaxLoops, program.Count);
var negative = OutputProgram.Build(Frames(3600, 3600), new PlaybackSettings { Loops = -3, FadeIn = -1, HoldEnd = double.NaN }, Fps25);
Assert.Equal((2, 7200L), (negative.Count, negative.Duration90k));
}
[Test]
public void TheHoldExtendsTheLastFrameByWholePeriods()
{
var program = OutputProgram.Build(Frames(3600, 3600, 3600), new PlaybackSettings { Direction = PlaybackDirection.Reverse, HoldEnd = 2 }, Fps25);
Assert.SequenceEqual([2, 1, 0], program.Entries.Select(e => e.PlanIndex));
Assert.SequenceEqual([3600L, 3600, 3600 + 180000], program.Entries.Select(e => e.Duration90k));
Assert.Approximately(2.12, program.DurationSeconds, 1e-12);
// A hold shorter than a period still shows one more period.
var brief = OutputProgram.Build(Frames(3600), new PlaybackSettings { HoldEnd = 0.001 }, Fps25);
Assert.Equal(7200L, brief.Duration90k);
}
[Test]
public void AHeldFrameInsideAFadeIsSplitPerPeriod()
{
// The first frame is held for ten periods (0.4 s) and the fade in lasts 0.2 s (five periods).
var program = OutputProgram.Build(Frames(36000, 3600, 3600), new PlaybackSettings { FadeIn = 0.2 }, Fps25);
Assert.Equal(12, program.Count);
Assert.True(program.Entries.Take(10).All(e => e.PlanIndex == 0 && e.Duration90k == 3600));
Assert.SequenceEqual([1, 2], program.Entries.Skip(10).Select(e => e.PlanIndex));
for (var k = 0; k < 10; k++)
Assert.Approximately(ColorSpace.SrgbToLinear(double.Min(1, k / 5.0)), program.Entries[k].Gain, 1e-12, $"period {k}");
Assert.Equal(0.0, program.Entries[0].Gain);
Assert.Equal(43200L, program.Duration90k);
// The fade out reaches into the hold at the end: the hold is split as well, the last period black.
var fadeOut = OutputProgram.Build(Frames(3600, 3600), new PlaybackSettings { FadeOut = 0.2, HoldEnd = 0.4 }, Fps25);
Assert.Equal(1 + 11, fadeOut.Count);
Assert.Equal(1.0, fadeOut.Entries[0].Gain);
Assert.Equal(0.0, fadeOut.Entries[^1].Gain);
Assert.Monotonic(fadeOut.Entries.Select(e => e.Gain), decreasing: true);
Assert.Equal(7200L + 36000, fadeOut.Duration90k);
}
[Test]
public void FadesLongerThanHalfTheProgramAreShortenedWithAWarning()
{
// 0.4 s of video with two 1 s fades: together they get half of it, 0.1 s each.
var program = OutputProgram.Build(Frames(Enumerable.Repeat(3600L, 10).ToArray()), new PlaybackSettings { FadeIn = 1, FadeOut = 1 }, Fps25);
Assert.Count(1, program.Warnings);
Assert.Equal(OutputProgram.FadesShortenedWarning, program.Warnings[0].Key);
Assert.Equal(10, program.Count);
Assert.Equal(0.0, program.Entries[0].Gain);
Assert.Equal(0.0, program.Entries[^1].Gain);
// 0.1 s is two and a half periods: the ramps take three frames each, the four between play as they are.
Assert.Approximately(ColorSpace.SrgbToLinear(0.4), program.Entries[1].Gain, 1e-12);
Assert.Approximately(ColorSpace.SrgbToLinear(0.8), program.Entries[2].Gain, 1e-12);
Assert.SequenceEqual([1.0, 1, 1, 1], program.Entries.Skip(3).Take(4).Select(e => e.Gain));
Assert.Approximately(ColorSpace.SrgbToLinear(0.8), program.Entries[7].Gain, 1e-12);
// Fades that fit leave no warning.
Assert.Equal(0, OutputProgram.Build(Frames(Enumerable.Repeat(3600L, 10).ToArray()), new PlaybackSettings { FadeIn = 0.08, FadeOut = 0.12 }, Fps25).Warnings.Count);
}
[Test]
public void TheTotalDurationIsExactOnTheNinetyKilohertzClock()
{
var rate = Rational.Fps2997;
var frames = Frames(Enumerable.Repeat(3003L, 7).ToArray());
var playback = new PlaybackSettings { Direction = PlaybackDirection.Boomerang, Loops = 2, HoldEnd = 0.5 };
var plain = OutputProgram.Build(frames, playback, rate);
// (7 + 6) + (6 + 6) frames of 3003 ticks, then 15 periods of hold at 30000/1001 (45045 ticks).
Assert.Equal(25, plain.Count);
Assert.Equal(25 * 3003L + RenderPlan.TicksAt(rate, 15), plain.Duration90k);
Assert.Equal(120120L, plain.Duration90k);
var faded = OutputProgram.Build(frames, playback with { FadeIn = 0.5, FadeOut = 0.5 }, rate);
Assert.Equal(plain.Duration90k, faded.Duration90k);
Assert.Equal(faded.Duration90k, faded.Entries.Sum(e => e.Duration90k));
Assert.Greater(faded.Count, plain.Count);
Assert.True(faded.Entries.All(e => e.Duration90k > 0));
}
[Test]
public void TheProgramOfAPlanUsesItsFrames()
{
var times = Enumerable.Range(0, 5).Select(i => (DateTime?)new DateTime(2026, 1, 1).AddSeconds(10 * i)).ToArray();
var plan = RenderPlan.Build(times, new ProjectSettings(), Fps25);
var program = OutputProgram.Build(plan, new PlaybackSettings { Direction = PlaybackDirection.Reverse }, Fps25);
Assert.Equal(plan.Frames.Count, program.Count);
Assert.Equal(plan.Duration90k, program.Duration90k);
Assert.Equal(plan.Frames.Count - 1, program.Entries[0].PlanIndex);
}
private static PlannedFrame[] Frames(params long[] durations)
{
var frames = new PlannedFrame[durations.Length];
long start = 0;
for (var i = 0; i < durations.Length; i++)
{
frames[i] = new PlannedFrame(i, i, i, 0, start, durations[i], i, (int)(durations[i] / 3600), 1, PlannedFrameFlags.None);
start += durations[i];
}
return frames;
}
}
@@ -0,0 +1,64 @@
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Video;
using Chronos.Testing;
namespace Chronos.Core.Tests.Render;
public sealed class OutputProgramTests
{
private static readonly Rational Fps25 = new(25, 1);
[Test]
public void TheDefaultPlaybackEmitsThePlanAsItIs()
{
var frames = Frames(3600, 3600, 7200);
foreach (var playback in new[] { null, new PlaybackSettings() })
{
var program = OutputProgram.Build(frames, playback, Fps25);
Assert.SequenceEqual([new ProgramEntry(0, 3600, 1), new ProgramEntry(1, 3600, 1), new ProgramEntry(2, 7200, 1)], program.Entries);
Assert.Equal((3, 14400L), (program.Count, program.Duration90k));
Assert.Approximately(0.16, program.DurationSeconds, 1e-12);
Assert.Equal(0, program.Warnings.Count);
}
Assert.Equal(0, OutputProgram.Build([], null, Fps25).Count);
}
[Test]
public void AnUnknownDirectionPlaysForwardWithAWarning()
{
var program = OutputProgram.Build(Frames(3600, 3600), new PlaybackSettings { Direction = "pingpong" }, Fps25);
Assert.SequenceEqual([0, 1], program.Entries.Select(e => e.PlanIndex));
Assert.Count(1, program.Warnings);
var warning = program.Warnings[0];
Assert.Equal(OutputProgram.DirectionUnknownWarning, warning.Key);
Assert.SequenceEqual(["pingpong"], warning.Args);
}
[Test]
public void ARateThatIsNotPositiveIsRefused() =>
Assert.Throws<ArgumentOutOfRangeException>(() => OutputProgram.Build(Frames(3600), null, new Rational(0, 1)));
[Test]
public void TheKindOfARenderFollowsItsColumnElseItsCodec()
{
Assert.Equal(RenderKind.Still, RenderKind.Of("still", "png-sequence"));
Assert.Equal(RenderKind.Sequence, RenderKind.Of(null, "png-sequence"));
Assert.Equal(RenderKind.Sequence, RenderKind.Of(null, "Tiff16Sequence"));
Assert.Equal(RenderKind.Video, RenderKind.Of(null, "h264"));
Assert.Equal(RenderKind.Video, RenderKind.Of(null, null));
}
private static PlannedFrame[] Frames(params long[] durations)
{
var frames = new PlannedFrame[durations.Length];
long start = 0;
for (var i = 0; i < durations.Length; i++)
{
frames[i] = new PlannedFrame(i, i, i, 0, start, durations[i], i, 1, 1, PlannedFrameFlags.None);
start += durations[i];
}
return frames;
}
}
@@ -0,0 +1,245 @@
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Codecs.Png;
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Video;
using Chronos.Testing;
using static Chronos.Core.Tests.Render.RenderFixture;
namespace Chronos.Core.Tests.Render;
/// <summary>Renders of the output program (owner review 1, R8) and of a still ("Save frame").</summary>
public sealed class PlaybackRenderTests
{
private readonly TestContext _context;
public PlaybackRenderTests(TestContext context) => _context = context;
[Test]
public async Task TheResultCountsTheFramesAndTheDurationOfTheProgram()
{
var source = Source(6);
var input = Input(source, Playing(new PlaybackSettings { Direction = PlaybackDirection.Boomerang, Loops = 2, HoldEnd = 1 }));
var setup = Pipeline().Setup(input, new RenderTarget(Preset("png-sequence"), "out"));
// 6 + 5 frames, then 5 + 5 from the second frame on.
Assert.Equal(21, setup.Program.Count);
Assert.SequenceEqual([0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0], setup.Program.Entries.Select(e => e.PlanIndex));
var (encode, result) = await CaptureAsync(input, cancellationToken: _context.Cancellation);
Assert.Equal(21, result.FrameCount);
Assert.Equal(21, encode.Frames.Count);
Assert.Equal(setup.Program.Duration90k, encode.Durations.Sum());
Assert.Approximately((21 + 30) / 30.0, result.DurationSeconds, 1e-9);
Assert.Equal(3000L + 90000, encode.Durations[^1]);
Assert.Null(result.Kind);
// The way back shows the very pictures of the way out.
Assert.True(double.IsPositiveInfinity(Psnr(encode.Frames[4], encode.Frames[6])));
}
[Test]
public async Task FadesStartAndEndInBlackAndLeaveTheMiddleAlone()
{
var source = Source(12);
var (plain, _) = await CaptureAsync(Input(source), cancellationToken: _context.Cancellation);
var (faded, result) = await CaptureAsync(Input(source, Playing(new PlaybackSettings { FadeIn = 0.1, FadeOut = 0.1 })), cancellationToken: _context.Cancellation);
Assert.Equal(12, faded.Frames.Count);
Assert.Equal(0, result.Warnings.Count(w => w.Key == OutputProgram.FadesShortenedWarning));
Assert.LessOrEqual(Peak(faded.Frames[0]), 1e-6);
Assert.LessOrEqual(Peak(faded.Frames[^1]), 1e-6);
Assert.Less(Mean(faded.Frames[1]), Mean(plain.Frames[1]));
Assert.True(double.IsPositiveInfinity(Psnr(plain.Frames[6], faded.Frames[6])));
// The ramp brightens in and darkens out.
Assert.Monotonic(faded.Frames.Take(4).Select(Mean));
Assert.Monotonic(faded.Frames.TakeLast(4).Select(Mean), decreasing: true);
}
[Test]
public async Task ReversedStarTrailsGrowFromTheEnd()
{
var stars = Source(10, motion: i => (1.0 * i, 0), configure: o => o with { StarField = true, StartEv = 0, EndEv = 0, StarCount = 60 });
var trails = new StackSettings { Mode = StackSetting.StarTrails, Length = 0 };
var (plain, _) = await CaptureAsync(Input(stars), cancellationToken: _context.Cancellation);
var (reversed, _) = await CaptureAsync(Input(stars, Playing(new PlaybackSettings { Direction = PlaybackDirection.Reverse }) with { Stack = trails }),
cancellationToken: _context.Cancellation);
Assert.Equal(10, reversed.Frames.Count);
// The first picture is the last frame alone; every later one only adds trails.
Assert.True(double.IsPositiveInfinity(Psnr(plain.Frames[^1], reversed.Frames[0])));
for (var k = 1; k < reversed.Frames.Count; k++)
{
var previous = reversed.Frames[k - 1].Data;
var current = reversed.Frames[k].Data;
for (var i = 0; i < current.Length; i++) Assert.True(current[i] >= previous[i] - 1e-6f, $"pixel {i} darkened at frame {k}");
}
// A boomerang with trails plays forward and says so.
var (boomerang, result) = await CaptureAsync(Input(stars, Playing(new PlaybackSettings { Direction = PlaybackDirection.Boomerang }) with { Stack = trails }),
cancellationToken: _context.Cancellation);
Assert.Equal(10, boomerang.Frames.Count);
Assert.Contains(result.Warnings, w => w.Key == OutputProgram.BoomerangStackWarning);
}
[Test]
public async Task EachLoopOfStarTrailsGrowsItsTrailsAgain()
{
var stars = Source(6, motion: i => (1.0 * i, 0), configure: o => o with { StarField = true, StartEv = 0, EndEv = 0, StarCount = 60 });
var trails = new StackSettings { Mode = StackSetting.StarTrails, Length = 0 };
var (looped, _) = await CaptureAsync(Input(stars, Playing(new PlaybackSettings { Loops = 2 }) with { Stack = trails }),
cancellationToken: _context.Cancellation);
Assert.Equal(12, looped.Frames.Count);
// The second pass starts from nothing again: frame 6 + k is frame k, never the finished trails of the first pass.
for (var k = 0; k < 6; k++)
Assert.True(double.IsPositiveInfinity(Psnr(looped.Frames[k], looped.Frames[6 + k])), $"frame {6 + k} differs from frame {k}");
Assert.False(double.IsPositiveInfinity(Psnr(looped.Frames[5], looped.Frames[6])), "the loop seam shows the trails start again");
}
[Test]
public async Task AMedianWindowIsTheSameFrameInEitherDirection()
{
var source = Source(9);
var median = new StackSettings { Mode = StackSetting.Median, Length = 5 };
var (forward, _) = await CaptureAsync(Input(source, Plain with { Stack = median }), cancellationToken: _context.Cancellation);
var (boomerang, _) = await CaptureAsync(Input(source, Playing(new PlaybackSettings { Direction = PlaybackDirection.Boomerang, Loops = 2 }) with { Stack = median }),
cancellationToken: _context.Cancellation);
int[] order = [0, 1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1, 0];
Assert.Equal(order.Length, boomerang.Frames.Count);
for (var k = 0; k < order.Length; k++)
Assert.True(double.IsPositiveInfinity(Psnr(forward.Frames[order[k]], boomerang.Frames[k])), $"program frame {k} (plan frame {order[k]})");
}
[Test]
public void TheEstimateGrowsWithTheLoopsAndTheHold()
{
var source = Source(12);
var export = Preset("png-sequence");
var once = Pipeline().Setup(Input(source), new RenderTarget(export, "out"));
var thrice = Pipeline().Setup(Input(source, Playing(new PlaybackSettings { Loops = 3, HoldEnd = 1 })), new RenderTarget(export, "out"));
Assert.Equal(3 * once.Workload().OutputFrames, thrice.Workload().OutputFrames);
Assert.Equal(3 * 12 + 30, thrice.Workload().OutputPeriods);
Assert.Approximately(once.Workload().DurationSeconds * 3 + 1, thrice.Workload().DurationSeconds, 1e-9);
Assert.Greater(thrice.Estimate().Time.TotalSeconds, once.Estimate().Time.TotalSeconds);
Assert.Greater(thrice.Estimate().Bytes, 3 * once.Estimate().Bytes);
}
[Theory]
[Case("png-sequence", 8)]
[Case("jpeg-sequence", 8)]
[Case("tiff16-sequence", 8)]
public async Task AStillWritesOneImageAtTheOutputSize(string presetId, int bitDepth)
{
var dir = _context.CreateTempDirectory();
var source = Source(8);
var export = Preset(presetId) with { BitDepth = bitDepth };
var context = new ExportNameContext { Date = new DateTime(2026, 9, 28), Title = "Harbour", PresetName = "Still", Codec = export.Codec };
var path = ExportNaming.StillPath(dir, "{date} {title}", context, 4);
Assert.Equal("2026-09-28 Harbour - 0005" + VideoCodecInfo.FileExtension(export.Codec), Path.GetFileName(path));
// Playback never reaches a still.
var input = Input(source, Playing(new PlaybackSettings { Direction = PlaybackDirection.Reverse, FadeIn = 5 }));
var target = new RenderTarget(export, path, StillFrame: 4);
var setup = Pipeline().Setup(input, target);
Assert.Equal(1, setup.Program.Count);
Assert.True(setup.Encoder.Settings.SingleImage);
Assert.Equal(export.Codec == VideoCodec.Tiff16Sequence ? 16 : 8, setup.Encoder.Settings.BitDepth);
Assert.Equal((1, 1, 0.0), (setup.Workload().OutputFrames, setup.Workload().OutputPeriods, setup.Workload().DurationSeconds));
var result = await Pipeline().RenderAsync(input, target, cancellationToken: _context.Cancellation);
Assert.SequenceEqual([Path.GetFileName(path)], Directory.GetFileSystemEntries(dir).Select(Path.GetFileName));
Assert.Equal((1, 0.0, RenderKind.Still), (result.FrameCount, result.DurationSeconds, result.Kind));
Assert.Equal(new FileInfo(path).Length, result.Bytes);
var entity = result.ToEntity(Guid.NewGuid(), "PNG", null, "test");
Assert.Equal((RenderKind.Still, 0.0, 0.0), (entity.Kind, entity.Fps, entity.DurationSeconds));
var bytes = File.ReadAllBytes(path);
using var decoded = export.Codec switch
{
VideoCodec.JpegSequence => JpegDecoder.DecodeToLinear(bytes),
VideoCodec.PngSequence => PngDecoder.DecodeToLinear(bytes),
_ => TiffImageReader.Decode(bytes),
};
Assert.Equal((96, 64), (decoded.Width, decoded.Height));
using var expected = source.Sequence.Render(4);
_context.Log($"{presetId}: {result.Bytes} bytes, PSNR {Psnr(expected, decoded):F1} dB");
Assert.Greater(Psnr(expected, decoded), 25);
}
[Test]
public async Task AStillRendersTheFrameItNames()
{
var source = Source(8);
var (plain, _) = await CaptureAsync(Input(source), cancellationToken: _context.Cancellation);
var capture = new CapturingEncoderProvider("capture", new EncoderCapability(VideoCodec.PngSequence, "Capture", false, 8192, 8192, true));
var result = await Pipeline(capture).RenderAsync(Input(source), new RenderTarget(Preset("png-sequence"), "still.png", 6), cancellationToken: _context.Cancellation);
var encode = capture.Encodes.Single();
Assert.True(encode.Settings.SingleImage);
Assert.Equal(1, encode.Frames.Count);
Assert.True(double.IsPositiveInfinity(Psnr(plain.Frames[6], encode.Frames[0])));
Assert.Equal(RenderKind.Still, result.Kind);
}
[Test]
public async Task AStillOfAFrameTheSequenceDoesNotHaveIsARenderError()
{
var source = Source(4);
var error = await Assert.ThrowsAsync<RenderException>(() => Pipeline().RenderAsync(Input(source), new RenderTarget(Preset("png-sequence"), "x.png", 4)));
Assert.Equal("Export.Render.StillMissing", error.ReasonKey);
Assert.Throws<RenderException>(() => Pipeline().Setup(Input(source), new RenderTarget(Preset("png-sequence"), "x.png", -1)));
}
[Test]
public void AStillIsOneFileWhateverTheSequenceCodec()
{
var provider = new Chronos.Core.Video.Managed.ManagedEncoderProvider();
EncodeSettings Still(VideoCodec codec, int depth) => new() { OutputPath = "x", Codec = codec, Width = 8, Height = 8, FrameRate = new Rational(30, 1), BitDepth = depth, SingleImage = true };
Assert.True(provider.CanEncode(Still(VideoCodec.PngSequence, 16)));
Assert.True(provider.CanEncode(Still(VideoCodec.JpegSequence, 8)));
Assert.True(provider.CanEncode(Still(VideoCodec.Tiff16Sequence, 16)));
Assert.False(provider.CanEncode(Still(VideoCodec.LinearDngSequence, 16)));
Assert.False(provider.CanEncode(Still(VideoCodec.Gif, 8)));
Assert.False(provider.CanEncode(Still(VideoCodec.Mjpeg, 8)));
}
[Test]
public void AStillTargetNeedsFormatThree()
{
var export = ExportResolver.Resolve(new ExportSettings());
Assert.Equal(1, RenderRules.RequiredFormat(new ProjectSettings(), new RenderTarget(export, "x"), 6000, 4000));
Assert.Equal(RenderRules.StillFormat, RenderRules.RequiredFormat(new ProjectSettings(), new RenderTarget(export, "x", 3), 6000, 4000));
// The playback a job renders raises the settings it carries to format 3.
var playing = new ProjectSettings { Export = new ExportSettings { Playback = new PlaybackSettings { Direction = PlaybackDirection.Reverse } } };
Assert.Equal(ProjectSettings.PlaybackVersion, RenderRules.RequiredFormat(playing, new RenderTarget(export, "x"), 6000, 4000));
}
[Test]
public void AFadeScalesEverySampleInPlace()
{
using var frame = new ImageBuffer(7, 5, 3);
frame.Data.Fill(0.5f);
FrameFinish.Fade(frame, 1);
Assert.True(frame.Data.ToArray().All(v => v == 0.5f));
FrameFinish.Fade(frame, 0.5);
Assert.True(frame.Data.ToArray().All(v => v == 0.25f));
FrameFinish.Fade(frame, double.NaN);
Assert.True(frame.Data.ToArray().All(v => v == 0.25f));
FrameFinish.Fade(frame, 0);
Assert.True(frame.Data.ToArray().All(v => v == 0));
}
private static ProjectSettings Playing(PlaybackSettings playback) => Plain with { Export = Plain.Export with { Playback = playback } };
private static double Peak(ImageBuffer frame)
{
var peak = 0f;
foreach (var v in frame.Data) peak = float.Max(peak, v);
return peak;
}
private static double Mean(ImageBuffer frame)
{
double sum = 0;
foreach (var v in frame.Data) sum += v;
return sum / frame.Data.Length;
}
}
@@ -142,6 +142,21 @@ public sealed class RenderPipelineTests
Assert.Equal(4, encode.Frames.Count);
}
[Test]
public async Task SettingsTheEncoderIgnoredAreRenderWarnings()
{
var capture = new CapturingEncoderProvider("capture", new EncoderCapability(VideoCodec.PngSequence, "Capture", false, 4096, 4096, true))
{
Ignores = [EncoderSetting.RateControl, EncoderSetting.BFrames],
};
var result = await Pipeline(capture).RenderAsync(Input(Source()), Target(_context.CreateTempDirectory(), Preset("png-sequence")));
Assert.Contains(result.Warnings, w => w.Key == "Export.Encoder.Ignored.RateControl");
Assert.Contains(result.Warnings, w => w.Key == "Export.Encoder.Ignored.BFrames");
// Each key is a message of the catalogue.
foreach (var setting in Enum.GetValues<EncoderSetting>())
Assert.NotEqual("Export.Encoder.Ignored." + setting, Chronos.Core.Localization.Loc.L("Export.Encoder.Ignored." + setting));
}
[Test]
public async Task ProgressReportsEveryFrameAndPreviews()
{
@@ -19,8 +19,18 @@ public sealed class RenderRulesTests
// 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));
var newer = ProjectSettings.FromJson("""{ "version": 4 }""", allowNewer: true);
Assert.Equal(4, RenderRules.RequiredFormat(newer, Export("4k-h264"), 6000, 4000));
}
[Test]
public void APlaybackOrAStillNeedsFormatThree()
{
var playback = new ProjectSettings { Export = new ExportSettings { Playback = new PlaybackSettings { FadeIn = 1 } } };
Assert.Equal(3, RenderRules.RequiredFormat(playback, Export("4k-h264"), 6000, 4000));
Assert.Equal(1, RenderRules.RequiredFormat(new ProjectSettings(), Export("4k-h264"), 6000, 4000, still: false));
Assert.Equal(RenderRules.StillFormat, RenderRules.RequiredFormat(new ProjectSettings(), Export("4k-h264"), 6000, 4000, still: true));
Assert.SequenceEqual([Chronos.Core.Video.VideoCodec.PngSequence, Chronos.Core.Video.VideoCodec.JpegSequence, Chronos.Core.Video.VideoCodec.Tiff16Sequence], RenderRules.StillCodecs);
}
private static CameraSettings Camera(string aspect) => new() { Aspect = new Auto<string>().WithManual(aspect) };