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
{
/// Every source frame lasts one output frame.
Constant,
/// Output time follows capture time (deliberate intervalometer pauses are kept short, gaps preserved).
Adaptive,
/// Missing frames in sparse gaps are synthesised from motion.
Interpolated,
/// A monotone curve maps output time to source position (speed ramps).
Remapped,
}
public enum RegionMode
{
Off,
Auto,
Horizon,
Luminance,
}
public enum FlowQualitySetting
{
Draft,
Balanced,
Best,
}
public enum StackSetting
{
None,
Median,
Mean,
StarTrails,
}
/// A control point of the time-remap curve: output fraction → source fraction (both 0..1).
public sealed record CurvePoint(double X, double Y)
{
/// Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.
[JsonExtensionData]
public Dictionary? Extra { get; set; }
}
/// Virtual-camera keyframe in normalised coordinates.
public sealed record CameraKey(int Frame, double CenterX, double CenterY, double Zoom, double Rotation, string Easing = "EaseInOut")
{
/// Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.
[JsonExtensionData]
public Dictionary? Extra { get; set; }
}
///
/// 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
/// ().
///
public sealed record PendingFrame
{
public string? Sha256 { get; init; }
public long Size { get; init; }
public DateTime? CapturedAt { get; init; }
///
/// Which of the frames holding the photo it names, in capture order, when a copy holds the photo more than once
/// (): 0, the first, is not written.
///
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public int Occurrence { get; init; }
/// The photo is excluded from renders.
public bool Excluded { get; init; }
/// The photo is the hero frame, unless another one is chosen before it arrives.
public bool Hero { get; init; }
/// Virtual-camera keyframes on the photo; their is set when it arrives.
public IReadOnlyList Keyframes { get; init; } = [];
[JsonIgnore]
public FramePhoto Photo => new(Sha256, Size, CapturedAt);
/// Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.
[JsonExtensionData]
public Dictionary? Extra { get; set; }
}
public sealed record TimingSettings
{
public Auto Mode { get; init; } = new();
/// Output frame rate as "num/den" or an integer (e.g. "24000/1001", "30").
public Auto FrameRate { get; init; } = new();
/// When set, the plan is scaled so the video lasts this many seconds.
public double? FitToSeconds { get; init; }
public IReadOnlyList RemapCurve { get; init; } = [new(0, 0), new(1, 1)];
/// Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.
[JsonExtensionData]
public Dictionary? Extra { get; set; }
}
public sealed record ExposureSettings
{
public Auto Deflicker { get; init; } = new();
/// Local-regression window in frames (odd).
public Auto DeflickerWindow { get; init; } = new();
/// 0..1: share of the flicker removed.
public Auto DeflickerStrength { get; init; } = new();
public Auto Regions { get; init; } = new();
public Auto HolyGrail { get; init; } = new();
/// Transition length in frames for redistributed exposure steps.
public Auto TransitionLength { get; init; } = new();
public Auto WhiteBalanceSmoothing { get; init; } = new();
/// Global exposure offset in EV applied after correction.
public double ExposureOffsetEv { get; init; }
/// Soft highlight knee (linear), null = hard clip at the encoder.
/// Written even when null: a missing value reads back as the default knee, which would turn "off" on.
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public double? HighlightKnee { get; init; } = 0.9;
/// Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.
[JsonExtensionData]
public Dictionary? Extra { get; set; }
}
public sealed record MotionSettings
{
public Auto MotionBlur { get; init; } = new();
/// Target shutter angle in degrees (180 = film look).
public Auto TargetShutterAngle { get; init; } = new();
public Auto FlowQuality { get; init; } = new();
public Auto Stabilize { get; init; } = new();
/// Path smoothing in frames (Gaussian sigma).
public Auto StabilizeSmoothing { get; init; } = new();
/// Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.
[JsonExtensionData]
public Dictionary? Extra { get; set; }
}
public sealed record CameraSettings
{
///
/// Normalised [x, y, width, height] of the view frame (oriented, straightened and cover-zoomed: see
/// ), or null for the whole view. The editor writes the box locked to with
/// the offsets at 0; the render fits any other rectangle to the aspect.
///
public double[]? Crop { get; init; }
///
/// The output proportions: "source", "16:9", "21:9", "4:3", "3:2", "1:1", "9:16", "4:5" or "w:h". A preset of a fixed
/// size adapts its size to them (4K at 9:16 = 2160×3840); "source" keeps the preset's own.
///
public Auto Aspect { get; init; } = new();
/// Placement of the aspect-fitted crop inside , −1..1 per axis; 0 for a crop the editor wrote.
public double OffsetX { get; init; }
///
public double OffsetY { get; init; }
/// Virtual-camera keyframes; their centres are normalised in the view frame, like .
public IReadOnlyList Keyframes { get; init; } = [];
///
/// Quarter turns of the picture in degrees clockwise (0, 90, 180 or 270), after the Exif orientation applied at decode.
/// A value that is not a multiple of 90 renders as 0 (Export.Render.RotationIgnored). Settings format 2.
///
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public int Rotate { get; init; }
/// Left and right swapped, in screen axes after . Settings format 2.
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public bool Mirror { get; init; }
/// Top and bottom swapped, in screen axes after . Settings format 2.
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public bool Flip { get; init; }
///
/// Free-angle levelling in degrees, positive clockwise, after and , with an
/// automatic cover zoom (never stored) that never shows a border. Clamped to ±15, a value that is not finite counting as
/// 0 (Export.Render.StraightenClamped). Settings format 2.
///
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public double Straighten { get; init; }
/// Quarter turns clockwise, 0..3; meaningful only when is a multiple of 90.
[JsonIgnore]
public int Turns => ((Rotate / 90 % 4) + 4) % 4;
/// A turn, mirror, flip or straighten is set: the view frame differs from the decoded frame.
[JsonIgnore]
public bool IsOriented => Rotate % 360 != 0 || Mirror || Flip || Straighten != 0;
/// Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.
[JsonExtensionData]
public Dictionary? Extra { get; set; }
}
public sealed record StackSettings
{
public StackSetting Mode { get; init; } = StackSetting.None;
/// Window (median/mean) or trail length (star trails) in frames.
public int Length { get; init; } = 9;
/// Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.
[JsonExtensionData]
public Dictionary? Extra { get; set; }
}
/// Values of an export; null fields take the preset's value (BRIEF §11.4: editing any value makes it "Custom").
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; }
/// Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.
[JsonExtensionData]
public Dictionary? Extra { get; set; }
}
public sealed record ExportSettings
{
/// Id of the selected preset (built-in or user); "custom" when values differ from every preset.
public Auto Preset { get; init; } = new();
public ExportOverrides Overrides { get; init; } = new();
/// Output file name template (tokens: date, title, preset, width, height, fps, codec).
public string NameTemplate { get; init; } = "{date} {title} - {preset}";
/// Output folder; null = the sequence's exports folder.
public string? Folder { get; init; }
/// Presets queued together by "Render another preset" / batch.
public IReadOnlyList Batch { get; init; } = [];
///
/// 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).
///
public bool SyncToServer { get; init; }
/// Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.
[JsonExtensionData]
public Dictionary? Extra { get; set; }
}
///
/// The colour look of a render (owner review 1, R6): a built-in parametric filter blended by its strength, applied to
/// every output frame in linear light before the highlight knee. is null for none.
///
public sealed record LookSettings
{
///
/// The filter's name: null or "none", "mono", "sepia", "warm", "cool", "vivid", "muted" or "fade"
/// (LookFilter.Names). A text, not an enum, so a newer Chronos can add looks; one this Chronos does not know
/// renders as none (Export.Render.LookIgnored).
///
public string? Filter { get; init; }
/// Share of the filter applied, 0..1; null for 1.
public double? Strength { get; init; }
/// The look leaves the picture as it is.
[JsonIgnore]
public bool IsIdentity => Filter is null or "none" || Strength is <= 0;
/// Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.
[JsonExtensionData]
public Dictionary? Extra { get; set; }
}
///
/// The "project" of a sequence (.chronos/project.json, BRIEF §7): every render decision. Originals are
/// never modified; all edits live here.
///
///
/// The settings format () is conditional: writes the lowest format that renders
/// the same (), so a project that uses nothing newer keeps format 1, its canonical text and its
/// hash, and older builds read it as before. Rules for a member added later: one that changes pixels and that the previous
/// format would ignore raises the written format only while it is used; it is declared after the existing members of its
/// section (before Extra) and omitted at its default, so an older build keeps it in Extra and writes it
/// back in the same place; a list of choices that may grow is a text, never an enum.
///
public sealed record ProjectSettings
{
/// The highest settings format this Chronos reads; a project of a higher one opens read-only ().
public const int CurrentVersion = 2;
/// The format of a project that uses nothing added since the first one, which most projects are written as.
public const int BaseVersion = 1;
/// Layout of a project edited as JSON (): indented like , with LF line ends on every OS.
private static readonly JsonSerializerOptions IndentedJson = new() { WriteIndented = true, NewLine = "\n" };
/// Member names as a project edited as JSON reads them (an older or hand-written file may use any casing).
private static readonly JsonNodeOptions CaseInsensitive = new() { PropertyNameCaseInsensitive = true };
/// The settings format read; writes .
public int Version { get; init; } = BaseVersion;
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();
/// Frame indices excluded from renders (positions in capture order; see ).
public IReadOnlyList ExcludedFrames { get; init; } = [];
/// Index of the hero frame (sequence thumbnail).
public int? HeroFrame { get; init; }
///
/// 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 ().
///
public IReadOnlyList? PendingFrames { get; init; }
/// The colour look (owner review 1, R6); null for none, which the editor writes whenever the look is the identity.
public LookSettings? Look { get; init; }
/// The hero waits for its photo, so advice does not choose one meanwhile.
[JsonIgnore]
public bool HeroPending => PendingFrames?.Any(p => p.Hero) == true;
///
/// 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).
///
[JsonExtensionData]
public Dictionary? Extra { get; set; }
///
/// Written by a newer Chronos ( above ), read with
/// allowing it: shown, never edited, as its known values may mean something else there.
///
[JsonIgnore]
public bool IsNewerFormat => Version > CurrentVersion;
///
/// The lowest settings format that renders these settings the same: 2 while a turn, mirror, flip or straighten
/// () or a look other than the identity is set, otherwise .
///
[JsonIgnore]
public int RequiredFormat => Camera.IsOriented || Look is { IsIdentity: false } ? 2 : BaseVersion;
/// The format writes: , or a newer format read, kept as it is.
[JsonIgnore]
public int WrittenFormat => IsNewerFormat ? Version : RequiredFormat;
///
/// The settings as JSON, stamped with . Every serialisation of a project goes through here,
/// so the version written always matches the members used.
///
public string ToJson() => JsonSerializer.Serialize(Version == WrittenFormat ? this : this with { Version = WrittenFormat }, ProjectJson.Default.ProjectSettings);
///
/// Reads a project; members missing from (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.
///
/// The text is not a JSON object, or repeats a member.
/// The project was written by a newer Chronos.
public static ProjectSettings FromJson(string json) => FromJson(json, allowNewer: false);
///
/// , reading a project of a newer Chronos too when : its
/// known values, its unknown members in , and set (open it read-only).
///
/// The text is not a JSON object, repeats a member, or a known member has another type.
/// The project was written by a newer Chronos and is false.
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;
}
///
/// Copies into , 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.
///
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();
}
}
///
/// Moves the frame positions of a project — , and the
/// virtual-camera s — after frames were inserted before them: 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 is not a project object.
///
public static string? MoveFramePositions(string json, IReadOnlyDictionary 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())
{
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;
}
}
///
/// A project written against the frames (frame ids, by index) moved to the frames
/// (in index order) the way the archive index moves its own copy when it takes them
/// (ProjectPositions in Chronos.Data): while every frame of is still there, its positions
/// move with their frames (), otherwise they stay; either way pending frames whose
/// photos are now there take their place (). An editor that read the frames
/// before frames were inserted saves its edit in the new order this way. Null when nothing changes.
///
public static string? FollowFrames(string json, IReadOnlyList before, IReadOnlyList after)
{
ArgumentNullException.ThrowIfNull(before);
ArgumentNullException.ThrowIfNull(after);
var now = new Dictionary(after.Count);
for (var i = 0; i < after.Count; i++) now[after[i].Id] = i;
Dictionary? 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 replace, IReadOnlyDictionary moves)
{
if (position is not JsonValue value || !value.TryGetValue(out var old) || !moves.TryGetValue(old, out var now) || now == old) return false;
replace(JsonValue.Create(now));
return true;
}
///
/// Whether a project names frames (exclusions, a hero, camera keyframes or ); settings
/// naming none cross between copies of a sequence as they are. False for text that is not a project object.
///
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;
}
}
///
/// Translates the frame positions of a project written against the frames of another copy of the sequence
/// (; 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 , by photo: each exclusion, the hero and each camera keyframe
/// moves to the frame of holding its photo, and a position on the n-th frame holding a photo
/// holds more than once to the n-th such frame (), so
/// duplicates stay apart. One whose photo (or that copy of it) lacks becomes
/// a , and pending frames whose photo 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
/// null the positions already name 's frames and only pending frames are
/// placed (photos that arrived). A position naming no frame of names nothing and goes. Edited
/// in place like ; null when nothing changes or is not a
/// project object.
///
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();
var unreadable = new List();
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;
}
}
/// Moves every position of from 's frames to 's.
private static bool TranslatePositions(JsonObject project, FramePhotos from, FramePhotos to, List pending)
{
var changed = false;
if (project["excludedFrames"] is JsonArray excluded)
{
var kept = new List(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(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(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;
}
///
/// Gives the pending frames whose photo 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.
///
private static bool PlacePending(JsonObject project, FramePhotos to, List 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())
{
// 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;
}
/// Exclusions in ascending order without repeats and keyframes by frame (values that are no position last, as they were).
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().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);
}
}
/// The pending entry of (the copy of it names), added when there is none.
private static Parked Park(List 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;
}
/// The photo a pending entry names; null when it names none.
private static FramePhoto? PhotoOf(JsonObject entry)
{
var sha = entry["sha256"] is JsonValue s && s.TryGetValue(out var text) ? text : null;
var size = entry["size"] is JsonValue z && z.TryGetValue(out var bytes) ? bytes : -1;
DateTime? captured = entry["capturedAt"] is JsonValue t && t.TryGetValue(out var time) ? time : null;
return string.IsNullOrEmpty(sha) && (captured is null || size < 0) ? null : new FramePhoto(sha, size, captured);
}
/// Which copy of its photo a pending entry names; the first when it says nothing (or nothing readable).
private static int OccurrenceOf(JsonObject entry) => entry["occurrence"] is JsonValue o && o.TryGetValue(out var occurrence) && occurrence > 0 ? occurrence : 0;
private static bool Flag(JsonObject entry, string name) => entry[name] is JsonValue value && value.TryGetValue(out var set) && set;
/// The members of a pending entry this Chronos knows: its photo, which copy of it, and the positions on it.
internal static readonly HashSet PendingMembers = new(StringComparer.OrdinalIgnoreCase)
{
"sha256", "size", "capturedAt", "occurrence", "excluded", "hero", "keyframes",
};
/// A pending entry has a position to give its photo.
private static bool HoldsPosition(JsonObject entry) => Flag(entry, "excluded") || Flag(entry, "hero") || entry["keyframes"] is JsonArray { Count: > 0 };
/// A pending entry holds members this Chronos does not know (written by a newer one).
private static bool HasUnknownMembers(JsonObject entry) => entry.Any(p => !PendingMembers.Contains(p.Key));
/// A pending entry still holds something: a position to give its photo, or members that are not this Chronos's to drop.
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 nodes)
{
var copy = nodes.ToList();
array.Clear();
foreach (var node in copy) array.Add(node);
}
/// A pending entry being edited: its photo (and which copy of it), its JSON, and whether its photo took its place.
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; }
}
}
// LF on every OS (not Environment.NewLine): the text is hashed, and a project must read and hash alike on Windows and on
// the Linux server.
[JsonSourceGenerationOptions(
WriteIndented = true,
NewLine = "\n",
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true,
PropertyNameCaseInsensitive = true)]
[JsonSerializable(typeof(ProjectSettings))]
internal sealed partial class ProjectJson : JsonSerializerContext;