The capture sample can mark an analysis of the editor sequence as running, so sequence-busy-<theme>.png shows the settings waiting with the viewing tools live. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
528 lines
27 KiB
C#
528 lines
27 KiB
C#
using System.IO;
|
||
using System.Net;
|
||
using Titano.App.About;
|
||
using Titano.App.Editor;
|
||
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.Protocol;
|
||
using Titano.Protocol.Client;
|
||
|
||
namespace Titano.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, a fake signed-in server 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";
|
||
|
||
private readonly AppServices _services;
|
||
private TitanoDatabase? _db;
|
||
|
||
private SampleData(AppServices services) => _services = services;
|
||
|
||
/// <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;
|
||
services.Server.Dispose();
|
||
services.Server = new ServerSession(settings, services.SaveSettings, new SampleServerApiFactory(), new PlainTokenProtector());
|
||
services.Encoders = new SampleEncoders();
|
||
services.CheckForUpdateAsync = _ => Task.FromResult<ReleaseInfo?>(null);
|
||
return new SampleData(services);
|
||
}
|
||
|
||
/// <summary>Opens the empty temporary index (first run: no archive, nothing indexed).</summary>
|
||
public async Task OpenEmptyAsync()
|
||
{
|
||
_db = await TitanoDatabase.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 = "TitanoArchive", RootPath = root, Created = DateTimeOffset.UtcNow.AddYears(-2) };
|
||
await db.Archives.UpsertAsync(archive);
|
||
|
||
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);
|
||
|
||
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;
|
||
}
|
||
|
||
/// <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 = DateTimeOffset.UtcNow.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.");
|
||
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),
|
||
});
|
||
}
|
||
|
||
/// <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)
|
||
{
|
||
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"]);
|
||
}
|
||
}
|
||
|
||
/// <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 = 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));
|
||
}
|
||
|
||
/// <summary>A server that always answers as "Studio NAS" with a self-signed certificate the sample trusts.</summary>
|
||
private sealed class SampleServerApiFactory : IServerApiFactory
|
||
{
|
||
public IServerApi Create(Uri baseAddress, IReadOnlyCollection<string> trustedFingerprints) => new SampleServerApi(baseAddress, trustedFingerprints);
|
||
}
|
||
|
||
private sealed class SampleServerApi(Uri baseAddress, IReadOnlyCollection<string> trusted) : IServerApi
|
||
{
|
||
private static readonly UserDto User = new(Guid.Empty, "alberto", "Alberto", "editor", 0, 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<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, DateTimeOffset.UtcNow.AddDays(30)));
|
||
}
|
||
|
||
public Task<UserDto> 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()
|
||
{
|
||
}
|
||
}
|
||
|
||
/// <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", "Titano", null, EncoderSource.BuiltInMjpeg, false, false, 0, 0, VideoCodec.Mjpeg),
|
||
new("GIF · APNG", "Titano", 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),
|
||
});
|
||
}
|
||
}
|