refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
namespace Chronos.Core.Project;
/// <summary>
/// A parameter the advisor can decide (BRIEF §10.4). In Auto the advisor's <see cref="AutoValue"/> applies and
/// <see cref="ReasonKey"/>/<see cref="ReasonArgs"/> explain it; touching the control stores a manual
/// <see cref="Manual"/> value; reset returns to Auto.
/// </summary>
public sealed record Auto<T>
{
public bool IsAuto { get; init; } = true;
/// <summary>The advisor's value; meaningful only when <see cref="HasAdvice"/>.</summary>
public T? AutoValue { get; init; }
/// <summary>True once the advisor stored a value. Needed because a value type's <see cref="AutoValue"/> is never
/// null: without it "no advice" and an advised 0 or false look the same.</summary>
public bool HasAdvice { get; init; }
/// <summary>The user's value when <see cref="IsAuto"/> is false.</summary>
public T? Manual { get; init; }
/// <summary>Localization key of the reason shown in the Auto pill tooltip.</summary>
public string? ReasonKey { get; init; }
public IReadOnlyList<string>? ReasonArgs { get; init; }
/// <summary>The value in force: manual when set by the user, otherwise the advisor's, otherwise <paramref name="fallback"/>.</summary>
public T Resolve(T fallback) => !IsAuto && Manual is not null ? Manual : HasAdvice && AutoValue is not null ? AutoValue : fallback;
public Auto<T> WithManual(T value) => this with { IsAuto = false, Manual = value };
public Auto<T> Reset() => this with { IsAuto = true, Manual = default };
public Auto<T> WithAdvice(T value, string? reasonKey, params string[] args) => this with { AutoValue = value, HasAdvice = true, ReasonKey = reasonKey, ReasonArgs = args };
}
+116
View File
@@ -0,0 +1,116 @@
namespace Chronos.Core.Project;
/// <summary>
/// A photo as every copy of a sequence knows it (BRIEF §14.5: originals are content-addressed): its SHA-256 once hashed,
/// else its size and capture time (a folder adopted and not verified yet). Frame ids and positions differ between a
/// server sequence and a PC's copy of it; the photo does not.
/// </summary>
/// <param name="Sha256">Hex SHA-256; null or empty while the copy has not hashed the file.</param>
public sealed record FramePhoto(string? Sha256, long Size, DateTime? CapturedAt)
{
public bool IsHashed => !string.IsNullOrEmpty(Sha256);
/// <summary>
/// The same photo: the same SHA-256 when both are hashed, otherwise the same size and capture time (to the
/// millisecond, as databases keep it).
/// </summary>
public bool Matches(FramePhoto other)
{
ArgumentNullException.ThrowIfNull(other);
if (IsHashed && other.IsHashed) return string.Equals(Sha256, other.Sha256, StringComparison.OrdinalIgnoreCase);
return Size == other.Size && CapturedAt is { } mine && other.CapturedAt is { } theirs && Millisecond(mine) == Millisecond(theirs);
}
internal static long Millisecond(DateTime time) => time.Ticks / TimeSpan.TicksPerMillisecond;
}
/// <summary>
/// The photos of one copy's frames by frame index (positions in capture order, BRIEF §5), and where a photo is among
/// them. A copy may hold one photo more than once (a folder adopted with 'IMG_0001.JPG' and 'IMG_0001 (1).JPG'); those
/// frames are told apart by their order (<see cref="Occurrence"/>). Immutable once built, so parallel workers may share it.
/// </summary>
public sealed class FramePhotos
{
private readonly FramePhoto?[] _byIndex;
private readonly Dictionary<string, List<int>> _bySha = new(StringComparer.Ordinal);
private readonly Dictionary<(long Size, long Time), List<int>> _bySizeAndTime = [];
/// <param name="frames">Each frame's index and photo, in any order.</param>
public FramePhotos(IEnumerable<(int Index, FramePhoto Photo)> frames)
{
ArgumentNullException.ThrowIfNull(frames);
var list = frames.Where(f => f.Index >= 0).ToList();
_byIndex = new FramePhoto?[list.Count == 0 ? 0 : list.Max(f => f.Index) + 1];
foreach (var (index, photo) in list) _byIndex[index] = photo;
for (var i = 0; i < _byIndex.Length; i++)
{
if (_byIndex[i] is not { } photo) continue;
if (photo.IsHashed)
{
var sha = photo.Sha256!.ToLowerInvariant();
if (!_bySha.TryGetValue(sha, out var copies)) _bySha[sha] = copies = [];
copies.Add(i);
}
if (photo.CapturedAt is not { } time) continue;
var key = (photo.Size, FramePhoto.Millisecond(time));
if (!_bySizeAndTime.TryGetValue(key, out var same)) _bySizeAndTime[key] = same = [];
same.Add(i);
}
}
public int Count => _byIndex.Length;
/// <summary>The photo at <paramref name="index"/>; null when no frame has that index.</summary>
public FramePhoto? this[int index] => (uint)index < (uint)_byIndex.Length ? _byIndex[index] : null;
/// <summary>Some frame is not hashed yet: matching it needs capture times.</summary>
public bool HasUnhashed => _byIndex.Any(p => p is { IsHashed: false });
/// <summary>
/// The index of the first frame holding <paramref name="photo"/> (<see cref="FramePhoto.Matches"/>), or with
/// <paramref name="occurrence"/> n of the (n+1)-th in index order; null when fewer frames hold it.
/// </summary>
public int? IndexOf(FramePhoto photo, int occurrence = 0)
{
ArgumentNullException.ThrowIfNull(photo);
ArgumentOutOfRangeException.ThrowIfNegative(occurrence);
var holding = Holding(photo);
return occurrence < holding.Count ? holding[occurrence] : null;
}
/// <summary>
/// Which of the frames holding the photo at <paramref name="index"/> it is, in index order: 0 for the first (and for
/// a photo held once), 1 for the second, … A position translated to another copy names the same one there.
/// </summary>
public int Occurrence(int index) => this[index] is { } photo ? Math.Max(Holding(photo).BinarySearch(index), 0) : 0;
/// <summary>
/// The indices of the frames holding <paramref name="photo"/>, ascending. A hashed photo is the frames with its SHA-256
/// when there are any: a frame not hashed yet with the same size and capture time may be another photo (a RAW of
/// constant size in a burst without sub-second times), so it counts only when no frame has the hash.
/// </summary>
private List<int> Holding(FramePhoto photo)
{
if (photo.IsHashed && _bySha.TryGetValue(photo.Sha256!.ToLowerInvariant(), out var hashed)) return hashed;
var holding = new List<int>(1);
if (photo.CapturedAt is not { } time || !_bySizeAndTime.TryGetValue((photo.Size, FramePhoto.Millisecond(time)), out var candidates)) return holding;
foreach (var index in candidates)
{
if (_byIndex[index]!.Matches(photo)) holding.Add(index);
}
return holding;
}
/// <summary>Both lists hold the same photos at the same indices: a position names the same photo on both.</summary>
public bool SameAs(FramePhotos other)
{
ArgumentNullException.ThrowIfNull(other);
if (other.Count != Count) return false;
for (var i = 0; i < Count; i++)
{
var (mine, theirs) = (this[i], other[i]);
if (mine is null != theirs is null || (mine is not null && !mine.Matches(theirs!))) return false;
}
return true;
}
}
+168
View File
@@ -0,0 +1,168 @@
using System.Globalization;
using System.Text;
using System.Text.Json;
using Chronos.Core.IO;
using Chronos.Core.Naming;
namespace Chronos.Core.Project;
/// <summary>The archive a project file's sequence lives in: its id, and its name and folder when the file was saved.</summary>
public sealed record BundleArchive(Guid Id, string Name, string? Path);
/// <summary>The sequence a project file applies to: its id, folder (relative to the archive), title and frame count when saved.</summary>
public sealed record BundleSequence(Guid Id, string Folder, string? Title, int Frames);
/// <summary>
/// A <c>.chronos</c> project file (BRIEF §18, file associations): which sequence of which archive, and the project
/// settings to open it with. The photos stay in the archive; opening the file opens that sequence in the editor with
/// these settings. UTF-8 JSON with a format name and version, so a newer file is refused rather than misread:
/// <code>{ "format": "chronos-project", "formatVersion": 1, "saved": …, "archive": { "id", "name", "path" },
/// "sequence": { "id", "folder", "title", "frames" }, "project": { …project.json… } }</code>
/// </summary>
public sealed record ProjectBundle(BundleArchive Archive, BundleSequence Sequence, ProjectSettings Project, DateTimeOffset Saved)
{
public const string Extension = ".chronos";
public const string FormatName = "chronos-project";
public const int CurrentFormatVersion = 1;
/// <summary>Project settings take a few kilobytes; a larger file is not a project file.</summary>
public const int MaxBytes = 4 << 20;
private static readonly JsonWriterOptions Indented = new() { Indented = true };
public string ToJson()
{
using var buffer = new MemoryStream();
using (var w = new Utf8JsonWriter(buffer, Indented))
{
w.WriteStartObject();
w.WriteString("format", FormatName);
w.WriteNumber("formatVersion", CurrentFormatVersion);
w.WriteString("saved", Saved);
w.WriteStartObject("archive");
w.WriteString("id", Archive.Id);
w.WriteString("name", Archive.Name);
if (Archive.Path is not null) w.WriteString("path", Archive.Path);
w.WriteEndObject();
w.WriteStartObject("sequence");
w.WriteString("id", Sequence.Id);
w.WriteString("folder", Sequence.Folder);
if (Sequence.Title is not null) w.WriteString("title", Sequence.Title);
w.WriteNumber("frames", Sequence.Frames);
w.WriteEndObject();
w.WritePropertyName("project");
// The project as project.json holds it, so both are read by the same tolerant reader.
using (var project = JsonDocument.Parse(Project.ToJson())) project.RootElement.WriteTo(w);
w.WriteEndObject();
}
return Encoding.UTF8.GetString(buffer.GetBuffer(), 0, (int)buffer.Length);
}
/// <summary>Reads a project file's text.</summary>
/// <exception cref="InvalidDataException">Not a Chronos project file, damaged, or written by a newer Chronos.</exception>
public static ProjectBundle Parse(string json)
{
JsonDocument document;
try
{
document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 64 });
}
catch (JsonException ex)
{
throw new InvalidDataException("The project file is not valid JSON.", ex);
}
using (document)
{
var root = document.RootElement;
if (root.ValueKind != JsonValueKind.Object || Text(root, "format") != FormatName) throw new InvalidDataException("Not a Chronos project file.");
if (!root.TryGetProperty("formatVersion", out var v) || v.ValueKind != JsonValueKind.Number || !v.TryGetInt32(out var version) || version < 1)
throw new InvalidDataException("The project file has no valid format version.");
if (version > CurrentFormatVersion) throw new InvalidDataException($"The project file uses format {version}, newer than this Chronos ({CurrentFormatVersion}).");
var archive = Section(root, "archive");
var sequence = Section(root, "sequence");
var folder = Text(sequence, "folder");
if (string.IsNullOrWhiteSpace(folder)) throw new InvalidDataException("The project file names no sequence folder.");
var frames = sequence.TryGetProperty("frames", out var f) && f.ValueKind == JsonValueKind.Number && f.TryGetInt32(out var count) && count >= 0 ? count : 0;
if (!root.TryGetProperty("project", out var project) || project.ValueKind != JsonValueKind.Object)
throw new InvalidDataException("The project file holds no project settings.");
ProjectSettings settings;
try
{
settings = ProjectSettings.FromJson(project.GetRawText());
}
catch (JsonException ex)
{
throw new InvalidDataException("The project settings in the file cannot be read.", ex);
}
var saved = root.TryGetProperty("saved", out var s) && s.ValueKind == JsonValueKind.String && s.TryGetDateTimeOffset(out var when) ? when : default;
return new ProjectBundle(
new BundleArchive(Id(archive), Text(archive, "name") ?? string.Empty, Text(archive, "path")),
new BundleSequence(Id(sequence), folder, Text(sequence, "title"), frames),
settings,
saved);
}
}
/// <summary>Reads a project file.</summary>
/// <exception cref="InvalidDataException">Not a Chronos project file (or too large to be one), damaged, or newer.</exception>
/// <exception cref="IOException">The file cannot be read.</exception>
public static ProjectBundle Load(string path)
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
if (stream.Length > MaxBytes) throw new InvalidDataException("The file is too large to be a Chronos project file.");
using var reader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
return Parse(reader.ReadToEnd());
}
/// <summary>Writes the file atomically (temp, flush, rename): an interrupted save never leaves half a file.</summary>
public void Save(string path) => AtomicFile.WriteAllText(path, ToJson());
/// <summary>
/// The settings to give the sequence when the file is opened, the sequence having <paramref name="frameCount"/>
/// frames and <paramref name="current"/> settings: the file's settings, except the frame positions (exclusions,
/// hero frame, camera keyframes) when frames were added or removed since the file was saved, as they would now
/// point at other frames; the sequence keeps its own.
/// </summary>
public ProjectSettings ProjectFor(ProjectSettings current, int frameCount) => frameCount == Sequence.Frames
? Project
: Project with
{
ExcludedFrames = current.ExcludedFrames,
HeroFrame = current.HeroFrame,
PendingFrames = current.PendingFrames,
Camera = Project.Camera with { Keyframes = current.Camera.Keyframes },
};
/// <summary>A file name for the project of a sequence titled <paramref name="title"/>, valid on every file system.</summary>
public static string FileNameFor(string title) =>
(PathTemplate.SanitizeSegment(title) is { Length: > 0 } name ? name : "Chronos") + Extension;
/// <summary>
/// A path in <paramref name="folder"/> for the project of <paramref name="title"/> that names no existing file
/// ("Harbour sunset.chronos", then "Harbour sunset (2).chronos"…): saving never replaces an earlier project file.
/// </summary>
public static string FreePathIn(string folder, string title)
{
var name = Path.GetFileNameWithoutExtension(FileNameFor(title));
var path = Path.Combine(folder, name + Extension);
for (var n = 2; File.Exists(path) || Directory.Exists(path); n++)
path = Path.Combine(folder, string.Create(CultureInfo.InvariantCulture, $"{name} ({n}){Extension}"));
return path;
}
private static JsonElement Section(JsonElement root, string name)
{
if (!root.TryGetProperty(name, out var section) || section.ValueKind != JsonValueKind.Object)
throw new InvalidDataException($"The project file has no '{name}' section.");
return section;
}
private static Guid Id(JsonElement section) =>
section.TryGetProperty("id", out var id) && id.ValueKind == JsonValueKind.String && id.TryGetGuid(out var guid) && guid != Guid.Empty
? guid
: throw new InvalidDataException("The project file has a missing or invalid id.");
private static string? Text(JsonElement section, string name) =>
section.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
}
+633
View File
@@ -0,0 +1,633 @@
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>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>
/// 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);
}
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)];
}
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;
}
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();
}
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; } = [];
}
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>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; }
}
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>
/// 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;
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)
{
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.Version > CurrentVersion)
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.</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;
parked.Placed = 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 (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>A pending entry still has a position to give its photo.</summary>
private static bool Waits(JsonObject entry) => Flag(entry, "excluded") || Flag(entry, "hero") || entry["keyframes"] is JsonArray { Count: > 0 };
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;