using System.IO; using System.Net; using Titano.App.About; using Titano.App.Editor; using Titano.App.Import; using Titano.App.Infrastructure; using Titano.App.Server; using Titano.App.Settings; using Titano.Core.Advice; using Titano.Core.Analysis; using Titano.Core.Analysis.Deep; using Titano.Core.Archiving; using Titano.Core.Codecs.Jpeg; using Titano.Core.Diagnostics.Synthetic; using Titano.Core.Imaging; using Titano.Core.Imaging.Decoders; using Titano.Core.Metadata; using Titano.Core.Model; using Titano.Core.Project; using Titano.Core.Video; using Titano.Data; using Titano.Data.Archiving; using Titano.Data.Jobs; using Titano.Data.Sync; using Titano.Protocol; using Titano.Protocol.Client; namespace Titano.App.DesignTime; /// /// Synthetic content for --capture 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, 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. /// 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"; private const string ServerAddress = "https://nas.local:8443"; private readonly AppServices _services; private readonly SampleSyncRemote _remote = new(); private TitanoDatabase? _db; private Guid _sunrise; private Guid _lakeComo; private Permissions _permissions = RolePermissions.Default(UserRole.Editor); private SampleData(AppServices services) => _services = services; /// The server-only sequence whose proxies keeps on this PC (Sunrise over Superga). public Guid ProxiedSequenceId => _sunrise; /// Points the services at fakes (server, encoders, update check) for an empty first-run state. 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.CheckForUpdateAsync = _ => Task.FromResult(null); services.Devices.Dispose(); services.Devices = new SampleDeviceMonitor(); services.Sync.RemoteFactory = (_, _, _) => sample._remote; services.Sync.EditorFactory = (_, _, _) => sample._remote; return sample; } /// Opens the empty temporary index (first run: no archive, nothing indexed). public async Task OpenEmptyAsync() { _db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(_services.Environment.DatabasePath)); await _services.AttachAsync(_db, startEngine: false); } /// Fills the index with sample sequences, frames and jobs, and saves a signed-in server session. 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 = "TitanoArchive", RootPath = root, Created = DateTimeOffset.UtcNow.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"]); foreach (var job in Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id)) await db.Jobs.EnqueueAsync(job); await FillServerAsync(db, sequences.Select(s => s.Sequence).ToList()); await SampleCards.InsertAsync(db, (SampleDeviceMonitor)_services.Devices, _services.Environment.DataDirectory); settings.LastArchivePath = @"D:\TitanoArchive"; 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; settings.FirstRunCompleted = true; } /// /// Transfers for the sync table: an upload at 46 % (Comet over the ridge), an upload waiting (Fog lifting, Asti), a /// download of originals running (Sunrise over Superga) and one paused (Lake Como storm). /// public async Task FillSyncAsync() { var db = _db ?? throw new InvalidOperationException("FillAsync first."); async Task LocalAsync(string text) => (await db.Sequences.ListAsync(new Data.Repositories.SequenceQuery { Text = text, Limit = 1 })).Items[0]; var now = DateTimeOffset.UtcNow; 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), }; 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.Running, 1_210, 2_880)); await db.Jobs.EnqueueAsync(Transfer(JobKind.Download, _lakeComo, "Lake Como storm", originals, JobState.Paused, 300, 1_450)); } /// /// 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. /// 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."); 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); } /// A render of Sunrise over Superga running on the sample server, 43 % done (the remote editor's server job). public void RunServerRender() => _remote.Run(_sunrise, "render", 1_240, 2_880); /// The sample server's jobs end (none waits or runs any more). public void EndServerJobs() => _remote.EndJobs(); /// /// 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. /// public async Task RestrictAccountAsync() { _permissions = Permissions.Read | Permissions.Upload | Permissions.Render; await _services.Server.RestoreAsync(); } /// /// 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 .titano folder. /// 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 } }; Titano.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); } /// /// 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; /// the others are only here. /// private async Task FillServerAsync(TitanoDatabase db, IReadOnlyList 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", FrameCount = 2_880, TotalBytes = 2_880 * 21_000_000L, Status = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt, RenderedCount = 1, UpdatedAt = DateTimeOffset.UtcNow, }), 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", FrameCount = 1_450, TotalBytes = 1_450 * 45_000_000L, Status = SequenceStatus.ThumbsBuilt, UpdatedAt = DateTimeOffset.UtcNow, }), null, 3); static string DeflickerWindow(int frames) => """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":""" + frames.ToString(System.Globalization.CultureInfo.InvariantCulture) + "}}}"; } /// /// 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 analysis.json), advised into project.json with one manual value and three camera /// keyframes, and given two past renders. /// /// The sequence id to open in the editor. public async Task 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 = DateTimeOffset.UtcNow.AddDays(-daysAgo), ProducedBy = "studio-pc", }); } return id; } /// A deep analysis of half way through: the editor's busy state (settings wait, viewing stays live). public async Task MarkAnalysingAsync(Guid sequenceId) { var db = _db ?? throw new InvalidOperationException("OpenEmptyAsync first."); var now = DateTimeOffset.UtcNow; 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 = Environment.MachineName, Attempts = 1, Created = now.AddSeconds(-5), Started = now.AddSeconds(-4), }); } /// A two-minute sunset at 2 s intervals: darkening scene, flicker, two shutter steps the pixels received, warming light. 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", }; /// /// 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. /// 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))]; } /// The sunset as the deep analysis reads it (the pixels written to the JPEGs, before compression). 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 LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken) => ValueTask.FromResult(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) { 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, Origin = origin, SyncState = sync, UpdatedAt = DateTimeOffset.UtcNow, }, 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); 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"]); } } /// Three small JPEG frames per sequence; a "raw" sequence wraps its JPEGs in a fake CR2 with an embedded preview. private static IEnumerable 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(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; } /// A vertical gradient through the given sRGB colours with a sun disc that moves with . 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 Jobs(IReadOnlyList s, Guid archiveId) { var now = DateTimeOffset.UtcNow; 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) => new() { Id = Guid.CreateVersion7(), Kind = kind, 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, }; 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), 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"); yield return Make(JobKind.DeepAnalyse, s[4], s[4].DisplayTitle, JobState.Running, 2_498, 8_920, 41, TimeSpan.FromMinutes(6), startedAgo: TimeSpan.FromMinutes(1.1)); yield return Make(JobKind.Proxies, s[1], s[1].DisplayTitle, JobState.Running, 915, 1_005, 118, TimeSpan.FromSeconds(8), startedAgo: TimeSpan.FromSeconds(8)); yield return Make(JobKind.Render, s[3], "Aurora, Tromsø → 1080p share H.264", JobState.Queued, 0, 0, createdAgo: TimeSpan.FromMinutes(12)); yield return Make(JobKind.Verify, null, "Archive · 2024", JobState.Queued, 0, 0, priority: JobPriority.Background, createdAgo: TimeSpan.FromMinutes(30)); 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"); 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)); } /// A server that always answers as "Studio NAS" with a self-signed certificate the sample trusts. private sealed class SampleServerApiFactory(SampleData sample) : IServerApiFactory { public IServerApi Create(Uri baseAddress, IReadOnlyCollection trustedFingerprints) => new SampleServerApi(sample, baseAddress, trustedFingerprints); } /// The sample account, an editor unless took the Edit right away. private sealed class SampleServerApi(SampleData sample, Uri baseAddress, IReadOnlyCollection 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), DateTimeOffset.UtcNow); public Uri BaseAddress { get; } = baseAddress; public string? Token { get; set; } public async Task 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 LoginAsync(string username, string password, CancellationToken ct) { Token = "sample-token"; return Task.FromResult(new LoginResponse(Token, User, false, DateTimeOffset.UtcNow.AddDays(30))); } public Task MeAsync(CancellationToken ct) => Token == "sample-token" ? Task.FromResult(User) : throw new TitanoApiException(HttpStatusCode.Unauthorized, new ApiError("unauthorized", "Sign in")); public Task LogoutAsync(CancellationToken ct) => Task.CompletedTask; public void Dispose() { } } /// /// 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 /// ); uploads, originals and analysis reports are not part of the screenshots. /// private sealed class SampleSyncRemote : ISyncRemote, IRemoteSequenceApi { private readonly Dictionary _sequences = []; private readonly Dictionary _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> ListSequencesAsync(CancellationToken cancellationToken) { lock (_sequences) return Task.FromResult>([.. _sequences.Values.Select(s => s.Dto)]); } public Task GetSequenceAsync(Guid id, CancellationToken cancellationToken) { lock (_sequences) return Task.FromResult(_sequences[id].Dto); } public Task 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> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken) { lock (_sequences) { return Task.FromResult>([.. _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 UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) { lock (_sequences) { var (dto, settings, frames) = _sequences[id]; var updated = dto with { SettingsVersion = dto.SettingsVersion + 1, UpdatedAt = DateTimeOffset.UtcNow }; _sequences[id] = (updated, request.SettingsJson ?? settings, frames); return Task.FromResult(updated); } } public Task UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt, CancellationToken cancellationToken) => throw new NotSupportedException("The sample server takes no uploads."); /// Proxies and thumbnails: a dawn gradient whose sun rises with the frame. 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 DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken) => throw new NotSupportedException("The sample server serves no renders."); public Task UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException("The sample server takes no renders."); public async IAsyncEnumerable EventsAsync([System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken) { await Task.Delay(Timeout.Infinite, cancellationToken); yield break; } public Task GetAnalysisReportAsync(Guid id, CancellationToken cancellationToken) => Task.FromResult(null); public Task 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, DateTimeOffset.UtcNow, null, null); lock (_jobs) _jobs[job.Id] = job; return Task.FromResult(job); } /// A job of running for , of frames. public void Run(Guid sequenceId, string kind, long done, long total) { var now = DateTimeOffset.UtcNow; 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 GetJobAsync(Guid id, CancellationToken cancellationToken) { lock (_jobs) return Task.FromResult(_jobs[id]); } public Task> ListActiveJobsAsync(CancellationToken cancellationToken) { lock (_jobs) return Task.FromResult>([.. _jobs.Values.Where(j => j.State is "queued" or "running" or "paused")]); } public Task CancelJobAsync(Guid id, CancellationToken cancellationToken) => Task.FromResult(Update(id, job => job with { State = "cancelled", Finished = DateTimeOffset.UtcNow })); public Task RetryJobAsync(Guid id, CancellationToken cancellationToken) => Task.FromResult(Update(id, job => job with { State = "queued", Error = null, Finished = null })); public Task SetJobPriorityAsync(Guid id, string priority, CancellationToken cancellationToken) => Task.FromResult(Update(id, job => job with { Priority = priority })); private JobDto Update(Guid id, Func change) { lock (_jobs) return _jobs[id] = change(_jobs[id]); } public void Dispose() { } } /// No encryption: the capture environment is thrown away. private sealed class PlainTokenProtector : ITokenProtector { public string Protect(string token) => token; public string? Unprotect(string protectedToken) => protectedToken; } /// The encoders of the mockup's PC (NVIDIA RTX with NVENC) and canned self-test speeds. private sealed class SampleEncoders : IEncoderInventory { public string? Adapter() => "NVIDIA GeForce RTX 4070"; public IReadOnlyList 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", "Titano", null, EncoderSource.BuiltInMjpeg, false, false, 0, 0, VideoCodec.Mjpeg), new("GIF · APNG", "Titano", null, EncoderSource.BuiltInAnimation, false, false, 0, 0, null), ]; public Task 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), }); } }