Files
Chronos/src/Chronos.Core/Project/ProjectSettings.cs
T
Alby96andClaude Opus 5.5 9b24cf74fc
CI / Build and test (push) Successful in 9m43s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 27s
CI / PostgreSQL 16 integration (push) Failing after 8m41s
CI / PostgreSQL 17 integration (push) Successful in 12m37s
CI / Docker image (push) Successful in 56s
Release / Build, test and publish (push) Successful in 14m59s
Release / Server image (push) Successful in 1m51s
feat: owner review 2 phase 5a: workspace and projects with a local home (#14)
Edit opens a sequence as a project of a workspace folder outside the library. Projects have linear version histories kept as sidecars in .chronos/projects/, Main mirrors the sequence's settings, and sync merges setting by setting. Migration 0009, JobKind.WorkspaceCopy = 20, Settings › Workspace, and 241 new strings in 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-11-04 09:22:08 +01:00

723 lines
34 KiB
C#

using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using Chronos.Core.Model;
namespace Chronos.Core.Project;
public enum TimingMode
{
/// <summary>Every source frame lasts one output frame.</summary>
Constant,
/// <summary>Output time follows capture time (deliberate intervalometer pauses are kept short, gaps preserved).</summary>
Adaptive,
/// <summary>Missing frames in sparse gaps are synthesised from motion.</summary>
Interpolated,
/// <summary>A monotone curve maps output time to source position (speed ramps).</summary>
Remapped,
}
public enum RegionMode
{
Off,
Auto,
Horizon,
Luminance,
}
public enum FlowQualitySetting
{
Draft,
Balanced,
Best,
}
public enum StackSetting
{
None,
Median,
Mean,
StarTrails,
}
/// <summary>A control point of the time-remap curve: output fraction → source fraction (both 0..1).</summary>
public sealed record CurvePoint(double X, double Y)
{
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
/// <summary>Virtual-camera keyframe in normalised coordinates.</summary>
public sealed record CameraKey(int Frame, double CenterX, double CenterY, double Zoom, double Rotation, string Easing = "EaseInOut")
{
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
/// <summary>
/// The frame positions of a project that name a photo this copy of the sequence does not hold: settings taken from a
/// copy that holds it (BRIEF §14.5). They become positions again when the photo arrives
/// (<see cref="ProjectSettings.TranslateFramePositions"/>).
/// </summary>
public sealed record PendingFrame
{
public string? Sha256 { get; init; }
public long Size { get; init; }
public DateTime? CapturedAt { get; init; }
/// <summary>
/// Which of the frames holding the photo it names, in capture order, when a copy holds the photo more than once
/// (<see cref="FramePhotos.Occurrence"/>): 0, the first, is not written.
/// </summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public int Occurrence { get; init; }
/// <summary>The photo is excluded from renders.</summary>
public bool Excluded { get; init; }
/// <summary>The photo is the hero frame, unless another one is chosen before it arrives.</summary>
public bool Hero { get; init; }
/// <summary>Virtual-camera keyframes on the photo; their <see cref="CameraKey.Frame"/> is set when it arrives.</summary>
public IReadOnlyList<CameraKey> Keyframes { get; init; } = [];
[JsonIgnore]
public FramePhoto Photo => new(Sha256, Size, CapturedAt);
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
public sealed record TimingSettings
{
public Auto<TimingMode> Mode { get; init; } = new();
/// <summary>Output frame rate as "num/den" or an integer (e.g. "24000/1001", "30").</summary>
public Auto<string> FrameRate { get; init; } = new();
/// <summary>When set, the plan is scaled so the video lasts this many seconds.</summary>
public double? FitToSeconds { get; init; }
public IReadOnlyList<CurvePoint> RemapCurve { get; init; } = [new(0, 0), new(1, 1)];
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
public sealed record ExposureSettings
{
public Auto<bool> Deflicker { get; init; } = new();
/// <summary>Local-regression window in frames (odd).</summary>
public Auto<int> DeflickerWindow { get; init; } = new();
/// <summary>0..1: share of the flicker removed.</summary>
public Auto<double> DeflickerStrength { get; init; } = new();
public Auto<RegionMode> Regions { get; init; } = new();
public Auto<bool> HolyGrail { get; init; } = new();
/// <summary>Transition length in frames for redistributed exposure steps.</summary>
public Auto<int> TransitionLength { get; init; } = new();
public Auto<bool> WhiteBalanceSmoothing { get; init; } = new();
/// <summary>Global exposure offset in EV applied after correction.</summary>
public double ExposureOffsetEv { get; init; }
/// <summary>Soft highlight knee (linear), null = hard clip at the encoder.</summary>
/// <remarks>Written even when null: a missing value reads back as the default knee, which would turn "off" on.</remarks>
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public double? HighlightKnee { get; init; } = 0.9;
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
public sealed record MotionSettings
{
public Auto<bool> MotionBlur { get; init; } = new();
/// <summary>Target shutter angle in degrees (180 = film look).</summary>
public Auto<double> TargetShutterAngle { get; init; } = new();
public Auto<FlowQualitySetting> FlowQuality { get; init; } = new();
public Auto<bool> Stabilize { get; init; } = new();
/// <summary>Path smoothing in frames (Gaussian sigma).</summary>
public Auto<double> StabilizeSmoothing { get; init; } = new();
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
public sealed record CameraSettings
{
/// <summary>Normalised crop (0..1) or null for the full frame.</summary>
public double[]? Crop { get; init; }
/// <summary>"source", "16:9", "21:9", "4:3", "3:2", "1:1", "9:16", "4:5" or "w:h".</summary>
public Auto<string> Aspect { get; init; } = new();
public double OffsetX { get; init; }
public double OffsetY { get; init; }
public IReadOnlyList<CameraKey> Keyframes { get; init; } = [];
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
public sealed record StackSettings
{
public StackSetting Mode { get; init; } = StackSetting.None;
/// <summary>Window (median/mean) or trail length (star trails) in frames.</summary>
public int Length { get; init; } = 9;
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
/// <summary>Values of an export; null fields take the preset's value (BRIEF §11.4: editing any value makes it "Custom").</summary>
public sealed record ExportOverrides
{
public string? Codec { get; init; }
public string? Container { get; init; }
public string? Profile { get; init; }
public int? BitDepth { get; init; }
public int? Width { get; init; }
public int? Height { get; init; }
public string? FrameRate { get; init; }
public long? BitRate { get; init; }
public int? GopFrames { get; init; }
public int? BFrames { get; init; }
public int? Quality { get; init; }
public string? RateControl { get; init; }
public string? Encoder { get; init; }
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
public sealed record ExportSettings
{
/// <summary>Id of the selected preset (built-in or user); "custom" when values differ from every preset.</summary>
public Auto<string> Preset { get; init; } = new();
public ExportOverrides Overrides { get; init; } = new();
/// <summary>Output file name template (tokens: date, title, preset, width, height, fps, codec).</summary>
public string NameTemplate { get; init; } = "{date} {title} - {preset}";
/// <summary>Output folder; null = the sequence's exports folder.</summary>
public string? Folder { get; init; }
/// <summary>Presets queued together by "Render another preset" / batch.</summary>
public IReadOnlyList<string> Batch { get; init; } = [];
/// <summary>
/// Export "Sync": a render made on this PC is sent to the server the sequence is linked to once it is done. Off
/// unless chosen, as renders travel on request (BRIEF §14.5).
/// </summary>
public bool SyncToServer { get; init; }
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
/// <summary>
/// The "project" of a sequence (<c>.chronos/project.json</c>, BRIEF §7): every render decision. Originals are
/// never modified; all edits live here.
/// </summary>
public sealed record ProjectSettings
{
public const int CurrentVersion = 1;
/// <summary>Layout of a project edited as JSON (<see cref="MoveFramePositions"/>): indented like <see cref="ToJson"/>.</summary>
private static readonly JsonSerializerOptions IndentedJson = new() { WriteIndented = true };
/// <summary>Member names as a project edited as JSON reads them (an older or hand-written file may use any casing).</summary>
private static readonly JsonNodeOptions CaseInsensitive = new() { PropertyNameCaseInsensitive = true };
public int Version { get; init; } = CurrentVersion;
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 ExportSettings Export { get; init; } = new();
/// <summary>Frame indices excluded from renders (positions in capture order; see <see cref="MoveFramePositions"/>).</summary>
public IReadOnlyList<int> ExcludedFrames { get; init; } = [];
/// <summary>Index of the hero frame (sequence thumbnail).</summary>
public int? HeroFrame { get; init; }
/// <summary>
/// Exclusions, hero and keyframes naming photos this copy does not hold yet (settings synced from a copy that holds
/// them); null when there are none. They take their place when the photos arrive (<see cref="TranslateFramePositions"/>).
/// </summary>
public IReadOnlyList<PendingFrame>? PendingFrames { get; init; }
/// <summary>The hero waits for its photo, so advice does not choose one meanwhile.</summary>
[JsonIgnore]
public bool HeroPending => PendingFrames?.Any(p => p.Hero) == true;
/// <summary>
/// Members this Chronos does not know (settings a newer Chronos added, such as filters): kept as they are, so a project
/// read and written again loses nothing (owner review 2, R8).
/// </summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
/// <summary>
/// Written by a newer Chronos (<see cref="Version"/> above <see cref="CurrentVersion"/>), read with
/// <see cref="FromJson(string, bool)"/> allowing it: shown, never edited, as its known values may mean something else there.
/// </summary>
[JsonIgnore]
public bool IsNewerFormat => Version > CurrentVersion;
public string ToJson() => JsonSerializer.Serialize(this, ProjectJson.Default.ProjectSettings);
/// <summary>
/// Reads a project; members missing from <paramref name="json"/> (an API client's partial settings, an older file)
/// keep their defaults. The JSON is laid over the default project first, because generated deserialisation leaves
/// missing init-only members null or false rather than at their initial values.
/// </summary>
/// <exception cref="JsonException">The text is not a JSON object, or repeats a member.</exception>
/// <exception cref="InvalidDataException">The project was written by a newer Chronos.</exception>
public static ProjectSettings FromJson(string json) => FromJson(json, allowNewer: false);
/// <summary>
/// <see cref="FromJson(string)"/>, reading a project of a newer Chronos too when <paramref name="allowNewer"/>: its
/// known values, its unknown members in <see cref="Extra"/>, and <see cref="IsNewerFormat"/> set (open it read-only).
/// </summary>
/// <exception cref="JsonException">The text is not a JSON object, repeats a member, or a known member has another type.</exception>
/// <exception cref="InvalidDataException">The project was written by a newer Chronos and <paramref name="allowNewer"/> is false.</exception>
public static ProjectSettings FromJson(string json, bool allowNewer)
{
var options = new JsonNodeOptions { PropertyNameCaseInsensitive = true };
var merged = JsonNode.Parse(new ProjectSettings().ToJson(), options)!.AsObject();
switch (JsonNode.Parse(json, options))
{
case JsonObject given:
try
{
Overlay(merged, given);
}
catch (ArgumentException ex)
{
// A parsed object builds its member table on first use and rejects a name given twice (in any casing).
throw new JsonException("A project member is given more than once.", ex);
}
break;
case not null:
throw new JsonException("A project must be a JSON object.");
}
var settings = JsonSerializer.Deserialize(merged, ProjectJson.Default.ProjectSettings) ?? new ProjectSettings();
if (settings.IsNewerFormat && !allowNewer)
throw new InvalidDataException($"project.json version {settings.Version} is newer than this Chronos ({CurrentVersion}).");
return settings;
}
/// <summary>
/// Copies <paramref name="source"/> into <paramref name="target"/>, merging nested objects. A null keeps a default that
/// is an object, a list or a text, since none of those members is nullable; elsewhere it clears a nullable value.
/// </summary>
private static void Overlay(JsonObject target, JsonObject source)
{
foreach (var (name, value) in source)
{
var current = target[name];
if (value is JsonObject child && current is JsonObject section) Overlay(section, child);
else if (value is not null || !(current is JsonObject or JsonArray || current?.GetValueKind() == JsonValueKind.String))
target[name] = value?.DeepClone();
}
}
/// <summary>
/// Moves the frame positions of a project — <see cref="ExcludedFrames"/>, <see cref="HeroFrame"/> and the
/// virtual-camera <see cref="CameraKey.Frame"/>s — after frames were inserted before them: <paramref name="moves"/> maps
/// an old position to the new one, and a position it does not list stays. The JSON is edited in place, so members
/// this Chronos does not know survive. Null when nothing moves or <paramref name="json"/> is not a project object.
/// </summary>
public static string? MoveFramePositions(string json, IReadOnlyDictionary<int, int> moves)
{
ArgumentNullException.ThrowIfNull(moves);
if (moves.Count == 0 || string.IsNullOrWhiteSpace(json)) return null;
try
{
if (JsonNode.Parse(json, new JsonNodeOptions { PropertyNameCaseInsensitive = true }) is not JsonObject project) return null;
var moved = false;
if (project["excludedFrames"] is JsonArray excluded)
{
for (var i = 0; i < excluded.Count; i++)
{
var at = i;
moved |= Move(excluded[at], value => excluded[at] = value, moves);
}
}
if (project["heroFrame"] is { } hero) moved |= Move(hero, value => project["heroFrame"] = value, moves);
if (project["camera"] is JsonObject camera && camera["keyframes"] is JsonArray keyframes)
{
foreach (var key in keyframes.OfType<JsonObject>())
{
if (key["frame"] is { } frame) moved |= Move(frame, value => key["frame"] = value, moves);
}
}
return moved ? project.ToJsonString(IndentedJson) : null;
}
catch (Exception ex) when (ex is JsonException or ArgumentException)
{
// Not JSON, or a member given twice (the case-insensitive member table refuses it): not a project to edit.
return null;
}
}
/// <summary>
/// A project written against the frames <paramref name="before"/> (frame ids, by index) moved to the frames
/// <paramref name="after"/> (in index order) the way the archive index moves its own copy when it takes them
/// (ProjectPositions in Chronos.Data): while every frame of <paramref name="before"/> is still there, its positions
/// move with their frames (<see cref="MoveFramePositions"/>), otherwise they stay; either way pending frames whose
/// photos are now there take their place (<see cref="TranslateFramePositions"/>). An editor that read the frames
/// before frames were inserted saves its edit in the new order this way. Null when nothing changes.
/// </summary>
public static string? FollowFrames(string json, IReadOnlyList<Guid> before, IReadOnlyList<Frame> after)
{
ArgumentNullException.ThrowIfNull(before);
ArgumentNullException.ThrowIfNull(after);
var now = new Dictionary<Guid, int>(after.Count);
for (var i = 0; i < after.Count; i++) now[after[i].Id] = i;
Dictionary<int, int>? moves = [];
for (var i = 0; i < before.Count; i++)
{
if (!now.TryGetValue(before[i], out var index))
{
moves = null;
break;
}
if (index != i) moves[i] = index;
}
var moved = moves is null ? null : MoveFramePositions(json, moves);
var current = moved ?? json;
// Most projects wait for no photo: the frames' photos are gathered only for those that do.
var placed = current.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase)
? TranslateFramePositions(current, null, new FramePhotos(after.Select((f, i) => (i, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))))
: null;
return placed ?? moved;
}
private static bool Move(JsonNode? position, Action<JsonNode> replace, IReadOnlyDictionary<int, int> moves)
{
if (position is not JsonValue value || !value.TryGetValue<int>(out var old) || !moves.TryGetValue(old, out var now) || now == old) return false;
replace(JsonValue.Create(now));
return true;
}
/// <summary>
/// Whether a project names frames (exclusions, a hero, camera keyframes or <see cref="PendingFrames"/>); settings
/// naming none cross between copies of a sequence as they are. False for text that is not a project object.
/// </summary>
public static bool NamesFrames(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return false;
try
{
return JsonNode.Parse(json, CaseInsensitive) is JsonObject project
&& (project["excludedFrames"] is JsonArray { Count: > 0 } || project["heroFrame"] is JsonValue || project["pendingFrames"] is JsonArray { Count: > 0 }
|| (project["camera"] is JsonObject camera && camera["keyframes"] is JsonArray { Count: > 0 }));
}
catch (Exception ex) when (ex is JsonException or ArgumentException)
{
return false;
}
}
/// <summary>
/// Translates the frame positions of a project written against the frames of another copy of the sequence
/// (<paramref name="from"/>; a server sequence and a PC's copy hold the same photos, though not always all of them,
/// BRIEF §14.5) to the frames of <paramref name="to"/>, by photo: each exclusion, the hero and each camera keyframe
/// moves to the frame of <paramref name="to"/> holding its photo, and a position on the n-th frame holding a photo
/// <paramref name="from"/> holds more than once to the n-th such frame (<see cref="FramePhotos.Occurrence"/>), so
/// duplicates stay apart. One whose photo (or that copy of it) <paramref name="to"/> lacks becomes
/// a <see cref="PendingFrame"/>, and pending frames whose photo <paramref name="to"/> holds become positions again; a
/// pending hero only while no other hero is chosen (a hero chosen since one was left pending is newer, so that one no
/// longer waits even when the chosen one must wait in turn), a pending keyframe only where no keyframe is. With
/// <paramref name="from"/> null the positions already name <paramref name="to"/>'s frames and only pending frames are
/// placed (photos that arrived). A position naming no frame of <paramref name="from"/> names nothing and goes. Edited
/// in place like <see cref="MoveFramePositions"/>; null when nothing changes or <paramref name="json"/> is not a
/// project object.
/// </summary>
public static string? TranslateFramePositions(string json, FramePhotos? from, FramePhotos to)
{
ArgumentNullException.ThrowIfNull(to);
if (string.IsNullOrWhiteSpace(json)) return null;
try
{
if (JsonNode.Parse(json, CaseInsensitive) is not JsonObject project) return null;
var pending = new List<Parked>();
var unreadable = new List<JsonNode?>();
if (project["pendingFrames"] is JsonArray stored)
{
foreach (var node in stored)
{
// An entry naming no photo is not this Chronos's to place: it stays as it is.
if (node is JsonObject entry && PhotoOf(entry) is { } photo) pending.Add(new Parked(photo, OccurrenceOf(entry), entry.DeepClone().AsObject()));
else unreadable.Add(node?.DeepClone());
}
}
var changed = false;
if (project["heroFrame"] is JsonValue && pending.Any(p => Flag(p.Entry, "hero")))
{
// Checked before the hero itself may be parked below, which leaves no hero chosen.
foreach (var parked in pending) parked.Entry["hero"] = false;
pending.RemoveAll(p => !Waits(p.Entry));
changed = true;
}
changed |= from is not null && !from.SameAs(to) && TranslatePositions(project, from, to, pending);
changed |= PlacePending(project, to, pending);
if (!changed) return null;
SortPositions(project);
var left = pending.Where(p => !p.Placed).Select(p => (JsonNode?)p.Entry).Concat(unreadable).ToArray();
if (left.Length == 0) project.Remove("pendingFrames");
else project["pendingFrames"] = new JsonArray(left);
return project.ToJsonString(IndentedJson);
}
catch (Exception ex) when (ex is JsonException or ArgumentException or InvalidOperationException)
{
// Not JSON, a member given twice, or a member of an unexpected kind: not a project to edit.
return null;
}
}
/// <summary>Moves every position of <paramref name="project"/> from <paramref name="from"/>'s frames to <paramref name="to"/>'s.</summary>
private static bool TranslatePositions(JsonObject project, FramePhotos from, FramePhotos to, List<Parked> pending)
{
var changed = false;
if (project["excludedFrames"] is JsonArray excluded)
{
var kept = new List<JsonNode?>(excluded.Count);
foreach (var node in excluded)
{
if (!IsPosition(node, out var at)) kept.Add(node?.DeepClone());
else if (from[at] is not { } photo) changed = true;
else if (to.IndexOf(photo, from.Occurrence(at)) is { } now)
{
kept.Add(JsonValue.Create(now));
changed |= now != at;
}
else
{
Park(pending, photo, from.Occurrence(at)).Entry["excluded"] = true;
changed = true;
}
}
Replace(excluded, kept);
}
if (project["heroFrame"] is JsonValue hero && hero.TryGetValue<int>(out var heroAt))
{
var photo = from[heroAt];
var now = photo is null ? null : to.IndexOf(photo, from.Occurrence(heroAt));
if (photo is not null && now is null) Park(pending, photo, from.Occurrence(heroAt)).Entry["hero"] = true;
if (now != heroAt)
{
project["heroFrame"] = now;
changed = true;
}
}
if (project["camera"] is JsonObject camera && camera["keyframes"] is JsonArray keyframes)
{
var kept = new List<JsonNode?>(keyframes.Count);
foreach (var node in keyframes)
{
if (node is not JsonObject key || !IsPosition(key["frame"], out var at))
{
kept.Add(node?.DeepClone());
continue;
}
var copy = key.DeepClone().AsObject();
if (from[at] is not { } photo)
{
changed = true;
}
else if (to.IndexOf(photo, from.Occurrence(at)) is { } now)
{
copy["frame"] = now;
kept.Add(copy);
changed |= now != at;
}
else
{
var parked = Park(pending, photo, from.Occurrence(at)).Entry;
if (parked["keyframes"] is not JsonArray keys) parked["keyframes"] = keys = new JsonArray();
keys.Add(copy);
changed = true;
}
}
Replace(keyframes, kept);
}
return changed;
}
/// <summary>
/// Gives the pending frames whose photo <paramref name="to"/> holds their positions back. An entry with members this
/// Chronos does not know (a newer one's values of the photo) stays, without its positions: those members are not this
/// Chronos's to drop, and the next portable form parks the positions in it again.
/// </summary>
private static bool PlacePending(JsonObject project, FramePhotos to, List<Parked> pending)
{
var changed = false;
foreach (var parked in pending)
{
if (to.IndexOf(parked.Photo, parked.Occurrence) is not { } at) continue;
var kept = HasUnknownMembers(parked.Entry);
if (kept && !HoldsPosition(parked.Entry)) continue;
parked.Placed = !kept;
changed = true;
if (Flag(parked.Entry, "excluded"))
{
if (project["excludedFrames"] is not JsonArray positions) project["excludedFrames"] = positions = new JsonArray();
if (!positions.Any(n => IsPosition(n, out var p) && p == at)) positions.Add(at);
}
// A hero chosen since the settings were taken is newer than the one that waited.
if (Flag(parked.Entry, "hero") && project["heroFrame"] is null) project["heroFrame"] = at;
if (parked.Entry["keyframes"] is JsonArray { Count: > 0 } keys)
{
if (project["camera"] is not JsonObject camera) project["camera"] = camera = new JsonObject();
if (camera["keyframes"] is not JsonArray keyframes) camera["keyframes"] = keyframes = new JsonArray();
foreach (var key in keys.OfType<JsonObject>())
{
// A keyframe set on that frame since is newer.
if (keyframes.Any(n => n is JsonObject k && IsPosition(k["frame"], out var f) && f == at)) continue;
var copy = key.DeepClone().AsObject();
copy["frame"] = at;
keyframes.Add(copy);
}
}
if (kept)
{
parked.Entry["excluded"] = false;
parked.Entry["hero"] = false;
parked.Entry["keyframes"] = new JsonArray();
}
}
if (project["heroFrame"] is null) return changed;
// A hero is chosen: none waits any more, and an entry left with nothing to place goes.
foreach (var parked in pending.Where(p => !p.Placed && Flag(p.Entry, "hero")))
{
parked.Entry["hero"] = false;
parked.Placed = !Waits(parked.Entry);
changed = true;
}
return changed;
}
/// <summary>Exclusions in ascending order without repeats and keyframes by frame (values that are no position last, as they were).</summary>
private static void SortPositions(JsonObject project)
{
if (project["excludedFrames"] is JsonArray excluded)
{
var positions = excluded.Select(n => IsPosition(n, out var p) ? p : (int?)null).OfType<int>().Distinct().Order().Select(p => (JsonNode?)JsonValue.Create(p));
Replace(excluded, [.. positions, .. excluded.Where(n => !IsPosition(n, out _)).Select(n => n?.DeepClone())]);
}
if (project["camera"] is JsonObject camera && camera["keyframes"] is JsonArray keyframes)
{
var sorted = keyframes.Select(n => n?.DeepClone())
.OrderBy(n => n is JsonObject key && IsPosition(key["frame"], out var f) ? f : int.MaxValue).ToList();
Replace(keyframes, sorted);
}
}
/// <summary>The pending entry of <paramref name="photo"/> (the copy of it <paramref name="occurrence"/> names), added when there is none.</summary>
private static Parked Park(List<Parked> pending, FramePhoto photo, int occurrence)
{
if (pending.FirstOrDefault(p => p.Occurrence == occurrence && p.Photo.Matches(photo)) is { } known) return known;
var entry = new JsonObject();
if (photo.IsHashed) entry["sha256"] = photo.Sha256!.ToLowerInvariant();
entry["size"] = photo.Size;
if (photo.CapturedAt is { } captured) entry["capturedAt"] = captured;
if (occurrence > 0) entry["occurrence"] = occurrence;
entry["excluded"] = false;
entry["hero"] = false;
entry["keyframes"] = new JsonArray();
var parked = new Parked(photo, occurrence, entry);
pending.Add(parked);
return parked;
}
/// <summary>The photo a pending entry names; null when it names none.</summary>
private static FramePhoto? PhotoOf(JsonObject entry)
{
var sha = entry["sha256"] is JsonValue s && s.TryGetValue<string>(out var text) ? text : null;
var size = entry["size"] is JsonValue z && z.TryGetValue<long>(out var bytes) ? bytes : -1;
DateTime? captured = entry["capturedAt"] is JsonValue t && t.TryGetValue<DateTime>(out var time) ? time : null;
return string.IsNullOrEmpty(sha) && (captured is null || size < 0) ? null : new FramePhoto(sha, size, captured);
}
/// <summary>Which copy of its photo a pending entry names; the first when it says nothing (or nothing readable).</summary>
private static int OccurrenceOf(JsonObject entry) => entry["occurrence"] is JsonValue o && o.TryGetValue<int>(out var occurrence) && occurrence > 0 ? occurrence : 0;
private static bool Flag(JsonObject entry, string name) => entry[name] is JsonValue value && value.TryGetValue<bool>(out var set) && set;
/// <summary>The members of a pending entry this Chronos knows: its photo, which copy of it, and the positions on it.</summary>
internal static readonly HashSet<string> PendingMembers = new(StringComparer.OrdinalIgnoreCase)
{
"sha256", "size", "capturedAt", "occurrence", "excluded", "hero", "keyframes",
};
/// <summary>A pending entry has a position to give its photo.</summary>
private static bool HoldsPosition(JsonObject entry) => Flag(entry, "excluded") || Flag(entry, "hero") || entry["keyframes"] is JsonArray { Count: > 0 };
/// <summary>A pending entry holds members this Chronos does not know (written by a newer one).</summary>
private static bool HasUnknownMembers(JsonObject entry) => entry.Any(p => !PendingMembers.Contains(p.Key));
/// <summary>A pending entry still holds something: a position to give its photo, or members that are not this Chronos's to drop.</summary>
private static bool Waits(JsonObject entry) => HoldsPosition(entry) || HasUnknownMembers(entry);
private static bool IsPosition(JsonNode? node, out int position)
{
position = 0;
return node is JsonValue value && value.TryGetValue(out position);
}
private static void Replace(JsonArray array, IEnumerable<JsonNode?> nodes)
{
var copy = nodes.ToList();
array.Clear();
foreach (var node in copy) array.Add(node);
}
/// <summary>A pending entry being edited: its photo (and which copy of it), its JSON, and whether its photo took its place.</summary>
private sealed class Parked(FramePhoto photo, int occurrence, JsonObject entry)
{
public FramePhoto Photo { get; } = photo;
public int Occurrence { get; } = occurrence;
public JsonObject Entry { get; } = entry;
public bool Placed { get; set; }
}
}
[JsonSourceGenerationOptions(
WriteIndented = true,
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true,
PropertyNameCaseInsensitive = true)]
[JsonSerializable(typeof(ProjectSettings))]
internal sealed partial class ProjectJson : JsonSerializerContext;