Owner review 2, R10 on the desktop: every timer that queued work out of sight is now a visible, editable schedule of this PC. - DesktopScheduleHost implements IScheduleHost: the PC's time zone, the archive at Settings › Archive's folder (refreshed from archive.json, none while it is offline), and three system schedules: archive-scan (every:<ScanIntervalMinutes>m, seeded once from the old setting, no catch-up), index-backup (every day with catch-up, replacing DatabaseBackups.RunDailyAsync) and housekeeping (daily 04:00 with catch-up: job history 90 days and the new cache-trim step). - AppServices starts the Scheduler after the engine, once the archive was reopened; an unplugged archive is looked for every minute and the scheduler woken when it is back. The rescan loop and the daily backup loop are gone; ApplyJobSettings wakes the scheduler. - CacheStore.Trim brings the cache to Settings › Storage › Cache limit, oldest files first, skipping files in use and the proxies, render-node and server-import folders; CacheTrimStep runs it as a clean-up step. - Jobs gets a Queue | Scheduled segmented control. Scheduled lists the schedules (switch, name, action, when, next run, last result) with Run now, Edit, Reset (system) or Delete (user's, confirmed), the selected schedule's last runs with Show in queue, and an in-window editor that checks every field with the scheduler's limits. Jobs a schedule queued carry a "Scheduled" pill; the history line follows the housekeeping's job-history days. - JobNotices: a scheduled background run raises a toast only when it fails (upkeep stays silent). - Settings › Archive › Rescan every is removed; ScanIntervalMinutes stays only as the seed. Strings in en and it; the others are retranslated. - The capture shows jobs-scheduled and jobs-schedule-editor on a stopped scheduler clock with sample schedules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit e25d812feb3f417cb9251c748c29e8035fd9b03c)
989 lines
53 KiB
C#
989 lines
53 KiB
C#
using System.IO;
|
||
using System.Net;
|
||
using Chronos.App.About;
|
||
using Chronos.App.Editor;
|
||
using Chronos.App.Import;
|
||
using Chronos.App.Infrastructure;
|
||
using Chronos.App.Jobs;
|
||
using Chronos.App.Library;
|
||
using Chronos.App.Server;
|
||
using Chronos.App.Settings;
|
||
using Chronos.Core.Advice;
|
||
using Chronos.Core.Analysis;
|
||
using Chronos.Core.Analysis.Deep;
|
||
using Chronos.Core.Archiving;
|
||
using Chronos.Core.Codecs.Jpeg;
|
||
using Chronos.Core.Diagnostics.Synthetic;
|
||
using Chronos.Core.Imaging;
|
||
using Chronos.Core.Imaging.Decoders;
|
||
using Chronos.Core.Localization;
|
||
using Chronos.Core.Metadata;
|
||
using Chronos.Core.Model;
|
||
using Chronos.Core.Project;
|
||
using Chronos.Core.Video;
|
||
using Chronos.Data;
|
||
using Chronos.Data.Archiving;
|
||
using Chronos.Data.Jobs;
|
||
using Chronos.Data.Scheduling;
|
||
using Chronos.Data.Sync;
|
||
using Chronos.Protocol;
|
||
using Chronos.Protocol.Client;
|
||
|
||
namespace Chronos.App.DesignTime;
|
||
|
||
/// <summary>
|
||
/// Synthetic content for <c>--capture</c> screenshots and the screen smoke tests ONLY: a temporary SQLite index
|
||
/// with an archive of generated JPEGs (one sequence stores its thumbnail as an embedded preview inside a fake RAW
|
||
/// file), jobs in every state, schedules (the system ones with runs, a weekly integrity check, a monthly report turned
|
||
/// off), a fake signed-in server with sequences to compare (one in conflict) and a fake encoder inventory. Everything lives in the
|
||
/// capture environment's temporary folder; nothing touches the network or the user's data.
|
||
/// </summary>
|
||
public sealed class SampleData
|
||
{
|
||
public const string ServerFingerprint = "9A:3C:71:E0:5B:12:C4:88:0F:6D:2A:91:E7:44:B3:5C:19:D2:6F:80:A1:3E:57:C9:0B:64:F8:2D:93:A6:71:CE";
|
||
|
||
/// <summary>
|
||
/// The sample's "now": every time it stores (jobs, transfers, renders, cards, the trash) is set from it, never from
|
||
/// the computer's clock, and <c>--capture</c> freezes <see cref="AppClock"/> at it, so the screenshots are the same
|
||
/// on any day (the running render's log reads 10:14 to 10:15).
|
||
/// </summary>
|
||
public static readonly DateTimeOffset Now = new(2026, 10, 2, 10, 18, 0, TimeSpan.Zero);
|
||
|
||
private const string ServerAddress = "https://nas.local:8443";
|
||
|
||
private readonly AppServices _services;
|
||
private readonly SampleSyncRemote _remote = new();
|
||
private ChronosDatabase? _db;
|
||
private Guid _sunrise;
|
||
private Guid _lakeComo;
|
||
private Guid _weeklyVerify = Guid.CreateVersion7();
|
||
private Guid? _scanSchedule;
|
||
private Permissions _permissions = RolePermissions.Default(UserRole.Editor);
|
||
|
||
private SampleData(AppServices services) => _services = services;
|
||
|
||
/// <summary>The server-only sequence whose proxies <see cref="CacheProxiesAsync"/> keeps on this PC (Sunrise over Superga).</summary>
|
||
public Guid ProxiedSequenceId => _sunrise;
|
||
|
||
/// <summary>Points the services at fakes (server, encoders, update check) for an empty first-run state.</summary>
|
||
public static SampleData Configure(AppServices services)
|
||
{
|
||
if (!services.Environment.IsCapture) throw new InvalidOperationException("Sample data only runs in a capture environment.");
|
||
var settings = services.Settings;
|
||
var sample = new SampleData(services);
|
||
services.Server.Dispose();
|
||
services.Server = new ServerSession(settings, services.SaveSettings, new SampleServerApiFactory(sample), new PlainTokenProtector());
|
||
services.Encoders = new SampleEncoders();
|
||
services.Formats = new SampleFormats();
|
||
services.CheckForUpdateAsync = _ => Task.FromResult<ReleaseInfo?>(null);
|
||
services.Devices.Dispose();
|
||
services.Devices = new SampleDeviceMonitor();
|
||
services.Sync.RemoteFactory = (_, _, _) => sample._remote;
|
||
services.Sync.EditorFactory = (_, _, _) => sample._remote;
|
||
// The schedules keep the sample's moment: nothing becomes due while the screenshots are taken.
|
||
services.SchedulerTime = new FixedTime(Now);
|
||
return sample;
|
||
}
|
||
|
||
/// <summary>Opens the empty temporary index (first run: no archive, nothing indexed).</summary>
|
||
public async Task OpenEmptyAsync()
|
||
{
|
||
_db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(_services.Environment.DatabasePath));
|
||
await _services.AttachAsync(_db, startEngine: false);
|
||
}
|
||
|
||
/// <summary>Fills the index with sample sequences, frames and jobs, and saves a signed-in server session.</summary>
|
||
public async Task FillAsync()
|
||
{
|
||
var db = _db ?? throw new InvalidOperationException("OpenEmptyAsync first.");
|
||
var settings = _services.Settings;
|
||
var root = Path.Combine(_services.Environment.DataDirectory, "archive");
|
||
Directory.CreateDirectory(root);
|
||
var archive = new Archive { Id = Guid.CreateVersion7(), Name = "ChronosArchive", RootPath = root, Created = Now.AddYears(-2) };
|
||
await db.Archives.UpsertAsync(archive);
|
||
var paths = new ArchivePaths(root);
|
||
Directory.CreateDirectory(paths.MetaDirectory);
|
||
ManifestStore.WriteArchive(paths.ManifestPath, new ArchiveManifest { Id = archive.Id, Name = archive.Name, Created = archive.Created });
|
||
|
||
var sequences = Sequences(archive.Id).ToList();
|
||
foreach (var (sequence, colours, raw) in sequences)
|
||
{
|
||
await db.Sequences.UpsertAsync(sequence);
|
||
await db.Frames.BulkInsertAsync(WriteFrames(root, sequence, colours, raw));
|
||
}
|
||
await db.Sequences.SetTagsAsync(sequences[0].Sequence.Id, ["sunset", "harbour"]);
|
||
await db.Sequences.SetTagsAsync(sequences[9].Sequence.Id, ["holy grail"]);
|
||
|
||
_scanSchedule = (await db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan))?.Id;
|
||
var jobs = Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id).ToList();
|
||
foreach (var job in jobs) await db.Jobs.EnqueueAsync(job);
|
||
await FillSchedulesAsync(db, jobs);
|
||
await FillServerAsync(db, sequences.Select(s => s.Sequence).ToList());
|
||
await SampleCards.InsertAsync(db, (SampleDeviceMonitor)_services.Devices, _services.Environment.DataDirectory);
|
||
await FillViewsAsync(db);
|
||
|
||
settings.LastArchivePath = @"D:\ChronosArchive";
|
||
settings.ServerUrl = "https://nas.local:8443";
|
||
settings.ServerUsername = "alberto";
|
||
settings.ProtectedToken = "sample-token";
|
||
settings.TrustedCertificates = [new TrustedCertificate { Fingerprint = ServerFingerprint, Server = "https://nas.local:8443", TrustedAt = new DateTimeOffset(2026, 9, 1, 9, 30, 0, TimeSpan.Zero) }];
|
||
settings.RecentServers = ["https://nas.local:8443"];
|
||
settings.RenderNodeOptIn = true;
|
||
// The jobs sample shows a deep analysis that yielded to the render (owner review 1).
|
||
settings.PriorityQueue = true;
|
||
settings.FirstRunCompleted = true;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Jobs › Scheduled (owner review 2, R10): the archive scan ran 4 minutes ago (its scan is in the history), the index
|
||
/// backup yesterday, the housekeeping never yet; a weekly integrity check the user made, whose run waits in the queue, and
|
||
/// a monthly orphans report turned off.
|
||
/// </summary>
|
||
private async Task FillSchedulesAsync(ChronosDatabase db, IReadOnlyList<Job> jobs)
|
||
{
|
||
var verify = jobs.First(j => j.ScheduleId == _weeklyVerify);
|
||
var weekly = ScheduleRecurrence.WeeklyAt([DayOfWeek.Sunday], new TimeOnly(2, 0));
|
||
var created = Now.AddDays(-40);
|
||
await db.Schedules.InsertAsync(new Schedule
|
||
{
|
||
Id = _weeklyVerify,
|
||
Name = "Weekly integrity check",
|
||
Action = ScheduleActions.Verify,
|
||
ParametersJson = ScheduleMapping.ParametersJson(ScheduleActions.Verify, new ScheduleParametersDto(OlderThanDays: 30, Percent: 25)),
|
||
Recurrence = weekly.Format(),
|
||
NextRun = weekly.Next(Now, TimeZoneInfo.Local),
|
||
LastRun = verify.Created,
|
||
LastJobId = verify.Id,
|
||
LastOutcome = ScheduleOutcome.Queued,
|
||
Created = created,
|
||
Updated = created,
|
||
});
|
||
var monthly = ScheduleRecurrence.MonthlyAt(1, new TimeOnly(5, 0));
|
||
await db.Schedules.InsertAsync(new Schedule
|
||
{
|
||
Id = Guid.CreateVersion7(),
|
||
Name = "Monthly orphans report",
|
||
Action = ScheduleActions.Orphans,
|
||
Recurrence = monthly.Format(),
|
||
Enabled = false,
|
||
Created = created.AddMinutes(5),
|
||
Updated = created.AddMinutes(5),
|
||
});
|
||
if (_scanSchedule is { } scan && jobs.FirstOrDefault(j => j.ScheduleId == scan) is { } scanned)
|
||
await db.Schedules.RecordOutcomeAsync(scan, scanned.Id, ScheduleOutcome.Queued, scanned.Created);
|
||
if (await db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.IndexBackup) is { } backup)
|
||
await db.Schedules.RecordOutcomeAsync(backup.Id, null, ScheduleOutcome.SkippedNothing, Now.AddDays(-1).AddHours(-2));
|
||
}
|
||
|
||
/// <summary>A clock stopped at one moment (the schedules of the capture).</summary>
|
||
private sealed class FixedTime(DateTimeOffset now) : TimeProvider
|
||
{
|
||
public override DateTimeOffset GetUtcNow() => now;
|
||
}
|
||
|
||
/// <summary>Two saved views of the Library ("Not analysed, largest" and one camera), BRIEF §12.2.</summary>
|
||
private static async Task FillViewsAsync(ChronosDatabase db)
|
||
{
|
||
var views = new SavedViewStore(db.Settings);
|
||
await views.SaveAsync(SavedView.Of(Guid.CreateVersion7(), "Not analysed, largest",
|
||
new LibraryFilter { Status = StatusFilter.NotAnalysed, Sort = Data.Repositories.SequenceSort.Size }));
|
||
await views.SaveAsync(SavedView.Of(Guid.CreateVersion7(), "Nikon Z 8", new LibraryFilter { Camera = "NIKON Z 8" }));
|
||
}
|
||
|
||
/// <summary>
|
||
/// Transfers for the sync table: an upload at 46 % (Comet over the ridge), an upload waiting (Fog lifting, Asti), a
|
||
/// download of originals waiting its turn halfway (Sunrise over Superga: jobs run one at a time) and one paused (Lake
|
||
/// Como storm).
|
||
/// </summary>
|
||
public async Task FillSyncAsync()
|
||
{
|
||
var db = _db ?? throw new InvalidOperationException("FillAsync first.");
|
||
async Task<Sequence> LocalAsync(string text) => (await db.Sequences.ListAsync(new Data.Repositories.SequenceQuery { Text = text, Limit = 1 })).Items[0];
|
||
var now = Now;
|
||
Job Transfer(JobKind kind, Guid target, string label, string parameters, JobState state, long done, long total) => new()
|
||
{
|
||
Id = Guid.CreateVersion7(),
|
||
Kind = kind,
|
||
TargetIds = [target],
|
||
TargetLabel = label,
|
||
ParametersJson = parameters,
|
||
State = state,
|
||
Priority = JobPriority.User,
|
||
ProgressDone = done,
|
||
ProgressTotal = total,
|
||
ItemsPerSecond = state == JobState.Running ? 1.6 : null,
|
||
Eta = state == JobState.Running ? TimeSpan.FromMinutes(4) : null,
|
||
NodeId = state == JobState.Queued ? null : _services.WorkerId,
|
||
Attempts = state == JobState.Queued ? 0 : 1,
|
||
Created = now.AddMinutes(-5),
|
||
Started = state == JobState.Queued ? null : now.AddMinutes(-5),
|
||
};
|
||
// One job at a time (owner review 1): the upload runs, so a job of this PC that ran waits for its turn, in the plain
|
||
// queue (the Jobs and Settings scenes, captured before, show the priority queue).
|
||
await RequeueLocalJobsAsync(db);
|
||
_services.Settings.PriorityQueue = false;
|
||
var upload = $$"""{"server":"{{ServerAddress}}"}""";
|
||
var originals = $$"""{"server":"{{ServerAddress}}","mode":"Originals"}""";
|
||
var comet = await LocalAsync("Comet");
|
||
var fog = await LocalAsync("Fog lifting");
|
||
await db.Jobs.EnqueueAsync(Transfer(JobKind.UploadCommit, comet.Id, comet.DisplayTitle, upload, JobState.Running, 462, 1_005));
|
||
await db.Jobs.EnqueueAsync(Transfer(JobKind.UploadCommit, fog.Id, fog.DisplayTitle, upload, JobState.Queued, 0, 0));
|
||
await db.Jobs.EnqueueAsync(Transfer(JobKind.Download, _sunrise, "Sunrise over Superga", originals, JobState.Queued, 1_210, 2_880));
|
||
await db.Jobs.EnqueueAsync(Transfer(JobKind.Download, _lakeComo, "Lake Como storm", originals, JobState.Paused, 300, 1_450));
|
||
}
|
||
|
||
/// <summary>
|
||
/// Fetches the proxies of Sunrise over Superga into the proxy cache through a download job on a one-off engine (the
|
||
/// capture's engine does not run jobs), so the sync table shows a sequence kept with proxies only.
|
||
/// </summary>
|
||
public async Task CacheProxiesAsync()
|
||
{
|
||
var db = _db ?? throw new InvalidOperationException("FillAsync first.");
|
||
var service = _services.Sync.Service ?? throw new InvalidOperationException("The index is not open.");
|
||
// The engine purges no history (the housekeeping schedule does): the sample's finished jobs, dated from Now, stay.
|
||
await using var engine = new JobEngine(db, service.CreateJobHandlers(_services.Sync),
|
||
new JobEngineOptions
|
||
{
|
||
Workers = 1,
|
||
WorkerId = "sample-proxies",
|
||
Kinds = [JobKind.Download],
|
||
PollInterval = TimeSpan.FromMilliseconds(50),
|
||
});
|
||
await engine.StartAsync();
|
||
var job = await service.EnqueueDownloadAsync(engine, ServerAddress, _sunrise, "Sunrise over Superga", SyncDownloadMode.Proxies, null);
|
||
for (var i = 0; i < 200 && await db.Jobs.GetAsync(job.Id) is { State: JobState.Queued or JobState.Running }; i++) await Task.Delay(50);
|
||
}
|
||
|
||
/// <summary>A render of Sunrise over Superga running on the sample server, 43 % done (the remote editor's server job).</summary>
|
||
public void RunServerRender() => _remote.Run(_sunrise, "render", 1_240, 2_880);
|
||
|
||
/// <summary>The sample server's jobs end (none waits or runs any more).</summary>
|
||
public void EndServerJobs() => _remote.EndJobs();
|
||
|
||
/// <summary>
|
||
/// The signed-in account keeps Read, Upload and Render but loses Edit (server sequences open read-only); the
|
||
/// session is read again so the client sees it.
|
||
/// </summary>
|
||
public async Task RestrictAccountAsync()
|
||
{
|
||
_permissions = Permissions.Read | Permissions.Upload | Permissions.Render;
|
||
await _services.Server.RestoreAsync();
|
||
}
|
||
|
||
/// <summary>
|
||
/// The editor's sample as a sequence the sample server also has (so its Export "Sync" applies), with two copies of
|
||
/// this PC's settings kept by "Save both" in its <c>.chronos</c> folder.
|
||
/// </summary>
|
||
public async Task KeepEditorCopiesAsync(Guid sequenceId)
|
||
{
|
||
var db = _db ?? throw new InvalidOperationException("FillAsync first.");
|
||
var sequence = await db.Sequences.GetAsync(sequenceId) ?? throw new InvalidOperationException("FillEditorAsync first.");
|
||
var archive = await db.Archives.GetAsync(sequence.ArchiveId) ?? throw new InvalidOperationException("FillEditorAsync first.");
|
||
var meta = new ArchivePaths(archive.RootPath).Sequence(sequence.Folder).MetaDirectory;
|
||
Directory.CreateDirectory(meta);
|
||
var project = sequence.SettingsJson is { } json ? ProjectSettings.FromJson(json) : new ProjectSettings();
|
||
var copies = new (DateTime Saved, double OffsetEv)[] { (new DateTime(2026, 9, 30, 21, 14, 5), 0.3), (new DateTime(2026, 10, 2, 8, 41, 37), -0.2) };
|
||
foreach (var (saved, offset) in copies)
|
||
{
|
||
var copy = project with { Exposure = project.Exposure with { ExposureOffsetEv = offset } };
|
||
Chronos.Core.IO.AtomicFile.WriteAllText(Path.Combine(meta, SyncService.SavedCopyName(saved)), copy.ToJson());
|
||
}
|
||
var remote = _remote.Add(SampleSyncRemote.Dto(sequence), sequence.SettingsJson, sequence.FrameCount);
|
||
await _services.Sync.Service!.LinkAsync(ServerAddress, remote, sequence.Id);
|
||
}
|
||
|
||
/// <summary>
|
||
/// The server's side: six sequences this PC also holds (two the same, one with settings changed on both sides, one
|
||
/// with more originals on the server, one with more here, one with renders this PC lacks) and two only on the server
|
||
/// (captured in the months the local sample spans, so they join the Library's year choices and timeline);
|
||
/// the others are only here.
|
||
/// </summary>
|
||
private async Task FillServerAsync(ChronosDatabase db, IReadOnlyList<Sequence> local)
|
||
{
|
||
Guid Id(string title) => local.First(s => s.Title == title).Id;
|
||
await db.Sequences.EditAsync(Id("Holy grail · Monviso"), new Data.Repositories.SequenceEdit { SettingsJson = DeflickerWindow(41) }, null);
|
||
var linked = new (string Title, int Frames, string? Settings, int Renders)[]
|
||
{
|
||
("Harbour sunset", 3, null, 0),
|
||
("Aurora, Tromsø", 3, null, 0),
|
||
("Holy grail · Monviso", 3, DeflickerWindow(33), 0),
|
||
("Construction cam · week 38", 8, null, 0),
|
||
("Milan skyline dusk", 1, null, 0),
|
||
("Star trails, Colle del Nivolet", 3, null, 3),
|
||
};
|
||
foreach (var (title, frames, settings, renders) in linked)
|
||
{
|
||
// The server's copy carries the same title, tags and rating as this PC's.
|
||
var sequence = (await db.Sequences.GetAsync(Id(title)))!;
|
||
var remote = _remote.Add(SampleSyncRemote.Dto(sequence) with { RenderedCount = renders }, settings, frames);
|
||
await _services.Sync.Service!.LinkAsync(ServerAddress, remote, sequence.Id);
|
||
}
|
||
_sunrise = _remote.Add(SampleSyncRemote.Dto(new Sequence
|
||
{
|
||
Id = Guid.CreateVersion7(),
|
||
ArchiveId = Guid.Empty,
|
||
Title = "Sunrise over Superga",
|
||
Folder = "2026/2026-07-02 Sony ILCE-7M4",
|
||
CameraMake = "SONY",
|
||
CameraModel = "ILCE-7M4",
|
||
FirstCapture = new DateTime(2026, 7, 2).AddHours(5.2),
|
||
LastCapture = new DateTime(2026, 7, 2).AddHours(6.8),
|
||
MedianInterval = 2,
|
||
FrameCount = 2_880,
|
||
TotalBytes = 2_880 * 21_000_000L,
|
||
Status = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt,
|
||
RenderedCount = 1,
|
||
UpdatedAt = Now,
|
||
}), null, 3);
|
||
_lakeComo = _remote.Add(SampleSyncRemote.Dto(new Sequence
|
||
{
|
||
Id = Guid.CreateVersion7(),
|
||
ArchiveId = Guid.Empty,
|
||
Title = "Lake Como storm",
|
||
Folder = "2026/2026-08-21 Canon EOS R5",
|
||
CameraMake = "Canon",
|
||
CameraModel = "Canon EOS R5",
|
||
FirstCapture = new DateTime(2026, 8, 21).AddHours(16.5),
|
||
LastCapture = new DateTime(2026, 8, 21).AddHours(17.3),
|
||
MedianInterval = 2,
|
||
FrameCount = 1_450,
|
||
TotalBytes = 1_450 * 45_000_000L,
|
||
Status = SequenceStatus.ThumbsBuilt,
|
||
UpdatedAt = Now,
|
||
}), null, 3);
|
||
|
||
static string DeflickerWindow(int frames) =>
|
||
"""{"exposure":{"deflickerWindow":{"isAuto":false,"manual":""" + frames.ToString(System.Globalization.CultureInfo.InvariantCulture) + "}}}";
|
||
}
|
||
|
||
/// <summary>
|
||
/// The sequence editor's sample: a second archive holding a synthetic harbour sunset of real JPEG frames with Exif
|
||
/// (flicker, two received exposure steps, white-balance drift, a horizon), indexed by a scan, analysed (light and
|
||
/// deep, saved as <c>analysis.json</c>), advised into <c>project.json</c> with one manual value and three camera
|
||
/// keyframes, and given two past renders.
|
||
/// </summary>
|
||
/// <returns>The sequence id to open in the editor.</returns>
|
||
public async Task<Guid> FillEditorAsync()
|
||
{
|
||
var db = _db ?? throw new InvalidOperationException("OpenEmptyAsync first.");
|
||
var archives = _services.Archives ?? throw new InvalidOperationException("The archive engine is not attached.");
|
||
var root = Path.Combine(_services.Environment.DataDirectory, "editor-archive");
|
||
var archive = await archives.CreateAsync(root, "Editor sample");
|
||
var sunset = SyntheticSequence.Create(EditorSunset);
|
||
var folder = Path.Combine(root, "2026", "2026-09-28 Canon EOS R5");
|
||
Directory.CreateDirectory(folder);
|
||
for (var i = 0; i < sunset.Count; i++)
|
||
{
|
||
using var image = SunsetFrame(sunset, i);
|
||
var exif = ExifWriter.BuildJpegApp1(sunset.Metadata[i]);
|
||
File.WriteAllBytes(Path.Combine(folder, $"IMG_{4211 + i:0000}.JPG"), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 88, App1Segments = [exif[4..]] }));
|
||
}
|
||
await archives.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, CancellationToken.None);
|
||
var id = (await db.Sequences.ListLocationsAsync(archive.Id)).Single().Id;
|
||
await archives.SetSequenceInfoAsync(id, "Harbour sunset", ["sunset", "harbour"], 4, null);
|
||
|
||
var source = new LocalSequenceSource(db, id, DecoderFactory.CreateClient(null), null);
|
||
var content = await source.LoadAsync(CancellationToken.None);
|
||
var deep = await DeepAnalyzer.AnalyzeAsync(new SunsetFrames(sunset));
|
||
var sequence = content.Sequence;
|
||
deep.Save(new ArchivePaths(root).Sequence(sequence.Folder).AnalysisPath);
|
||
var advice = Advisor.Recommend(content.Light, deep, SequenceContext.FromFrames(content.Frames));
|
||
// As a user leaves it: the advice applied, one value taken over by hand (Sun track) and a slow push-in.
|
||
var advised = Advisor.Apply(content.Project, advice);
|
||
var project = advised with
|
||
{
|
||
Exposure = advised.Exposure with { DeflickerStrength = advised.Exposure.DeflickerStrength.WithManual(0.8) },
|
||
Camera = advised.Camera with { Keyframes = [new CameraKey(0, 0.5, 0.5, 1, 0), new CameraKey(48, 0.6, 0.46, 1.4, 0), new CameraKey(95, 0.64, 0.4, 1.9, 0)] },
|
||
};
|
||
await source.SaveProjectAsync(project, content.Project, CancellationToken.None);
|
||
await db.Sequences.RecordAnalysisAsync(id, SequenceStatus.AnalyzedLight | SequenceStatus.AnalyzedDeep | SequenceStatus.HasWarnings, SequenceStatus.None,
|
||
advice.Findings.Count(f => f.Severity >= FindingSeverity.Warning), AnalysisSummary.From(deep).ToJson());
|
||
foreach (var (preset, codec, width, height, daysAgo, bytes) in new[] { ("4K archive", "hevc", 3840, 2160, 7, 2_210_000_000L), ("1080p share", "h264", 1920, 1080, 3, 412_000_000L) })
|
||
{
|
||
await db.Renders.InsertAsync(new Render
|
||
{
|
||
Id = Guid.CreateVersion7(),
|
||
SequenceId = id,
|
||
PresetName = preset,
|
||
OutputPath = Path.Combine(folder, "exports", $"2026-09-28 Harbour sunset - {preset}.mp4"),
|
||
Codec = codec,
|
||
Width = width,
|
||
Height = height,
|
||
Fps = 24,
|
||
DurationSeconds = 5,
|
||
Bytes = bytes,
|
||
Created = Now.AddDays(-daysAgo),
|
||
ProducedBy = "studio-pc",
|
||
});
|
||
}
|
||
return id;
|
||
}
|
||
|
||
/// <summary>A deep analysis of <paramref name="sequenceId"/> half way through: the editor's busy state (settings wait, viewing stays live).</summary>
|
||
public async Task MarkAnalysingAsync(Guid sequenceId)
|
||
{
|
||
var db = _db ?? throw new InvalidOperationException("OpenEmptyAsync first.");
|
||
// The analysis is the one job this PC runs (owner review 1).
|
||
await RequeueLocalJobsAsync(db);
|
||
var now = Now;
|
||
await db.Jobs.EnqueueAsync(new Job
|
||
{
|
||
Id = Guid.CreateVersion7(),
|
||
Kind = JobKind.DeepAnalyse,
|
||
TargetIds = [sequenceId],
|
||
TargetLabel = "Harbour sunset",
|
||
State = JobState.Running,
|
||
Priority = JobPriority.User,
|
||
ProgressDone = 40,
|
||
ProgressTotal = 96,
|
||
ItemsPerSecond = 12,
|
||
NodeId = _services.WorkerId,
|
||
Attempts = 1,
|
||
Created = now.AddSeconds(-5),
|
||
Started = now.AddSeconds(-4),
|
||
});
|
||
}
|
||
|
||
/// <summary>Puts the jobs this PC runs back in the queue, so the job a scene starts is the one running (owner review 1).</summary>
|
||
private async Task RequeueLocalJobsAsync(ChronosDatabase db)
|
||
{
|
||
foreach (var running in (await db.Jobs.ListAsync(JobState.Running, 50)).Items.Where(j => j.NodeId is { } node && JobText.IsLocal(node, _services.WorkerId)))
|
||
await db.Jobs.RequeueAsync(running.Id, running.NodeId!);
|
||
}
|
||
|
||
/// <summary>A two-minute sunset at 2 s intervals: darkening scene, flicker, two shutter steps the pixels received, warming light.</summary>
|
||
private static readonly SyntheticSequenceOptions EditorSunset = new()
|
||
{
|
||
Width = 600,
|
||
Height = 400,
|
||
FrameCount = 96,
|
||
Seed = 28,
|
||
Start = new DateTime(2026, 9, 28, 18, 2, 11),
|
||
IntervalSeconds = 2,
|
||
StartEv = 0.5,
|
||
EndEv = -2.5,
|
||
FlickerEv = 0.12,
|
||
ExposureSteps = [new SyntheticExposureStep(32, -1), new SyntheticExposureStep(64, -1)],
|
||
HorizonFraction = 0.62,
|
||
HorizonWave = 0.02,
|
||
SkyLevel = 0.32,
|
||
LandLevel = 0.06,
|
||
StartKelvin = 5600,
|
||
EndKelvin = 3200,
|
||
WhiteBalanceJitter = 0.03,
|
||
NoiseSigma = 0.002,
|
||
BaseExposureTime = 1.0 / 125,
|
||
BaseFNumber = 8,
|
||
BaseIso = 100,
|
||
CameraMake = "Canon",
|
||
CameraModel = "Canon EOS R5",
|
||
Lens = "RF15-35mm F2.8 L IS USM",
|
||
};
|
||
|
||
/// <summary>
|
||
/// The synthetic frame (its exposure truth: scene, steps, flicker, white balance) coloured as a harbour sunset: a
|
||
/// blue-to-amber sky gradient normalised to unit luminance, so the measured luminance keeps the truth, and a setting sun.
|
||
/// </summary>
|
||
private static ImageBuffer SunsetFrame(SyntheticSequence sequence, int index)
|
||
{
|
||
var image = sequence.Render(index);
|
||
var (w, h) = (image.Width, image.Height);
|
||
var t = index / (double)(sequence.Count - 1);
|
||
var horizon = sequence.Options.HorizonFraction * h;
|
||
var (sunX, sunY) = (w * 0.64, h * (0.28 + 0.3 * t));
|
||
var gain = Math.Pow(2, sequence.SceneEv[index] + sequence.ExposureOffsetEv[index] + sequence.FlickerEv[index]);
|
||
double[][] sky = [Linear("#2A2F6B"), Linear("#8E3F57"), Linear("#E07A48"), Linear("#F5B45E")];
|
||
var land = Linear("#3A3540");
|
||
for (var y = 0; y < h; y++)
|
||
{
|
||
double[] colour;
|
||
if (y < horizon)
|
||
{
|
||
var f = y / horizon * (sky.Length - 1);
|
||
var k = Math.Min((int)f, sky.Length - 2);
|
||
colour = [.. Enumerable.Range(0, 3).Select(c => sky[k][c] + (sky[k + 1][c] - sky[k][c]) * (f - k))];
|
||
}
|
||
else
|
||
{
|
||
colour = land;
|
||
}
|
||
var luminance = 0.2126 * colour[0] + 0.7152 * colour[1] + 0.0722 * colour[2];
|
||
for (var x = 0; x < w; x++)
|
||
{
|
||
var d = Math.Sqrt((x - sunX) * (x - sunX) + (y - sunY) * (y - sunY));
|
||
var sun = y < horizon ? gain * 4 * Math.Exp(-d * d / 220) : 0;
|
||
for (var c = 0; c < 3; c++)
|
||
{
|
||
var plane = image.Plane(c);
|
||
plane[y * w + x] = (float)(plane[y * w + x] * colour[c] / luminance + sun * (c == 0 ? 1.0 : c == 1 ? 0.75 : 0.45));
|
||
}
|
||
}
|
||
}
|
||
return image;
|
||
}
|
||
|
||
private static double[] Linear(string hex)
|
||
{
|
||
var rgb = Convert.FromHexString(hex.TrimStart('#'));
|
||
return [.. rgb.Select(v => ColorSpace.SrgbToLinear(v / 255.0))];
|
||
}
|
||
|
||
/// <summary>The sunset as the deep analysis reads it (the pixels written to the JPEGs, before compression).</summary>
|
||
private sealed class SunsetFrames(SyntheticSequence sequence) : IFrameSource
|
||
{
|
||
public int Count => sequence.Count;
|
||
|
||
public LightFrame Metadata(int index) => LightFrame.From(sequence.Metadata[index], index);
|
||
|
||
public ValueTask<ImageBuffer?> LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken) =>
|
||
ValueTask.FromResult<ImageBuffer?>(SunsetFrame(sequence, index));
|
||
}
|
||
|
||
private IEnumerable<(Sequence Sequence, string[] Colours, bool Raw)> Sequences(Guid archiveId)
|
||
{
|
||
var now = new DateTime(2026, 9, 28, 18, 2, 11);
|
||
(Sequence, string[], bool) Make(string? title, string folder, string make, string model, int frames, TimeSpan span, double interval, int daysAgo,
|
||
SequenceStatus status, string[] colours, int renders = 0, int warnings = 0, SequenceOrigin origin = SequenceOrigin.Local,
|
||
SyncState sync = SyncState.LocalOnly, bool raw = false, int previewOnly = 0)
|
||
{
|
||
var start = now.AddDays(-daysAgo);
|
||
return (new Sequence
|
||
{
|
||
Id = Guid.CreateVersion7(),
|
||
ArchiveId = archiveId,
|
||
Title = title,
|
||
Folder = folder,
|
||
CameraMake = make,
|
||
CameraModel = model,
|
||
FirstCapture = start,
|
||
LastCapture = start + span,
|
||
FrameCount = frames,
|
||
MedianInterval = interval,
|
||
TotalBytes = frames * 24_000_000L,
|
||
Status = status,
|
||
RenderedCount = renders,
|
||
WarningCount = warnings,
|
||
PreviewOnlyCount = previewOnly,
|
||
Origin = origin,
|
||
SyncState = sync,
|
||
UpdatedAt = Now,
|
||
}, colours, raw);
|
||
}
|
||
|
||
const SequenceStatus Analysed = SequenceStatus.AnalyzedLight | SequenceStatus.AnalyzedDeep;
|
||
const SequenceStatus Full = Analysed | SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt | SequenceStatus.Verified;
|
||
yield return Make("Harbour sunset", "2026/2026-09-28 Canon EOS R5", "Canon", "Canon EOS R5", 3_600, TimeSpan.FromHours(2), 2, 0, Full,
|
||
["#2A2F6B", "#B8452F", "#F0A04B", "#2B2B33"], renders: 2, sync: SyncState.InSync, raw: true);
|
||
yield return Make("Comet over the ridge", "2026/2026-08-13 GoPro HERO8 Black", "GoPro", "HERO8 Black", 1_005, new TimeSpan(5, 34, 0), 20, 46, Full,
|
||
["#050914", "#0F1D3A", "#1E3A2F"], warnings: 1);
|
||
yield return Make(null, "2026/2026-09-27 Sony ILCE-7M4", "SONY", "ILCE-7M4", 2_140, new TimeSpan(1, 11, 0), 2, 1, Analysed,
|
||
["#4A7FB5", "#A9C9E6", "#6F7D6A"]);
|
||
yield return Make("Aurora, Tromsø", "2026/2026-02-20 Nikon Z 8", "NIKON CORPORATION", "NIKON Z 8", 1_860, new TimeSpan(4, 8, 0), 8, 220, Full,
|
||
["#0C2A3A", "#1AA08C", "#0B1A26"], sync: SyncState.InSync, previewOnly: 1_860);
|
||
yield return Make("Construction cam · week 38", "2026/2026-09-14 Brinno TLC2020", "Brinno", "TLC2020", 8_920, TimeSpan.FromDays(7), 60, 14,
|
||
SequenceStatus.None, ["#7C8AA0", "#C9CFD6", "#4C5058"], origin: SequenceOrigin.Server, sync: SyncState.RemoteOnly);
|
||
yield return Make("Milan skyline dusk", "2026/2026-06-03 Apple iPhone 16 Pro", "Apple", "iPhone 16 Pro", 2_400, new TimeSpan(1, 20, 0), 2, 117, Full,
|
||
["#1B2B4A", "#D67A4E", "#3A2A2A"], renders: 1);
|
||
yield return Make("Clouds over the Langhe", "2026/2026-05-11 Canon EOS R5", "Canon", "Canon EOS R5", 1_320, TimeSpan.FromMinutes(44), 2, 140,
|
||
SequenceStatus.None, ["#3B6FA6", "#E6EEF5", "#5C7A52"]);
|
||
yield return Make("Star trails, Colle del Nivolet", "2025/2025-08-02 Sony ILCE-7M4", "SONY", "ILCE-7M4", 640, new TimeSpan(5, 20, 0), 30, 422, Full,
|
||
["#08101C", "#142A4A", "#0D0F14"], renders: 3);
|
||
yield return Make("Fog lifting, Asti", "2025/2025-11-21 DJI Osmo Action 5 Pro", "DJI", "Osmo Action 5 Pro", 980, new TimeSpan(1, 38, 0), 6, 311,
|
||
Analysed, ["#6A8FB0", "#F2E6D0", "#7A6A55"]);
|
||
yield return Make("Holy grail · Monviso", "2025/2025-07-14 Nikon Z 8", "NIKON CORPORATION", "NIKON Z 8", 1_720, new TimeSpan(3, 2, 0), 6, 441, Full,
|
||
["#2C1F4D", "#C2455A", "#F5A524", "#26262C"], renders: 1, sync: SyncState.InSync);
|
||
for (var i = 0; i < 26; i++)
|
||
{
|
||
var shade = 40 + i * 6;
|
||
yield return Make($"Rooftop · day {i + 1}", $"2025/2025-03-{i + 1:00} Canon EOS R6", "Canon", "Canon EOS R6", 1_200 + i * 37, TimeSpan.FromHours(9), 30,
|
||
480 + i, i % 3 == 0 ? Analysed : Full, [$"#{shade:X2}5A8C", "#C9D6E2", "#3D4A3A"]);
|
||
}
|
||
}
|
||
|
||
/// <summary>Three small JPEG frames per sequence; a "raw" sequence wraps its JPEGs in a fake CR2 with an embedded preview.</summary>
|
||
private static IEnumerable<Frame> WriteFrames(string root, Sequence sequence, string[] colours, bool raw)
|
||
{
|
||
var folder = Path.Combine(root, sequence.Folder.Replace('/', Path.DirectorySeparatorChar));
|
||
Directory.CreateDirectory(folder);
|
||
var count = sequence.Title?.StartsWith("Rooftop", StringComparison.Ordinal) == true ? 1 : 3;
|
||
var frames = new List<Frame>(count);
|
||
for (var i = 0; i < count; i++)
|
||
{
|
||
var jpeg = Gradient(colours, 320, 180, i / 3.0);
|
||
var name = $"{sequence.FirstCapture:yyyy-MM-dd}_{i + 1:0000}.{(raw ? "CR2" : "JPG")}";
|
||
long? previewOffset = null;
|
||
long? previewLength = null;
|
||
var bytes = jpeg;
|
||
if (raw)
|
||
{
|
||
// A fake RAW: a header the decoders cannot read, the JPEG preview, then trailing data.
|
||
var header = new byte[4096];
|
||
"II*\0"u8.CopyTo(header);
|
||
bytes = [.. header, .. jpeg, .. new byte[2048]];
|
||
previewOffset = header.Length;
|
||
previewLength = jpeg.Length;
|
||
}
|
||
File.WriteAllBytes(Path.Combine(folder, name), bytes);
|
||
frames.Add(new Frame
|
||
{
|
||
Id = Guid.CreateVersion7(),
|
||
SequenceId = sequence.Id,
|
||
Index = i,
|
||
RelativePath = sequence.Folder + "/" + name,
|
||
FileName = name,
|
||
Size = bytes.Length,
|
||
CapturedAt = sequence.FirstCapture!.Value.AddSeconds(i * (sequence.MedianInterval ?? 2)),
|
||
TimestampSource = TimestampSource.ExifOriginal,
|
||
Width = 320,
|
||
Height = 180,
|
||
Format = raw ? ImageFileFormat.Cr2 : ImageFileFormat.Jpeg,
|
||
PreviewOffset = previewOffset,
|
||
PreviewLength = previewLength,
|
||
ExposureTime = 1.0 / 250,
|
||
FNumber = 8,
|
||
Iso = 100,
|
||
});
|
||
}
|
||
return frames;
|
||
}
|
||
|
||
/// <summary>A vertical gradient through the given sRGB colours with a sun disc that moves with <paramref name="phase"/>.</summary>
|
||
private static byte[] Gradient(string[] colours, int width, int height, double phase)
|
||
{
|
||
using var image = new ImageBuffer(width, height, 3, clear: false);
|
||
var stops = colours.Select(Parse).ToArray();
|
||
var sunX = width * (0.3 + 0.4 * phase);
|
||
var sunY = height * (0.55 - 0.1 * phase);
|
||
for (var y = 0; y < height; y++)
|
||
{
|
||
var t = y / (double)(height - 1) * (stops.Length - 1);
|
||
var k = Math.Min((int)t, stops.Length - 2);
|
||
var f = t - k;
|
||
for (var x = 0; x < width; x++)
|
||
{
|
||
var d = Math.Sqrt((x - sunX) * (x - sunX) + (y - sunY) * (y - sunY));
|
||
var sun = Math.Clamp(1 - d / 14, 0, 1);
|
||
for (var c = 0; c < 3; c++)
|
||
{
|
||
var value = stops[k][c] * (1 - f) + stops[k + 1][c] * f;
|
||
image.Plane(c)[y * width + x] = (float)(value + sun * (1.0 - value) * 0.9);
|
||
}
|
||
}
|
||
}
|
||
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85 });
|
||
|
||
static double[] Parse(string hex)
|
||
{
|
||
var rgb = Convert.FromHexString(hex.TrimStart('#'));
|
||
return [Linear(rgb[0]), Linear(rgb[1]), Linear(rgb[2])];
|
||
}
|
||
|
||
static double Linear(byte v)
|
||
{
|
||
var s = v / 255.0;
|
||
return s <= 0.04045 ? s / 12.92 : Math.Pow((s + 0.055) / 1.055, 2.4);
|
||
}
|
||
}
|
||
|
||
private IEnumerable<Job> Jobs(IReadOnlyList<Sequence> s, Guid archiveId)
|
||
{
|
||
var now = Now;
|
||
var here = _services.WorkerId;
|
||
Job Make(JobKind kind, Sequence? target, string label, JobState state, long done, long total, double? rate = null, TimeSpan? eta = null,
|
||
TimeSpan? startedAgo = null, TimeSpan? runFor = null, string? node = null, string? error = null, string? log = null,
|
||
JobPriority priority = JobPriority.Normal, TimeSpan? createdAgo = null, Guid? schedule = null) => new()
|
||
{
|
||
Id = Guid.CreateVersion7(),
|
||
Kind = kind,
|
||
ScheduleId = schedule,
|
||
TargetIds = target is null ? [archiveId] : [target.Id],
|
||
TargetLabel = label,
|
||
State = state,
|
||
Priority = priority,
|
||
ProgressDone = done,
|
||
ProgressTotal = total,
|
||
ItemsPerSecond = rate,
|
||
Eta = eta,
|
||
NodeId = state == JobState.Queued ? null : node ?? here,
|
||
Error = error,
|
||
LogTail = log,
|
||
Attempts = state == JobState.Queued ? 0 : 1,
|
||
Created = now - (createdAgo ?? startedAgo ?? TimeSpan.FromMinutes(1)),
|
||
Started = startedAgo is { } ago ? now - ago : null,
|
||
Finished = state is JobState.Done or JobState.Failed && startedAgo is { } a2 ? now - a2 + (runFor ?? TimeSpan.FromMinutes(1)) : null,
|
||
};
|
||
|
||
// The user's render runs before the older render the batch queued (higher priority).
|
||
yield return Make(JobKind.Render, s[0], "Harbour sunset → 4K 10-bit HEVC · 24 fps", JobState.Running, 2_232, 3_600, 11.3, TimeSpan.FromMinutes(2),
|
||
startedAgo: TimeSpan.FromMinutes(3.4), priority: JobPriority.User, log:
|
||
"10:14:02 window 41 · deflicker −67 % · 3 exposure steps redistributed over 18 frames\n" +
|
||
"10:14:03 stabilisation on · mean shake 0.42 px · crop 1.8 %\n" +
|
||
"10:14:03 encoder NVENC HEVC Main10 · 3840×2160 · 120 Mb/s · 24 fps · GOP 48\n" +
|
||
"10:15:41 frame 2232 / 3600 · 11.3 fps · spill 0 · memory 6.1 GB of 8 GB budget");
|
||
// Jobs run one at a time (owner review 1): the deep analysis yielded to the render and resumes after it; the user
|
||
// paused the proxies, so the render started at once.
|
||
yield return Make(JobKind.DeepAnalyse, s[4], s[4].DisplayTitle, JobState.Queued, 2_498, 8_920, createdAgo: TimeSpan.FromMinutes(9),
|
||
log: "10:12:40 " + Loc.L("Jobs.Line.Yielded", Loc.L("Jobs.Kind.Render")));
|
||
yield return Make(JobKind.Proxies, s[1], s[1].DisplayTitle, JobState.Paused, 915, 1_005, startedAgo: TimeSpan.FromMinutes(14),
|
||
priority: JobPriority.Background);
|
||
yield return Make(JobKind.Render, s[3], "Aurora, Tromsø → 1080p share H.264", JobState.Queued, 0, 0, createdAgo: TimeSpan.FromMinutes(12));
|
||
// The weekly integrity check the user scheduled waits behind the user's jobs.
|
||
yield return Make(JobKind.Verify, null, "Archive · 2024", JobState.Queued, 0, 0, priority: JobPriority.Background, createdAgo: TimeSpan.FromMinutes(30),
|
||
schedule: _weeklyVerify);
|
||
yield return Make(JobKind.Verify, s[7], s[7].DisplayTitle, JobState.Failed, 640, 640, 900, startedAgo: TimeSpan.FromMinutes(25), runFor: TimeSpan.FromSeconds(43),
|
||
error: "2 files whose hash no longer matches the sidecar", log: "09:58:01 verify 640 files\n09:58:43 2 hash mismatches: 2025-08-02_0213.ARW, 2025-08-02_0214.ARW");
|
||
// The archive scan schedule's latest run.
|
||
yield return Make(JobKind.Scan, null, "ChronosArchive", JobState.Done, 412, 412, 640, startedAgo: TimeSpan.FromMinutes(4), runFor: TimeSpan.FromSeconds(1),
|
||
priority: JobPriority.Background, schedule: _scanSchedule);
|
||
yield return Make(JobKind.Render, s[5], "Milan skyline dusk → 4K HEVC", JobState.Done, 2_400, 2_400, 14.8, startedAgo: TimeSpan.FromMinutes(70),
|
||
runFor: new TimeSpan(0, 2, 41), node: "studio-pc");
|
||
yield return Make(JobKind.Import, s[0], "EOS R5 · card A → Archive · 4,812 photos", JobState.Done, 4_812, 4_812, 7.1, startedAgo: TimeSpan.FromMinutes(110),
|
||
runFor: new TimeSpan(0, 11, 52));
|
||
yield return Make(JobKind.Thumbs, s[2], s[2].DisplayTitle, JobState.Done, 2_140, 2_140, 2_300, startedAgo: TimeSpan.FromMinutes(108), runFor: TimeSpan.FromSeconds(1));
|
||
}
|
||
|
||
/// <summary>A server that always answers as "Studio NAS" with a self-signed certificate the sample trusts.</summary>
|
||
private sealed class SampleServerApiFactory(SampleData sample) : IServerApiFactory
|
||
{
|
||
public IServerApi Create(Uri baseAddress, IReadOnlyCollection<string> trustedFingerprints) => new SampleServerApi(sample, baseAddress, trustedFingerprints);
|
||
}
|
||
|
||
/// <summary>The sample account, an editor unless <see cref="RestrictAccountAsync"/> took the Edit right away.</summary>
|
||
private sealed class SampleServerApi(SampleData sample, Uri baseAddress, IReadOnlyCollection<string> trusted) : IServerApi
|
||
{
|
||
private UserDto User => new(Guid.Empty, "alberto", "Alberto", "editor", (long)sample._permissions, 5_000_000_000_000, 2_100_000_000_000, false, false,
|
||
new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero), Now);
|
||
|
||
public Uri BaseAddress { get; } = baseAddress;
|
||
|
||
public string? Token { get; set; }
|
||
|
||
public async Task<ServerInfo> GetInfoAsync(CancellationToken ct)
|
||
{
|
||
await Task.Delay(14, ct);
|
||
if (!trusted.Contains(ServerFingerprint, StringComparer.OrdinalIgnoreCase)) throw new UntrustedCertificateException(ServerFingerprint);
|
||
return new ServerInfo("Studio NAS", "1.3.0", 1, [], ServerFingerprint, [], new ServerLimits(0, 0));
|
||
}
|
||
|
||
public Task<LoginResponse> LoginAsync(string username, string password, CancellationToken ct)
|
||
{
|
||
Token = "sample-token";
|
||
return Task.FromResult(new LoginResponse(Token, User, false, Now.AddDays(30)));
|
||
}
|
||
|
||
public Task<UserDto> MeAsync(CancellationToken ct) =>
|
||
Token == "sample-token" ? Task.FromResult(User) : throw new ChronosApiException(HttpStatusCode.Unauthorized, new ApiError("unauthorized", "Sign in"));
|
||
|
||
public Task LogoutAsync(CancellationToken ct) => Task.CompletedTask;
|
||
|
||
public void Dispose()
|
||
{
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// The sample server's sequences for the sync table and the editor of a server sequence: listings, manifests
|
||
/// (frames hashed from their index, so unhashed sample frames match them by count; renders as many as the listing
|
||
/// says), settings edits, proxies (generated JPEGs) and jobs the editor posts (kept queued until cancelled, or run by
|
||
/// <see cref="Run"/>); uploads, originals and analysis reports are not part of the screenshots.
|
||
/// </summary>
|
||
private sealed class SampleSyncRemote : ISyncRemote, IRemoteSequenceApi
|
||
{
|
||
private readonly Dictionary<Guid, (SequenceDto Dto, string? Settings, Guid[] Frames)> _sequences = [];
|
||
private readonly Dictionary<Guid, JobDto> _jobs = [];
|
||
|
||
public string Server => ServerAddress;
|
||
|
||
public static SequenceDto Dto(Sequence s) => new(Guid.CreateVersion7(), s.Title, s.DisplayTitle, s.Folder, s.CameraMake, s.CameraModel, s.Lens,
|
||
s.FirstCapture, s.LastCapture, s.FrameCount, s.MedianInterval, s.TotalBytes, (long)s.Status, s.RenderedCount, null, s.Tags, s.Rating, s.Notes, 2, 1,
|
||
0, null, s.UpdatedAt);
|
||
|
||
public Guid Add(SequenceDto dto, string? settings, int frames)
|
||
{
|
||
lock (_sequences) _sequences[dto.Id] = (dto, settings, [.. Enumerable.Range(0, frames).Select(_ => Guid.CreateVersion7())]);
|
||
return dto.Id;
|
||
}
|
||
|
||
public Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken)
|
||
{
|
||
lock (_sequences) return Task.FromResult<IReadOnlyList<SequenceDto>>([.. _sequences.Values.Select(s => s.Dto)]);
|
||
}
|
||
|
||
public Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken)
|
||
{
|
||
lock (_sequences) return Task.FromResult(_sequences[id].Dto);
|
||
}
|
||
|
||
public Task<Protocol.SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken)
|
||
{
|
||
lock (_sequences)
|
||
{
|
||
var (dto, settings, frames) = _sequences[id];
|
||
var hasProxy = (dto.Status & (long)SequenceStatus.ProxiesBuilt) != 0;
|
||
var created = new DateTimeOffset(2026, 9, 20, 21, 0, 0, TimeSpan.Zero);
|
||
return Task.FromResult(new Protocol.SequenceManifest(id, dto.FramesVersion, dto.SettingsVersion, settings, dto.Tags,
|
||
[.. frames.Select((frame, i) => new ManifestFrame(frame, i, $"IMG_{i + 1:0000}.JPG", 24_000_000,
|
||
Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(BitConverter.GetBytes(i))), hasProxy, true))],
|
||
[.. Enumerable.Range(0, dto.RenderedCount).Select(i => new RenderDto(Guid.CreateVersion7(), i == 0 ? "4K HEVC" : "1080p H.264", "hevc",
|
||
3840, 2160, 30, 21.3, 640_000_000, created.AddHours(i), "Studio NAS"))]));
|
||
}
|
||
}
|
||
|
||
public Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
|
||
{
|
||
lock (_sequences)
|
||
{
|
||
return Task.FromResult<IReadOnlyList<FrameDto>>([.. _sequences[sequenceId].Frames.Select((frame, i) => new FrameDto(frame, sequenceId, i,
|
||
$"IMG_{i + 1:0000}.JPG", 24_000_000, null, new DateTime(2026, 7, 2, 5, 40, 0).AddSeconds(30 * i), null, 1.0 / 250, 8, 100, 24, 1, 320, 180,
|
||
"jpeg", 0))]);
|
||
}
|
||
}
|
||
|
||
public Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken)
|
||
{
|
||
lock (_sequences)
|
||
{
|
||
var (dto, settings, frames) = _sequences[id];
|
||
var updated = dto with { SettingsVersion = dto.SettingsVersion + 1, UpdatedAt = Now };
|
||
_sequences[id] = (updated, request.SettingsJson ?? settings, frames);
|
||
return Task.FromResult(updated);
|
||
}
|
||
}
|
||
|
||
public Task<CompleteUploadResponse?> UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt,
|
||
CancellationToken cancellationToken) => throw new NotSupportedException("The sample server takes no uploads.");
|
||
|
||
/// <summary>Proxies and thumbnails: a dawn gradient whose sun rises with the frame.</summary>
|
||
public async Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken)
|
||
{
|
||
if (kind == "original") throw new NotSupportedException("The sample server serves no originals.");
|
||
int index;
|
||
lock (_sequences) index = _sequences.Values.Select(s => Array.IndexOf(s.Frames, frameId)).Max();
|
||
await destination.WriteAsync(Gradient(["#1B2A4A", "#E8925A", "#F6D28B"], 320, 180, index / 3.0), cancellationToken);
|
||
}
|
||
|
||
public Task<string?> DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken) =>
|
||
throw new NotSupportedException("The sample server serves no renders.");
|
||
|
||
public Task<RenderDto?> UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken) =>
|
||
throw new NotSupportedException("The sample server takes no renders.");
|
||
|
||
public async IAsyncEnumerable<ServerEvent> EventsAsync([System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
|
||
{
|
||
await Task.Delay(Timeout.Infinite, cancellationToken);
|
||
yield break;
|
||
}
|
||
|
||
public Task<string?> GetAnalysisReportAsync(Guid id, CancellationToken cancellationToken) => Task.FromResult<string?>(null);
|
||
|
||
public Task<JobDto> CreateJobAsync(CreateJobRequest request, CancellationToken cancellationToken)
|
||
{
|
||
var job = new JobDto(Guid.CreateVersion7(), request.Kind, request.Target, null, "queued", "user", 0, 0, null, null, null, null, 0, null,
|
||
Now, null, null);
|
||
lock (_jobs) _jobs[job.Id] = job;
|
||
return Task.FromResult(job);
|
||
}
|
||
|
||
/// <summary>A job of <paramref name="kind"/> running for <paramref name="sequenceId"/>, <paramref name="done"/> of <paramref name="total"/> frames.</summary>
|
||
public void Run(Guid sequenceId, string kind, long done, long total)
|
||
{
|
||
var now = Now;
|
||
var job = new JobDto(Guid.CreateVersion7(), kind, [sequenceId], null, "running", "user", done, total, 11.3, (total - done) / 11.3, null, "studio-pc", 1,
|
||
null, now.AddMinutes(-2), now.AddMinutes(-2), null);
|
||
lock (_jobs) _jobs[job.Id] = job;
|
||
}
|
||
|
||
public void EndJobs()
|
||
{
|
||
lock (_jobs) _jobs.Clear();
|
||
}
|
||
|
||
public Task<JobDto> GetJobAsync(Guid id, CancellationToken cancellationToken)
|
||
{
|
||
lock (_jobs) return Task.FromResult(_jobs[id]);
|
||
}
|
||
|
||
public Task<IReadOnlyList<JobDto>> ListActiveJobsAsync(CancellationToken cancellationToken)
|
||
{
|
||
lock (_jobs) return Task.FromResult<IReadOnlyList<JobDto>>([.. _jobs.Values.Where(j => j.State is "queued" or "running" or "paused")]);
|
||
}
|
||
|
||
public Task<JobDto> CancelJobAsync(Guid id, CancellationToken cancellationToken) =>
|
||
Task.FromResult(Update(id, job => job with { State = "cancelled", Finished = Now }));
|
||
|
||
public Task<JobDto> RetryJobAsync(Guid id, CancellationToken cancellationToken) =>
|
||
Task.FromResult(Update(id, job => job with { State = "queued", Error = null, Finished = null }));
|
||
|
||
public Task<JobDto> SetJobPriorityAsync(Guid id, string priority, CancellationToken cancellationToken) =>
|
||
Task.FromResult(Update(id, job => job with { Priority = priority }));
|
||
|
||
private JobDto Update(Guid id, Func<JobDto, JobDto> change)
|
||
{
|
||
lock (_jobs) return _jobs[id] = change(_jobs[id]);
|
||
}
|
||
|
||
public void Dispose()
|
||
{
|
||
}
|
||
}
|
||
|
||
/// <summary>No encryption: the capture environment is thrown away.</summary>
|
||
private sealed class PlainTokenProtector : ITokenProtector
|
||
{
|
||
public string Protect(string token) => token;
|
||
|
||
public string? Unprotect(string protectedToken) => protectedToken;
|
||
}
|
||
|
||
/// <summary>The encoders of the mockup's PC (NVIDIA RTX with NVENC) and canned self-test speeds.</summary>
|
||
private sealed class SampleEncoders : IEncoderInventory
|
||
{
|
||
public string? Adapter() => "NVIDIA GeForce RTX 4070";
|
||
|
||
public IReadOnlyList<EncoderRow> Detect() =>
|
||
[
|
||
new("HEVC", "NVIDIA HEVC Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Hevc),
|
||
new("H.264", "NVIDIA H.264 Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, false, 4096, 4096, VideoCodec.H264),
|
||
new("AV1", "NVIDIA AV1 Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Av1),
|
||
new("H.264", "H264 Encoder MFT", "Microsoft", EncoderSource.MediaFoundation, false, false, 4096, 2304, VideoCodec.H264),
|
||
new("MJPEG · AVI", "Chronos", null, EncoderSource.BuiltInMjpeg, false, false, 0, 0, VideoCodec.Mjpeg),
|
||
new("GIF · APNG", "Chronos", null, EncoderSource.BuiltInAnimation, false, false, 0, 0, null),
|
||
];
|
||
|
||
public Task<SelfTestResult> SelfTestAsync(EncoderRow row, CancellationToken ct) => Task.FromResult(row.Codec switch
|
||
{
|
||
"HEVC" => new SelfTestResult(true, 142, null),
|
||
"AV1" => new SelfTestResult(true, 96, null),
|
||
"H.264" when row.Hardware => new SelfTestResult(true, 188, null),
|
||
"H.264" => new SelfTestResult(true, 21, null),
|
||
_ => new SelfTestResult(true, 64, null),
|
||
});
|
||
}
|
||
|
||
/// <summary>A PC with the HEVC Video Extensions but without the Raw Image and HEIF extensions: RAW files decode through
|
||
/// Chronos's own developers or their previews, HEIF only through its preview (Settings › Formats and its notice).</summary>
|
||
private sealed class SampleFormats : IFormatInventory
|
||
{
|
||
private static readonly Core.Windows.Codecs.StoreExtension Raw = Core.Windows.Codecs.StoreExtension.Get(Core.Windows.Codecs.StoreExtensionKind.RawImage);
|
||
private static readonly Core.Windows.Codecs.StoreExtension Heif = Core.Windows.Codecs.StoreExtension.Get(Core.Windows.Codecs.StoreExtensionKind.HeifImage);
|
||
private static readonly Core.Windows.Codecs.StoreExtension Webp = Core.Windows.Codecs.StoreExtension.Get(Core.Windows.Codecs.StoreExtensionKind.WebpImage);
|
||
|
||
public FormatReport Detect(bool refresh) => new(
|
||
[
|
||
.. DecoderFactory.DescribeFormats(DecoderFactory.CreateClient(null)).Select(f => new FormatRow(f.Format, f.Tier, f.Provider, f.Format.Format switch
|
||
{
|
||
_ when f.Format.IsRaw => [Raw],
|
||
ImageFileFormat.Heif or ImageFileFormat.Avif => [Heif],
|
||
ImageFileFormat.WebP => [Webp],
|
||
_ => [],
|
||
})),
|
||
],
|
||
[Raw, Heif, Webp]);
|
||
|
||
public void OpenStore(Core.Windows.Codecs.StoreExtension extension)
|
||
{
|
||
// Capture and smoke tests never open the Store.
|
||
}
|
||
}
|
||
}
|