feat: phase 5 groundwork (playback format 3, videos contracts, migration 0010, strings)

Lays down every contract the later parcels of owner review 1 phase 5 build on,
so they compile against shared types without touching each other's files.

- Settings format 3: export.playback (direction, loops, fades, hold), omitted
  at its default and member by member; RequiredFormat is 3 only while used.
- OutputProgram public API with a forward-only body; still-frame job
  parameters (StillFrame, StillPhoto) routed to format-3 nodes only.
- Render.Sha256/Kind, RenderCopy, RenderKind; JobKind.VideoCopy = 24.
- Migration 0010 (sqlite, postgres): renders.sha256/kind, ix_renders_created,
  render_copies without a foreign key.
- Videos protocol DTOs, client calls, ServerCapabilities.Videos (declared,
  not announced yet), ServerSettingsDto.VideosPath.
- IVideoLibrary with a NotImplemented stub registered on the server;
  TrashKind.Videos, VideoTrashNames, VideoErrors.
- en and it strings for the whole phase, five icons, decisions 1-22 and the
  open-question defaults; tests that used format 3 as "newer" now use 4.

Refs #21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-05 01:48:33 +01:00
1 parent 86aa07c1d7
commit d472dfdec1
67 files changed
+2233 -244

No files matched your search

@@ -204,7 +204,7 @@ public sealed class CameraTabTests
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");
Assert.Equal(2, 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");
@@ -232,7 +232,7 @@ public sealed class CameraTabTests
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);
Assert.Equal(2, session.Project.RequiredFormat);
Refresh(rows);
Assert.True(strength.IsApplicable);
Assert.Equal(1.0, strength.Value);
@@ -497,7 +497,7 @@ public sealed class EditorSessionTests
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");
Assert.Equal(2, session.Project.RequiredFormat, "a straighten needs format 2");
}
}
@@ -117,7 +117,7 @@ public sealed class ProjectHistoryTests
[Test]
public void SettingsOfANewerChronosAdoptedDropTheStepsInsteadOfMergingThem()
{
var newer = ProjectSettings.FromJson("""{ "version": 3, "exposure": { "exposureOffsetEv": 1.5 }, "grade": { "look": "film" } }""", allowNewer: true);
var newer = ProjectSettings.FromJson("""{ "version": 4, "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 })
@@ -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;
@@ -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;
}
}
@@ -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) };
@@ -13,6 +13,7 @@ public sealed class JobWireTests
[Case(JobKind.WorkspaceRender, 21, "workspace-render")]
[Case(JobKind.WorkspaceSend, 22, "workspace-send")]
[Case(JobKind.WorkspaceMove, 23, "workspace-move")]
[Case(JobKind.VideoCopy, 24, "video-copy")]
public void TheWorkspaceJobsKeepTheirValueAndName(JobKind kind, int value, string name)
{
Assert.Equal(value, (int)kind);
@@ -11,6 +11,7 @@ public abstract class MigrationTests(TestContext context) : RepositoryTest(conte
[
"archives", "sequences", "frames", "renders", "jobs", "media_cards", "import_history", "users", "tokens",
"render_nodes", "settings", "tags", "sequence_tags", "audit_log", "uploads", "schedules", "frame_removals", "projects", "project_versions",
"render_copies",
];
[Test]
@@ -103,6 +104,41 @@ public abstract class MigrationTests(TestContext context) : RepositoryTest(conte
Assert.Null(await chronos.Projects.GetVersionAsync(version.Id, Ct));
}
[Test]
public async Task RendersKeepTheirHashAndKindAndCopiesOutliveThem()
{
var chronos = await OpenChronosAsync();
var archive = TestData.Archive("Main");
await chronos.Archives.UpsertAsync(archive, Ct);
var sequence = TestData.Sequence(archive.Id);
await chronos.Sequences.UpsertAsync(sequence, Ct);
var now = DateTimeOffset.UtcNow;
var render = new Render { Id = Guid.CreateVersion7(), SequenceId = sequence.Id, PresetName = "PNG", OutputPath = "x/exports/a.png", Created = now };
await chronos.Renders.InsertAsync(render, Ct);
await using var session = await chronos.Database.OpenAsync(Ct);
// Rows recorded before migration 0010 have neither: null, told apart by the codec.
Assert.Equal(1L, await session.ScalarAsync<long>("SELECT count(*) FROM renders WHERE sha256 IS NULL AND kind IS NULL", [], Ct));
var hash = new string('a', 64);
await session.ExecuteAsync("UPDATE renders SET sha256 = $1, kind = $2 WHERE id = $3", [hash, "still", render.Id], Ct);
Assert.Equal(hash, await session.ScalarAsync<string>("SELECT sha256 FROM renders WHERE id = $1", [render.Id], Ct));
Assert.Equal("still", await session.ScalarAsync<string>("SELECT kind FROM renders WHERE id = $1", [render.Id], Ct));
// A copy names its render without a foreign key: it is kept when the render goes, and may name one never stored here.
foreach (var renderId in new[] { render.Id, Guid.CreateVersion7() })
{
await session.ExecuteAsync(
"INSERT INTO render_copies (id, render_id, path, sha256, bytes, copied_at, copied_by) VALUES ($1, $2, $3, $4, $5, $6, $7)",
[Guid.CreateVersion7(), renderId, $"C:/Videos/{renderId:N}.png", hash, 1234L, now, "admin"], Ct);
}
await chronos.Renders.DeleteAsync(render.Id, Ct);
Assert.Equal(2L, await session.ScalarAsync<long>("SELECT count(*) FROM render_copies", [], Ct));
Assert.Equal(1234L, await session.ScalarAsync<long>("SELECT bytes FROM render_copies WHERE render_id = $1", [render.Id], Ct));
// Bytes default to 0 and the hash and author may be null.
await session.ExecuteAsync("INSERT INTO render_copies (id, render_id, path, copied_at) VALUES ($1, $2, $3, $4)", [Guid.CreateVersion7(), render.Id, "C:/Videos/b", now], Ct);
Assert.Equal(0L, await session.ScalarAsync<long>("SELECT bytes FROM render_copies WHERE path = $1", ["C:/Videos/b"], Ct));
}
[Test]
public async Task AppliesOnlyPendingMigrations()
{
@@ -45,7 +45,7 @@ public sealed class ProjectStoreTests(TestContext context)
[Test]
public void SettingsOfANewerChronosAreRefusedSayingSo()
{
var refused = Assert.Throws<InvalidDataException>(() => ProjectStore.Parse("""{"version":3,"camera":{"rotate":90}}"""));
var refused = Assert.Throws<InvalidDataException>(() => ProjectStore.Parse("""{"version":4,"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.
@@ -687,11 +687,11 @@ public sealed class RenderJobTests(TestContext context)
var parameters = ProcessingJobs.ReadRender(ProcessingJobs.Render(sequence, Mjpeg, 96, 64).ParametersJson).Parameters with
{
SettingsJson = """{"version":3,"camera":{"rotate":90},"grade":{"lut":"teal"}}""",
SettingsJson = """{"version":4,"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,
Assert.Equal(4, 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);
@@ -110,11 +110,11 @@ public sealed class ProjectMergeTests
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 newer = ProjectSettings.FromJson("""{ "version": 4, "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);
Assert.Equal(4, ProjectMerge.MergeWithConflicts(basis, basis, newer).Merged.Version);
}
[Test]
@@ -165,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": 3, "exposure": { "exposureOffsetEv": 0.5 }, "grade": { "look": "film" } }""", allowNewer: true);
var newer = ProjectSettings.FromJson("""{ "version": 4, "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": 3, "exposure": { "exposureOffsetEv": 0.5 }, "futureThing": true }""";
var settings = """{ "version": 4, "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 = 3,
SettingsFormat = 4,
FramesVersion = head.FramesVersion,
CreatedAt = now,
StoredAt = now,
@@ -254,7 +254,7 @@ public sealed class SyncRulesTests
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");
Assert.Contains(SyncRules.Differences("""{"version":4,"camera":{"rotate":90}}""", turned, max: 5), d => d.Path == "version");
}
[Test]
@@ -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\": 3", StringComparison.Ordinal));
File.WriteAllText(project.BundlePath, bundle.ToJson().Replace("\"version\": 1", "\"version\": 4", StringComparison.Ordinal));
var session = await sync.OpenAsync(project.ProjectId, fx.Ct);
Assert.True(session.IsReadOnly);
@@ -508,7 +508,7 @@ public sealed class ProjectTests(TestContext context)
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);
Assert.Equal(3, ProjectSettings.CurrentVersion);
var (http, _, token) = await server.UserAsync("alberto", "editor");
using var alberto = Client(server, token);
@@ -527,8 +527,8 @@ public sealed class ProjectTests(TestContext context)
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 };
const string future = """{"version":4,"camera":{"rotate":90}}""";
var newer = Version(v3, new ProjectSettings(), home) with { SettingsJson = future, ContentHash = ProjectContent.Hash(future), SettingsFormat = 4 };
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);
@@ -0,0 +1,115 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Videos;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Server.Tests.Api;
/// <summary>
/// The wire shapes of the videos library (owner review 1, phase 5): camelCase members, nulls left out, and the members
/// added to existing DTOs trailing and optional, so a client or server of before reads and writes them as it did.
/// </summary>
public sealed class VideoContractTests
{
private static readonly Guid RenderId = Guid.Parse("01890000-0000-7000-8000-000000000001");
private static readonly Guid SequenceId = Guid.Parse("01890000-0000-7000-8000-000000000002");
private static readonly DateTimeOffset Created = new(2026, 11, 5, 18, 30, 0, TimeSpan.Zero);
[Test]
public void AVideoTravelsWithItsSequenceStateAndCopies()
{
var video = new VideoDto(RenderId, SequenceId, "Web 1080p", "h264", 1920, 1080, 25, 12.5, 4_000_000, Created, "PC-A", null, null,
new string('a', 64), RenderKind.Video, "Harbour sunset", new DateTime(2026, 10, 1, 18, 0, 0), "Main", 3, VideoStates.Ok,
[new VideoCopyDto("/videos/Harbour sunset.mp4", Created)], "Harbour sunset.mp4");
var json = JsonNode.Parse(JsonSerializer.Serialize(video, ProtocolJson.Default.VideoDto))!.AsObject();
Assert.SequenceEqual(
["id", "sequenceId", "presetName", "codec", "width", "height", "fps", "durationSeconds", "bytes", "created", "producedBy", "sha256",
"kind", "sequenceTitle", "sequenceFirstCapture", "projectName", "projectVersionNumber", "state", "copies", "fileName"],
json.Select(p => p.Key));
Assert.Equal("video", json["kind"]!.GetValue<string>());
Assert.Equal("/videos/Harbour sunset.mp4", json["copies"]![0]!["path"]!.GetValue<string>());
var back = JsonSerializer.Deserialize(json.ToJsonString(), ProtocolJson.Default.VideoDto)!;
Assert.Equal(video with { Copies = back.Copies }, back);
Assert.Equal(video.Copies[0], back.Copies[0]);
var page = new VideoPageDto([video], "cursor-2");
var pageJson = JsonNode.Parse(JsonSerializer.Serialize(page, ProtocolJson.Default.VideoPageDto))!.AsObject();
Assert.SequenceEqual(["items", "next"], pageJson.Select(p => p.Key));
}
[Test]
public void DeletingIsADryRunThenTheSameFingerprint()
{
var request = JsonSerializer.Serialize(new VideoDeleteRequest([RenderId], DryRun: true), ProtocolJson.Default.VideoDeleteRequest);
Assert.Equal($$"""{"ids":["{{RenderId}}"],"dryRun":true}""", request);
var real = JsonSerializer.Deserialize("""{ "ids": [], "dryRun": false, "fingerprint": "abc" }""", ProtocolJson.Default.VideoDeleteRequest)!;
Assert.Equal((false, "abc"), (real.DryRun, real.Fingerprint));
var plan = new VideoDeletePlanDto([new VideoDeleteItemDto(RenderId, SequenceId, "Harbour sunset", "a.mp4", 10, Missing: false)], 10,
[new VideoBlockedDto(Guid.Empty, VideoBlockReasons.Busy)], "f1", DryRun: true);
var json = JsonNode.Parse(JsonSerializer.Serialize(plan, ProtocolJson.Default.VideoDeletePlanDto))!.AsObject();
Assert.SequenceEqual(["items", "bytes", "blocked", "fingerprint", "dryRun"], json.Select(p => p.Key));
Assert.Equal("busy", json["blocked"]![0]!["reason"]!.GetValue<string>());
var copy = JsonSerializer.Serialize(new VideoCopyRequest([RenderId]), ProtocolJson.Default.VideoCopyRequest);
Assert.Equal($$"""{"ids":["{{RenderId}}"]}""", copy);
Assert.Equal(RenderId, JsonSerializer.Deserialize($$"""{"jobId":"{{RenderId}}"}""", ProtocolJson.Default.VideoCopyResultDto)!.JobId);
Assert.Equal("videos", ServerCapabilities.Videos);
}
[Test]
public void TheMembersAddedToOlderDtosAreLeftOutUntilSet()
{
var render = new RenderDto(RenderId, "MJPEG", "mjpeg", 96, 64, 25, 1, 10, Created, null);
var renderJson = JsonSerializer.Serialize(render, ProtocolJson.Default.RenderDto);
Assert.False(renderJson.Contains("sha256", StringComparison.Ordinal) || renderJson.Contains("kind", StringComparison.Ordinal), renderJson);
var hashed = JsonNode.Parse(JsonSerializer.Serialize(render with { Sha256 = "ab", Kind = RenderKind.Still }, ProtocolJson.Default.RenderDto))!;
Assert.Equal(("ab", "still"), (hashed["sha256"]!.GetValue<string>(), hashed["kind"]!.GetValue<string>()));
var parameters = new RenderJobParameters("MJPEG", "{}", "mjpeg", 96, 64, false, null);
var parametersJson = JsonSerializer.Serialize(parameters, ProtocolJson.Default.RenderJobParameters);
Assert.False(parametersJson.Contains("still", StringComparison.OrdinalIgnoreCase), parametersJson);
Assert.False(parameters.IsStill);
var still = JsonSerializer.Deserialize(
JsonSerializer.Serialize(parameters with { StillFrame = 41, StillPhoto = "cd", RequiredSettingsFormat = 3 }, ProtocolJson.Default.RenderJobParameters),
ProtocolJson.Default.RenderJobParameters)!;
Assert.Equal(((int?)41, "cd", 3, true), (still.StillFrame, still.StillPhoto, still.RequiredSettingsFormat, still.IsStill));
var result = JsonSerializer.Deserialize("""{ "fileName": "a.png", "size": 1, "sha256": "ab", "presetName": "PNG", "width": 1, "height": 1, "fps": 0, "durationSeconds": 0 }""",
ProtocolJson.Default.RenderResultRequest)!;
Assert.Null(result.Kind);
}
[Test]
public void TheLibraryStubAnswersEmptyUntilTheLibraryLands()
{
var stub = NotImplementedVideoLibrary.Instance;
Assert.False(stub.IsAvailable);
Assert.Equal(VideoErrors.FolderUnset, stub.FolderProblem(" "));
Assert.Null(stub.FolderProblem("/videos"));
Assert.Empty(stub.ListAsync(new VideoQuery()).GetAwaiter().GetResult().Items);
Assert.Null(stub.GetAsync(RenderId).GetAwaiter().GetResult());
}
[Test]
public void TrashEntriesAndCopyParametersReadBack()
{
var name = VideoTrashNames.EntryName(RenderId, Created);
Assert.True(name.StartsWith(VideoTrashNames.Prefix, StringComparison.Ordinal));
Assert.True(VideoTrashNames.TryParse(name, out var id, out var ticks));
Assert.Equal((RenderId, Created.UtcTicks), (id, ticks));
Assert.False(VideoTrashNames.IsEntryName($"sequence-{RenderId}"));
Assert.False(VideoTrashNames.IsEntryName(null));
Assert.Equal("videos", TrashKind.Videos.ToString().ToLowerInvariant());
var parameters = new VideoCopyParameters([RenderId], "/videos", FromServer: true, RequestedBy: "alberto");
var back = Assert.NotNull(VideoCopyParameters.Read(parameters.ToJson()));
Assert.Equal((parameters.Folder, parameters.FromServer, parameters.RequestedBy), (back.Folder, back.FromServer, back.RequestedBy));
Assert.SequenceEqual(parameters.RenderIds, back.RenderIds);
Assert.Null(VideoCopyParameters.Read("not json"));
Assert.Equal(24, (int)JobKind.VideoCopy);
}
}
+22
View File
@@ -0,0 +1,22 @@
{
"version": 3,
"exposure": {
"exposureOffsetEv": 0.25
},
"camera": {
"rotate": 90
},
"export": {
"nameTemplate": "{date} {title} - {preset}",
"batch": [
"web-1080p"
],
"playback": {
"direction": "boomerang",
"loops": 2,
"fadeIn": 1.5,
"fadeOut": 2,
"holdEnd": 3
}
}
}