diff --git a/i18n/en/Advisor.resx b/i18n/en/Advisor.resx
index 111c3a07..7c3ab191 100644
--- a/i18n/en/Advisor.resx
+++ b/i18n/en/Advisor.resx
@@ -33,6 +33,7 @@
{0} frames are blown out to white.{0} frame count
Automatic values of {0} updated.job log line; {0} sequence title
Deep analysis of {0}: {1} frames, {2} warnings.job log line; {0} sequence title; {1} frame count; {2} warning count
+ {0} could not be analysed: {1}long: job log line; {0} sequence title; {1} reason
Light analysis of {0}: {1} frames, {2} warnings.job log line; {0} sequence title; {1} frame count; {2} warning count
Suggested presets: {0}job log line; {0} preset names separated by dots
The project settings of {0} cannot be read; their automatic values were left as they were.job log line; {0} sequence title
diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx
index 22ce17de..13da03d2 100644
--- a/i18n/en/Errors.resx
+++ b/i18n/en/Errors.resx
@@ -4,6 +4,7 @@
2.0
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ {0} of {1} sequences could not be analysed; see the job log.long; {0} failed count (2 or more); {1} total count
The archive could not be opened.long
Enter a whole number from {0} to {1}.
Enter a folder.
@@ -13,6 +14,7 @@
Enter a full path that starts with a drive or a network share.
{0} could not be downloaded intact.{0} file name
{0} of {1} exports failed; see the job log.{0} failed count; {1} total count
+ Render nodes send back one file per job; post each preset of a batch as its own job.long
Render nodes send back one file per job; image sequences render where the archive is.
The render job has no valid export settings.
The sequence to render is no longer in the archive.
diff --git a/i18n/en/Export.resx b/i18n/en/Export.resx
index 3477a2d4..34850b65 100644
--- a/i18n/en/Export.resx
+++ b/i18n/en/Export.resx
@@ -16,6 +16,7 @@
Downloading framesrender node progress stage
Measuring framesjob progress stage
{0} failed: {1}long: job log line; {0} preset name; {1} reason
+ No render node can encode {1}; {0} is rendered as {2} instead.long: job log line; {0} preset name; {1} codec asked for; {2} managed codec used
{0} saved as {1}long: job log line; {0} preset name; {1} output file name
Playback rate not understood; the export frame rate is used.long
No capture times: frames are spaced evenly.long
diff --git a/i18n/it/Advisor.it.resx b/i18n/it/Advisor.it.resx
index 892a7f6e..c50b0774 100644
--- a/i18n/it/Advisor.it.resx
+++ b/i18n/it/Advisor.it.resx
@@ -33,6 +33,7 @@
{0} fotogrammi sono completamente bruciati.
Valori automatici di {0} aggiornati.
Analisi approfondita di {0}: {1} fotogrammi, {2} avvisi.
+ Impossibile analizzare {0}: {1}
Analisi rapida di {0}: {1} fotogrammi, {2} avvisi.
Preset suggeriti: {0}
Le impostazioni del progetto di {0} non sono leggibili; i valori automatici sono rimasti invariati.
diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx
index 31b8b300..a973d15d 100644
--- a/i18n/it/Errors.it.resx
+++ b/i18n/it/Errors.it.resx
@@ -4,6 +4,7 @@
2.0
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ {0} sequenze su {1} non sono state analizzate; vedi il registro del job.
Impossibile aprire l'archivio.
Inserisci un numero intero da {0} a {1}.
Inserisci una cartella.
@@ -13,6 +14,7 @@
Inserisci un percorso completo che inizi con un'unità o una condivisione di rete.
{0} non è stato scaricato integro.
{0} esportazioni su {1} non riuscite; vedi il registro del job.
+ I nodi di rendering restituiscono un file per job; invia ogni preset di un gruppo come job a sé.
I nodi di rendering restituiscono un file per job; le sequenze di immagini si renderizzano dove si trova l'archivio.
Il job di rendering non ha impostazioni di esportazione valide.
La sequenza da renderizzare non è più nell'archivio.
diff --git a/i18n/it/Export.it.resx b/i18n/it/Export.it.resx
index 27aed9a6..da3ab965 100644
--- a/i18n/it/Export.it.resx
+++ b/i18n/it/Export.it.resx
@@ -16,6 +16,7 @@
Download dei fotogrammi
Misura dei fotogrammi
{0} non riuscito: {1}
+ Nessun nodo di rendering può codificare {1}; {0} viene esportato in {2}.
{0} salvato come {1}
Velocità di riproduzione non valida; viene usata la frequenza di esportazione.
Nessun orario di scatto: fotogrammi distribuiti in modo uniforme.
diff --git a/src/Titano.App/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs
index 4744f842..55f956e0 100644
--- a/src/Titano.App/Infrastructure/AppServices.cs
+++ b/src/Titano.App/Infrastructure/AppServices.cs
@@ -31,12 +31,17 @@ namespace Titano.App.Infrastructure;
/// , thumbnails, the server session, the render node, the encoder inventory and the
/// update check. Started after the window shows, stopped when the app exits. The last archive is reopened at start and
/// rescanned every (BRIEF §7: polling, no file-system watchers). The render node runs while
-/// the user offers this PC () and a server session is open.
+/// the user offers this PC () and a server session is open (never in capture
+/// mode). Renders and the render node use hardware encoders as Settings › Rendering allows
+/// (). Disposal never needs the UI thread, which waits for it.
///
public sealed class AppServices : IAsyncDisposable
{
public static readonly TimeSpan ScanInterval = TimeSpan.FromMinutes(10);
+ /// The quick preview preset: the one render "Hardware for previews only" leaves on the GPU.
+ private const string PreviewPresetId = "720p-preview";
+
private static readonly Lazy Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) });
/// Update packages are large: their download fails when it stalls (), never after a fixed total time.
@@ -44,9 +49,8 @@ public sealed class AppServices : IAsyncDisposable
private readonly CancellationTokenSource _stopping = new();
private readonly Dictionary _scans = [];
private Task _polling = Task.CompletedTask;
+ private readonly RenderNodeHost _renderNode;
private ServerSession _server = null!;
- private Task _nodeSwitch = Task.CompletedTask;
- private (RenderNodeClient Node, TitanoClient Client, Uri Address, string Token)? _node;
public AppServices(AppEnvironment environment, AppSettings settings, Action saveSettings, IAppDialogs dialogs)
{
@@ -54,6 +58,7 @@ public sealed class AppServices : IAsyncDisposable
Settings = settings;
SaveSettingsAction = saveSettings;
Dialogs = dialogs;
+ _renderNode = new RenderNodeHost(StartRenderNode);
ArchiveSetup = new EngineArchiveSetup(this);
Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector());
Encoders = new MediaFoundationInventory();
@@ -145,8 +150,18 @@ public sealed class AppServices : IAsyncDisposable
UpdateRenderNode();
}
- /// Starts or stops the render node to match the opt-in and the server session (BRIEF §14.7); switches run in order.
- public void UpdateRenderNode() => _nodeSwitch = SwitchRenderNodeAsync(_nodeSwitch);
+ /// Starts, restarts or stops the render node to match the opt-in, the server session and the trusted certificates (BRIEF §14.7).
+ public void UpdateRenderNode() =>
+ _renderNode.Update(RenderNodeSession.For(Settings.RenderNodeOptIn && Processing is not null && !Environment.IsCapture, _server.IsConnected,
+ _server.Flow.Address, _server.Flow.Token, _server.Fingerprints, AllowsHardware(Settings.HardwareEncoding, ExportResolver.CustomId)));
+
+ /// Settings › Rendering: whether a render of may use hardware encoders.
+ public static bool AllowsHardware(HardwarePreference preference, string presetId) => preference switch
+ {
+ HardwarePreference.PreferHardware => true,
+ HardwarePreference.HardwareForPreviews => presetId.Equals(PreviewPresetId, StringComparison.OrdinalIgnoreCase),
+ _ => false,
+ };
/// Opens (or creates) the index at , migrates it and starts the job engine.
public async Task OpenAsync(string databasePath, CancellationToken ct = default)
@@ -175,34 +190,36 @@ public sealed class AppServices : IAsyncDisposable
Thumbnails = new ThumbnailService(database, Settings.ThumbnailMemoryItems);
}
+ /// Stops polling, the render node and the engine, then closes the index. The app's exit waits for this on the UI
+ /// thread, so nothing here continues on it.
public async ValueTask DisposeAsync()
{
- await _stopping.CancelAsync();
- await _polling;
+ await _stopping.CancelAsync().ConfigureAwait(false);
+ await _polling.ConfigureAwait(false);
_stopping.Dispose();
_server.PropertyChanged -= OnServerChanged;
- await _nodeSwitch;
- await StopRenderNodeAsync();
+ await _renderNode.DisposeAsync().ConfigureAwait(false);
(Jobs as IDisposable)?.Dispose();
- if (Engine is not null) await Engine.DisposeAsync();
+ if (Engine is not null) await Engine.DisposeAsync().ConfigureAwait(false);
Thumbnails?.Dispose();
Server.Dispose();
- if (Database is not null) await Database.DisposeAsync();
+ if (Database is not null) await Database.DisposeAsync().ConfigureAwait(false);
}
- /// Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically.
+ /// Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically,
+ /// off the UI thread (disposal waits for it there).
private async Task PollAsync(string root, CancellationToken ct)
{
try
{
if (Archives is null) return;
- var archive = await Task.Run(() => Archives.OpenAsync(root, ct), ct);
+ var archive = await Task.Run(() => Archives.OpenAsync(root, ct), ct).ConfigureAwait(false);
using var timer = new PeriodicTimer(ScanInterval);
do
{
- if (ArchiveService.GetAvailability(archive) == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct);
+ if (ArchiveService.GetAvailability(archive) == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct).ConfigureAwait(false);
}
- while (await timer.WaitForNextTickAsync(ct));
+ while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false));
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
@@ -229,12 +246,14 @@ public sealed class AppServices : IAsyncDisposable
UpdateRenderNode();
}
- /// Media Foundation (hardware first, software H.264) then managed encoders; frames spill into the cache folder
- /// within the memory budget of Settings › Rendering (Auto: a quarter of the installed memory).
+ /// Media Foundation (hardware first, software H.264; hardware as Settings › Rendering allows) then managed
+ /// encoders; frames spill into the cache folder within the memory budget of Settings › Rendering (Auto: a quarter of
+ /// the installed memory).
private ProcessingOptions ProcessingOptions(ArchiveServiceOptions archive) => new()
{
Archive = archive,
Encoders = [new MediaFoundationEncoderProvider(), new ManagedEncoderProvider()],
+ AllowsHardware = presetId => AllowsHardware(Settings.HardwareEncoding, presetId),
Host = EncoderHost.Client,
ProducedBy = System.Environment.MachineName,
FrameWindow = new FrameWindowOptions
@@ -246,45 +265,38 @@ public sealed class AppServices : IAsyncDisposable
private void OnServerChanged(object? sender, PropertyChangedEventArgs e) => UpdateRenderNode();
- /// Waits for the previous switch, then runs the node for the current session, or stops it.
- private async Task SwitchRenderNodeAsync(Task previous)
+ ///
+ /// The render node of : this PC's encoders (Media Foundation, then managed), downloads and
+ /// outputs in the cache folder within its size limit.
+ ///
+ private IRenderNode StartRenderNode(RenderNodeSession session)
{
- await previous;
- var flow = _server.Flow;
- (ProcessingService Engine, Uri Address, string Token)? wanted =
- Settings.RenderNodeOptIn && _server.IsConnected && Processing is { } processing && flow.Address is { } address && flow.Token is { } token
- ? (processing, address, token)
- : null;
- if (_node is { } running && wanted is { } same && running.Address == same.Address && running.Token == same.Token) return;
- await StopRenderNodeAsync();
- if (wanted is not { } start) return;
- try
+ var processing = Processing ?? throw new InvalidOperationException("The index is not open.");
+ var cache = CacheStore.Folder(Environment, Settings);
+ CacheStore.Prepare(cache);
+ var client = new TitanoClient(session.Address, new CertificatePinning(session.TrustedFingerprints), $"Titano ({System.Environment.MachineName})")
{
- var cache = CacheStore.Folder(Environment, Settings);
- CacheStore.Prepare(cache);
- var client = new TitanoClient(start.Address, new CertificatePinning(_server.Fingerprints), $"Titano ({System.Environment.MachineName})") { Token = start.Token };
- var node = new RenderNodeClient(client, start.Engine.Options, new RenderNodeOptions
- {
- ClientName = System.Environment.MachineName,
- CacheDirectory = Path.Combine(cache, "render-node"),
- CacheLimitBytes = Settings.CacheLimitGb * (1L << 30),
- });
- node.Start();
- _node = (node, client, start.Address, start.Token);
- Log.Info("render-node", $"Offering this PC as render node to {start.Address}");
- }
- catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ Token = session.Token,
+ };
+ var node = new RenderNodeClient(client, processing.Options, new RenderNodeOptions
{
- Log.Warning("render-node", "The render node could not start", ex);
- }
+ ClientName = System.Environment.MachineName,
+ CacheDirectory = Path.Combine(cache, "render-node"),
+ CacheLimitBytes = Settings.CacheLimitGb * (1L << 30),
+ });
+ node.Start();
+ return new RunningNode(node, client);
}
- private async Task StopRenderNodeAsync()
+ /// A started node and the client it owns.
+ private sealed class RunningNode(RenderNodeClient node, TitanoClient client) : IRenderNode
{
- if (_node is not { } running) return;
- _node = null;
- await running.Node.DisposeAsync();
- running.Client.Dispose();
- Log.Info("render-node", "Render node stopped");
+ public Task Completion => node.Completion;
+
+ public async ValueTask DisposeAsync()
+ {
+ await node.DisposeAsync().ConfigureAwait(false);
+ client.Dispose();
+ }
}
}
diff --git a/src/Titano.App/Infrastructure/RenderNodeHost.cs b/src/Titano.App/Infrastructure/RenderNodeHost.cs
new file mode 100644
index 00000000..5b21c6c7
--- /dev/null
+++ b/src/Titano.App/Infrastructure/RenderNodeHost.cs
@@ -0,0 +1,124 @@
+using Titano.Core.Diagnostics;
+
+namespace Titano.App.Infrastructure;
+
+///
+/// What a render node runs with: the server session (address and token), the certificates it may trust and whether it
+/// offers hardware encoders. A change of any of them means another node.
+///
+public sealed record RenderNodeSession(Uri Address, string Token, IReadOnlyCollection TrustedFingerprints, bool Hardware)
+{
+ ///
+ /// The session a node should run for, or null when it should be off: the user offers this PC
+ /// (), a server session is open and signed in.
+ ///
+ public static RenderNodeSession? For(bool offered, bool connected, Uri? address, string? token, IReadOnlyCollection trustedFingerprints,
+ bool hardware) =>
+ offered && connected && address is not null && token is not null ? new RenderNodeSession(address, token, trustedFingerprints, hardware) : null;
+
+ public bool Equals(RenderNodeSession? other) =>
+ other is not null && Address == other.Address && Token == other.Token && Hardware == other.Hardware
+ && TrustedFingerprints.Order(StringComparer.Ordinal).SequenceEqual(other.TrustedFingerprints.Order(StringComparer.Ordinal), StringComparer.Ordinal);
+
+ public override int GetHashCode() => HashCode.Combine(Address, Token, Hardware, TrustedFingerprints.Count);
+}
+
+/// A started render node.
+public interface IRenderNode : IAsyncDisposable
+{
+ /// Completes when the node has stopped, by itself (refused by the server) or when disposed.
+ Task Completion { get; }
+}
+
+///
+/// Keeps this PC's render node (BRIEF §14.7) in line with "Offer this PC as render node" and the server session:
+/// starts the node for the wanted session, restarts it for another session or when it stopped by
+/// itself, and stops it when none is wanted. Switches run one after the other, off the caller's thread, and never fail:
+/// a node that cannot start is logged and stays off until the next update.
+///
+public sealed class RenderNodeHost(Func start) : IAsyncDisposable
+{
+ private readonly Lock _gate = new();
+ private Task _switching = Task.CompletedTask;
+ private (RenderNodeSession Session, IRenderNode Node)? _running;
+ private bool _disposed;
+
+ /// The session the node runs for; null when it is off.
+ public RenderNodeSession? Session
+ {
+ get
+ {
+ lock (_gate) return _running?.Session;
+ }
+ }
+
+ /// Completes when every switch requested so far has run.
+ public Task Switching
+ {
+ get
+ {
+ lock (_gate) return _switching;
+ }
+ }
+
+ /// Runs the node for , or stops it when null.
+ public void Update(RenderNodeSession? wanted)
+ {
+ lock (_gate)
+ {
+ if (_disposed) return;
+ var previous = _switching;
+ _switching = Task.Run(async () =>
+ {
+ await previous.ConfigureAwait(false);
+ await SwitchAsync(wanted).ConfigureAwait(false);
+ });
+ }
+ }
+
+ /// Stops the node after the pending switches; later updates are ignored.
+ public async ValueTask DisposeAsync()
+ {
+ Task pending;
+ lock (_gate)
+ {
+ _disposed = true;
+ pending = _switching;
+ }
+ await pending.ConfigureAwait(false);
+ await SwitchAsync(null).ConfigureAwait(false);
+ }
+
+ private async Task SwitchAsync(RenderNodeSession? wanted)
+ {
+ (RenderNodeSession Session, IRenderNode Node)? running;
+ lock (_gate) running = _running;
+ // A node the server refused has stopped by itself: the same session starts it again (the right may be granted now).
+ if (running?.Session == wanted && running?.Node.Completion.IsCompleted != true) return;
+ if (running is { } old)
+ {
+ lock (_gate) _running = null;
+ try
+ {
+ await old.Node.DisposeAsync().ConfigureAwait(false);
+ Log.Info("render-node", "Render node stopped");
+ }
+ catch (Exception ex)
+ {
+ // A node that fails to stop is gone anyway; the next one must still be able to start.
+ Log.Warning("render-node", "The render node did not stop cleanly", ex);
+ }
+ }
+ if (wanted is null) return;
+ try
+ {
+ var node = start(wanted);
+ lock (_gate) _running = (wanted, node);
+ Log.Info("render-node", $"Offering this PC as render node to {wanted.Address}");
+ }
+ catch (Exception ex)
+ {
+ Log.Warning("render-node", "The render node could not start", ex);
+ }
+ }
+}
diff --git a/src/Titano.Core/Export/ExportNaming.cs b/src/Titano.Core/Export/ExportNaming.cs
index f594b0b1..f0194676 100644
--- a/src/Titano.Core/Export/ExportNaming.cs
+++ b/src/Titano.Core/Export/ExportNaming.cs
@@ -105,33 +105,34 @@ public static class ExportNaming
///
/// Full output path inside : the expanded name plus the codec's extension, or the bare name
- /// for image sequences (a folder), made unique against existing files and folders.
+ /// for image sequences (a folder), made unique against existing files and folders and the paths
+ /// says are being written.
///
- public static string OutputPath(string folder, string template, ExportNameContext context)
+ public static string OutputPath(string folder, string template, ExportNameContext context, Func? taken = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
var name = Expand(template, context).Name;
var extension = VideoCodecInfo.DefaultContainer(context.Codec) == ContainerFormat.ImageSequence ? string.Empty : VideoCodecInfo.FileExtension(context.Codec);
- return Unique(folder, name, extension);
+ return Unique(folder, name, extension, taken);
}
///
/// Output path of a project's export: or, when unset, the sequence's exports folder,
/// named by .
///
- public static string OutputPath(ExportSettings settings, string sequenceExportsFolder, ExportNameContext context)
+ public static string OutputPath(ExportSettings settings, string sequenceExportsFolder, ExportNameContext context, Func? taken = null)
{
ArgumentNullException.ThrowIfNull(settings);
- return OutputPath(string.IsNullOrWhiteSpace(settings.Folder) ? sequenceExportsFolder : settings.Folder, settings.NameTemplate, context);
+ return OutputPath(string.IsNullOrWhiteSpace(settings.Folder) ? sequenceExportsFolder : settings.Folder, settings.NameTemplate, context, taken);
}
- /// "name.ext", or "name (2).ext", "name (3).ext"… when a file or folder of that name exists.
- public static string Unique(string folder, string name, string extension)
+ /// "name.ext", or "name (2).ext", "name (3).ext"… when a file or folder of that name exists or is .
+ public static string Unique(string folder, string name, string extension, Func? taken = null)
{
for (var n = 1; ; n++)
{
var candidate = Path.Combine(folder, (n == 1 ? name : string.Create(CultureInfo.InvariantCulture, $"{name} ({n})")) + extension);
- if (!File.Exists(candidate) && !Directory.Exists(candidate)) return candidate;
+ if (!File.Exists(candidate) && !Directory.Exists(candidate) && taken?.Invoke(candidate) != true) return candidate;
}
}
diff --git a/src/Titano.Core/Project/ProjectSettings.cs b/src/Titano.Core/Project/ProjectSettings.cs
index 970a6dc7..42cb5690 100644
--- a/src/Titano.Core/Project/ProjectSettings.cs
+++ b/src/Titano.Core/Project/ProjectSettings.cs
@@ -84,6 +84,8 @@ public sealed record ExposureSettings
public double ExposureOffsetEv { get; init; }
/// Soft highlight knee (linear), null = hard clip at the encoder.
+ /// Written even when null: a missing value reads back as the default knee, which would turn "off" on.
+ [JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public double? HighlightKnee { get; init; } = 0.9;
}
@@ -187,7 +189,7 @@ public sealed record ProjectSettings
/// keep their defaults. The JSON is laid over the default project first, because generated deserialisation leaves
/// missing init-only members null or false rather than at their initial values.
///
- /// The text is not a JSON object.
+ /// The text is not a JSON object, or repeats a member.
/// The project was written by a newer Titano.
public static ProjectSettings FromJson(string json)
{
@@ -196,7 +198,15 @@ public sealed record ProjectSettings
switch (JsonNode.Parse(json, options))
{
case JsonObject given:
- Overlay(merged, given);
+ try
+ {
+ Overlay(merged, given);
+ }
+ catch (ArgumentException ex)
+ {
+ // A parsed object builds its member table on first use and rejects a name given twice (in any casing).
+ throw new JsonException("A project member is given more than once.", ex);
+ }
break;
case not null:
throw new JsonException("A project must be a JSON object.");
@@ -207,13 +217,18 @@ public sealed record ProjectSettings
return settings;
}
- /// Copies into , merging nested objects; a null never replaces an object.
+ ///
+ /// Copies into , merging nested objects. A null keeps a default that
+ /// is an object, a list or a text, since none of those members is nullable; elsewhere it clears a nullable value.
+ ///
private static void Overlay(JsonObject target, JsonObject source)
{
foreach (var (name, value) in source)
{
- if (value is JsonObject child && target[name] is JsonObject existing) Overlay(existing, child);
- else if (value is not null || target[name] is not JsonObject) target[name] = value?.DeepClone();
+ var current = target[name];
+ if (value is JsonObject child && current is JsonObject section) Overlay(section, child);
+ else if (value is not null || !(current is JsonObject or JsonArray || current?.GetValueKind() == JsonValueKind.String))
+ target[name] = value?.DeepClone();
}
}
}
diff --git a/src/Titano.Data/Archiving/ArchiveIndexer.cs b/src/Titano.Data/Archiving/ArchiveIndexer.cs
index 84cc6266..ff13cb34 100644
--- a/src/Titano.Data/Archiving/ArchiveIndexer.cs
+++ b/src/Titano.Data/Archiving/ArchiveIndexer.cs
@@ -160,7 +160,11 @@ public sealed class ArchiveIndexer
if (reconcile || File.Exists(sequence.IngestJournalPath))
{
var before = manifest;
- manifest = await _writer.UpdateAsync(paths, manifest.Id, folder.RelativeFolder, m => SequenceAdopter.Reconcile(sequence, m, cancellationToken),
+ // Photos added, gone or back: the light analysis no longer describes the frames, so the scan's follow-up runs it again.
+ manifest = await _writer.UpdateAsync(paths, manifest.Id, folder.RelativeFolder,
+ m => SequenceAdopter.Reconcile(sequence, m, cancellationToken) is { } reconciled
+ ? reconciled with { Status = reconciled.Status & ~SequenceStatus.AnalyzedLight }
+ : null,
cancellationToken).ConfigureAwait(false);
if (!ReferenceEquals(before, manifest)) bytes = null;
}
diff --git a/src/Titano.Data/Archiving/ArchiveService.cs b/src/Titano.Data/Archiving/ArchiveService.cs
index 96a62969..24c8a4d9 100644
--- a/src/Titano.Data/Archiving/ArchiveService.cs
+++ b/src/Titano.Data/Archiving/ArchiveService.cs
@@ -48,7 +48,7 @@ public sealed class ArchiveService : IJobHandlerProvider
new ScanJobHandler(_db, Indexer, JobKind.Scan),
new ScanJobHandler(_db, Indexer, JobKind.Rebuild),
new VerifyJobHandler(_db, Verifier),
- new ImportJobHandler(Imports),
+ new ImportJobHandler(_db, Imports),
new ImageJobHandler(_db, Images, JobKind.Thumbs),
new ImageJobHandler(_db, Images, JobKind.Proxies),
new MaintenanceJobHandler(_db, Maintenance),
diff --git a/src/Titano.Data/Archiving/ImportService.cs b/src/Titano.Data/Archiving/ImportService.cs
index e7db6a6e..cc90c435 100644
--- a/src/Titano.Data/Archiving/ImportService.cs
+++ b/src/Titano.Data/Archiving/ImportService.cs
@@ -143,6 +143,18 @@ public sealed class ImportService
}, progress, cancellationToken).ConfigureAwait(false);
}
+ /// The sequences the sessions of an import went into (new or continued), as far as they exist.
+ internal async Task> SequencesOfAsync(ImportJobParameters job, CancellationToken cancellationToken)
+ {
+ var ids = new List();
+ foreach (var session in job.Plan.Sessions)
+ {
+ if (await _db.Sequences.FindBySessionKeyAsync(job.ArchiveId, session.SessionKey, cancellationToken).ConfigureAwait(false) is { } id
+ && !ids.Contains(id)) ids.Add(id);
+ }
+ return ids;
+ }
+
/// Dry run of "delete imported": every card file with a recorded import, checked against its archive copy.
public async Task PlanEraseAsync(Archive archive, Guid cardId, string sourceRoot, IProgress? progress = null,
CancellationToken cancellationToken = default)
diff --git a/src/Titano.Data/Archiving/Jobs/ImportJobHandler.cs b/src/Titano.Data/Archiving/Jobs/ImportJobHandler.cs
index bf48eaa5..bdd6ac58 100644
--- a/src/Titano.Data/Archiving/Jobs/ImportJobHandler.cs
+++ b/src/Titano.Data/Archiving/Jobs/ImportJobHandler.cs
@@ -4,15 +4,16 @@ using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Jobs;
+using Titano.Data.Processing;
namespace Titano.Data.Archiving.Jobs;
///
/// : executes the confirmed plan in its parameters; progress in bytes. Checkpoint: the
/// number of plan items done. A removed card fails the job at a batch boundary; resuming it after re-insertion
-/// continues there.
+/// continues there. The sequences the import went into are then queued for light analysis.
///
-internal sealed class ImportJobHandler(ImportService imports) : IJobHandler
+internal sealed class ImportJobHandler(TitanoDatabase db, ImportService imports) : IJobHandler
{
public JobKind Kind => JobKind.Import;
@@ -29,5 +30,6 @@ internal sealed class ImportJobHandler(ImportService imports) : IJobHandler
.ConfigureAwait(false);
}, p => context.ReportAsync(p.BytesDone, p.BytesTotal, p.Current), context.Cancellation).ConfigureAwait(false);
context.Log(Loc.L("Archive.Log.ImportDone", final.Copied, final.Skipped, final.Failed));
+ await AnalysisFollowUp.QueueAsync(db, context, await imports.SequencesOfAsync(parameters, context.Cancellation).ConfigureAwait(false)).ConfigureAwait(false);
}
}
diff --git a/src/Titano.Data/Archiving/Jobs/ScanJobHandler.cs b/src/Titano.Data/Archiving/Jobs/ScanJobHandler.cs
index 3b010fd4..7935157f 100644
--- a/src/Titano.Data/Archiving/Jobs/ScanJobHandler.cs
+++ b/src/Titano.Data/Archiving/Jobs/ScanJobHandler.cs
@@ -1,6 +1,7 @@
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Jobs;
+using Titano.Data.Processing;
namespace Titano.Data.Archiving.Jobs;
@@ -15,7 +16,9 @@ internal static class JobArchive
///
/// (incremental, or full with ) and
-/// . Checkpoint: after:<folder>, the last folder indexed.
+/// . Checkpoint: after:<folder>, the last folder indexed. When anything was
+/// indexed, the sequences without a current light analysis (adopted folders, new sidecars, photos added to a folder) are
+/// queued for it.
///
internal sealed class ScanJobHandler(TitanoDatabase db, ArchiveIndexer indexer, JobKind kind) : IJobHandler
{
@@ -37,5 +40,9 @@ internal sealed class ScanJobHandler(TitanoDatabase db, ArchiveIndexer indexer,
}, context.Cancellation).ConfigureAwait(false);
foreach (var (folder, error) in summary.Failed) context.Log(Loc.L("Archive.Log.FolderFailed", folder, error));
context.Log(Loc.L("Archive.Log.ScanDone", summary.Folders, summary.Indexed, summary.Adopted, summary.Removed));
+ // A resumed scan may have indexed its folders before the interruption.
+ if (summary.Indexed > 0 || resume is not null)
+ await AnalysisFollowUp.QueueAsync(db, context, await AnalysisFollowUp.UnanalysedAsync(db, archive.Id, context.Cancellation).ConfigureAwait(false))
+ .ConfigureAwait(false);
}
}
diff --git a/src/Titano.Data/Jobs/JobEngine.cs b/src/Titano.Data/Jobs/JobEngine.cs
index e6229cba..f9c2d250 100644
--- a/src/Titano.Data/Jobs/JobEngine.cs
+++ b/src/Titano.Data/Jobs/JobEngine.cs
@@ -28,13 +28,22 @@ public sealed record JobEngineOptions
///
/// Persistent job queue runner (BRIEF §14.6): N workers claim queued jobs from the database by priority, run the
/// registered handler, checkpoint progress, and survive crashes (running jobs are requeued at start with their
-/// checkpoints). Used by the desktop client (local mode) and the server.
+/// checkpoints). Used by the desktop client (local mode) and the server. Jobs an
+/// declines stay queued for other claimers.
///
public sealed class JobEngine : IAsyncDisposable
{
+ /// Queued jobs of selective kinds examined per claim; jobs declined beyond it wait until those ahead leave the queue.
+ private const int SelectiveWindow = 100;
+
+ /// Claims lost to other workers before a worker waits for the next poll.
+ private const int MaxClaimRaces = 16;
+
private readonly TitanoDatabase _db;
private readonly Dictionary _handlers;
private IReadOnlyCollection _kinds = [];
+ private Dictionary _selective = [];
+ private IReadOnlyCollection _others = [];
private readonly ConcurrentDictionary _running = new();
private readonly Channel _wake = Channel.CreateBounded(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
private readonly CancellationTokenSource _shutdown = new();
@@ -65,6 +74,8 @@ public sealed class JobEngine : IAsyncDisposable
await _db.Jobs.PurgeHistoryAsync(DateTimeOffset.UtcNow - Options.HistoryRetention, cancellationToken).ConfigureAwait(false);
// Only kinds this engine can run: an empty filter would claim (and fail) every job, render-node work included.
_kinds = [.. (Options.Kinds ?? _handlers.Keys).Where(_handlers.ContainsKey).Distinct()];
+ _selective = _kinds.Select(k => _handlers[k]).OfType().ToDictionary(h => h.Kind);
+ _others = [.. _kinds.Where(k => !_selective.ContainsKey(k))];
if (_kinds.Count == 0)
{
Log.Info("jobs", "No job handlers; this engine claims nothing");
@@ -150,6 +161,9 @@ public sealed class JobEngine : IAsyncDisposable
}
}
+ /// True when this engine claims jobs of (it has a handler and the kind is not filtered out).
+ internal bool Runs(JobKind kind) => _kinds.Contains(kind);
+
internal void StopJob(Guid id)
{
if (_running.TryGetValue(id, out var cts)) cts.Cancel();
@@ -167,6 +181,7 @@ public sealed class JobEngine : IAsyncDisposable
if (await _db.Jobs.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } job) JobChanged?.Invoke(job);
}
+ /// Claims and runs jobs until shutdown. Nothing a job or a handler throws ends the worker.
private async Task WorkerLoopAsync(string workerId, CancellationToken shutdown)
{
while (!shutdown.IsCancellationRequested)
@@ -174,13 +189,13 @@ public sealed class JobEngine : IAsyncDisposable
Job? job;
try
{
- job = await _db.Jobs.ClaimNextAsync(workerId, _kinds, shutdown).ConfigureAwait(false);
+ job = await ClaimAsync(workerId, shutdown).ConfigureAwait(false);
}
- catch (OperationCanceledException)
+ catch (OperationCanceledException) when (shutdown.IsCancellationRequested)
{
return;
}
- catch (DatabaseException ex)
+ catch (Exception ex)
{
Log.Warning("jobs", "Claiming a job failed", ex);
job = null;
@@ -201,10 +216,68 @@ public sealed class JobEngine : IAsyncDisposable
continue;
}
- await RunAsync(job, shutdown).ConfigureAwait(false);
+ try
+ {
+ await RunAsync(job, shutdown).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ // The job's final state could not be stored (also while stopping): it stays running and is requeued at the
+ // next start. The worker never faults, so disposing the engine never throws.
+ Log.Error("jobs", $"{job.Kind} job {job.Id} could not be finished", ex);
+ }
}
}
+ ///
+ /// The next job in claim order (priority, then age). Without selective handlers the database picks it atomically.
+ /// With them, the first job a selective handler accepts among the first of its kinds
+ /// competes with the head of the other kinds: the other kinds are still claimed atomically, the selective job by id.
+ /// A lost race means another worker took a job, so looking again at once makes progress.
+ ///
+ private async Task ClaimAsync(string workerId, CancellationToken cancellationToken)
+ {
+ if (_selective.Count == 0) return await _db.Jobs.ClaimNextAsync(workerId, _kinds, cancellationToken).ConfigureAwait(false);
+ for (var attempt = 0; attempt < MaxClaimRaces; attempt++)
+ {
+ Job? candidate = null;
+ foreach (var queued in await _db.Jobs.ListQueuedAsync(_selective.Keys, SelectiveWindow, cancellationToken).ConfigureAwait(false))
+ {
+ if (!await AcceptsAsync(queued, cancellationToken).ConfigureAwait(false)) continue;
+ candidate = queued;
+ break;
+ }
+ if (candidate is null) return _others.Count > 0 ? await _db.Jobs.ClaimNextAsync(workerId, _others, cancellationToken).ConfigureAwait(false) : null;
+ if (_others.Count > 0 && (await _db.Jobs.ListQueuedAsync(_others, 1, cancellationToken).ConfigureAwait(false)).FirstOrDefault() is { } head
+ && ClaimsBefore(head, candidate))
+ {
+ if (await _db.Jobs.ClaimNextAsync(workerId, _others, cancellationToken).ConfigureAwait(false) is { } next) return next;
+ }
+ else if (await _db.Jobs.TryClaimAsync(candidate.Id, workerId, cancellationToken).ConfigureAwait(false) is { } claimed)
+ {
+ return claimed;
+ }
+ }
+ return null;
+ }
+
+ /// A job its handler cannot judge is taken, so it fails here with its reason instead of blocking the queue.
+ private async ValueTask AcceptsAsync(Job job, CancellationToken cancellationToken)
+ {
+ try
+ {
+ return await _selective[job.Kind].AcceptsAsync(job, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (!(ex is OperationCanceledException && cancellationToken.IsCancellationRequested))
+ {
+ Log.Warning("jobs", $"{job.Kind} job {job.Id} could not be examined; it is claimed so that it fails with its reason", ex);
+ return true;
+ }
+ }
+
+ private static bool ClaimsBefore(Job a, Job b) =>
+ a.Priority != b.Priority ? a.Priority > b.Priority : a.Created != b.Created ? a.Created < b.Created : a.Id.CompareTo(b.Id) < 0;
+
private async Task RunAsync(Job job, CancellationToken shutdown)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(shutdown);
diff --git a/src/Titano.Data/Jobs/JobHandler.cs b/src/Titano.Data/Jobs/JobHandler.cs
index 52539c9a..f78f9246 100644
--- a/src/Titano.Data/Jobs/JobHandler.cs
+++ b/src/Titano.Data/Jobs/JobHandler.cs
@@ -13,6 +13,17 @@ public interface IJobHandler
Task RunAsync(JobContext context);
}
+///
+/// A handler that runs only some jobs of its kind. The engine leaves the others queued for other claimers and asks again
+/// at every claim, so an answer may change while the job waits: the server renders what its managed encoders produce,
+/// leaves the rest to render nodes, and takes those too in a managed format once no node can (BRIEF §14.5, §14.7).
+///
+public interface ISelectiveJobHandler : IJobHandler
+{
+ /// Whether this handler takes now. A job it cannot read should be taken, so it fails with its reason.
+ ValueTask AcceptsAsync(Job job, CancellationToken cancellationToken);
+}
+
/// A component that brings several handlers (the archive engine: scan, rebuild, verify, import, images, maintenance).
public interface IJobHandlerProvider
{
@@ -75,6 +86,15 @@ public sealed class JobContext
return ReportCoreAsync(done, total, Message, force: true);
}
+ ///
+ /// Queues follow-up work on this job's engine for the same user (light analysis after an import); null when the
+ /// engine has no handler for , since nothing here would run it.
+ ///
+ public async Task EnqueueFollowUpAsync(JobKind kind, IReadOnlyList targets, string? label, string? parametersJson, JobPriority priority) =>
+ _engine.Runs(kind)
+ ? await _engine.EnqueueAsync(kind, targets, label, parametersJson, priority, Job.CreatedBy, Cancellation).ConfigureAwait(false)
+ : null;
+
/// Appends a line to the job log (the last lines are kept with the job).
public void Log(string line)
{
diff --git a/src/Titano.Data/Processing/AnalysisFollowUp.cs b/src/Titano.Data/Processing/AnalysisFollowUp.cs
new file mode 100644
index 00000000..7af05474
--- /dev/null
+++ b/src/Titano.Data/Processing/AnalysisFollowUp.cs
@@ -0,0 +1,41 @@
+using Titano.Core.Model;
+using Titano.Data.Jobs;
+using Titano.Data.Repositories;
+
+namespace Titano.Data.Processing;
+
+///
+/// Light analysis queued after work that brings sequences or frames into the index (card import, adoption, scan), so the
+/// advisor's Auto values and recommended preset exist without any user action (BRIEF §1.1, §4.3). Nothing is queued
+/// when the engine cannot run light analysis, and a sequence already waiting in a queued light analysis is not queued
+/// again (that job runs after the changes that led here).
+///
+internal static class AnalysisFollowUp
+{
+ /// Queues one light analysis of (labelled like the job that found them).
+ public static async Task QueueAsync(TitanoDatabase db, JobContext context, IReadOnlyCollection sequenceIds)
+ {
+ if (sequenceIds.Count == 0) return;
+ var waiting = (await db.Jobs.ListQueuedAsync([JobKind.LightAnalyse], 1000, context.Cancellation).ConfigureAwait(false))
+ .SelectMany(j => j.TargetIds).ToHashSet();
+ var targets = sequenceIds.Where(id => !waiting.Contains(id)).Distinct().ToList();
+ if (targets.Count == 0) return;
+ var request = ProcessingJobs.LightAnalysis(targets, context.Job.TargetLabel);
+ await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
+ }
+
+ /// Sequences of without a current light analysis (new, adopted, or with frames a scan added).
+ public static async Task> UnanalysedAsync(TitanoDatabase db, Guid archiveId, CancellationToken cancellationToken)
+ {
+ var ids = new List();
+ var query = new SequenceQuery { ArchiveId = archiveId, WithoutStatus = SequenceStatus.AnalyzedLight, Sort = SequenceSort.Oldest, Limit = 1000 };
+ do
+ {
+ var page = await db.Sequences.ListAsync(query, cancellationToken).ConfigureAwait(false);
+ ids.AddRange(page.Items.Select(s => s.Id));
+ query = query with { Cursor = page.NextCursor };
+ }
+ while (query.Cursor is not null);
+ return ids;
+ }
+}
diff --git a/src/Titano.Data/Processing/Jobs/AnalyseJobHandler.cs b/src/Titano.Data/Processing/Jobs/AnalyseJobHandler.cs
index 26a35203..e1c27d07 100644
--- a/src/Titano.Data/Processing/Jobs/AnalyseJobHandler.cs
+++ b/src/Titano.Data/Processing/Jobs/AnalyseJobHandler.cs
@@ -1,5 +1,6 @@
using System.Globalization;
using Titano.Core.Analysis.Deep;
+using Titano.Core.Archiving;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Jobs;
@@ -8,8 +9,10 @@ namespace Titano.Data.Processing.Jobs;
///
/// and over the target sequences, one after the
-/// other. Progress counts sequences (light) or frames (deep); checkpoint: the number of sequences done. A deep pass
-/// interrupted inside a sequence resumes from that sequence's analysis.partial.
+/// other. Progress counts sequences (light) or frames (deep). A sequence that cannot be analysed is logged and the
+/// others still run; the job then fails, and a retry analyses only the failed ones. An offline archive stops the job at
+/// once. Checkpoint: the next target and the failed ones (next[;i,j…]). A deep pass interrupted inside a
+/// sequence resumes from that sequence's analysis.partial.
///
internal sealed class AnalyseJobHandler(TitanoDatabase db, SequenceAnalyser analyser, JobKind kind) : IJobHandler
{
@@ -19,29 +22,50 @@ internal sealed class AnalyseJobHandler(TitanoDatabase db, SequenceAnalyser anal
{
var deep = kind == JobKind.DeepAnalyse;
var targets = context.Job.TargetIds;
- var first = int.TryParse(context.Checkpoint, NumberStyles.None, CultureInfo.InvariantCulture, out var next) ? next : 0;
+ var (next, retry) = Parse(context.Checkpoint, targets.Count);
// Deep progress is in frames across all targets, so the bar and the ETA cover the whole job.
- var frames = new long[targets.Count];
- if (deep)
- {
- for (var i = 0; i < targets.Count; i++)
- frames[i] = (await db.Sequences.GetAsync(targets[i], context.Cancellation).ConfigureAwait(false))?.FrameCount ?? 0;
- }
- var total = deep ? frames.Sum() : targets.Count;
- for (var i = first; i < targets.Count; i++)
+ var units = new long[targets.Count];
+ for (var i = 0; i < targets.Count; i++)
+ units[i] = deep ? (await db.Sequences.GetAsync(targets[i], context.Cancellation).ConfigureAwait(false))?.FrameCount ?? 0 : 1;
+ var total = units.Sum();
+ var done = Enumerable.Range(0, next).Where(i => !retry.Contains(i)).Sum(i => units[i]);
+ var failed = new List();
+ string? failure = null;
+ int[] order = [.. retry, .. Enumerable.Range(next, targets.Count - next)];
+ for (var k = 0; k < order.Length; k++)
{
context.Cancellation.ThrowIfCancellationRequested();
- var before = deep ? frames[..i].Sum() : i;
+ var i = order[k];
+ var before = done;
var chain = new ProgressChain(context.ReportAsync);
var progress = deep ? chain.For(p => (before + p.Done, total, null)) : null;
- var outcome = await analyser.AnalyseAsync(targets[i], deep, progress, context.Cancellation).ConfigureAwait(false);
- await chain.FlushAsync().ConfigureAwait(false);
- if (outcome is null) context.Log(Loc.L("Archive.Log.SequenceMissing", targets[i]));
- else Report(context, outcome, deep);
- await context.CheckpointAsync((i + 1).ToString(CultureInfo.InvariantCulture), deep ? before + frames[i] : i + 1, total).ConfigureAwait(false);
+ try
+ {
+ var outcome = await analyser.AnalyseAsync(targets[i], deep, progress, context.Cancellation).ConfigureAwait(false);
+ await chain.FlushAsync().ConfigureAwait(false);
+ if (outcome is null) context.Log(Loc.L("Archive.Log.SequenceMissing", targets[i]));
+ else Report(context, outcome, deep);
+ }
+ catch (Exception ex) when (ex is not (OperationCanceledException or ArchiveOfflineException))
+ {
+ await chain.FlushAsync().ConfigureAwait(false);
+ Core.Diagnostics.Log.Warning("processing", $"Analysis of sequence {targets[i]} failed", ex);
+ failure = Loc.L("Advisor.Log.Failed", await TitleAsync(targets[i], context.Cancellation).ConfigureAwait(false), ex.Message);
+ context.Log(failure);
+ failed.Add(i);
+ }
+ done += units[i];
+ next = int.Max(next, i + 1);
+ // Failed targets of an earlier attempt not retried yet stay listed.
+ await context.CheckpointAsync(Format(next, [.. failed, .. retry.Skip(k + 1)]), done, total).ConfigureAwait(false);
}
+ // One failure is the job's error as it was logged; several are counted (the log names each).
+ if (failed.Count > 0) throw new InvalidOperationException(failed.Count == 1 ? failure : Loc.L("Errors.Analysis.Failed", failed.Count, targets.Count));
}
+ private async Task TitleAsync(Guid sequenceId, CancellationToken cancellationToken) =>
+ (await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false))?.DisplayTitle ?? sequenceId.ToString();
+
private static void Report(JobContext context, AnalysisOutcome outcome, bool deep)
{
var title = outcome.Sequence.DisplayTitle;
@@ -50,4 +74,23 @@ internal sealed class AnalyseJobHandler(TitanoDatabase db, SequenceAnalyser anal
if (outcome.SettingsUnreadable) context.Log(Loc.L("Advisor.Log.ProjectUnreadable", title));
if (outcome.Presets.Count > 0) context.Log(Loc.L("Advisor.Log.Presets", string.Join(" · ", outcome.Presets.Select(p => p.DisplayName()))));
}
+
+ /// Next target and the failed targets to retry first; a missing or unreadable checkpoint starts over.
+ internal static (int Next, IReadOnlyList Retry) Parse(string? checkpoint, int count)
+ {
+ var parts = checkpoint?.Split(';');
+ if (parts is not ([_] or [_, _]) || !int.TryParse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture, out var next) || next > count) return (0, []);
+ var retry = new List();
+ foreach (var item in parts.Length == 2 ? parts[1].Split(',') : [])
+ {
+ if (!int.TryParse(item, NumberStyles.None, CultureInfo.InvariantCulture, out var index) || index >= next) return (0, []);
+ if (!retry.Contains(index)) retry.Add(index);
+ }
+ return (next, retry);
+ }
+
+ internal static string Format(int next, IReadOnlyCollection failed) =>
+ failed.Count == 0
+ ? next.ToString(CultureInfo.InvariantCulture)
+ : string.Create(CultureInfo.InvariantCulture, $"{next};{string.Join(',', failed.Order())}");
}
diff --git a/src/Titano.Data/Processing/Jobs/ManagedRenderJobHandler.cs b/src/Titano.Data/Processing/Jobs/ManagedRenderJobHandler.cs
new file mode 100644
index 00000000..7151b807
--- /dev/null
+++ b/src/Titano.Data/Processing/Jobs/ManagedRenderJobHandler.cs
@@ -0,0 +1,88 @@
+using Titano.Core.Diagnostics;
+using Titano.Core.Export;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Core.Video;
+using Titano.Data.Jobs;
+using Titano.Protocol;
+
+namespace Titano.Data.Processing.Jobs;
+
+///
+/// on the server (BRIEF §4.4, §14.5, §14.7): it takes the jobs whose every output (the preset
+/// and each batch preset) its managed encoders produce, and runs them like a client does. Jobs that need a platform
+/// encoder (MP4) wait for render nodes while says one may take them;
+/// after that the server takes them too, writes each output it cannot encode as MJPEG in AVI at the same size and frame
+/// rate, and says so in the job log. A job it started (it left a checkpoint) resumes here, and jobs whose parameters
+/// cannot be read are taken, so they fail with their reason instead of waiting for a claimer that never comes.
+///
+internal sealed class ManagedRenderJobHandler(RenderJobHandler render, ProcessingOptions options) : ISelectiveJobHandler
+{
+ /// The managed preset whose values stand in for an output only a render node could make.
+ private const string FallbackPresetId = "mjpeg-avi";
+
+ private readonly EncoderCapability[] _capabilities = [.. options.Encoders.SelectMany(e => e.Capabilities)];
+
+ public JobKind Kind => JobKind.Render;
+
+ public async ValueTask AcceptsAsync(Job job, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(job);
+ RenderJobParameters parameters;
+ try
+ {
+ parameters = ProcessingJobs.ReadParameters(job.ParametersJson);
+ // Most jobs are decided by the main codec, before the export is read.
+ if (Produces(parameters.Codec) && RenderJobHandler.Targets(ProcessingJobs.ReadExport(parameters.PresetJson), parameters.PresetName).All(t => Produces(t.Export)))
+ return true;
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ return true;
+ }
+ if (job.Checkpoint is not null) return true;
+ if (options.AwaitsRenderNode is not { } awaits) return false;
+ try
+ {
+ return !await awaits(job, parameters, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ // Unknown whether a node could take it: the job keeps waiting rather than losing its format.
+ Log.Warning("processing", $"Render job {job.Id}: render node availability unknown", ex);
+ return false;
+ }
+ }
+
+ public Task RunAsync(JobContext context) =>
+ render.RunAsync(context, target => Produces(target.Export) ? target : Fallback(context, target));
+
+ /// The output as MJPEG in AVI with the managed preset's quality, at the size and frame rate asked for.
+ private static ExportTarget Fallback(JobContext context, ExportTarget target)
+ {
+ var mjpeg = ExportResolver.FromPreset(ExportPresets.Find(FallbackPresetId)!);
+ context.Log(Loc.L("Export.Log.NoRenderNode", target.PresetName, ExportNaming.CodecLabel(target.Export.Codec), ExportNaming.CodecLabel(mjpeg.Codec)));
+ return target with
+ {
+ Export = target.Export with
+ {
+ PresetId = ExportResolver.CustomId,
+ NameKey = null,
+ Codec = mjpeg.Codec,
+ Profile = mjpeg.Profile,
+ BitDepth = mjpeg.BitDepth,
+ BitRate = 0,
+ BitsPerPixel = 0,
+ Quality = mjpeg.Quality,
+ RateControl = mjpeg.RateControl,
+ Encoder = null,
+ },
+ };
+ }
+
+ private bool Produces(string codec) =>
+ _capabilities.Any(c => string.Equals(ProcessingJobs.CodecName(c.Codec), codec, StringComparison.OrdinalIgnoreCase));
+
+ private bool Produces(ResolvedExport export) =>
+ _capabilities.Any(c => c.Codec == export.Codec && export.Width <= c.MaxWidth && export.Height <= c.MaxHeight);
+}
diff --git a/src/Titano.Data/Processing/Jobs/RenderJobHandler.cs b/src/Titano.Data/Processing/Jobs/RenderJobHandler.cs
index 515ea14c..359361d5 100644
--- a/src/Titano.Data/Processing/Jobs/RenderJobHandler.cs
+++ b/src/Titano.Data/Processing/Jobs/RenderJobHandler.cs
@@ -1,3 +1,5 @@
+using System.Buffers.Binary;
+using System.Security.Cryptography;
using Titano.Core.Archiving;
using Titano.Core.Export;
using Titano.Core.Localization;
@@ -13,15 +15,20 @@ namespace Titano.Data.Processing.Jobs;
/// RenderJobParameters whose preset JSON is the export section of a project (preset, overrides, name template,
/// folder, batch). The project is the embedded one or the sequence's own; frames flagged missing, corrupt, excluded or
/// undecodable are left out. The preset and every batch preset render after one preparation pass into the sequence's
-/// exports/ (or the export folder), named by the template, and each finished output is recorded at once.
-/// Checkpoint: the batch entries recorded and the output being written, so a crashed attempt's leftovers are removed and
-/// only unfinished entries render again. A failed entry fails the job after the others ran; retrying renders it alone.
+/// exports/ (or the export folder, never on a server), named by the template without taking a name another render
+/// of this process is writing, and each finished output is recorded at once (its row id derives from the job and the
+/// entry, so every attempt knows what is recorded). Checkpoint: the entries recorded and the output being written, so a
+/// crashed attempt's leftovers are removed and only unfinished entries render again. A failed entry fails the job after
+/// the others ran; retrying renders it alone.
///
internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions options) : IJobHandler
{
public JobKind Kind => JobKind.Render;
- public async Task RunAsync(JobContext context)
+ public Task RunAsync(JobContext context) => RunAsync(context, target => target);
+
+ /// Runs the job with each output still to render passed through (the server's managed stand-ins).
+ internal async Task RunAsync(JobContext context, Func adapt)
{
var cancellation = context.Cancellation;
var (parameters, export) = ProcessingJobs.ReadRender(context.Job.ParametersJson);
@@ -31,19 +38,28 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var folder = paths.Sequence(sequence.Folder);
+ // A server writes only inside its archive (BRIEF §14.2): an export folder chosen on a client means nothing there.
+ if (options.Host == EncoderHost.Server) export = export with { Folder = null };
var project = (parameters.SettingsJson is { } embedded ? ProjectStore.Parse(embedded) : ProjectStore.Read(sequence, folder)) with { Export = export };
var settingsJson = project.ToJson();
+ using var names = new OutputNames();
+ var all = Targets(export, parameters.PresetName);
var resume = RenderCheckpoint.Parse(context.Checkpoint);
var done = resume.Done.ToList();
- if (resume is { Pending: { } pending, PendingOutput: { } output })
+ // A crash after a render row was written but before the checkpoint: that entry is finished.
+ for (var i = 0; i < all.Count; i++)
{
- // A crash after the render row was written but before the checkpoint: that entry is finished.
- var recorded = await db.Renders.ListBySequenceAsync(sequence.Id, cancellation).ConfigureAwait(false);
- if (recorded.Any(r => r.OutputPath == Stored(paths, output))) done.Add(pending);
- else Discard(output);
+ if (!done.Contains(i) && await db.Renders.GetAsync(RenderId(context.Job.Id, i), cancellation).ConfigureAwait(false) is not null) done.Add(i);
}
- var targets = Targets(export, parameters.PresetName).Select((t, i) => (i, t)).Where(t => !done.Contains(t.i)).ToList();
+ if (resume is { Pending: { } pending, PendingOutput: { } output } && !done.Contains(pending) && names.TryReserve(output))
+ {
+ // Unless another render recorded that name since (the output did not exist yet when it chose it).
+ var recorded = await db.Renders.ListBySequenceAsync(sequence.Id, cancellation).ConfigureAwait(false);
+ Discard(output, keepOutput: recorded.Any(r => r.OutputPath == Stored(paths, output)));
+ names.Release(output); // free again for the entry's new attempt
+ }
+ var targets = all.Select((t, i) => (i, t)).Where(t => !done.Contains(t.i)).Select(t => (t.i, adapt(t.t))).ToList();
if (targets.Count == 0) return;
var frames = await SequenceFrames.LoadAsync(db, archive, sequence, parameters.UseProxies, cancellation).ConfigureAwait(false);
@@ -52,17 +68,22 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
{
outcomes = await render.RenderAllAsync(
targets,
- (target, setup) => ExportNaming.OutputPath(project.Export, folder.Exports, SequenceRender.NameContext(sequence, target, setup)),
+ (target, setup) => names.Reserve(taken => ExportNaming.OutputPath(project.Export, folder.Exports, SequenceRender.NameContext(sequence, target, setup), taken)),
(index, path) => context.CheckpointAsync(new RenderCheckpoint(done, index, path).ToJson(), context.Done, context.Total),
async (index, target, result) =>
{
// The output is complete: record it even if the job is being cancelled, so it is never orphaned.
- var entity = result.ToEntity(sequence.Id, target.PresetName, settingsJson, options.ProducedBy) with { OutputPath = Stored(paths, result.OutputPath) };
+ var entity = result.ToEntity(sequence.Id, target.PresetName, settingsJson, options.ProducedBy) with
+ {
+ Id = RenderId(context.Job.Id, index),
+ OutputPath = Stored(paths, result.OutputPath),
+ };
await db.Renders.InsertAsync(entity, CancellationToken.None).ConfigureAwait(false);
done.Add(index);
await context.CheckpointAsync(new RenderCheckpoint(done, null, null).ToJson(), context.Done, context.Total).ConfigureAwait(false);
context.Log(Loc.L("Export.Log.Rendered", target.PresetName, Path.GetFileName(result.OutputPath)));
foreach (var remark in SequenceRender.Remarks(result)) context.Log(remark);
+ await options.NotifyAsync(sequence.Id, ProcessingOptions.RenderedChange, CancellationToken.None).ConfigureAwait(false);
},
context.ReportAsync,
cancellation).ConfigureAwait(false);
@@ -74,18 +95,12 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
}
/// The job's preset, then every other preset of the batch with its own values.
- internal static List Targets(ExportSettings export, string presetName)
- {
- var main = ExportResolver.Resolve(export);
- var targets = new List { new(main, presetName) };
- foreach (var id in export.Batch.Distinct(StringComparer.OrdinalIgnoreCase))
- {
- if (id.Equals(main.BasePresetId, StringComparison.OrdinalIgnoreCase)) continue;
- var resolved = ExportResolver.Resolve(new ExportSettings { Preset = new Auto().WithManual(id) });
- targets.Add(new ExportTarget(resolved, ProcessingJobs.PresetName(resolved)));
- }
- return targets;
- }
+ internal static List Targets(ExportSettings export, string presetName) =>
+ [
+ new(ExportResolver.Resolve(export), presetName),
+ .. ProcessingJobs.BatchPresets(export).Select(id => ExportResolver.Resolve(ProcessingJobs.BatchExport(export, id)))
+ .Select(resolved => new ExportTarget(resolved, ProcessingJobs.PresetName(resolved))),
+ ];
/// Archive-relative for outputs inside the archive (like the server's renders), absolute otherwise.
private static string Stored(ArchivePaths paths, string output)
@@ -94,15 +109,32 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
return relative.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(relative) ? output : relative;
}
+ ///
+ /// The id of the render row of entry of a job: the same in every attempt, so a resumed job
+ /// finds what it recorded (a name-based UUID, version 8).
+ ///
+ internal static Guid RenderId(Guid jobId, int index)
+ {
+ Span name = stackalloc byte[20];
+ jobId.TryWriteBytes(name, bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32BigEndian(name[16..], index);
+ Span hash = stackalloc byte[SHA256.HashSizeInBytes];
+ SHA256.HashData(name, hash);
+ hash[6] = (byte)((hash[6] & 0x0F) | 0x80);
+ hash[8] = (byte)((hash[8] & 0x3F) | 0x80);
+ return new Guid(hash[..16], bigEndian: true);
+ }
+
///
/// Removes what an interrupted attempt left of : the encoder's hidden temporary file or
/// folder, and an output that was completed but never recorded (it renders again under the same name).
///
- private static void Discard(string output)
+ private static void Discard(string output, bool keepOutput)
{
var parent = Path.GetDirectoryName(output);
if (parent is null || !Directory.Exists(parent)) return;
- foreach (var leftover in Directory.EnumerateFileSystemEntries(parent, "." + Path.GetFileName(output) + ".*.tmp").Append(output))
+ var leftovers = Directory.EnumerateFileSystemEntries(parent, "." + Path.GetFileName(output) + ".*.tmp");
+ foreach (var leftover in keepOutput ? leftovers : leftovers.Append(output))
{
if (Directory.Exists(leftover)) Directory.Delete(leftover, recursive: true);
else if (File.Exists(leftover)) File.Delete(leftover);
diff --git a/src/Titano.Data/Processing/OutputNames.cs b/src/Titano.Data/Processing/OutputNames.cs
new file mode 100644
index 00000000..f4d97b28
--- /dev/null
+++ b/src/Titano.Data/Processing/OutputNames.cs
@@ -0,0 +1,55 @@
+using System.Collections.Concurrent;
+
+namespace Titano.Data.Processing;
+
+///
+/// The output paths the renders of this process are writing. Encoders write to a hidden temporary file and rename it over
+/// the output when they finish, so two renders that picked the same free name (the same preset queued twice) would
+/// overwrite each other: a render reserves each name it picks until it ends.
+///
+internal sealed class OutputNames : IDisposable
+{
+ private static readonly ConcurrentDictionary Writing = new(StringComparer.OrdinalIgnoreCase);
+ private readonly List _mine = [];
+
+ /// A path from , given the test for paths other renders are writing, reserved for this render.
+ public string Reserve(Func, string> pick)
+ {
+ while (true)
+ {
+ var path = pick(p => Writing.ContainsKey(Key(p)));
+ // Another render may have taken the same name since: pick again.
+ if (TryReserve(path)) return path;
+ }
+ }
+
+ /// Reserves for this render; false when another render is writing it.
+ public bool TryReserve(string path)
+ {
+ var key = Key(path);
+ if (!Writing.TryAdd(key, 0)) return false;
+ lock (_mine) _mine.Add(key);
+ return true;
+ }
+
+ /// Gives back a path this render reserved, so it can be picked again.
+ public void Release(string path)
+ {
+ var key = Key(path);
+ lock (_mine)
+ {
+ if (_mine.Remove(key)) Writing.TryRemove(key, out _);
+ }
+ }
+
+ public void Dispose()
+ {
+ lock (_mine)
+ {
+ foreach (var key in _mine) Writing.TryRemove(key, out _);
+ _mine.Clear();
+ }
+ }
+
+ private static string Key(string path) => Path.GetFullPath(path);
+}
diff --git a/src/Titano.Data/Processing/ProcessingJobs.cs b/src/Titano.Data/Processing/ProcessingJobs.cs
index 2dac8db8..bc990d70 100644
--- a/src/Titano.Data/Processing/ProcessingJobs.cs
+++ b/src/Titano.Data/Processing/ProcessingJobs.cs
@@ -36,14 +36,65 @@ public static class ProcessingJobs
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentNullException.ThrowIfNull(export);
- var resolved = ExportResolver.Resolve(export);
- var name = PresetName(resolved);
- var parameters = new RenderJobParameters(name, JsonSerializer.Serialize(export, ProcessingJson.Default.ExportSettings), CodecName(resolved.Codec),
- resolved.Width > 0 ? resolved.Width : sourceWidth, resolved.Height > 0 ? resolved.Height : sourceHeight, useProxies, project?.ToJson());
- return new ArchiveJobRequest(JobKind.Render, [sequence.Id], $"{sequence.DisplayTitle} → {name}",
+ var parameters = Parameters(export, sourceWidth, sourceHeight, project?.ToJson(), useProxies);
+ return new ArchiveJobRequest(JobKind.Render, [sequence.Id], $"{sequence.DisplayTitle} → {parameters.PresetName}",
JsonSerializer.Serialize(parameters, ProtocolJson.Default.RenderJobParameters), JobPriority.User);
}
+ ///
+ /// A posted render job as one job per preset, as makes them (a render node uploads one file
+ /// per job): the job itself when it has no batch; otherwise its own preset, then each batch preset with its own values,
+ /// all with the job's project and proxy choice. × stands in
+ /// for a batch preset without a fixed size.
+ ///
+ /// The preset JSON is not an export section.
+ public static IReadOnlyList Split(RenderJobParameters parameters, int sourceWidth, int sourceHeight)
+ {
+ ArgumentNullException.ThrowIfNull(parameters);
+ var export = ReadExport(parameters.PresetJson);
+ var batch = BatchPresets(export).ToList();
+ if (batch.Count == 0) return [parameters];
+ return
+ [
+ parameters with { PresetJson = JsonSerializer.Serialize(export with { Batch = [] }, ProcessingJson.Default.ExportSettings) },
+ .. batch.Select(id => Parameters(BatchExport(export, id), sourceWidth, sourceHeight, parameters.SettingsJson, parameters.UseProxies)),
+ ];
+ }
+
+ ///
+ /// One job per preset of : its preset, then each batch preset with its
+ /// own values. For a server: a render node uploads one file per job, so a batch must not travel as one job.
+ ///
+ public static IReadOnlyList RenderEach(Sequence sequence, ExportSettings export, int sourceWidth, int sourceHeight,
+ ProjectSettings? project = null, bool useProxies = false)
+ {
+ ArgumentNullException.ThrowIfNull(export);
+ return
+ [
+ Render(sequence, export with { Batch = [] }, sourceWidth, sourceHeight, project, useProxies),
+ .. BatchPresets(export).Select(id => Render(sequence, BatchExport(export, id), sourceWidth, sourceHeight, project, useProxies)),
+ ];
+ }
+
+ /// The batch presets of an export besides its own, each once (blank entries of a hand-written batch are skipped).
+ internal static IEnumerable BatchPresets(ExportSettings export)
+ {
+ var main = ExportResolver.Resolve(export).BasePresetId;
+ return export.Batch.Where(id => !string.IsNullOrWhiteSpace(id)).Distinct(StringComparer.OrdinalIgnoreCase)
+ .Where(id => !id.Equals(main, StringComparison.OrdinalIgnoreCase));
+ }
+
+ /// A batch preset rendered with its own values, named and placed like the export it belongs to.
+ internal static ExportSettings BatchExport(ExportSettings export, string presetId) =>
+ new() { Preset = new Auto().WithManual(presetId), NameTemplate = export.NameTemplate, Folder = export.Folder };
+
+ private static RenderJobParameters Parameters(ExportSettings export, int sourceWidth, int sourceHeight, string? settingsJson, bool useProxies)
+ {
+ var resolved = ExportResolver.Resolve(export);
+ return new RenderJobParameters(PresetName(resolved), JsonSerializer.Serialize(export, ProcessingJson.Default.ExportSettings), CodecName(resolved.Codec),
+ resolved.Width > 0 ? resolved.Width : sourceWidth, resolved.Height > 0 ? resolved.Height : sourceHeight, useProxies, settingsJson);
+ }
+
/// Codec name in job parameters and render-node capabilities ("h264", "hevc", "mjpeg", "pngsequence"…).
public static string CodecName(VideoCodec codec) => codec.ToString().ToLowerInvariant();
@@ -57,11 +108,20 @@ public static class ProcessingJobs
/// The parameters of a render job and the export they select.
/// The job has no valid render parameters.
internal static (RenderJobParameters Parameters, ExportSettings Export) ReadRender(string? parametersJson)
+ {
+ var parameters = ReadParameters(parametersJson);
+ return (parameters, ReadExport(parameters.PresetJson));
+ }
+
+ /// The protocol record of a render job, without reading its export.
+ /// The job has no valid render parameters.
+ internal static RenderJobParameters ReadParameters(string? parametersJson)
{
try
{
- if (parametersJson is { Length: > 0 } && JsonSerializer.Deserialize(parametersJson, ProtocolJson.Default.RenderJobParameters) is { } parameters)
- return (parameters, ReadExport(parameters.PresetJson));
+ if (parametersJson is { Length: > 0 } && JsonSerializer.Deserialize(parametersJson, ProtocolJson.Default.RenderJobParameters)
+ is { PresetName.Length: > 0, PresetJson.Length: > 0, Codec.Length: > 0 } parameters)
+ return parameters;
}
catch (JsonException ex)
{
diff --git a/src/Titano.Data/Processing/ProcessingOptions.cs b/src/Titano.Data/Processing/ProcessingOptions.cs
index b6cfcf78..e14efb8e 100644
--- a/src/Titano.Data/Processing/ProcessingOptions.cs
+++ b/src/Titano.Data/Processing/ProcessingOptions.cs
@@ -1,10 +1,12 @@
using Titano.Core.Analysis.Deep;
using Titano.Core.Export;
using Titano.Core.Imaging;
+using Titano.Core.Model;
using Titano.Core.Render;
using Titano.Core.Video;
using Titano.Core.Video.Managed;
using Titano.Data.Archiving;
+using Titano.Protocol;
namespace Titano.Data.Processing;
@@ -15,15 +17,41 @@ namespace Titano.Data.Processing;
///
public sealed record ProcessingOptions
{
+ /// after a render was recorded.
+ public const string RenderedChange = "renders";
+
+ /// after the advisor changed the project.
+ public const string SettingsChange = "settings";
+
/// Decoders, lease owner and lease timing for the sidecar and project writes.
public ArchiveServiceOptions Archive { get; init; } = new();
/// Encoder providers in priority order.
public IReadOnlyList Encoders { get; init; } = [new ManagedEncoderProvider()];
- /// The server delegates platform codecs to render nodes and never runs them itself.
+ ///
+ /// Whether a render of the given preset (its base preset id) may use hardware encoders (Settings › Rendering); when
+ /// not, it gets only the software ones. Asked at every render, so a changed preference applies to the next one.
+ ///
+ public Func AllowsHardware { get; init; } = _ => true;
+
+ ///
+ /// Told after a job changed a sequence: (a render was recorded) or
+ /// (the advisor changed Auto values). A server tells its connected clients (BRIEF §14.3).
+ /// A failure is logged and never fails the job.
+ ///
+ public Func? SequenceChanged { get; init; }
+
+ /// The server delegates platform codecs to render nodes ().
public EncoderHost Host { get; init; } = EncoderHost.Client;
+ ///
+ /// Server: whether a queued render job that needs a platform encoder still waits for a render node (BRIEF §14.7). Once
+ /// it does not, the server renders it itself, every output only a node could make as MJPEG in AVI at the same size and
+ /// frame rate, and says so in the job log. Null: such jobs always wait for a node.
+ ///
+ public Func>? AwaitsRenderNode { get; init; }
+
/// Recorded with every render this host produces (client or server name).
public string ProducedBy { get; init; } = Environment.MachineName;
@@ -34,6 +62,24 @@ public sealed record ProcessingOptions
public RenderOptions Render { get; init; } = RenderOptions.Default;
+ /// Tells ; a failure is logged, never passed on to the job.
+ internal async Task NotifyAsync(Guid sequenceId, string change, CancellationToken cancellationToken)
+ {
+ if (SequenceChanged is null) return;
+ try
+ {
+ await SequenceChanged(sequenceId, change, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ Core.Diagnostics.Log.Warning("processing", $"The {change} change of sequence {sequenceId} could not be announced", ex);
+ }
+ }
+
+ /// without their hardware encoders, for renders keeps off them.
+ internal IReadOnlyList SoftwareEncoders =>
+ [.. Encoders.Select(e => e.Capabilities.Any(c => c.Hardware) ? new SoftwareEncoderProvider(e) : e)];
+
///
/// Encoders the advisor may count on: this machine's on a client; none listed on the server (render nodes can
/// produce any codec, so the advisor rules none out).
diff --git a/src/Titano.Data/Processing/ProcessingService.cs b/src/Titano.Data/Processing/ProcessingService.cs
index 3a06bd42..581a87b7 100644
--- a/src/Titano.Data/Processing/ProcessingService.cs
+++ b/src/Titano.Data/Processing/ProcessingService.cs
@@ -1,3 +1,4 @@
+using Titano.Core.Export;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
@@ -8,8 +9,9 @@ namespace Titano.Data.Processing;
///
/// The analysis and render engine of a host (BRIEF §4.3, §10, §11): job handlers for light analysis, deep analysis and
/// renders over the archive in the index, built with the host's decoders and encoders ().
-/// Register it on the next to the archive engine; a server engine leaves render jobs to render
-/// nodes. Create jobs with .
+/// Register it on the next to the archive engine. A client renders every job it is given; a
+/// server takes the renders its managed encoders produce and leaves the others to render nodes until none can take them
+/// (). Create jobs with .
///
public sealed class ProcessingService : IJobHandlerProvider
{
@@ -28,10 +30,14 @@ public sealed class ProcessingService : IJobHandlerProvider
public ProcessingOptions Options { get; }
/// Handlers for , and .
- public IReadOnlyList CreateJobHandlers() =>
- [
- new AnalyseJobHandler(_db, _analyser, JobKind.LightAnalyse),
- new AnalyseJobHandler(_db, _analyser, JobKind.DeepAnalyse),
- new RenderJobHandler(_db, Options),
- ];
+ public IReadOnlyList CreateJobHandlers()
+ {
+ var render = new RenderJobHandler(_db, Options);
+ return
+ [
+ new AnalyseJobHandler(_db, _analyser, JobKind.LightAnalyse),
+ new AnalyseJobHandler(_db, _analyser, JobKind.DeepAnalyse),
+ Options.Host == EncoderHost.Server ? new ManagedRenderJobHandler(render, Options) : render,
+ ];
+ }
}
diff --git a/src/Titano.Data/Processing/RenderNodeClient.cs b/src/Titano.Data/Processing/RenderNodeClient.cs
index 8361caab..aa53c5df 100644
--- a/src/Titano.Data/Processing/RenderNodeClient.cs
+++ b/src/Titano.Data/Processing/RenderNodeClient.cs
@@ -36,16 +36,23 @@ public sealed record RenderNodeOptions
/// Concurrent frame downloads.
public int Downloads { get; init; } = 4;
+
+ /// Retries of a frame download cut by the network or a busy server, each resuming the partial file.
+ public int DownloadRetries { get; init; } = 5;
+
+ /// Wait before the first retry; it doubles with each further one.
+ public TimeSpan RetryDelay { get; init; } = TimeSpan.FromSeconds(1);
}
///
/// "Offer this PC as render node" (BRIEF §14.7): registers this machine's single-file encoders with the server,
/// heart-beats, claims one render job at a time that it can encode, downloads the frames it needs (originals
-/// hash-verified into a content-addressed cache, or proxies when the job asks), renders the job's preset with the
-/// host's encoders and uploads the output, which the server files as a render of the sequence. Progress goes to the
-/// server; a job cancelled or reassigned there stops here; a failure is reported with its reason. Stopping abandons
-/// the job in flight without reporting it, so the server requeues it once the heartbeats stop. Image sequences are
-/// not offered: the protocol uploads one file per job.
+/// hash-verified into a content-addressed cache, or proxies when the job asks; a dropped download resumes), renders the
+/// job's preset with the host's encoders and uploads the output, which the server files as a render of the sequence.
+/// Progress and render remarks go to the server; a job cancelled or reassigned there stops here; a failure is reported
+/// with its reason. Stopping abandons the job in flight without reporting it: the server requeues it when the node
+/// registers again or its heartbeats stop. Image sequences are not offered and batches are refused: the protocol uploads
+/// one file per job.
///
public sealed class RenderNodeClient : IAsyncDisposable
{
@@ -65,14 +72,22 @@ public sealed class RenderNodeClient : IAsyncDisposable
_options = options;
}
- /// The encoders this node offers: every single-file capability of the host's providers.
+ ///
+ /// The encoders this node offers, each with its largest output: every single-file capability of the host's
+ /// providers, hardware ones only when the user lets renders use them ().
+ ///
public IReadOnlyList Encoders =>
[
.. _processing.Encoders.SelectMany(p => p.Capabilities)
- .Where(c => VideoCodecInfo.DefaultContainer(c.Codec) != ContainerFormat.ImageSequence)
- .Select(c => new NodeEncoder(ProcessingJobs.CodecName(c.Codec), c.Name, c.Hardware, c.SupportsTenBit)),
+ .Where(c => VideoCodecInfo.DefaultContainer(c.Codec) != ContainerFormat.ImageSequence
+ && (!c.Hardware || _processing.AllowsHardware(ExportResolver.CustomId)))
+ .Select(c => new NodeEncoder(ProcessingJobs.CodecName(c.Codec), c.Name, c.Hardware, c.SupportsTenBit, c.MaxWidth, c.MaxHeight)),
];
+ /// Completes when the node has stopped: asked to, or refused by the server (signed out, no render-node right,
+ /// changed certificate), which only the user can change.
+ public Task Completion => _running;
+
/// Starts registering, heart-beating and claiming in the background.
public void Start() => _running = Task.Run(() => RunAsync(_stopping.Token));
@@ -92,9 +107,10 @@ public sealed class RenderNodeClient : IAsyncDisposable
/// Registers this node (again) and returns its id.
public async Task RegisterAsync(CancellationToken cancellationToken)
{
- var capabilities = _processing.Encoders.SelectMany(p => p.Capabilities).ToList();
- var request = new RegisterNodeRequest(_options.ClientName, Encoders, capabilities.Count > 0 ? capabilities.Max(c => c.MaxWidth) : 0,
- capabilities.Count > 0 ? capabilities.Max(c => c.MaxHeight) : 0);
+ // Each encoder carries its own limit; the node-wide one (for servers that read only that) is the largest offered.
+ var encoders = Encoders;
+ var request = new RegisterNodeRequest(_options.ClientName, encoders, encoders.Select(e => e.MaxWidth).DefaultIfEmpty().Max(),
+ encoders.Select(e => e.MaxHeight).DefaultIfEmpty().Max());
var node = await _client.RegisterNodeAsync(request, cancellationToken).ConfigureAwait(false);
_nodeId = node.Id;
return node.Id;
@@ -148,20 +164,20 @@ public sealed class RenderNodeClient : IAsyncDisposable
{
break;
}
- catch (TitanoApiException ex) when (ex.Status is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
+ catch (Exception ex) when (ex is TitanoApiException { Status: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } or UntrustedCertificateException)
{
- // Signed out, or the account lacks the render-node right: nothing to retry until the user acts.
+ // Signed out, no render-node right, or a changed certificate: nothing to retry until the user acts.
Log.Warning(LogCategory, "The server refused this render node", ex);
break;
}
- catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
+ catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound && _nodeId is not null)
{
- _nodeId = null; // removed on the server: register again
+ _nodeId = null; // removed on the server: register again at once
continue;
}
catch (Exception ex)
{
- // Server unreachable or busy: the node keeps trying until it is stopped.
+ // Server unreachable, busy or without the render-node routes: the node keeps trying until it is stopped.
Log.Warning(LogCategory, "Render node cycle failed; retrying", ex);
}
try
@@ -193,8 +209,9 @@ public sealed class RenderNodeClient : IAsyncDisposable
{
_nodeId = null;
}
- catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or IOException or UntrustedCertificateException)
+ catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
+ // Unreachable or refusing: the claim loop decides whether to go on; beating must not stop the node.
Log.Warning(LogCategory, "Heartbeat failed", ex);
}
}
@@ -210,6 +227,8 @@ public sealed class RenderNodeClient : IAsyncDisposable
var resolved = ExportResolver.Resolve(export);
var target = new ExportTarget(resolved, ProcessingJobs.PresetName(resolved));
if (target.Export.Container == ContainerFormat.ImageSequence) throw new InvalidOperationException(Loc.L("Errors.Render.NodeSequence"));
+ // One output per job: a server splits batches into one job per preset when they are posted.
+ if (ProcessingJobs.BatchPresets(export).Any()) throw new InvalidOperationException(Loc.L("Errors.Render.NodeBatch"));
var project = ProjectStore.Parse(claimed.SettingsJson) with { Export = export };
var sequence = ToSequence(await _client.GetSequenceAsync(claimed.SequenceId, cancellationToken).ConfigureAwait(false));
@@ -224,7 +243,12 @@ public sealed class RenderNodeClient : IAsyncDisposable
[(0, target)],
(t, setup) => ExportNaming.OutputPath(work, project.Export.NameTemplate, SequenceRender.NameContext(sequence, t, setup)),
(_, _) => ValueTask.CompletedTask,
- (_, t, result) => new ValueTask(UploadAsync(reporter.NodeId, claimed.Job.Id, t, result, cancellationToken)),
+ async (_, t, result) =>
+ {
+ // Remarks first: completing the upload ends the job on the server.
+ foreach (var remark in SequenceRender.Remarks(result)) await reporter.LogAsync(remark).ConfigureAwait(false);
+ await UploadAsync(reporter.NodeId, claimed.Job.Id, t, result, cancellationToken).ConfigureAwait(false);
+ },
reporter.ReportAsync,
cancellationToken).ConfigureAwait(false);
}
@@ -257,34 +281,44 @@ public sealed class RenderNodeClient : IAsyncDisposable
///
/// The files of the job's frames: originals verified against their SHA-256 into the content-addressed cache (reused
- /// across jobs), or proxies into the job folder when the job asks for them and the server has them.
+ /// across jobs, fetched once per content), or proxies into the job folder when the job asks for them and the server
+ /// has them.
///
private async Task> DownloadAsync(ClaimedJob claimed, string work, NodeReporter reporter, CancellationToken cancellationToken)
{
var files = new Dictionary();
var done = 0;
- await reporter.ReportAsync(0, claimed.Frames.Count, Loc.L("Export.Job.Downloading")).ConfigureAwait(false);
- await Parallel.ForEachAsync(claimed.Frames, new ParallelOptions { MaxDegreeOfParallelism = _options.Downloads, CancellationToken = cancellationToken },
- async (frame, ct) =>
+ var total = claimed.Frames.Count;
+ await reporter.ReportAsync(0, total, Loc.L("Export.Job.Downloading")).ConfigureAwait(false);
+ var downloads = claimed.Frames.GroupBy(f => claimed.UseProxies && f.HasProxy ? f.Id.ToString("N") : f.Sha256.ToLowerInvariant()).ToList();
+ await Parallel.ForEachAsync(downloads, new ParallelOptions { MaxDegreeOfParallelism = _options.Downloads, CancellationToken = cancellationToken },
+ async (frames, ct) =>
{
+ var frame = frames.First();
var path = claimed.UseProxies && frame.HasProxy
? await DownloadProxyAsync(frame, work, ct).ConfigureAwait(false)
: await DownloadOriginalAsync(frame, ct).ConfigureAwait(false);
- lock (files) files[frame.Id] = path;
- await reporter.ReportAsync(Interlocked.Increment(ref done), claimed.Frames.Count, null).ConfigureAwait(false);
+ lock (files)
+ {
+ foreach (var f in frames) files[f.Id] = path;
+ }
+ await reporter.ReportAsync(Interlocked.Add(ref done, frames.Count()), total, null).ConfigureAwait(false);
}).ConfigureAwait(false);
return files;
}
- /// A proxy into the job folder (regenerable, so not cached); the original when the server has none for the frame.
+ ///
+ /// A proxy into the job folder (regenerable, so neither cached nor hashed: the server keeps no hash of it, and a retry
+ /// fetches it whole, since a proxy rebuilt meanwhile must not be resumed from the old one); the original when the server
+ /// has none for the frame.
+ ///
private async Task DownloadProxyAsync(ManifestFrame frame, string work, CancellationToken cancellationToken)
{
var path = Path.Combine(work, "proxies", frame.Id.ToString("N") + ".jpg");
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
try
{
- await using (var file = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
- await _client.DownloadFrameAsync(frame.Id, "proxy", file, null, cancellationToken).ConfigureAwait(false);
+ await FetchAsync(frame, "proxy", path, resume: false, cancellationToken).ConfigureAwait(false);
return path;
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
@@ -309,8 +343,8 @@ public sealed class RenderNodeClient : IAsyncDisposable
var part = path + ".part";
for (var attempt = 1; ; attempt++)
{
- await using (var file = new FileStream(part, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
- await _client.DownloadFrameAsync(frame.Id, "original", file, null, cancellationToken).ConfigureAwait(false);
+ // A part as long as the file was complete when the last attempt stopped: only its hash is left to check.
+ if (!File.Exists(part) || new FileInfo(part).Length < frame.Size) await FetchAsync(frame, "original", part, resume: true, cancellationToken).ConfigureAwait(false);
if (await TitanoClient.HashFileAsync(part, cancellationToken).ConfigureAwait(false) == sha)
{
File.Move(part, path, overwrite: true);
@@ -321,6 +355,34 @@ public sealed class RenderNodeClient : IAsyncDisposable
}
}
+ ///
+ /// Fetches a frame resource into . A dropped connection or a busy server is retried (up to
+ /// times, the wait doubling from );
+ /// with (a download its hash verifies) each attempt appends to what the last one left,
+ /// otherwise it starts over.
+ ///
+ private async Task FetchAsync(ManifestFrame frame, string kind, string path, bool resume, CancellationToken cancellationToken)
+ {
+ for (var attempt = 0; ; attempt++)
+ {
+ try
+ {
+ await using var file = new FileStream(path, resume ? FileMode.OpenOrCreate : FileMode.Create, FileAccess.ReadWrite, FileShare.None);
+ await _client.DownloadFrameAsync(frame.Id, kind, file, null, cancellationToken).ConfigureAwait(false);
+ return;
+ }
+ catch (Exception ex) when (attempt < _options.DownloadRetries && !cancellationToken.IsCancellationRequested && IsTransient(ex))
+ {
+ Log.Info(LogCategory, $"Download of {frame.FileName} ({kind}) interrupted, resuming: {ex.Message}");
+ await Task.Delay(_options.RetryDelay * (1 << attempt), cancellationToken).ConfigureAwait(false);
+ }
+ }
+ }
+
+ /// Failures a later attempt can get past: the network, a busy server, a timeout (not a cancellation of ours).
+ private static bool IsTransient(Exception ex) =>
+ ex is HttpRequestException or IOException or OperationCanceledException or TitanoApiException { IsTransient: true };
+
private async Task ReportFailureAsync(Guid nodeId, Guid jobId, string error, CancellationToken cancellationToken)
{
try
@@ -406,7 +468,7 @@ public sealed class RenderNodeClient : IAsyncDisposable
///
/// Progress of the job in flight to the server, at most every interval (and at the end). A refusal (409) means the
- /// job was cancelled or given to another node: is set and the job's token cancelled.
+ /// job was cancelled or given to another node: the job's token is cancelled.
///
private sealed class NodeReporter(TitanoClient client, Guid nodeId, Guid jobId, TimeSpan interval, CancellationTokenSource job)
{
@@ -414,28 +476,41 @@ public sealed class RenderNodeClient : IAsyncDisposable
private readonly SemaphoreSlim _gate = new(1, 1);
private TimeSpan _last = TimeSpan.MinValue;
private long _lastDone;
+ private long _lastTotal;
private string? _lastMessage;
public Guid NodeId => nodeId;
- public bool Lost { get; private set; }
+ /// Progress, sent at most every interval; a stage message is sent when it changes.
+ public ValueTask ReportAsync(long done, long total, string? message) => SendAsync(done, total, message, remark: false);
- public async ValueTask ReportAsync(long done, long total, string? message)
+ /// A line for the job's log on the server, sent with the progress last reported.
+ public ValueTask LogAsync(string line) => SendAsync(0, 0, line, remark: true);
+
+ private async ValueTask SendAsync(long done, long total, string? message, bool remark)
{
await _gate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
try
{
- var now = _clock.Elapsed;
- var line = message is not null && message != _lastMessage ? message : null;
- if (line is null && done < total && now - _last < interval) return;
- double? rate = _last == TimeSpan.MinValue || done < _lastDone ? null : (done - _lastDone) / double.Max((now - _last).TotalSeconds, 1e-3);
- (_last, _lastDone) = (now, done);
- if (line is not null) _lastMessage = line;
- await client.ReportNodeProgressAsync(nodeId, jobId, new NodeProgress(done, total, rate, line), job.Token).ConfigureAwait(false);
+ NodeProgress progress;
+ if (remark)
+ {
+ progress = new NodeProgress(_lastDone, _lastTotal, null, message);
+ }
+ else
+ {
+ var now = _clock.Elapsed;
+ var line = message is not null && message != _lastMessage ? message : null;
+ if (line is null && done < total && now - _last < interval) return;
+ double? rate = _last == TimeSpan.MinValue || done < _lastDone ? null : (done - _lastDone) / double.Max((now - _last).TotalSeconds, 1e-3);
+ (_last, _lastDone, _lastTotal) = (now, done, total);
+ if (line is not null) _lastMessage = line;
+ progress = new NodeProgress(done, total, rate, line);
+ }
+ await client.ReportNodeProgressAsync(nodeId, jobId, progress, job.Token).ConfigureAwait(false);
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
{
- Lost = true;
await job.CancelAsync().ConfigureAwait(false);
}
catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or IOException)
diff --git a/src/Titano.Data/Processing/SequenceAnalyser.cs b/src/Titano.Data/Processing/SequenceAnalyser.cs
index ef663e28..c99cd8c7 100644
--- a/src/Titano.Data/Processing/SequenceAnalyser.cs
+++ b/src/Titano.Data/Processing/SequenceAnalyser.cs
@@ -44,13 +44,14 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
? await AnalyseDeepAsync(frames, metadata, folder, progress, cancellationToken).ConfigureAwait(false)
: ReadReport(folder, frames.Count);
var context = SequenceContext.FromFrames(frames.Frames, options.AdvisorCodecs);
- var advice = Advisor.Recommend(light, report, context);
- var warnings = advice.Findings.Count(f => f.Severity >= FindingSeverity.Warning);
bool changed, unreadable = false;
try
{
- changed = await projects.UpdateAsync(paths, sequence, settings => Advisor.Apply(settings, advice), cancellationToken).ConfigureAwait(false);
+ // The frame rate follows the user's "fit to N seconds" when one is set (BRIEF §10.3).
+ changed = await projects.UpdateAsync(paths, sequence,
+ settings => Advisor.Apply(settings, Advisor.Recommend(light, report, context with { TargetDurationSeconds = settings.Timing.FitToSeconds })),
+ cancellationToken).ConfigureAwait(false);
}
catch (InvalidDataException ex)
{
@@ -58,18 +59,26 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
(changed, unreadable) = (false, true);
}
- var set = SequenceStatus.AnalyzedLight | (report is null ? SequenceStatus.None : SequenceStatus.AnalyzedDeep)
- | (warnings > 0 ? SequenceStatus.HasWarnings : SequenceStatus.None);
- // Without a current report (none, or made before frames were added) the deep status no longer holds.
- var clear = (report is null ? SequenceStatus.AnalyzedDeep : SequenceStatus.None) | (warnings > 0 ? SequenceStatus.None : SequenceStatus.HasWarnings);
- var summary = deep && report is not null ? AnalysisSummary.From(report).ToJson() : null;
- await writer.UpdateAsync(paths, sequence.Id, sequence.Folder, m =>
+ if (changed) await options.NotifyAsync(sequence.Id, ProcessingOptions.SettingsChange, cancellationToken).ConfigureAwait(false);
+
+ int warnings;
+ // Under the sequence lock, which a deep pass of the same sequence also takes to record its report: a light pass
+ // then either sees that report or runs before it is recorded, and never clears what it recorded.
+ await using (await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
- var status = (m.Status | set) & ~clear;
- return status == m.Status ? null : m with { Status = status, UpdatedAt = DateTimeOffset.UtcNow };
- }, cancellationToken).ConfigureAwait(false);
- await db.Sequences.RecordAnalysisAsync(sequence.Id, set, clear, warnings, summary, cancellationToken).ConfigureAwait(false);
- await indexer.RecordStampsAsync(archive, folder, sequence.Id, cancellationToken).ConfigureAwait(false);
+ report ??= ReadReport(folder, frames.Count);
+ warnings = Advisor.Recommend(light, report, context).Findings.Count(f => f.Severity >= FindingSeverity.Warning);
+ var set = SequenceStatus.AnalyzedLight | (report is null ? SequenceStatus.None : SequenceStatus.AnalyzedDeep)
+ | (warnings > 0 ? SequenceStatus.HasWarnings : SequenceStatus.None);
+ // Without a current report (none, or made before frames were added) the deep status no longer holds.
+ var clear = (report is null ? SequenceStatus.AnalyzedDeep : SequenceStatus.None) | (warnings > 0 ? SequenceStatus.None : SequenceStatus.HasWarnings);
+ var manifest = SequenceWriter.ReadLocked(folder, sequence.Id);
+ var status = (manifest.Status | set) & ~clear;
+ if (status != manifest.Status) ManifestStore.WriteSequence(folder.ManifestPath, manifest with { Status = status, UpdatedAt = DateTimeOffset.UtcNow });
+ var summary = deep && report is not null ? AnalysisSummary.From(report).ToJson() : null;
+ await db.Sequences.RecordAnalysisAsync(sequence.Id, set, clear, warnings, summary, cancellationToken).ConfigureAwait(false);
+ await indexer.RecordStampsAsync(archive, folder, sequence.Id, cancellationToken).ConfigureAwait(false);
+ }
var presets = deep ? SequencePresets.Generate(light, report, context) : [];
return new AnalysisOutcome(sequence, frames.Count, warnings, changed, unreadable, presets);
diff --git a/src/Titano.Data/Processing/SequenceRender.cs b/src/Titano.Data/Processing/SequenceRender.cs
index 3ab64003..2c5e8ca4 100644
--- a/src/Titano.Data/Processing/SequenceRender.cs
+++ b/src/Titano.Data/Processing/SequenceRender.cs
@@ -19,12 +19,14 @@ internal sealed record TargetOutcome(ExportTarget Target, RenderResult? Result,
/// frames that cannot be rendered excluded, and the pipeline with the host's encoders. Targets share one preparation
/// pass; each is named once its encoder (and so its codec and size) is known, and failures of one target do not stop
/// the others. Outputs are written by the encoder sessions to temporary names and renamed on completion, so a
-/// cancelled or failed target leaves nothing behind.
+/// cancelled or failed target leaves nothing behind. A target gets the hardware encoders only when the user allows them
+/// for its preset ().
///
internal sealed class SequenceRender : IAsyncDisposable
{
private readonly SequenceFrameSource _source;
- private readonly RenderPipeline _pipeline;
+ private readonly ProcessingOptions _processing;
+ private readonly Dictionary _pipelines = [];
private readonly RenderOptions _options;
/// The sequence's deep report, when current: its luminance spares the preparation a decode pass.
@@ -32,7 +34,7 @@ internal sealed class SequenceRender : IAsyncDisposable
{
var metadata = frames.LightFrames();
_source = new SequenceFrameSource(frames, metadata, options.Archive.Decoder, options.FrameWindow);
- _pipeline = new RenderPipeline(options.Encoders, options.Host);
+ _processing = options;
_options = options.Render;
Input = new RenderInput
{
@@ -46,7 +48,7 @@ internal sealed class SequenceRender : IAsyncDisposable
public RenderInput Input { get; }
/// Encoder, geometry and plan of an export before its output is named.
- public RenderSetup Setup(ResolvedExport export) => _pipeline.Setup(Input, new RenderTarget(export, ExportNaming.FallbackName), _options);
+ public RenderSetup Setup(ResolvedExport export) => Pipeline(export).Setup(Input, new RenderTarget(export, ExportNaming.FallbackName), _options);
///
/// Prepares the sequence once and renders every target. gives the output path of a target
@@ -97,7 +99,7 @@ internal sealed class SequenceRender : IAsyncDisposable
await starting(index, output).ConfigureAwait(false);
try
{
- var result = await _pipeline.RenderAsync(Input, corrections, new RenderTarget(target.Export, output), _options,
+ var result = await Pipeline(target.Export).RenderAsync(Input, corrections, new RenderTarget(target.Export, output), _options,
Stage(chain, done, setup.Plan.Frames.Count, total, target.PresetName), cancellationToken).ConfigureAwait(false);
await chain.FlushAsync().ConfigureAwait(false);
await finished(index, target, result).ConfigureAwait(false);
@@ -134,6 +136,15 @@ internal sealed class SequenceRender : IAsyncDisposable
public ValueTask DisposeAsync() => _source.DisposeAsync();
+ /// The pipeline with the encoders may use.
+ private RenderPipeline Pipeline(ResolvedExport export)
+ {
+ var hardware = _processing.AllowsHardware(export.BasePresetId);
+ if (!_pipelines.TryGetValue(hardware, out var pipeline))
+ _pipelines[hardware] = pipeline = new RenderPipeline(hardware ? _processing.Encoders : _processing.SoftwareEncoders, _processing.Host);
+ return pipeline;
+ }
+
private static string Reason(RenderSetup setup)
{
if (setup.Plan.Frames.Count == 0) return Loc.L("Export.Render.NoFrames");
diff --git a/src/Titano.Data/Processing/SoftwareEncoderProvider.cs b/src/Titano.Data/Processing/SoftwareEncoderProvider.cs
new file mode 100644
index 00000000..ed4b7ae7
--- /dev/null
+++ b/src/Titano.Data/Processing/SoftwareEncoderProvider.cs
@@ -0,0 +1,30 @@
+using Titano.Core.Video;
+
+namespace Titano.Data.Processing;
+
+///
+/// The software encoders of a provider, for renders the user keeps off the GPU (Settings › Rendering): hardware
+/// capabilities are hidden, so the encoder selector falls back as on a PC without them (HEVC → software H.264), and an
+/// encode opens the software encoder by name, ignoring a hardware one named in the export.
+///
+internal sealed class SoftwareEncoderProvider(IVideoEncoderProvider inner) : IVideoEncoderProvider
+{
+ public string Name => inner.Name;
+
+ public IReadOnlyList Capabilities { get; } = [.. inner.Capabilities.Where(c => !c.Hardware)];
+
+ public bool CanEncode(EncodeSettings settings) => Software(settings) is not null;
+
+ public IVideoEncoderSession Open(EncodeSettings settings) =>
+ inner.Open(Software(settings) ?? throw new NotSupportedException($"No software encoder of {inner.Name} accepts {settings.Codec} {settings.Width}×{settings.Height}"));
+
+ /// The settings naming the first software encoder that accepts them; null when none does.
+ private EncodeSettings? Software(EncodeSettings settings)
+ {
+ var named = settings.EncoderName is { } name && Capabilities.Any(c => c.Name == name);
+ return Capabilities
+ .Where(c => c.Codec == settings.Codec && (!named || c.Name == settings.EncoderName))
+ .Select(c => settings with { EncoderName = c.Name, PreferHardware = false })
+ .FirstOrDefault(inner.CanEncode);
+ }
+}
diff --git a/src/Titano.Data/Repositories/JobRepository.cs b/src/Titano.Data/Repositories/JobRepository.cs
index 0a663325..1226f9dc 100644
--- a/src/Titano.Data/Repositories/JobRepository.cs
+++ b/src/Titano.Data/Repositories/JobRepository.cs
@@ -39,9 +39,7 @@ public sealed class JobRepository
///
public Task ClaimNextAsync(string workerId, IReadOnlyCollection? kinds = null, CancellationToken cancellationToken = default)
{
- var kindFilter = kinds is { Count: > 0 }
- ? " AND kind IN (" + string.Join(", ", kinds.Select(k => ((int)k).ToString(CultureInfo.InvariantCulture))) + ")"
- : string.Empty;
+ var kindFilter = kinds is { Count: > 0 } ? $" AND kind IN ({KindList(kinds)})" : string.Empty;
var pick = $"SELECT id FROM jobs WHERE state = {(int)JobState.Queued}{kindFilter} ORDER BY priority DESC, created, id LIMIT 1";
var claim = $"UPDATE jobs SET state = {(int)JobState.Running}, node_id = $1, started = $2, finished = NULL, error = NULL, attempts = attempts + 1";
DbParam[] args = [workerId, DateTimeOffset.UtcNow];
@@ -130,9 +128,13 @@ public sealed class JobRepository
/// Queued jobs of one kind in claim order (highest priority, then oldest).
public Task> ListQueuedAsync(JobKind kind, int limit = 50, CancellationToken cancellationToken = default) =>
- _db.ListAsync(
- $"SELECT {Columns} FROM jobs WHERE state = {(int)JobState.Queued} AND kind = $1 ORDER BY priority DESC, created, id LIMIT $2",
- [(int)kind, Cursor.ClampLimit(limit)], Map, cancellationToken);
+ ListQueuedAsync([kind], limit, cancellationToken);
+
+ /// Queued jobs of the given kinds in claim order (highest priority, then oldest).
+ public Task> ListQueuedAsync(IReadOnlyCollection kinds, int limit = 50, CancellationToken cancellationToken = default) =>
+ kinds.Count == 0 ? Task.FromResult>([]) : _db.ListAsync(
+ $"SELECT {Columns} FROM jobs WHERE state = {(int)JobState.Queued} AND kind IN ({KindList(kinds)}) ORDER BY priority DESC, created, id LIMIT $1",
+ [Cursor.ClampLimit(limit)], Map, cancellationToken);
/// Running jobs claimed by .
public Task> ListRunningByNodeAsync(string nodeId, CancellationToken cancellationToken = default) =>
@@ -193,6 +195,8 @@ public sealed class JobRepository
return new JobCounts(row.GetInt32(0), row.GetInt32(1), row.GetInt32(2), row.GetInt32(3), row.GetInt32(4));
}, cancellationToken);
+ private static string KindList(IEnumerable kinds) => string.Join(", ", kinds.Select(k => ((int)k).ToString(CultureInfo.InvariantCulture)));
+
private static Job Map(DbRow r) => new()
{
Id = r.GetGuid(0),
diff --git a/src/Titano.Protocol/Jobs.cs b/src/Titano.Protocol/Jobs.cs
index 6a6d8e5c..38ba16cf 100644
--- a/src/Titano.Protocol/Jobs.cs
+++ b/src/Titano.Protocol/Jobs.cs
@@ -22,10 +22,17 @@ public sealed record JobDto(
/// POST /api/v1/jobs: kind = render, deep-analyse, proxies, thumbs, verify, scan, rebuild, maintenance…
public sealed record CreateJobRequest(string Kind, IReadOnlyList Target, string? ParametersJson);
-/// POST /api/v1/nodes/register: a client offers its GPU encoders (BRIEF §14.7).
+///
+/// POST /api/v1/nodes/register: a client offers its GPU encoders (BRIEF §14.7). ×
+/// is the largest output of any of them, for encoders that announce no limit of their own.
+///
public sealed record RegisterNodeRequest(string ClientName, IReadOnlyList Encoders, int MaxWidth, int MaxHeight);
-public sealed record NodeEncoder(string Codec, string Name, bool Hardware, bool TenBit);
+///
+/// One encoder of a render node. × is its largest output (0 = not announced:
+/// the node's own limit applies), so jobs go only to a node with an encoder of their codec that takes their size.
+///
+public sealed record NodeEncoder(string Codec, string Name, bool Hardware, bool TenBit, int MaxWidth = 0, int MaxHeight = 0);
public sealed record RenderNodeDto(Guid Id, string ClientName, string Username, IReadOnlyList Encoders, DateTimeOffset LastHeartbeat, string State);
diff --git a/src/Titano.Server/Api/JobEndpoints.cs b/src/Titano.Server/Api/JobEndpoints.cs
index c07e5f00..a86a08db 100644
--- a/src/Titano.Server/Api/JobEndpoints.cs
+++ b/src/Titano.Server/Api/JobEndpoints.cs
@@ -1,6 +1,7 @@
using System.Text.Json;
using Titano.Core.Model;
using Titano.Data;
+using Titano.Data.Processing;
using Titano.Protocol;
using Titano.Server.Jobs;
using Titano.Server.Security;
@@ -9,8 +10,8 @@ using Titano.Server.Storage;
namespace Titano.Server.Api;
///
-/// /api/v1/jobs (BRIEF §14.6): queue and history, creation, cancel, pause, resume, retry and priority. Changes
-/// reach WebSocket clients as jobState and jobProgress events.
+/// /api/v1/jobs (BRIEF §14.6): queue and history, creation (a render batch becomes one job per preset), cancel,
+/// pause, resume, retry and priority. Changes reach WebSocket clients as jobState and jobProgress events.
///
public static class JobEndpoints
{
@@ -88,21 +89,46 @@ public static class JobEndpoints
targets = ids;
label = titles.Count == 1 ? titles[0] : string.Join(", ", titles.Take(3)) + (titles.Count > 3 ? " …" : string.Empty);
}
+ List<(string Label, string? Parameters)> queue = [(label, request.ParametersJson)];
if (kind == JobKind.Render)
{
if (ParseRender(request.ParametersJson) is not { } render) return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
- label = $"{label} → {render.PresetName}";
+ // A batch becomes one job per preset: a render node uploads one file per job (BRIEF §14.7).
+ IReadOnlyList each;
+ try
+ {
+ var (width, height) = await SourceSizeAsync(db, targets[0], render, ct);
+ each = ProcessingJobs.Split(render, width, height);
+ }
+ catch (InvalidDataException)
+ {
+ return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
+ }
+ queue = each.Count == 1
+ ? [($"{label} → {render.PresetName}", request.ParametersJson)]
+ : [.. each.Select(p => ($"{label} → {p.PresetName}", (string?)JsonSerializer.Serialize(p, ProtocolJson.Default.RenderJobParameters)))];
}
else if (request.ParametersJson is not null && !IsJsonObject(request.ParametersJson))
{
return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
}
- var job = await host.Engine.EnqueueAsync(kind, targets, label, request.ParametersJson, JobPriority.User, caller.Id, ct);
- await audit.WriteAsync(caller, context, "job_created", "job", job.Id.ToString(), $"{JobWire.Kind(kind)} · {label}");
- return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
+ Job? first = null;
+ foreach (var (jobLabel, parameters) in queue)
+ {
+ var job = await host.Engine.EnqueueAsync(kind, targets, jobLabel, parameters, JobPriority.User, caller.Id, ct);
+ await audit.WriteAsync(caller, context, "job_created", "job", job.Id.ToString(), $"{JobWire.Kind(kind)} · {jobLabel}");
+ first ??= job;
+ }
+ return Results.Json(Dto.Job(first!), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
}
+ /// The oriented size of the sequence's first frame (what a preset without a fixed size renders at), else the job's size.
+ private static async Task<(int Width, int Height)> SourceSizeAsync(TitanoDatabase db, Guid sequenceId, RenderJobParameters render, CancellationToken ct) =>
+ (await db.Frames.ListBySequenceAsync(sequenceId, limit: 1, cancellationToken: ct)).FirstOrDefault() is { Width: > 0, Height: > 0 } frame
+ ? frame.Orientation is >= 5 and <= 8 ? (frame.Height, frame.Width) : (frame.Width, frame.Height)
+ : (render.Width, render.Height);
+
private static async Task PriorityAsync(HttpContext context, Caller caller, Guid id, JobPriorityRequest request, TitanoDatabase db, JobEngineHost host)
{
if (!JobWire.TryParsePriority(request.Priority, out var priority)) return ApiErrors.BadRequest(context, "invalid_priority");
diff --git a/src/Titano.Server/Jobs/JobEngineHost.cs b/src/Titano.Server/Jobs/JobEngineHost.cs
index e73b989b..e9ea3401 100644
--- a/src/Titano.Server/Jobs/JobEngineHost.cs
+++ b/src/Titano.Server/Jobs/JobEngineHost.cs
@@ -12,8 +12,9 @@ namespace Titano.Server.Jobs;
///
/// Hosts the server's (BRIEF §14.6) with the s registered in DI (directly or
/// through s) and
-/// relays its state changes and progress as WebSocket events. Render jobs are never run here: render nodes claim them
-/// (BRIEF §14.7). On shutdown running jobs stay marked running and are requeued from their checkpoints at the next start.
+/// relays its state changes and progress as WebSocket events. Render jobs run here only when the registered render
+/// handler accepts them (: managed formats, and MP4 jobs no render node can take);
+/// render nodes claim the others (BRIEF §14.5, §14.7). On shutdown running jobs stay marked running and are requeued from their checkpoints at the next start.
///
public sealed class JobEngineHost : IHostedService
{
@@ -30,7 +31,8 @@ public sealed class JobEngineHost : IHostedService
{
_db = db;
_events = events;
- var local = handlers.Concat(providers.SelectMany(p => p.CreateJobHandlers())).Where(h => h.Kind != JobKind.Render).ToList();
+ // A render handler must be selective: a plain one would take the jobs that need a render node's encoder.
+ var local = handlers.Concat(providers.SelectMany(p => p.CreateJobHandlers())).Where(h => h.Kind != JobKind.Render || h is ISelectiveJobHandler).ToList();
_kinds = [.. local.Select(h => h.Kind)];
// Without handlers no worker starts: an engine with an empty kind list would claim every kind.
Workers = _kinds.Count == 0 ? 0 : options.Workers;
diff --git a/src/Titano.Server/Jobs/RenderNodeAvailability.cs b/src/Titano.Server/Jobs/RenderNodeAvailability.cs
new file mode 100644
index 00000000..44d3e7b3
--- /dev/null
+++ b/src/Titano.Server/Jobs/RenderNodeAvailability.cs
@@ -0,0 +1,42 @@
+using System.Diagnostics;
+using Titano.Core.Model;
+using Titano.Data;
+using Titano.Protocol;
+using Titano.Server.Api;
+using Titano.Server.Configuration;
+
+namespace Titano.Server.Jobs;
+
+///
+/// Whether a queued render job that needs a platform encoder still waits for a render node (BRIEF §14.7); once it does
+/// not, the server's own engine renders it in a managed format. A job waits at least as long as a node may stay silent
+/// (), so a node that is restarting or reconnecting takes it back, and
+/// then as long as an online node can encode its codec at its size. The server's render handler asks for every queued
+/// job it examines, so the online nodes are read at most once a second.
+///
+public sealed class RenderNodeAvailability(TitanoDatabase db, ServerOptions options, TimeProvider time)
+{
+ private static readonly TimeSpan SnapshotAge = TimeSpan.FromSeconds(1);
+
+ private Snapshot? _snapshot;
+
+ public async Task AwaitsNodeAsync(Job job, RenderJobParameters parameters, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(job);
+ ArgumentNullException.ThrowIfNull(parameters);
+ var now = time.GetUtcNow();
+ var timeout = TimeSpan.FromSeconds(options.NodeTimeoutSeconds);
+ if (now - job.Created < timeout) return true;
+ var snapshot = Volatile.Read(ref _snapshot);
+ if (snapshot is null || Stopwatch.GetElapsedTime(snapshot.Read) >= SnapshotAge)
+ {
+ var online = await db.RenderNodes.ListOnlineAsync(now - timeout, cancellationToken);
+ snapshot = new Snapshot(Stopwatch.GetTimestamp(), [.. online.Select(Dto.Capabilities).OfType()]);
+ Volatile.Write(ref _snapshot, snapshot);
+ }
+ return snapshot.Nodes.Any(node => RenderNodeService.CanEncode(node, parameters));
+ }
+
+ /// What the online nodes announced, and when it was read (a timestamp).
+ private sealed record Snapshot(long Read, IReadOnlyList Nodes);
+}
diff --git a/src/Titano.Server/Jobs/RenderNodeMonitor.cs b/src/Titano.Server/Jobs/RenderNodeMonitor.cs
index f8d5b73d..c315d8c0 100644
--- a/src/Titano.Server/Jobs/RenderNodeMonitor.cs
+++ b/src/Titano.Server/Jobs/RenderNodeMonitor.cs
@@ -47,26 +47,8 @@ public sealed class RenderNodeMonitor(TitanoDatabase db, ServerOptions options,
{
await db.RenderNodes.SetStateAsync(node.Id, RenderNodeService.Offline, cancellationToken);
events.Publish(new NodeStateEvent(node.Id, node.ClientName, RenderNodeService.Offline));
- var key = RenderNodeService.NodeKey(node);
- var lost = await db.Jobs.ListRunningByNodeAsync(key, cancellationToken);
- foreach (var job in lost)
- {
- var line = RenderNodeService.AppendLog(job.LogTail, $"Render node {node.ClientName} stopped responding.");
- if (job.Attempts >= MaxAttempts)
- {
- await db.Jobs.FinishNodeJobAsync(job.Id, key, JobState.Failed, $"Lost its render node {job.Attempts} times.", line, cancellationToken);
- }
- else
- {
- await db.Jobs.UpdateNodeProgressAsync(job.Id, key, job.ProgressDone, job.ProgressTotal, null, null, line, cancellationToken);
- }
- }
- var requeued = await db.Jobs.RequeueRunningAsync(key, cancellationToken);
+ var requeued = await RenderNodeService.ReleaseJobsAsync(db, jobs, node, $"Render node {node.ClientName} stopped responding.", cancellationToken);
logger.LogWarning("Render node {Node} is offline; {Count} job(s) back in the queue", node.ClientName, requeued);
- foreach (var job in lost)
- {
- if (await db.Jobs.GetAsync(job.Id, cancellationToken) is { } current) jobs.Publish(current);
- }
}
}
}
diff --git a/src/Titano.Server/Jobs/RenderNodeService.cs b/src/Titano.Server/Jobs/RenderNodeService.cs
index 1e6f5e6a..b9f22d6f 100644
--- a/src/Titano.Server/Jobs/RenderNodeService.cs
+++ b/src/Titano.Server/Jobs/RenderNodeService.cs
@@ -41,16 +41,17 @@ public sealed class RenderNodeService(
return Outcome.Fail(400, "bad_request", "encoders");
var existing = (await db.RenderNodes.ListAsync(cancellationToken)).FirstOrDefault(n => n.UserId == caller.Id && n.ClientName == name);
- var id = existing?.Id ?? Guid.CreateVersion7();
- var running = await db.Jobs.ListRunningByNodeAsync(id.ToString(), cancellationToken);
+ // A node registers when it starts, holding no job: what the server still lists as running on it was abandoned
+ // by its previous run (stopped, restarted or crashed within the heartbeat timeout) and goes back to the queue.
+ if (existing is not null) await ReleaseJobsAsync(db, jobs, existing, $"Render node {name} restarted.", cancellationToken);
var node = new RenderNode
{
- Id = id,
+ Id = existing?.Id ?? Guid.CreateVersion7(),
UserId = caller.Id,
ClientName = name,
CapabilitiesJson = JsonSerializer.Serialize(request with { ClientName = name }, ProtocolJson.Default.RegisterNodeRequest),
LastHeartbeat = time.GetUtcNow(),
- State = running.Count > 0 ? Busy : Idle,
+ State = Idle,
};
await db.RenderNodes.RegisterAsync(node, cancellationToken);
events.Publish(new NodeStateEvent(node.Id, node.ClientName, node.State));
@@ -71,6 +72,9 @@ public sealed class RenderNodeService(
var capabilities = Dto.Capabilities(node);
foreach (var queued in await db.Jobs.ListQueuedAsync(JobKind.Render, 50, cancellationToken))
{
+ // A render the server's own engine started (it left a checkpoint) resumes there: only it knows that attempt's
+ // leftovers and the batch entries it recorded.
+ if (queued.Checkpoint is not null) continue;
if (JobEndpoints.ParseRender(queued.ParametersJson) is not { } parameters || capabilities is null || !CanEncode(capabilities, parameters)) continue;
if (await db.Jobs.TryClaimAsync(queued.Id, NodeKey(node), cancellationToken) is not { } job) continue;
jobs.Publish(job);
@@ -182,6 +186,31 @@ public sealed class RenderNodeService(
/// Running-job owner key stored in jobs.node_id.
public static string NodeKey(RenderNode node) => node.Id.ToString();
+ ///
+ /// Gives the jobs running on back to the queue with in their log
+ /// (checkpoint and progress kept); a job that already lost its node times
+ /// fails instead. Returns how many went back.
+ ///
+ internal static async Task ReleaseJobsAsync(TitanoDatabase db, JobEngineHost jobs, RenderNode node, string reason, CancellationToken cancellationToken)
+ {
+ var key = NodeKey(node);
+ var lost = await db.Jobs.ListRunningByNodeAsync(key, cancellationToken);
+ foreach (var job in lost)
+ {
+ var line = AppendLog(job.LogTail, reason);
+ if (job.Attempts >= RenderNodeMonitor.MaxAttempts)
+ await db.Jobs.FinishNodeJobAsync(job.Id, key, JobState.Failed, $"Lost its render node {job.Attempts} times.", line, cancellationToken);
+ else
+ await db.Jobs.UpdateNodeProgressAsync(job.Id, key, job.ProgressDone, job.ProgressTotal, null, null, line, cancellationToken);
+ }
+ var requeued = await db.Jobs.RequeueRunningAsync(key, cancellationToken);
+ foreach (var job in lost)
+ {
+ if (await db.Jobs.GetAsync(job.Id, cancellationToken) is { } current) jobs.Publish(current);
+ }
+ return requeued;
+ }
+
private async Task OwnedNodeAsync(Caller caller, Guid nodeId, CancellationToken cancellationToken) =>
await db.RenderNodes.GetAsync(nodeId, cancellationToken) is { } node && node.UserId == caller.Id ? node : null;
@@ -221,11 +250,16 @@ public sealed class RenderNodeService(
}
}
- /// The node has an encoder for the job's codec and handles its resolution (0 = no announced limit).
- private static bool CanEncode(RegisterNodeRequest node, RenderJobParameters job) =>
- node.Encoders.Any(e => string.Equals(e.Codec, job.Codec, StringComparison.OrdinalIgnoreCase))
- && (node.MaxWidth <= 0 || job.Width <= node.MaxWidth)
- && (node.MaxHeight <= 0 || job.Height <= node.MaxHeight);
+ ///
+ /// The node has an encoder for the job's codec that handles its resolution: the encoder's own limit, else the node's
+ /// (0 = no announced limit).
+ ///
+ internal static bool CanEncode(RegisterNodeRequest node, RenderJobParameters job) =>
+ node.Encoders.Any(e => string.Equals(e.Codec, job.Codec, StringComparison.OrdinalIgnoreCase)
+ && Fits(job.Width, e.MaxWidth > 0 ? e.MaxWidth : node.MaxWidth)
+ && Fits(job.Height, e.MaxHeight > 0 ? e.MaxHeight : node.MaxHeight));
+
+ private static bool Fits(int size, int limit) => limit <= 0 || size <= limit;
internal static string? AppendLog(string? tail, string? line)
{
diff --git a/src/Titano.Server/Program.cs b/src/Titano.Server/Program.cs
index 06d2e08d..caed2df6 100644
--- a/src/Titano.Server/Program.cs
+++ b/src/Titano.Server/Program.cs
@@ -26,15 +26,22 @@ switch (command.Command)
case ServerCommand.UninstallService when OperatingSystem.IsWindows():
return ServiceAction(ServiceInstaller.Uninstall, $"Removed the {WindowsServiceHost.ServiceName} service.");
case ServerCommand.Service when OperatingSystem.IsWindows():
- if (WindowsServiceHost.Run(() => ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], ArchiveModule.Register))) return 0;
+ if (WindowsServiceHost.Run(() => ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], RegisterModules))) return 0;
await Console.Error.WriteLineAsync("--service is used by the Service Control Manager; start the service with 'sc start TitanoServer'.");
return 1;
default:
- var app = ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], ArchiveModule.Register);
+ var app = ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], RegisterModules);
await app.RunAsync();
return 0;
}
+// The archive engine, then analysis and managed rendering over it.
+static void RegisterModules(IServiceCollection services)
+{
+ ArchiveModule.Register(services);
+ ProcessingModule.Register(services);
+}
+
static int ServiceAction(Action action, string done)
{
try
diff --git a/src/Titano.Server/Storage/ArchiveModule.cs b/src/Titano.Server/Storage/ArchiveModule.cs
index d1738a91..3002c9d4 100644
--- a/src/Titano.Server/Storage/ArchiveModule.cs
+++ b/src/Titano.Server/Storage/ArchiveModule.cs
@@ -7,8 +7,8 @@ namespace Titano.Server.Storage;
///
/// The archive engine behind the server (BRIEF §7, §14.4): ingest of verified uploads, lookup of proxies and
-/// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance), plus the
-/// analysis handlers of . Decoding is managed only (BRIEF §4.2).
+/// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance). Decoding is
+/// managed only (BRIEF §4.2).
///
public static class ArchiveModule
{
@@ -22,6 +22,5 @@ public static class ArchiveModule
services.AddSingleton(sp => sp.GetRequiredService().Ingest);
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
- ProcessingModule.Register(services);
}
}
diff --git a/src/Titano.Server/Storage/ProcessingModule.cs b/src/Titano.Server/Storage/ProcessingModule.cs
index 591ef564..26b47a9a 100644
--- a/src/Titano.Server/Storage/ProcessingModule.cs
+++ b/src/Titano.Server/Storage/ProcessingModule.cs
@@ -5,26 +5,44 @@ using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
using Titano.Data.Processing;
+using Titano.Protocol;
using Titano.Server.Configuration;
+using Titano.Server.Events;
+using Titano.Server.Jobs;
namespace Titano.Server.Storage;
///
-/// Analysis and render engine of the server (BRIEF §4.2, §10, §14.6): light and deep analysis job handlers with managed
-/// decoders, so the light analysis queued after uploads runs here. Its render handler is registered too, but the job
-/// engine host never runs render jobs: render nodes claim them (BRIEF §14.7).
+/// Analysis and render engine of the server (BRIEF §4.2, §10, §14.5, §14.6): light and deep analysis with managed
+/// decoders (the light analysis queued after uploads runs here) and renders with managed encoders only. The render
+/// handler takes the jobs whose every output a managed encoder produces (AVI MJPEG, image sequences, GIF, APNG); MP4
+/// jobs wait for render nodes until none can take them (), and then render here as
+/// MJPEG in AVI with a line in the job log (BRIEF §14.7). Renders recorded and Auto values changed here reach connected
+/// clients as sequenceChanged events (§14.3).
///
public static class ProcessingModule
{
public static void Register(IServiceCollection services)
{
- services.AddSingleton(sp => new ProcessingService(sp.GetRequiredService(), new ProcessingOptions
+ services.AddSingleton();
+ services.AddSingleton(sp =>
{
- Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner },
- Encoders = [new ManagedEncoderProvider()],
- Host = EncoderHost.Server,
- ProducedBy = sp.GetRequiredService().ServerName,
- }));
+ var db = sp.GetRequiredService();
+ var events = sp.GetRequiredService();
+ return new ProcessingService(db, new ProcessingOptions
+ {
+ Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner },
+ Encoders = [new ManagedEncoderProvider()],
+ Host = EncoderHost.Server,
+ AwaitsRenderNode = sp.GetRequiredService().AwaitsNodeAsync,
+ ProducedBy = sp.GetRequiredService().ServerName,
+ SequenceChanged = async (id, change, ct) =>
+ {
+ if (await db.Sequences.GetAsync(id, ct) is { } sequence)
+ events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
+ },
+ });
+ });
services.AddSingleton(sp => sp.GetRequiredService());
}
}
diff --git a/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs b/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs
new file mode 100644
index 00000000..9d2268d2
--- /dev/null
+++ b/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs
@@ -0,0 +1,53 @@
+using System.IO;
+using Titano.App.Infrastructure;
+using Titano.App.Tests.Uploader;
+using Titano.Core.Model;
+using Titano.Data;
+using Titano.Data.Archiving;
+using Titano.Testing;
+
+namespace Titano.App.Tests.Infrastructure;
+
+public sealed class AppServicesTests
+{
+ /// Dialogs that answer like a user who cancels everything.
+ private sealed class NoDialogs : IAppDialogs
+ {
+ public string? PickFolder(string title, string? initialFolder = null) => null;
+ public string? PickJsonFile(string title) => null;
+ public bool Confirm(ConfirmRequest request) => false;
+ public bool SignIn(string server, string? username, Func> signIn) => false;
+ }
+
+ [Test]
+ [WindowsOnly]
+ public void ExitStopsPollingAndTheEngineWhileTheUiThreadWaits()
+ {
+ var environment = AppEnvironment.ForCapture();
+ try
+ {
+ SingleThreadedContext.Run(async () =>
+ {
+ var root = Path.Combine(environment.DataDirectory, "archive");
+ await using (var setup = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(environment.DataDirectory, "setup.db"))))
+ await new ArchiveService(setup).CreateAsync(root, "Exit");
+ var services = new AppServices(environment, new AppSettings { Language = "en", LastArchivePath = root }, () => { }, new NoDialogs());
+ await services.OpenAsync(environment.DatabasePath);
+ // The archive was reopened and its first rescan queued: polling now waits for the next one.
+ var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
+ while ((await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items.Count == 0)
+ {
+ Assert.True(DateTime.UtcNow < until, "no rescan queued");
+ await Task.Delay(50);
+ }
+
+ // App.OnExit blocks the UI thread until the services stop: nothing they await may continue on it.
+ Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped");
+ });
+ }
+ finally
+ {
+ environment.DeleteCaptureData();
+ }
+ }
+}
diff --git a/tests/Titano.App.Tests/Server/RenderNodeHostTests.cs b/tests/Titano.App.Tests/Server/RenderNodeHostTests.cs
new file mode 100644
index 00000000..c3711e3c
--- /dev/null
+++ b/tests/Titano.App.Tests/Server/RenderNodeHostTests.cs
@@ -0,0 +1,146 @@
+using System.IO;
+using Titano.App.Infrastructure;
+using Titano.Testing;
+
+namespace Titano.App.Tests.Server;
+
+public sealed class RenderNodeHostTests
+{
+ private static readonly RenderNodeSession Nas = new(new Uri("https://nas.local:8443/"), "token-a", ["AA:BB", "CC:DD"], Hardware: true);
+
+ /// Records the nodes it starts; fails the first starts.
+ private sealed class Nodes
+ {
+ public List<(RenderNodeSession Session, Node Node)> Started { get; } = [];
+ public int Failures { get; set; }
+
+ public IRenderNode Start(RenderNodeSession session)
+ {
+ if (Failures-- > 0) throw new IOException("cache folder unavailable");
+ var node = new Node();
+ Started.Add((session, node));
+ return node;
+ }
+ }
+
+ private sealed class Node : IRenderNode
+ {
+ private readonly TaskCompletionSource _completion = new();
+
+ public bool Stopped { get; private set; }
+
+ public Task Completion => _completion.Task;
+
+ /// The server refused the node (signed out, no render-node right): it ends by itself.
+ public void Refuse() => _completion.TrySetResult();
+
+ public ValueTask DisposeAsync()
+ {
+ Stopped = true;
+ _completion.TrySetResult();
+ return ValueTask.CompletedTask;
+ }
+ }
+
+ [Test]
+ public async Task TheNodeFollowsTheWantedSession()
+ {
+ var nodes = new Nodes();
+ await using var host = new RenderNodeHost(nodes.Start);
+
+ host.Update(Nas);
+ host.Update(Nas);
+ await host.Switching;
+ Assert.Equal(Nas, host.Session);
+ Assert.Count(1, nodes.Started);
+
+ // An equal session (fingerprints in another order) keeps the node.
+ host.Update(Nas with { TrustedFingerprints = ["CC:DD", "AA:BB"] });
+ await host.Switching;
+ Assert.Count(1, nodes.Started);
+
+ // A new token (signed in again) is another session: the old node stops before the new one starts.
+ var renewed = Nas with { Token = "token-b" };
+ host.Update(renewed);
+ await host.Switching;
+ Assert.True(nodes.Started[0].Node.Stopped, "old node stopped");
+ Assert.Equal((renewed, false), (nodes.Started[1].Session, nodes.Started[1].Node.Stopped));
+
+ // A forgotten certificate or another hardware choice also needs a new node.
+ host.Update(renewed with { TrustedFingerprints = [] });
+ await host.Switching;
+ host.Update(renewed with { TrustedFingerprints = [], Hardware = false });
+ await host.Switching;
+ Assert.Count(4, nodes.Started);
+ Assert.True(nodes.Started[2].Node.Stopped, "replaced again");
+
+ host.Update(null);
+ await host.Switching;
+ Assert.Null(host.Session);
+ Assert.True(nodes.Started[3].Node.Stopped, "stopped when no longer wanted");
+ }
+
+ [Test]
+ public async Task ANodeThatStoppedItselfIsStartedAgainByTheNextUpdate()
+ {
+ var nodes = new Nodes();
+ await using var host = new RenderNodeHost(nodes.Start);
+ host.Update(Nas);
+ await host.Switching;
+
+ nodes.Started[0].Node.Refuse();
+ host.Update(Nas);
+ await host.Switching;
+ Assert.Count(2, nodes.Started);
+ Assert.Equal((Nas, false), (host.Session, nodes.Started[1].Node.Stopped));
+ }
+
+ [Test]
+ public void TheNodeIsWantedOnlyWhenOfferedAndSignedIn()
+ {
+ var address = new Uri("https://nas.local:8443/");
+ Assert.Equal(Nas, RenderNodeSession.For(offered: true, connected: true, address, "token-a", ["AA:BB", "CC:DD"], hardware: true));
+ Assert.Null(RenderNodeSession.For(offered: false, connected: true, address, "token-a", [], hardware: true));
+ Assert.Null(RenderNodeSession.For(offered: true, connected: false, address, "token-a", [], hardware: true));
+ Assert.Null(RenderNodeSession.For(offered: true, connected: true, address, null, [], hardware: true)); // signed out
+ Assert.Null(RenderNodeSession.For(offered: true, connected: true, null, "token-a", [], hardware: true));
+ }
+
+ [Test]
+ public void HardwarePreferenceDecidesPerPreset()
+ {
+ Assert.True(AppServices.AllowsHardware(HardwarePreference.PreferHardware, "4k-hevc"));
+ Assert.False(AppServices.AllowsHardware(HardwarePreference.SoftwareOnly, "720p-preview"));
+ Assert.True(AppServices.AllowsHardware(HardwarePreference.HardwareForPreviews, "720p-preview"));
+ Assert.False(AppServices.AllowsHardware(HardwarePreference.HardwareForPreviews, "4k-hevc10-archive"));
+ }
+
+ [Test]
+ public async Task ANodeThatCannotStartIsRetriedByTheNextUpdate()
+ {
+ var nodes = new Nodes { Failures = 1 };
+ await using var host = new RenderNodeHost(nodes.Start);
+
+ host.Update(Nas);
+ await host.Switching;
+ Assert.Null(host.Session);
+
+ host.Update(Nas);
+ await host.Switching;
+ Assert.Equal(Nas, host.Session);
+ }
+
+ [Test]
+ public async Task DisposingStopsTheNodeAndIgnoresLaterUpdates()
+ {
+ var nodes = new Nodes();
+ var host = new RenderNodeHost(nodes.Start);
+ host.Update(Nas);
+ await host.DisposeAsync();
+
+ Assert.True(nodes.Started.Single().Node.Stopped, "stopped on exit");
+ host.Update(Nas);
+ await host.Switching;
+ Assert.Count(1, nodes.Started);
+ }
+}
diff --git a/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs b/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs
index c22c0835..2536f475 100644
--- a/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs
+++ b/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs
@@ -59,6 +59,68 @@ public sealed class ProjectSettingsTests
public void NewerVersionIsRefused() =>
Assert.Throws(() => ProjectSettings.FromJson("{\"version\": 99}"));
+ [Test]
+ public void MissingMembersKeepTheirDefaults()
+ {
+ var defaults = new ProjectSettings().ToJson();
+ Assert.Equal(defaults, ProjectSettings.FromJson("{}").ToJson());
+ Assert.Equal(defaults, ProjectSettings.FromJson("null").ToJson());
+
+ // An API client's partial edit: one manual value, a section given as null, keys in another casing.
+ var partial = ProjectSettings.FromJson(
+ """{ "Exposure": { "deflicker": { "isAuto": false, "manual": false } }, "motion": null, "export": { "preset": { "isAuto": false, "manual": "4k-hevc" } } }""");
+ Assert.False(partial.Exposure.Deflicker.Resolve(true));
+ Assert.True(partial.Exposure.HolyGrail.IsAuto);
+ Assert.Equal(0.9, partial.Exposure.HighlightKnee);
+ Assert.True(partial.Motion.Stabilize.IsAuto);
+ Assert.Equal("4k-hevc", partial.Export.Preset.Resolve("1080p-h264"));
+ Assert.Equal("{date} {title} - {preset}", partial.Export.NameTemplate);
+ Assert.SequenceEqual(new[] { 0.0, 1.0 }, partial.Timing.RemapCurve.Select(p => p.X));
+ Assert.Equal(9, partial.Stack.Length);
+ Assert.Equal(ProjectSettings.CurrentVersion, partial.Version);
+
+ // An explicit null clears a nullable value; arrays are replaced, not merged.
+ var cleared = ProjectSettings.FromJson("""{ "exposure": { "highlightKnee": null }, "timing": { "remapCurve": [ { "x": 0, "y": 0.5 } ] } }""");
+ Assert.Null(cleared.Exposure.HighlightKnee);
+ Assert.Equal(1, cleared.Timing.RemapCurve.Count);
+ }
+
+ [Test]
+ public void NullHighlightKneeSurvivesTheRoundTrip()
+ {
+ // "No knee, hard clip" must not come back as the default knee when the project is rewritten.
+ var off = new ProjectSettings { Exposure = new ExposureSettings { HighlightKnee = null } };
+ Assert.Contains("\"highlightKnee\": null", off.ToJson());
+ Assert.Null(ProjectSettings.FromJson(off.ToJson()).Exposure.HighlightKnee);
+ Assert.Equal(0.9, ProjectSettings.FromJson(new ProjectSettings().ToJson()).Exposure.HighlightKnee);
+ }
+
+ [Test]
+ public void NullListsAndTextsKeepTheirDefaults()
+ {
+ var project = ProjectSettings.FromJson(
+ """{ "excludedFrames": null, "export": { "batch": null, "nameTemplate": null }, "timing": { "remapCurve": null }, "camera": { "keyframes": null } }""");
+ Assert.Count(0, project.ExcludedFrames);
+ Assert.Count(0, project.Export.Batch);
+ Assert.Equal("{date} {title} - {preset}", project.Export.NameTemplate);
+ Assert.Count(2, project.Timing.RemapCurve);
+ Assert.Count(0, project.Camera.Keyframes);
+ // Nullable members without a default still clear.
+ Assert.Null(ProjectSettings.FromJson("""{ "export": { "folder": null }, "heroFrame": null }""").HeroFrame);
+ }
+
+ [Test]
+ public void DuplicateKeysAreAJsonError()
+ {
+ Assert.Throws(() => ProjectSettings.FromJson("""{ "version": 1, "version": 1 }"""));
+ Assert.Throws(() => ProjectSettings.FromJson("""{ "Export": {}, "export": {} }"""));
+ Assert.Throws(() => ProjectSettings.FromJson("""{ "export": { "batch": [], "Batch": [] } }"""));
+ }
+
+ [Test]
+ public void ProjectMustBeAnObject() =>
+ Assert.Throws(() => ProjectSettings.FromJson("[1, 2]"));
+
[Test]
public void BuiltInPresetIdsAreUnique() =>
Assert.Equal(ExportPresets.BuiltIn.Count, ExportPresets.BuiltIn.Select(p => p.Id).Distinct().Count());
diff --git a/tests/Titano.Data.Tests/Archiving/ArchiveFixture.cs b/tests/Titano.Data.Tests/Archiving/ArchiveFixture.cs
index 299674ff..8635995f 100644
--- a/tests/Titano.Data.Tests/Archiving/ArchiveFixture.cs
+++ b/tests/Titano.Data.Tests/Archiving/ArchiveFixture.cs
@@ -80,11 +80,11 @@ internal sealed class ArchiveFixture : IAsyncDisposable
}
/// Queues a job directly with a checkpoint, as a crashed earlier attempt would have left it.
- public async Task EnqueueWithCheckpointAsync(JobEngine engine, Titano.Data.Archiving.Jobs.ArchiveJobRequest request, string checkpoint)
+ public async Task EnqueueWithCheckpointAsync(JobEngine engine, Titano.Data.Archiving.Jobs.ArchiveJobRequest request, string checkpoint, Guid? id = null)
{
var job = new Job
{
- Id = Guid.CreateVersion7(),
+ Id = id ?? Guid.CreateVersion7(),
Kind = request.Kind,
TargetIds = request.Targets,
ParametersJson = request.ParametersJson,
diff --git a/tests/Titano.Data.Tests/Jobs/JobEngineTests.cs b/tests/Titano.Data.Tests/Jobs/JobEngineTests.cs
index 4820dc60..d4d8d15b 100644
--- a/tests/Titano.Data.Tests/Jobs/JobEngineTests.cs
+++ b/tests/Titano.Data.Tests/Jobs/JobEngineTests.cs
@@ -27,6 +27,37 @@ public sealed class JobEngineTests(TestContext context)
}
}
+ /// Takes only jobs whose parameters say they are its own.
+ private sealed class SelectiveHandler(JobKind kind) : ISelectiveJobHandler
+ {
+ public const string Mine = """{"mine":true}""";
+
+ public JobKind Kind => kind;
+
+ public ValueTask AcceptsAsync(Job job, CancellationToken cancellationToken) => ValueTask.FromResult(job.ParametersJson == Mine);
+
+ public Task RunAsync(JobContext c) => Task.CompletedTask;
+ }
+
+ /// Cannot judge jobs without parameters (as a render handler with a malformed preset) and fails them when run.
+ private sealed class FragileHandler(JobKind kind) : ISelectiveJobHandler
+ {
+ public JobKind Kind => kind;
+
+ public ValueTask AcceptsAsync(Job job, CancellationToken cancellationToken) =>
+ job.ParametersJson?.Length > 0 ? ValueTask.FromResult(true) : throw new ArgumentNullException(nameof(job));
+
+ public Task RunAsync(JobContext c) =>
+ c.Job.ParametersJson is null ? throw new InvalidDataException("no parameters") : Task.CompletedTask;
+ }
+
+ private sealed class CallbackHandler(JobKind kind, Func run) : IJobHandler
+ {
+ public JobKind Kind => kind;
+
+ public Task RunAsync(JobContext context) => run(context);
+ }
+
private async Task OpenAsync() =>
await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "jobs.db")), context.Cancellation);
@@ -159,6 +190,68 @@ public sealed class JobEngineTests(TestContext context)
Assert.Equal(JobKind.Render, pending[0].Kind);
}
+ [Test]
+ public async Task SelectiveHandlersLeaveDeclinedJobsQueuedWithoutHoldingUpOthers()
+ {
+ await using var db = await OpenAsync();
+ await using var engine = new JobEngine(db, [new SelectiveHandler(JobKind.Render), new CountingHandler(JobKind.Thumbs, 1)],
+ new JobEngineOptions { Workers = 1, WorkerId = "t", PollInterval = TimeSpan.FromMilliseconds(50) });
+ var declined = await engine.EnqueueAsync(JobKind.Render, [], parametersJson: """{"mine":false}""", priority: JobPriority.User);
+ var thumbs = await engine.EnqueueAsync(JobKind.Thumbs, [], priority: JobPriority.Background);
+ var accepted = await engine.EnqueueAsync(JobKind.Render, [], parametersJson: SelectiveHandler.Mine, priority: JobPriority.User);
+ await engine.StartAsync();
+
+ var render = await WaitForStateAsync(db, accepted.Id, JobState.Done, TimeSpan.FromSeconds(10));
+ var other = await WaitForStateAsync(db, thumbs.Id, JobState.Done, TimeSpan.FromSeconds(10));
+ Assert.True(render.Started <= other.Started, "claim order: priority first, across selective and other kinds");
+ await Task.Delay(200);
+ var waiting = (await db.Jobs.GetAsync(declined.Id))!;
+ Assert.Equal((JobState.Queued, (string?)null), (waiting.State, waiting.NodeId));
+ }
+
+ [Test]
+ public async Task ASelectiveHandlerThatThrowsDoesNotStopTheWorkers()
+ {
+ await using var db = await OpenAsync();
+ await using var engine = new JobEngine(db, [new FragileHandler(JobKind.Render), new CountingHandler(JobKind.Thumbs, 1)],
+ new JobEngineOptions { Workers = 2, WorkerId = "t", PollInterval = TimeSpan.FromMilliseconds(50) });
+ var broken = await engine.EnqueueAsync(JobKind.Render, [], priority: JobPriority.User);
+ await engine.StartAsync();
+
+ var failed = await WaitForStateAsync(db, broken.Id, JobState.Failed, TimeSpan.FromSeconds(10));
+ Assert.Equal("no parameters", failed.Error);
+ // The workers are still there for every kind.
+ var thumbs = await engine.EnqueueAsync(JobKind.Thumbs, []);
+ var render = await engine.EnqueueAsync(JobKind.Render, [], parametersJson: "{}");
+ await WaitForStateAsync(db, thumbs.Id, JobState.Done, TimeSpan.FromSeconds(10));
+ await WaitForStateAsync(db, render.Id, JobState.Done, TimeSpan.FromSeconds(10));
+ }
+
+ [Test]
+ public async Task FollowUpsAreQueuedOnlyForKindsTheEngineRuns()
+ {
+ await using var db = await OpenAsync();
+ var target = Guid.CreateVersion7();
+ Job? thumbs = null, light = null;
+ var scan = new CallbackHandler(JobKind.Scan, async c =>
+ {
+ thumbs = await c.EnqueueFollowUpAsync(JobKind.Thumbs, [target], "Roof", null, JobPriority.Background);
+ light = await c.EnqueueFollowUpAsync(JobKind.LightAnalyse, [target], "Roof", null, JobPriority.Background);
+ });
+ await using var engine = new JobEngine(db, [scan, new CountingHandler(JobKind.Thumbs, 1)],
+ new JobEngineOptions { Workers = 1, WorkerId = "t", PollInterval = TimeSpan.FromMilliseconds(50) });
+ await engine.StartAsync();
+ var user = Guid.CreateVersion7();
+ var job = await engine.EnqueueAsync(JobKind.Scan, [], createdBy: user);
+ await WaitForStateAsync(db, job.Id, JobState.Done, TimeSpan.FromSeconds(10));
+
+ Assert.Null(light);
+ var followUp = await WaitForStateAsync(db, Assert.NotNull(thumbs).Id, JobState.Done, TimeSpan.FromSeconds(10));
+ Assert.Equal((user, JobPriority.Background, "Roof"), (followUp.CreatedBy!.Value, followUp.Priority, followUp.TargetLabel!));
+ Assert.SequenceEqual([target], followUp.TargetIds);
+ Assert.Empty((await db.Jobs.ListAsync(null, JobKind.LightAnalyse)).Items);
+ }
+
[Test]
public async Task HandlerFailureMarksJobFailedWithMessage()
{
diff --git a/tests/Titano.Data.Tests/Processing/AnalysisFollowUpTests.cs b/tests/Titano.Data.Tests/Processing/AnalysisFollowUpTests.cs
new file mode 100644
index 00000000..0484c71d
--- /dev/null
+++ b/tests/Titano.Data.Tests/Processing/AnalysisFollowUpTests.cs
@@ -0,0 +1,120 @@
+using Titano.Core.Archiving;
+using Titano.Core.Diagnostics.Synthetic;
+using Titano.Core.Import;
+using Titano.Core.Model;
+using Titano.Core.Project;
+using Titano.Data.Archiving;
+using Titano.Data.Tests.Archiving;
+using Titano.Testing;
+
+namespace Titano.Data.Tests.Processing;
+
+/// New sequences get their light analysis (and so their Auto values) without any user action (BRIEF §1.1).
+[Category("processing")]
+public sealed class AnalysisFollowUpTests(TestContext context)
+{
+ [Test]
+ public async Task AnAdoptingScanQueuesLightAnalysisOfTheNewSequencesOnly()
+ {
+ await using var fx = await ProcessingFixture.CreateAsync(context);
+ fx.Write(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Roof");
+ await fx.StartEngineAsync(withArchive: true);
+
+ var scan = await fx.EnqueueAsync(ArchiveJobs.Scan(fx.Archive.Archive, full: true));
+ await fx.WaitForAsync(scan.Id, JobState.Done);
+ var light = Assert.NotNull(await SingleLightJobAsync(fx));
+ await fx.WaitForAsync(light.Id, JobState.Done);
+
+ var sequence = (await fx.Db.Sequences.GetAsync(light.TargetIds.Single(), fx.Ct))!;
+ Assert.Equal("Roof", sequence.Folder);
+ Assert.True(sequence.Status.HasFlag(SequenceStatus.AnalyzedLight), "analysed");
+ Assert.True(ProjectSettings.FromJson(await File.ReadAllTextAsync(fx.Folder(sequence).ProjectPath, fx.Ct)).Timing.Mode.HasAdvice, "advised");
+
+ // Scans that find nothing new queue nothing more.
+ foreach (var full in new[] { false, true })
+ {
+ var again = await fx.EnqueueAsync(ArchiveJobs.Scan(fx.Archive.Archive, full));
+ await fx.WaitForAsync(again.Id, JobState.Done);
+ }
+ Assert.Equal(light.Id, (await SingleLightJobAsync(fx))?.Id);
+ }
+
+ [Test]
+ public async Task AnImportQueuesLightAnalysisOfTheSequencesItFilled()
+ {
+ await using var fx = await ProcessingFixture.CreateAsync(context);
+ var card = context.CreateTempDirectory("card");
+ Photos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), ArchiveFixture.Start, 10);
+ var plan = await fx.Archive.Service.PlanImportAsync(fx.Archive.Archive.Id, card, new ImportOptions(), null, null, fx.Ct);
+ await fx.StartEngineAsync(withArchive: true);
+
+ var import = await fx.Engine.EnqueueAsync(ArchiveJobs.Import(fx.Archive.Archive, plan, null), createdBy: Guid.CreateVersion7(), cancellationToken: fx.Ct);
+ await fx.WaitForAsync(import.Id, JobState.Done);
+ var light = Assert.NotNull(await SingleLightJobAsync(fx));
+ await fx.WaitForAsync(light.Id, JobState.Done);
+
+ var sequenceId = await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Archive.Id, plan.Sessions.Single().SessionKey, fx.Ct);
+ Assert.SequenceEqual([Assert.NotNull(sequenceId)], light.TargetIds);
+ Assert.Equal(import.CreatedBy, light.CreatedBy);
+ Assert.Equal(JobPriority.Background, light.Priority);
+ Assert.True((await fx.Db.Sequences.GetAsync(sequenceId.Value, fx.Ct))!.Status.HasFlag(SequenceStatus.AnalyzedLight), "analysed");
+ }
+
+ [Test]
+ public async Task PhotosAddedToAnAnalysedFolderAreAnalysedAgain()
+ {
+ await using var fx = await ProcessingFixture.CreateAsync(context);
+ var sequence = await fx.AddAsync(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Roof");
+ await fx.StartEngineAsync(withArchive: true);
+ var first = await fx.EnqueueAsync(Titano.Data.Processing.ProcessingJobs.LightAnalysis([sequence.Id]));
+ await fx.WaitForAsync(first.Id, JobState.Done);
+
+ // The camera kept shooting into the folder: the next scan indexes the new photos and analyses the sequence again.
+ fx.Write(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 18 }), "Roof", first: 12);
+ var scan = await fx.EnqueueAsync(ArchiveJobs.Scan(fx.Archive.Archive));
+ await fx.WaitForAsync(scan.Id, JobState.Done);
+ var again = (await fx.Db.Jobs.ListAsync(null, JobKind.LightAnalyse, cancellationToken: fx.Ct)).Items.Single(j => j.Id != first.Id);
+ await fx.WaitForAsync(again.Id, JobState.Done);
+
+ var analysed = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
+ Assert.Equal(18, analysed.FrameCount);
+ Assert.True(analysed.Status.HasFlag(SequenceStatus.AnalyzedLight), "analysed again");
+ Assert.True(ManifestStore.ReadSequence(fx.Folder(sequence).ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedLight), "sidecar status");
+ }
+
+ [Test]
+ public async Task ASequenceWaitingForLightAnalysisIsNotQueuedAgain()
+ {
+ await using var fx = await ProcessingFixture.CreateAsync(context);
+ var sequence = await fx.AddAsync(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Roof");
+ // Queued before the scan, which runs first (user priority) and finds the sequence not analysed yet.
+ var waiting = await QueueAsync(fx, Titano.Data.Processing.ProcessingJobs.LightAnalysis([sequence.Id]));
+ var scan = await QueueAsync(fx, ArchiveJobs.Scan(fx.Archive.Archive, full: true));
+ await fx.StartEngineAsync(withArchive: true);
+
+ await fx.WaitForAsync(scan.Id, JobState.Done);
+ await fx.WaitForAsync(waiting.Id, JobState.Done);
+ Assert.Equal(waiting.Id, (await SingleLightJobAsync(fx))?.Id);
+ }
+
+ /// Queues a job before the engine starts.
+ private static async Task QueueAsync(ProcessingFixture fx, Titano.Data.Archiving.Jobs.ArchiveJobRequest request)
+ {
+ var job = new Job
+ {
+ Id = Guid.CreateVersion7(),
+ Kind = request.Kind,
+ TargetIds = request.Targets,
+ TargetLabel = request.Label,
+ ParametersJson = request.ParametersJson,
+ Priority = request.Priority,
+ State = JobState.Queued,
+ Created = DateTimeOffset.UtcNow,
+ };
+ await fx.Db.Jobs.EnqueueAsync(job, fx.Ct);
+ return job;
+ }
+
+ private static async Task SingleLightJobAsync(ProcessingFixture fx) =>
+ (await fx.Db.Jobs.ListAsync(null, JobKind.LightAnalyse, cancellationToken: fx.Ct)).Items.SingleOrDefault();
+}
diff --git a/tests/Titano.Data.Tests/Processing/AnalysisJobTests.cs b/tests/Titano.Data.Tests/Processing/AnalysisJobTests.cs
index 7673915d..8fb31ae9 100644
--- a/tests/Titano.Data.Tests/Processing/AnalysisJobTests.cs
+++ b/tests/Titano.Data.Tests/Processing/AnalysisJobTests.cs
@@ -5,6 +5,7 @@ using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Processing;
+using Titano.Data.Processing.Jobs;
using Titano.Data.Repositories;
using Titano.Testing;
@@ -29,7 +30,12 @@ public sealed class AnalysisJobTests(TestContext context)
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering());
var manual = new ProjectSettings();
- manual = manual with { Timing = manual.Timing with { FrameRate = manual.Timing.FrameRate.WithManual("25") } };
+ // The user's frame rate, and the highlight knee turned off (hard clip).
+ manual = manual with
+ {
+ Timing = manual.Timing with { FrameRate = manual.Timing.FrameRate.WithManual("25") },
+ Exposure = manual.Exposure with { HighlightKnee = null },
+ };
await fx.Db.Sequences.EditAsync(sequence.Id, new SequenceEdit { SettingsJson = manual.ToJson() }, null, fx.Ct);
await fx.StartEngineAsync();
@@ -39,6 +45,7 @@ public sealed class AnalysisJobTests(TestContext context)
var folder = fx.Folder(sequence);
var project = ProjectSettings.FromJson(await File.ReadAllTextAsync(folder.ProjectPath, fx.Ct));
Assert.Equal((false, "25"), (project.Timing.FrameRate.IsAuto, project.Timing.FrameRate.Resolve("30")));
+ Assert.Null(project.Exposure.HighlightKnee);
Assert.True(project.Timing.Mode.HasAdvice, "timing mode advised");
Assert.True(project.Timing.FrameRate.HasAdvice, "the advice is kept next to the manual frame rate");
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
@@ -105,6 +112,55 @@ public sealed class AnalysisJobTests(TestContext context)
Assert.Contains(Loc.L("Advisor.Log.Presets", string.Empty), done.LogTail);
}
+ [Test]
+ public async Task ASequenceThatFailsDoesNotStopTheOthersAndARetryRedoesOnlyIt()
+ {
+ await using var fx = await ProcessingFixture.CreateAsync(context);
+ var a = await fx.AddAsync(Flickering(10), "A");
+ var b = await fx.AddAsync(Flickering(10), "B");
+ var c = await fx.AddAsync(Flickering(10), "C");
+ // B's sidecar is gone for a while: its status cannot be recorded.
+ var sidecar = fx.Folder(b).ManifestPath;
+ var saved = await File.ReadAllBytesAsync(sidecar, fx.Ct);
+ File.Delete(sidecar);
+ await fx.StartEngineAsync();
+
+ var job = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([a.Id, b.Id, c.Id]));
+ var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
+ Assert.True(failed.Error!.StartsWith(Loc.L("Advisor.Log.Failed", b.DisplayTitle, string.Empty), StringComparison.Ordinal), failed.Error);
+ Assert.Equal("3;1", failed.Checkpoint);
+ Assert.SequenceEqual([true, false, true], await AnalysedAsync(fx, a, b, c));
+
+ await File.WriteAllBytesAsync(sidecar, saved, fx.Ct);
+ await fx.Engine.ResumeAsync(job.Id, fx.Ct);
+ var done = await fx.WaitForAsync(job.Id, JobState.Done);
+ Assert.SequenceEqual([true, true, true], await AnalysedAsync(fx, a, b, c));
+ Assert.Equal((3L, 3L), (done.ProgressDone, done.ProgressTotal));
+ // The retry analysed B alone.
+ var lightOfA = Loc.L("Advisor.Log.LightDone", a.DisplayTitle, 10, 0).Split(',')[0];
+ Assert.Equal(1, done.LogTail!.Split('\n').Count(line => line.Contains(lightOfA, StringComparison.Ordinal)));
+ }
+
+ [Test]
+ public void AnalysisCheckpointsKeepTheFailedTargets()
+ {
+ Assert.Equal("3", AnalyseJobHandler.Format(3, []));
+ Assert.Equal("4;0,2", AnalyseJobHandler.Format(4, [2, 0]));
+ var (next, retry) = AnalyseJobHandler.Parse("4;0,2", 5);
+ Assert.Equal(4, next);
+ Assert.SequenceEqual([0, 2], retry);
+ Assert.Equal(2, AnalyseJobHandler.Parse("2", 5).Next);
+ // Anything else starts over: no checkpoint, beyond the targets, a failed target not yet reached, garbage.
+ foreach (var text in new[] { null, "6", "2;3", "2;x", "a" }) Assert.Equal(0, AnalyseJobHandler.Parse(text, 5).Next);
+ }
+
+ private static async Task> AnalysedAsync(ProcessingFixture fx, params Sequence[] sequences)
+ {
+ var analysed = new List();
+ foreach (var s in sequences) analysed.Add((await fx.Db.Sequences.GetAsync(s.Id, fx.Ct))!.Status.HasFlag(SequenceStatus.AnalyzedLight));
+ return analysed;
+ }
+
[Test]
public async Task LightAnalysisAfterNewFramesDropsTheStaleDeepStatus()
{
diff --git a/tests/Titano.Data.Tests/Processing/HardwarePolicyTests.cs b/tests/Titano.Data.Tests/Processing/HardwarePolicyTests.cs
new file mode 100644
index 00000000..e24ed20b
--- /dev/null
+++ b/tests/Titano.Data.Tests/Processing/HardwarePolicyTests.cs
@@ -0,0 +1,83 @@
+using Titano.Core.Export;
+using Titano.Core.Video;
+using Titano.Core.Video.Managed;
+using Titano.Data.Processing;
+using Titano.Protocol.Client;
+using Titano.Testing;
+
+namespace Titano.Data.Tests.Processing;
+
+/// Settings › Rendering "Software only" and "Hardware for previews only" keep renders off the GPU encoders.
+[Category("processing")]
+public sealed class HardwarePolicyTests
+{
+ /// A PC with GPU HEVC and H.264 encoders and the software H.264 encoder; records what it opens.
+ private sealed class GpuProvider : IVideoEncoderProvider
+ {
+ public List Opened { get; } = [];
+
+ public string Name => "gpu";
+
+ public IReadOnlyList Capabilities { get; } =
+ [
+ new(VideoCodec.Hevc, "GPU HEVC", true, 8192, 8192, true),
+ new(VideoCodec.H264, "GPU H.264", true, 4096, 4096, false),
+ new(VideoCodec.H264, "Software H.264", false, 4096, 2304, false),
+ ];
+
+ public bool CanEncode(EncodeSettings settings) =>
+ Capabilities.Any(c => c.Codec == settings.Codec && (settings.EncoderName is null || settings.EncoderName == c.Name)
+ && settings.Width <= c.MaxWidth && settings.Height <= c.MaxHeight);
+
+ public IVideoEncoderSession Open(EncodeSettings settings)
+ {
+ Opened.Add(settings);
+ throw new NotSupportedException("recorded");
+ }
+ }
+
+ private static EncodeSettings Hevc4k(string? encoder = null) => new()
+ {
+ OutputPath = "out.mp4",
+ Codec = VideoCodec.Hevc,
+ Width = 3840,
+ Height = 2160,
+ FrameRate = new Rational(30, 1),
+ BitRate = 40_000_000,
+ EncoderName = encoder,
+ };
+
+ [Test]
+ public void SoftwareOnlyFallsBackToTheSoftwareEncoder()
+ {
+ var gpu = new GpuProvider();
+ var options = new ProcessingOptions { Encoders = [gpu, new ManagedEncoderProvider()], AllowsHardware = _ => false };
+
+ var selection = EncoderSelector.Select(Hevc4k(), options.SoftwareEncoders, EncoderHost.Client);
+ Assert.True(selection.IsReady, "software H.264 instead");
+ Assert.Equal((VideoCodec.H264, "Software H.264"), (selection.Settings.Codec, selection.Capability!.Name));
+ Assert.Contains(selection.Notices, n => n.Key == EncoderNotices.FallbackToH264);
+ Assert.Throws(() => selection.Open());
+ Assert.Equal(("Software H.264", false), (gpu.Opened.Single().EncoderName, gpu.Opened.Single().PreferHardware));
+
+ // A GPU encoder named in the export is not used either.
+ var named = EncoderSelector.Select(Hevc4k("GPU H.264") with { Codec = VideoCodec.H264, Width = 1920, Height = 1080 }, options.SoftwareEncoders, EncoderHost.Client);
+ Assert.Equal("Software H.264", named.Capability?.Name);
+ Assert.True(options.SoftwareEncoders[1] is ManagedEncoderProvider, "managed encoders are untouched");
+ }
+
+ [Test]
+ public void ARenderNodeOffersGpuEncodersOnlyWhenRendersMayUseThem()
+ {
+ using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "studio-pc");
+ var nodeOptions = new RenderNodeOptions { ClientName = "studio-pc", CacheDirectory = Path.GetTempPath() };
+ string[] Offered(Func allows) =>
+ [
+ .. new RenderNodeClient(client, new ProcessingOptions { Encoders = [new GpuProvider()], AllowsHardware = allows }, nodeOptions).Encoders
+ .Select(e => e.Name),
+ ];
+
+ Assert.SequenceEqual(["GPU HEVC", "GPU H.264", "Software H.264"], Offered(_ => true));
+ Assert.SequenceEqual(["Software H.264"], Offered(id => id == "720p-preview"));
+ }
+}
diff --git a/tests/Titano.Data.Tests/Processing/ProcessingFixture.cs b/tests/Titano.Data.Tests/Processing/ProcessingFixture.cs
index 39939b2e..d5b9ad90 100644
--- a/tests/Titano.Data.Tests/Processing/ProcessingFixture.cs
+++ b/tests/Titano.Data.Tests/Processing/ProcessingFixture.cs
@@ -23,16 +23,17 @@ internal sealed class ProcessingFixture : IAsyncDisposable
private JobEngine? _engine;
- private ProcessingFixture(ArchiveFixture archive, GateDecoder decoder)
+ private ProcessingFixture(ArchiveFixture archive, GateDecoder decoder, Func? configure)
{
Archive = archive;
Decoder = decoder;
- Processing = new ProcessingService(archive.Db, new ProcessingOptions
+ var options = new ProcessingOptions
{
Archive = new ArchiveServiceOptions { Decoder = new ImageDecoder([decoder]), Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) },
DeepAnalysis = DeepOptions,
ProducedBy = "test-pc",
- });
+ };
+ Processing = new ProcessingService(archive.Db, configure?.Invoke(options) ?? options);
}
public ArchiveFixture Archive { get; }
@@ -43,13 +44,15 @@ internal sealed class ProcessingFixture : IAsyncDisposable
public JobEngine Engine => _engine ?? throw new InvalidOperationException("Start the engine first.");
- public static async Task CreateAsync(TestContext context) => new(await ArchiveFixture.CreateAsync(context), new GateDecoder());
+ /// Changes to the processing options (a server's host and render-node check).
+ public static async Task CreateAsync(TestContext context, Func? configure = null) =>
+ new(await ArchiveFixture.CreateAsync(context), new GateDecoder(), configure);
- /// A started engine with the processing handlers (one worker, fast checkpoints).
- public async Task StartEngineAsync()
+ /// A started engine with the processing handlers, and the archive's when asked (one worker unless asked, fast checkpoints).
+ public async Task StartEngineAsync(bool withArchive = false, int workers = 1)
{
- _engine = new JobEngine(Db, Processing.CreateJobHandlers(),
- new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
+ _engine = new JobEngine(Db, [.. withArchive ? Archive.Service.CreateJobHandlers() : [], .. Processing.CreateJobHandlers()],
+ new JobEngineOptions { Workers = workers, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await _engine.StartAsync(Ct);
return _engine;
}
@@ -61,6 +64,15 @@ internal sealed class ProcessingFixture : IAsyncDisposable
/// Writes frames … of as JPEGs with their Exif into
/// (adopted in place) and indexes the archive.
public async Task AddAsync(SyntheticSequence sequence, string folder = "Synthetic", int first = 0)
+ {
+ Write(sequence, folder, first);
+ await Archive.ScanAsync(ScanMode.Full);
+ var location = (await Db.Sequences.ListLocationsAsync(Archive.Archive.Id, Ct)).Single(l => l.Folder == folder);
+ return (await Db.Sequences.GetAsync(location.Id, Ct))!;
+ }
+
+ /// Writes frames … of as JPEGs with their Exif into .
+ public void Write(SyntheticSequence sequence, string folder = "Synthetic", int first = 0)
{
var directory = Path.Combine(Archive.Paths.Root, folder);
Directory.CreateDirectory(directory);
@@ -70,9 +82,6 @@ internal sealed class ProcessingFixture : IAsyncDisposable
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i]);
File.WriteAllBytes(Path.Combine(directory, FileName(i)), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 95, App1Segments = [exif[4..]] }));
}
- await Archive.ScanAsync(ScanMode.Full);
- var location = (await Db.Sequences.ListLocationsAsync(Archive.Archive.Id, Ct)).Single(l => l.Folder == folder);
- return (await Db.Sequences.GetAsync(location.Id, Ct))!;
}
public static string FileName(int index) => $"IMG_{index + 1:0000}.JPG";
diff --git a/tests/Titano.Data.Tests/Processing/RenderJobTests.cs b/tests/Titano.Data.Tests/Processing/RenderJobTests.cs
index bf1bc8a7..656032ef 100644
--- a/tests/Titano.Data.Tests/Processing/RenderJobTests.cs
+++ b/tests/Titano.Data.Tests/Processing/RenderJobTests.cs
@@ -6,6 +6,8 @@ using Titano.Core.Imaging.Decoders;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
+using Titano.Core.Video;
+using Titano.Data.Jobs;
using Titano.Data.Processing;
using Titano.Testing;
@@ -24,6 +26,9 @@ public sealed class RenderJobTests(TestContext context)
NameTemplate = "clip-{codec}",
};
+ /// HEVC (a render node's codec) at the size of .
+ private static readonly ExportSettings Hevc = Mjpeg with { Preset = new Auto().WithManual("4k-hevc") };
+
private static SyntheticSequence Scene() => SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 });
[Test]
@@ -125,18 +130,13 @@ public sealed class RenderJobTests(TestContext context)
Directory.CreateDirectory(exports);
var recorded = Encoding.ASCII.GetBytes("RIFF recorded before the crash");
await File.WriteAllBytesAsync(output, recorded, fx.Ct);
- await fx.Db.Renders.InsertAsync(new Render
- {
- Id = Guid.CreateVersion7(),
- SequenceId = sequence.Id,
- PresetName = "MJPEG",
- OutputPath = "Synthetic/exports/clip-MJPEG.avi",
- Created = DateTimeOffset.UtcNow,
- }, fx.Ct);
+ // The crash came after the job recorded its first entry and before its checkpoint said so.
+ var jobId = Guid.CreateVersion7();
+ await fx.Db.Renders.InsertAsync(RecordedRender(sequence, Titano.Data.Processing.Jobs.RenderJobHandler.RenderId(jobId, 0)), fx.Ct);
await fx.StartEngineAsync();
var job = await fx.Archive.EnqueueWithCheckpointAsync(fx.Engine, ProcessingJobs.Render(sequence, Mjpeg with { Batch = ["gif-preview"] }, 96, 64),
- new RenderCheckpoint([], 0, output).ToJson());
+ new RenderCheckpoint([], 0, output).ToJson(), jobId);
await fx.WaitForAsync(job.Id, JobState.Done);
var kept = await File.ReadAllBytesAsync(output, fx.Ct);
@@ -145,6 +145,164 @@ public sealed class RenderJobTests(TestContext context)
Assert.Count(2, await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
}
+ [Test]
+ public async Task ARenderResumedAfterAnotherRecordedItsNameKeepsThatOutput()
+ {
+ await using var fx = await ProcessingFixture.CreateAsync(context);
+ var sequence = await fx.AddAsync(Scene());
+ var exports = fx.Folder(sequence).Exports;
+ var output = Path.Combine(exports, "clip-MJPEG.avi");
+ Directory.CreateDirectory(exports);
+ // While this job waited to resume, another render of the same preset finished under the name it had chosen.
+ var other = Encoding.ASCII.GetBytes("RIFF another render's output");
+ await File.WriteAllBytesAsync(output, other, fx.Ct);
+ await fx.Db.Renders.InsertAsync(RecordedRender(sequence, Guid.CreateVersion7()), fx.Ct);
+ await fx.StartEngineAsync();
+
+ var job = await fx.Archive.EnqueueWithCheckpointAsync(fx.Engine, ProcessingJobs.Render(sequence, Mjpeg, 96, 64), new RenderCheckpoint([], 0, output).ToJson());
+ await fx.WaitForAsync(job.Id, JobState.Done);
+
+ var kept = await File.ReadAllBytesAsync(output, fx.Ct);
+ Assert.BytesEqual(other, kept);
+ Assert.SequenceEqual(["clip-MJPEG (2).avi", "clip-MJPEG.avi"], Entries(exports));
+ Assert.Count(2, await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
+ }
+
+ [Test]
+ public async Task ConcurrentRendersOfOnePresetKeepBothOutputs()
+ {
+ await using var fx = await ProcessingFixture.CreateAsync(context);
+ var sequence = await fx.AddAsync(Scene());
+ await fx.StartEngineAsync(workers: 2);
+
+ var first = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
+ var second = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
+ await fx.WaitForAsync(first.Id, JobState.Done);
+ await fx.WaitForAsync(second.Id, JobState.Done);
+
+ Assert.SequenceEqual(["clip-MJPEG (2).avi", "clip-MJPEG.avi"], Entries(fx.Folder(sequence).Exports));
+ var renders = await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct);
+ Assert.Equal(2, renders.Select(r => r.OutputPath).Distinct().Count());
+ }
+
+ [Test]
+ public void ANameBeingWrittenIsNotPickedAgain()
+ {
+ var folder = context.CreateTempDirectory("exports");
+ var name = new ExportNameContext { Date = new DateTime(2026, 6, 1), Title = "Roof", PresetName = "MJPEG", Codec = VideoCodec.Mjpeg };
+ using var a = new OutputNames();
+ using var b = new OutputNames();
+ var first = a.Reserve(taken => ExportNaming.OutputPath(folder, "{title}", name, taken));
+ var second = b.Reserve(taken => ExportNaming.OutputPath(folder, "{title}", name, taken));
+ Assert.Equal((Path.Combine(folder, "Roof.avi"), Path.Combine(folder, "Roof (2).avi")), (first, second));
+ Assert.False(b.TryReserve(first), "held by the first render");
+
+ a.Dispose();
+ using var c = new OutputNames();
+ Assert.Equal(first, c.Reserve(taken => ExportNaming.OutputPath(folder, "{title}", name, taken)));
+ }
+
+ [Test]
+ public void RenderRowIdsAreStablePerJobAndEntry()
+ {
+ var job = Guid.CreateVersion7();
+ var id = Titano.Data.Processing.Jobs.RenderJobHandler.RenderId(job, 0);
+ Assert.Equal(id, Titano.Data.Processing.Jobs.RenderJobHandler.RenderId(job, 0));
+ Assert.NotEqual(id, Titano.Data.Processing.Jobs.RenderJobHandler.RenderId(job, 1));
+ Assert.NotEqual(id, Titano.Data.Processing.Jobs.RenderJobHandler.RenderId(Guid.CreateVersion7(), 0));
+ Assert.Equal(8, id.Version);
+ }
+
+ [Test]
+ public async Task AServerTakesOnlyTheRendersItsManagedEncodersProduce()
+ {
+ await using var fx = await ProcessingFixture.CreateAsync(context);
+ var server = new ProcessingService(fx.Db, new ProcessingOptions { Host = EncoderHost.Server, AwaitsRenderNode = (_, _, _) => Task.FromResult(true) });
+ var handler = Assert.NotNull(server.CreateJobHandlers().Single(h => h.Kind == JobKind.Render) as ISelectiveJobHandler);
+ var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "Synthetic" };
+ Job Job(ExportSettings export) => new() { Id = Guid.CreateVersion7(), Kind = JobKind.Render, ParametersJson = ProcessingJobs.Render(sequence, export, 96, 64).ParametersJson };
+ async Task AcceptsAsync(string? parametersJson) =>
+ await handler.AcceptsAsync(new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Render, ParametersJson = parametersJson }, fx.Ct);
+
+ Assert.True(await handler.AcceptsAsync(Job(Mjpeg with { Batch = ["png-sequence", "gif-preview"] }), fx.Ct), "managed outputs only");
+ Assert.False(await handler.AcceptsAsync(Job(Hevc), fx.Ct), "HEVC waits for a render node");
+ Assert.False(await handler.AcceptsAsync(Job(Mjpeg with { Batch = ["1080p-h264"] }), fx.Ct), "one MP4 in the batch");
+ Assert.True(await handler.AcceptsAsync(Job(Hevc) with { Checkpoint = """{"done":[],"pending":0}""" }, fx.Ct), "started here: resumes here");
+ Assert.True(await AcceptsAsync("{}"), "unreadable: fails with its reason");
+ Assert.True(await AcceptsAsync(WithPreset("""{"preset":{},"Preset":{}}""")), "a member given twice: fails with its reason");
+ Assert.True(await AcceptsAsync(WithPreset("""{"preset":{"isAuto":false,"manual":"mjpeg-avi"},"batch":null}""")), "a null batch is no batch");
+
+ var client = new ProcessingService(fx.Db).CreateJobHandlers().Single(h => h.Kind == JobKind.Render);
+ Assert.False(client is ISelectiveJobHandler, "a client renders whatever it is given");
+ }
+
+ [Test]
+ public async Task AServerTakesMp4JobsOnceNoRenderNodeCanAndOnlyThen()
+ {
+ await using var fx = await ProcessingFixture.CreateAsync(context);
+ var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "Synthetic" };
+ var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Render, ParametersJson = ProcessingJobs.Render(sequence, Hevc, 96, 64).ParametersJson };
+ async Task AcceptsAsync(Func>? awaits)
+ {
+ var server = new ProcessingService(fx.Db, new ProcessingOptions { Host = EncoderHost.Server, AwaitsRenderNode = awaits });
+ return await ((ISelectiveJobHandler)server.CreateJobHandlers().Single(h => h.Kind == JobKind.Render)).AcceptsAsync(job, fx.Ct);
+ }
+
+ Titano.Protocol.RenderJobParameters? asked = null;
+ Assert.True(await AcceptsAsync((_, p, _) => { asked = p; return Task.FromResult(false); }), "no node can take it");
+ Assert.Equal(("hevc", 96, 64), (asked!.Codec, asked.Width, asked.Height));
+ Assert.False(await AcceptsAsync(null), "without a node check, MP4 jobs always wait");
+ Assert.False(await AcceptsAsync((_, _, _) => throw new InvalidOperationException("database unreachable")), "unknown: keeps waiting");
+ }
+
+ [Test]
+ public async Task AServerRendersAsMjpegWhatNoRenderNodeTookAndSaysSo()
+ {
+ await using var fx = await ProcessingFixture.CreateAsync(context, o => o with { Host = EncoderHost.Server, AwaitsRenderNode = (_, _, _) => Task.FromResult(false) });
+ var sequence = await fx.AddAsync(Scene());
+ await fx.StartEngineAsync();
+
+ var request = ProcessingJobs.Render(sequence, Hevc, 96, 64);
+ var job = await fx.WaitForAsync((await fx.EnqueueAsync(request)).Id, JobState.Done);
+
+ var avi = await File.ReadAllBytesAsync(Path.Combine(fx.Folder(sequence).Exports, "clip-MJPEG.avi"), fx.Ct);
+ Assert.Equal(("RIFF", "AVI "), (Encoding.ASCII.GetString(avi, 0, 4), Encoding.ASCII.GetString(avi, 8, 4)));
+ var render = (await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct)).Single();
+ var preset = Loc.L("Export.Preset.Custom");
+ Assert.Equal((preset, "Mjpeg", 96, 64), (render.PresetName, render.Codec, render.Width, render.Height));
+ Assert.Contains(Loc.L("Export.Log.NoRenderNode", preset, "HEVC", "MJPEG"), job.LogTail);
+ }
+
+ [Test]
+ public void ABatchForAServerBecomesOneJobPerPreset()
+ {
+ var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "Synthetic", Title = "Roof" };
+ var jobs = ProcessingJobs.RenderEach(sequence, Mjpeg with { Batch = ["mjpeg-avi", "gif-preview", "GIF-preview", "4k-hevc"] }, 96, 64);
+ var parameters = jobs.Select(j => System.Text.Json.JsonSerializer.Deserialize(j.ParametersJson!, Titano.Protocol.ProtocolJson.Default.RenderJobParameters)!).ToList();
+ Assert.SequenceEqual(["mjpeg", "gif", "hevc"], parameters.Select(p => p.Codec));
+ Assert.True(jobs.All(j => j.Kind == JobKind.Render && j.Targets.SequenceEqual([sequence.Id])), "render jobs of the sequence");
+ Assert.True(parameters.All(p => ProcessingJobs.ReadExport(p.PresetJson).Batch.Count == 0), "no job carries a batch");
+ Assert.Equal((3840, 2160), (parameters[2].Width, parameters[2].Height));
+
+ // A posted batch written by hand may hold blank entries: they name no preset.
+ var posted = System.Text.Json.JsonSerializer.Deserialize(WithPreset("""{"preset":{"isAuto":false,"manual":"mjpeg-avi"},"batch":[null," ","gif-preview"]}"""),
+ Titano.Protocol.ProtocolJson.Default.RenderJobParameters)!;
+ Assert.SequenceEqual(["mjpeg", "gif"], ProcessingJobs.Split(posted, 96, 64).Select(p => p.Codec));
+ }
+
+ /// MJPEG job parameters whose preset JSON is .
+ private static string WithPreset(string presetJson) => System.Text.Json.JsonSerializer.Serialize(
+ new Titano.Protocol.RenderJobParameters("MJPEG", presetJson, "mjpeg", 96, 64, false, null), Titano.Protocol.ProtocolJson.Default.RenderJobParameters);
+
+ private static Render RecordedRender(Sequence sequence, Guid id) => new()
+ {
+ Id = id,
+ SequenceId = sequence.Id,
+ PresetName = "MJPEG",
+ OutputPath = "Synthetic/exports/clip-MJPEG.avi",
+ Created = DateTimeOffset.UtcNow,
+ };
+
private static List Entries(string folder) =>
Directory.Exists(folder) ? [.. Directory.EnumerateFileSystemEntries(folder).Select(e => Path.GetFileName(e)).Order(StringComparer.Ordinal)] : [];
diff --git a/tests/Titano.Data.Tests/Repositories/JobRepositoryTests.cs b/tests/Titano.Data.Tests/Repositories/JobRepositoryTests.cs
index cacf4de9..1ead5d8f 100644
--- a/tests/Titano.Data.Tests/Repositories/JobRepositoryTests.cs
+++ b/tests/Titano.Data.Tests/Repositories/JobRepositoryTests.cs
@@ -59,6 +59,28 @@ public abstract class JobRepositoryTests(TestContext context) : RepositoryTest(c
Assert.SequenceEqual([oldUser.Id, normal.Id, oldBackground.Id], order);
}
+ [Test]
+ public async Task SelectiveClaimersListQueuedKindsInClaimOrderAndClaimById()
+ {
+ var db = await OpenTitanoAsync(multiConnection: true);
+ var oldBackground = TestData.Job(JobKind.Render, JobPriority.Background, TestData.Now.AddMinutes(-10));
+ var newUser = TestData.Job(JobKind.Thumbs, JobPriority.User, TestData.Now);
+ var oldUser = TestData.Job(JobKind.Render, JobPriority.User, TestData.Now.AddMinutes(-1));
+ var otherKind = TestData.Job(JobKind.Scan, JobPriority.User, TestData.Now.AddMinutes(-20));
+ foreach (var job in new[] { oldBackground, newUser, oldUser, otherKind }) await db.Jobs.EnqueueAsync(job, Ct);
+
+ var queued = await db.Jobs.ListQueuedAsync([JobKind.Render, JobKind.Thumbs], 10, Ct);
+ Assert.SequenceEqual([oldUser.Id, newUser.Id, oldBackground.Id], queued.Select(j => j.Id));
+ Assert.Count(1, await db.Jobs.ListQueuedAsync([JobKind.Render, JobKind.Thumbs], 1, Ct));
+ Assert.Empty(await db.Jobs.ListQueuedAsync([], 10, Ct));
+
+ // Workers racing for the same listed job: exactly one gets it, and it leaves the listing.
+ var claims = await Task.WhenAll(Enumerable.Range(0, 6).Select(w => Task.Run(() => db.Jobs.TryClaimAsync(oldUser.Id, "worker-" + w, Ct))));
+ var claimed = Assert.NotNull(claims.SingleOrDefault(c => c is not null));
+ Assert.Equal((JobState.Running, 1), (claimed.State, claimed.Attempts));
+ Assert.SequenceEqual([newUser.Id, oldBackground.Id], (await db.Jobs.ListQueuedAsync([JobKind.Render, JobKind.Thumbs], 10, Ct)).Select(j => j.Id));
+ }
+
[Test]
public async Task ConcurrentClaimersNeverShareAJob()
{
diff --git a/tests/Titano.Server.Tests/Jobs/RenderNodeClientTests.cs b/tests/Titano.Server.Tests/Jobs/RenderNodeClientTests.cs
index f5ea40c8..ef445c21 100644
--- a/tests/Titano.Server.Tests/Jobs/RenderNodeClientTests.cs
+++ b/tests/Titano.Server.Tests/Jobs/RenderNodeClientTests.cs
@@ -1,14 +1,17 @@
using System.Text;
+using Microsoft.Extensions.DependencyInjection;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Core.Export;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Localization;
+using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Archiving;
using Titano.Data.Processing;
using Titano.Protocol;
using Titano.Protocol.Client;
+using Titano.Server.Jobs;
using Titano.Testing;
namespace Titano.Server.Tests.Jobs;
@@ -84,16 +87,248 @@ public sealed class RenderNodeClientTests(TestContext context)
var id = await node.RegisterAsync(context.Cancellation);
var registered = (await client.ListNodesAsync(context.Cancellation)).Single(n => n.Id == id);
Assert.SequenceEqual(["apng", "gif", "mjpeg"], registered.Encoders.Select(e => e.Codec).Order(StringComparer.Ordinal));
+ // Each encoder announces its own largest output, so the server matches job sizes per codec.
+ Assert.True(registered.Encoders.All(e => (e.MaxWidth, e.MaxHeight) == (65535, 65535)), "per-encoder limits");
}
- private static RenderNodeClient Node(TitanoClient client, string cache) =>
- new(client, new ProcessingOptions { Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer() } },
- new RenderNodeOptions { ClientName = "studio-pc", CacheDirectory = cache, ProgressInterval = TimeSpan.Zero });
+ [Test]
+ public async Task AStartedNodeRegistersBeatsClaimsAndStopsCleanly()
+ {
+ await using var server = await TestServer.StartAsync(context);
+ var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
+ var sequenceId = await UploadSequenceAsync(editor, Photos());
+ // A posted batch becomes one job per preset, so each output travels back on its own.
+ var job = await CreateRenderAsync(server, editor, sequenceId, Mjpeg with { Batch = ["gif-preview"] });
+ var gif = (await server.Database.Jobs.ListAsync(JobState.Queued, JobKind.Render)).Items.Single(j => j.Id != job.Id);
- private static async Task CreateRenderAsync(TestServer server, HttpClient editor, Guid sequenceId)
+ using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
+ var cache = context.CreateTempDirectory("node");
+ // Claims only when started and after each job: between them only heartbeats reach the server.
+ var node = Node(client, cache, poll: TimeSpan.FromMinutes(5), heartbeat: TimeSpan.FromMilliseconds(100));
+ node.Start();
+ await JobApiTests.WaitForAsync(editor, job.Id, "done");
+ await JobApiTests.WaitForAsync(editor, gif.Id, "done");
+ // Past the claim that found the queue empty, only heartbeats move the node's last sign of life.
+ await Task.Delay(300);
+ var beat = (await server.Database.RenderNodes.ListAsync()).Single().LastHeartbeat;
+ await Task.Delay(400);
+ Assert.Greater((await server.Database.RenderNodes.ListAsync()).Single().LastHeartbeat.Ticks, beat.Ticks);
+ await node.DisposeAsync();
+
+ Assert.True(node.Completion.IsCompleted, "stopped");
+ Assert.SequenceEqual(["gif", "mjpeg"], (await server.Database.Renders.ListBySequenceAsync(sequenceId)).Select(r => r.Codec!).Order(StringComparer.Ordinal));
+ Assert.False(Directory.EnumerateFileSystemEntries(Path.Combine(cache, "jobs")).Any(), "job folder removed");
+ }
+
+ [Test]
+ public async Task ANodeRestartedDuringAJobDoesNotLeaveItRunning()
+ {
+ await using var server = await TestServer.StartAsync(context);
+ var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
+ var sequenceId = await UploadSequenceAsync(editor, Photos());
+ var job = await CreateRenderAsync(server, editor, sequenceId);
+ var cache = context.CreateTempDirectory("node");
+
+ // The first run stops while downloading (sign-out, exit): the job is still running on the server.
+ var held = new HoldDownloads(new SocketsHttpHandler());
+ using (var slow = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc", held) { Token = token })
+ {
+ await using var first = Node(slow, cache);
+ using var stopping = new CancellationTokenSource();
+ var run = first.RunOnceAsync(stopping.Token);
+ await held.Holding.Task.WaitAsync(TimeSpan.FromSeconds(30));
+ Assert.Equal("running", (await JobApiTests.GetAsync(editor, job.Id)).State);
+ await stopping.CancelAsync();
+ Assert.True(await run, "the job was claimed");
+ }
+ Assert.Equal("running", (await JobApiTests.GetAsync(editor, job.Id)).State);
+
+ // Started again within the heartbeat timeout under the same name: registering gives the job back to the queue.
+ using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
+ await using var second = Node(client, cache);
+ Assert.True(await second.RunOnceAsync(context.Cancellation), "the abandoned job was claimed again");
+
+ var done = await JobApiTests.GetAsync(editor, job.Id);
+ Assert.Equal("done", done.State);
+ Assert.Contains("Render node studio-pc restarted.", done.LogTail);
+ Assert.Count(1, await server.Database.Renders.ListBySequenceAsync(sequenceId));
+ }
+
+ [Test]
+ public async Task ADroppedDownloadIsResumedNotFailed()
+ {
+ await using var server = await TestServer.StartAsync(context);
+ var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
+ var sequenceId = await UploadSequenceAsync(editor, Photos());
+ var job = await CreateRenderAsync(server, editor, sequenceId);
+
+ var cut = new CutFirst("original", new SocketsHttpHandler());
+ using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc", cut) { Token = token };
+ await using var node = Node(client, context.CreateTempDirectory("node"));
+ Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
+
+ Assert.Equal("done", (await JobApiTests.GetAsync(editor, job.Id)).State);
+ Assert.Equal(1, cut.Cuts);
+ Assert.Equal(1, cut.Resumed);
+ }
+
+ [Test]
+ public async Task ADroppedProxyIsFetchedWholeAgain()
+ {
+ await using var server = await TestServer.StartAsync(context);
+ var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
+ var photos = Photos();
+ var sequence = (await server.Database.Sequences.GetAsync(await UploadSequenceAsync(editor, photos)))!;
+ // The archive has proxies of every frame (the test locator serves /proxies/NNNN.jpg).
+ var proxies = Path.Combine(server.Options.ArchivePath, sequence.Folder, "proxies");
+ Directory.CreateDirectory(proxies);
+ foreach (var frame in await server.Database.Frames.ListBySequenceAsync(sequence.Id))
+ await File.WriteAllBytesAsync(Path.Combine(proxies, $"{frame.Index:D4}.jpg"), photos[frame.Index]);
+ await server.Database.Sequences.UpsertAsync(sequence with { Status = sequence.Status | SequenceStatus.ProxiesBuilt });
+ var job = await JobApiTests.CreateAsync(editor, "render", sequence.Id, ProcessingJobs.Render(sequence, Mjpeg, 96, 64, useProxies: true).ParametersJson);
+
+ var cut = new CutFirst("proxy", new SocketsHttpHandler());
+ using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc", cut) { Token = token };
+ var cache = context.CreateTempDirectory("node");
+ await using var node = Node(client, cache);
+ Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
+
+ Assert.Equal("done", (await JobApiTests.GetAsync(editor, job.Id)).State);
+ // Nothing verifies a proxy against a hash, so a retry never appends to what the dropped attempt left.
+ Assert.Equal((1, 0), (cut.Cuts, cut.Resumed));
+ Assert.False(Directory.Exists(Path.Combine(cache, "originals")), "no original needed");
+ }
+
+ [Test]
+ public async Task ANodeLeavesARenderTheServerStartedToTheServer()
+ {
+ await using var server = await TestServer.StartAsync(context);
+ var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
+ var sequenceId = await UploadSequenceAsync(editor, Photos());
+ var job = await CreateRenderAsync(server, editor, sequenceId);
+ // The server's own engine was rendering it when it crashed: its checkpoint names its leftovers.
+ Assert.NotNull(await server.Database.Jobs.TryClaimAsync(job.Id, "server:test#0"));
+ Assert.True(await server.Database.Jobs.UpdateProgressAsync(job.Id, 3, 12, null, null, """{"done":[],"pending":0}""", null));
+ await server.Database.Jobs.RequeueRunningAsync("server:test");
+
+ using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
+ await using var node = Node(client, context.CreateTempDirectory("node"));
+ Assert.False(await node.RunOnceAsync(context.Cancellation), "nothing for the node");
+ Assert.Equal("queued", (await JobApiTests.GetAsync(editor, job.Id)).State);
+ }
+
+ [Test]
+ public async Task ANodeRefusesABatchItCannotSendBack()
+ {
+ await using var server = await TestServer.StartAsync(context);
+ var (editor, user, token) = await server.UserAsync("alberto", "editor", renderNode: true);
+ var sequence = (await server.Database.Sequences.GetAsync(await UploadSequenceAsync(editor, Photos())))!;
+ // Queued as one job (an older server did not split batches).
+ var request = ProcessingJobs.Render(sequence, Mjpeg with { Batch = ["gif-preview"] }, 96, 64);
+ var job = await server.Services.GetRequiredService().Engine
+ .EnqueueAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority, user.Id);
+
+ using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
+ await using var node = Node(client, context.CreateTempDirectory("node"));
+ Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
+
+ var failed = await JobApiTests.GetAsync(editor, job.Id);
+ Assert.Equal(("failed", Loc.L("Errors.Render.NodeBatch")), (failed.State, failed.Error));
+ Assert.Empty(await server.Database.Renders.ListBySequenceAsync(sequence.Id));
+ }
+
+ [Test]
+ public async Task ADownloadThatEndedBeforeItsCheckIsVerifiedNotFetchedAgain()
+ {
+ await using var server = await TestServer.StartAsync(context);
+ var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
+ var photos = Photos();
+ var sequenceId = await UploadSequenceAsync(editor, photos);
+ await CreateRenderAsync(server, editor, sequenceId, Mjpeg);
+ // A crash after the last byte arrived but before the hash check left a complete part file.
+ var cache = context.CreateTempDirectory("node");
+ var sha = Uploads.Sha(photos[0]);
+ var part = Path.Combine(cache, "originals", sha[..2], sha + ".jpg.part");
+ Directory.CreateDirectory(Path.GetDirectoryName(part)!);
+ await File.WriteAllBytesAsync(part, photos[0]);
+
+ using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
+ await using var node = Node(client, cache);
+ Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
+
+ Assert.Count(1, await server.Database.Renders.ListBySequenceAsync(sequenceId));
+ Assert.FileMissing(part);
+ Assert.FileExists(part[..^".part".Length]);
+ }
+
+ private static RenderNodeClient Node(TitanoClient client, string cache, TimeSpan? poll = null, TimeSpan? heartbeat = null) =>
+ new(client, new ProcessingOptions { Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer() } },
+ new RenderNodeOptions
+ {
+ ClientName = "studio-pc",
+ CacheDirectory = cache,
+ ProgressInterval = TimeSpan.Zero,
+ PollInterval = poll ?? TimeSpan.FromSeconds(10),
+ HeartbeatInterval = heartbeat ?? TimeSpan.FromSeconds(30),
+ RetryDelay = TimeSpan.FromMilliseconds(10),
+ });
+
+ /// Holds every frame download until the request is cancelled.
+ private sealed class HoldDownloads(HttpMessageHandler inner) : DelegatingHandler(inner)
+ {
+ public TaskCompletionSource Holding { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ if (request.RequestUri!.AbsolutePath.StartsWith("/api/v1/frames/", StringComparison.Ordinal))
+ {
+ Holding.TrySetResult();
+ await Task.Delay(Timeout.Infinite, cancellationToken);
+ }
+ return await base.SendAsync(request, cancellationToken);
+ }
+ }
+
+ /// Drops the connection halfway through the first resource of it serves; counts the downloads resumed with a range.
+ private sealed class CutFirst(string kind, HttpMessageHandler inner) : DelegatingHandler(inner)
+ {
+ private int _cuts;
+ private int _resumed;
+
+ public int Cuts => _cuts;
+ public int Resumed => _resumed;
+
+ protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ if (request.Headers.Range is not null) Interlocked.Increment(ref _resumed);
+ var response = await base.SendAsync(request, cancellationToken);
+ if (!request.RequestUri!.AbsolutePath.EndsWith("/" + kind, StringComparison.Ordinal) || Interlocked.CompareExchange(ref _cuts, 1, 0) != 0)
+ return response;
+ var body = await response.Content.ReadAsByteArrayAsync(cancellationToken);
+ var content = new StreamContent(new CutStream(body, body.Length / 2));
+ foreach (var header in response.Content.Headers) content.Headers.TryAddWithoutValidation(header.Key, header.Value);
+ response.Content = content;
+ return response;
+ }
+ }
+
+ /// The first cut bytes, then a reset connection.
+ private sealed class CutStream(byte[] data, int cut) : MemoryStream(data, 0, cut)
+ {
+ public override int Read(byte[] buffer, int offset, int count) => Check(base.Read(buffer, offset, count));
+
+ public override int Read(Span buffer) => Check(base.Read(buffer));
+
+ public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) =>
+ Check(await base.ReadAsync(buffer, cancellationToken));
+
+ private static int Check(int read) => read > 0 ? read : throw new IOException("Connection reset by peer");
+ }
+
+ private static async Task CreateRenderAsync(TestServer server, HttpClient editor, Guid sequenceId, ExportSettings? export = null)
{
var sequence = (await server.Database.Sequences.GetAsync(sequenceId))!;
- var request = ProcessingJobs.Render(sequence, Mjpeg, 96, 64);
+ var request = ProcessingJobs.Render(sequence, export ?? Mjpeg, 96, 64);
return await JobApiTests.CreateAsync(editor, "render", sequenceId, request.ParametersJson);
}
diff --git a/tests/Titano.Server.Tests/Jobs/RenderNodeTests.cs b/tests/Titano.Server.Tests/Jobs/RenderNodeTests.cs
index 0b7610fc..14c52128 100644
--- a/tests/Titano.Server.Tests/Jobs/RenderNodeTests.cs
+++ b/tests/Titano.Server.Tests/Jobs/RenderNodeTests.cs
@@ -70,6 +70,26 @@ public sealed class RenderNodeTests(TestContext context)
}
}
+ [Test]
+ public async Task EachEncoderTakesOnlyJobsWithinItsOwnSizeLimit()
+ {
+ await using var server = await TestServer.StartAsync(context);
+ var (editor, _, _) = await server.UserAsync("alberto", "editor", renderNode: true);
+ var sequence = await JobApiTests.CreateSequenceAsync(editor);
+ // The software H.264 encoder stops at 4096 px although the node's MJPEG encoder writes far larger frames.
+ using var registered = await editor.PostAsJsonAsync("/api/v1/nodes/register", new RegisterNodeRequest("studio-pc",
+ [new NodeEncoder("h264", "H.264 Encoder MFT", false, false, 4096, 2304), new NodeEncoder("mjpeg", "Managed MJPEG", false, false, 65535, 65535)],
+ 65535, 65535), ProtocolJson.Default.RegisterNodeRequest);
+ var node = await registered.ReadAsync(ProtocolJson.Default.RenderNodeDto);
+ Assert.Equal((4096, 2304), (node.Encoders[0].MaxWidth, node.Encoders[0].MaxHeight));
+
+ await JobApiTests.CreateAsync(editor, "render", sequence, H264Job(6144, 3456));
+ using (var none = await editor.PostAsync($"/api/v1/nodes/{node.Id}/claim", null)) await none.ExpectAsync(HttpStatusCode.NoContent);
+ var uhd = await JobApiTests.CreateAsync(editor, "render", sequence, H264Job(3840, 2160));
+ using var claim = await editor.PostAsync($"/api/v1/nodes/{node.Id}/claim", null);
+ Assert.Equal(uhd.Id, (await claim.ReadAsync(ProtocolJson.Default.ClaimedJob)).Job.Id);
+ }
+
[Test]
public async Task TheOutputUploadBecomesARenderAndFinishesTheJob()
{
@@ -123,6 +143,10 @@ public sealed class RenderNodeTests(TestContext context)
await foreign.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
}
+ private static string H264Job(int width, int height) => JsonSerializer.Serialize(
+ new RenderJobParameters("H.264", """{"preset":{"isAuto":false,"manual":"4k-h264"}}""", "h264", width, height, UseProxies: false, null),
+ ProtocolJson.Default.RenderJobParameters);
+
private static async Task RegisterAsync(HttpClient client, string name, string codec, int maxWidth)
{
using var response = await client.PostAsJsonAsync("/api/v1/nodes/register",
diff --git a/tests/Titano.Server.Tests/Storage/ProcessingModuleTests.cs b/tests/Titano.Server.Tests/Storage/ProcessingModuleTests.cs
index 821c4155..6cb2d346 100644
--- a/tests/Titano.Server.Tests/Storage/ProcessingModuleTests.cs
+++ b/tests/Titano.Server.Tests/Storage/ProcessingModuleTests.cs
@@ -1,32 +1,47 @@
+using System.Net;
+using System.Net.Http.Json;
+using System.Text.Json;
+using Microsoft.Extensions.DependencyInjection;
using Titano.Core.Archiving;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Core.Metadata;
using Titano.Core.Model;
+using Titano.Core.Localization;
using Titano.Core.Project;
+using Titano.Data.Processing;
+using Titano.Protocol;
+using Titano.Server.Events;
+using Titano.Server.Jobs;
using Titano.Server.Storage;
+using Titano.Server.Tests.Jobs;
using Titano.Testing;
namespace Titano.Server.Tests.Storage;
-/// The production composition: frames committed by the archive engine are light-analysed by the processing handlers.
+///
+/// The production composition: frames committed by the archive engine are light-analysed by the processing handlers,
+/// and the server renders the managed formats itself.
+///
[Category("processing")]
public sealed class ProcessingModuleTests(TestContext context)
{
+ private const int Frames = 10;
+
+ /// The registrations of Program.cs.
+ private static void Production(IServiceCollection services)
+ {
+ ArchiveModule.Register(services);
+ ProcessingModule.Register(services);
+ }
+
[Test]
public async Task UploadedFramesAreLightAnalysedAndAdvised()
{
- await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
+ await using var server = await TestServer.StartAsync(context, services: Production);
+ using var events = server.Services.GetRequiredService().Subscribe();
var (editor, _, _) = await server.UserAsync("alberto", "editor");
- var scene = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 10, StartEv = 0.5, EndEv = -0.5 });
- Guid sequenceId = default;
- for (var i = 0; i < scene.Count; i++)
- {
- using var image = scene.Render(i);
- var exif = ExifWriter.BuildJpegApp1(scene.Metadata[i]);
- var photo = JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] });
- sequenceId = (await Uploads.UploadAsync(editor, photo, $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
- }
+ var sequenceId = await UploadSceneAsync(editor);
// The commits queue a light analysis; its handler comes from the processing module.
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
@@ -34,7 +49,7 @@ public sealed class ProcessingModuleTests(TestContext context)
while (true)
{
sequence = (await server.Database.Sequences.GetAsync(sequenceId))!;
- if (sequence.Status.HasFlag(SequenceStatus.AnalyzedLight) && sequence.FrameCount == scene.Count
+ if (sequence.Status.HasFlag(SequenceStatus.AnalyzedLight) && sequence.FrameCount == Frames
&& !await server.Database.Jobs.IsQueuedAsync(JobKind.LightAnalyse, sequenceId)) break;
Assert.True(DateTime.UtcNow < until, $"not analysed: {sequence.Status}, {sequence.FrameCount} frames");
await Task.Delay(100);
@@ -44,5 +59,155 @@ public sealed class ProcessingModuleTests(TestContext context)
var folder = new ArchivePaths(server.Options.ArchivePath).Sequence(sequence.Folder);
Assert.FileExists(folder.ProjectPath);
Assert.True(ManifestStore.ReadSequence(folder.ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedLight), "sidecar status");
+ // Connected clients learn that the Auto values changed (BRIEF §14.3).
+ Assert.Contains(Drain(events), e => e is SequenceChangedEvent { Change: "settings" } changed && changed.SequenceId == sequenceId);
+ }
+
+ [Test]
+ public async Task TheServerRendersManagedFormatsAndLeavesMp4ToRenderNodes()
+ {
+ await using var server = await TestServer.StartAsync(context, services: Production);
+ using var events = server.Services.GetRequiredService().Subscribe();
+ var (editor, _, _) = await server.UserAsync("alberto", "editor");
+ var sequence = (await server.Database.Sequences.GetAsync(await UploadSceneAsync(editor)))!;
+ // A client's export folder means nothing on the server: the output still goes to the sequence's exports.
+ var avi = new ExportSettings
+ {
+ Preset = new Auto().WithManual("mjpeg-avi"),
+ Overrides = new ExportOverrides { Width = 96, Height = 64 },
+ NameTemplate = "clip",
+ Folder = context.CreateTempDirectory("elsewhere"),
+ };
+ var hevc = new ExportSettings { Preset = new Auto().WithManual("4k-hevc") };
+
+ var mp4 = await JobApiTests.CreateAsync(editor, "render", sequence.Id, ProcessingJobs.Render(sequence, hevc, 96, 64).ParametersJson);
+ var managed = await JobApiTests.CreateAsync(editor, "render", sequence.Id, ProcessingJobs.Render(sequence, avi, 96, 64).ParametersJson);
+ var done = await JobApiTests.WaitForAsync(editor, managed.Id, "done");
+
+ Assert.Equal(JobEngineHost.WorkerId, done.NodeId?.Split('#')[0]);
+ var render = (await server.Database.Renders.ListBySequenceAsync(sequence.Id)).Single();
+ Assert.Equal(($"{sequence.Folder}/exports/clip.avi", server.Options.ServerName, "Mjpeg"), (render.OutputPath, render.ProducedBy, render.Codec));
+ Assert.FileExists(Path.Combine(server.Options.ArchivePath, render.OutputPath));
+ Assert.Empty(Directory.EnumerateFileSystemEntries(avi.Folder));
+ var waiting = await JobApiTests.GetAsync(editor, mp4.Id);
+ Assert.Equal(("queued", (string?)null), (waiting.State, waiting.NodeId));
+ Assert.Contains(Drain(events), e => e is SequenceChangedEvent { Change: "renders" } changed && changed.SequenceId == sequence.Id);
+ }
+
+ [Test]
+ public async Task Mp4JobsNoRenderNodeCanTakeAreRenderedAsMjpegAndTheLogSaysSo()
+ {
+ var clock = new ManualTimeProvider();
+ await using var server = await TestServer.StartAsync(context, o => o.NodeTimeoutSeconds = 60, s =>
+ {
+ Production(s);
+ s.AddSingleton(clock);
+ });
+ var engine = server.Services.GetRequiredService().Engine;
+ var (editor, _, _) = await server.UserAsync("alberto", "editor", renderNode: true);
+ var sequence = (await server.Database.Sequences.GetAsync(await UploadSceneAsync(editor)))!;
+ var hevc = new ExportSettings
+ {
+ Preset = new Auto().WithManual("4k-hevc"),
+ Overrides = new ExportOverrides { Width = 96, Height = 64 },
+ NameTemplate = "clip-{codec}",
+ };
+ var job = await JobApiTests.CreateAsync(editor, "render", sequence.Id, ProcessingJobs.Render(sequence, hevc, 96, 64).ParametersJson);
+
+ // A node that encodes HEVC is online: the job waits for it, however long it has been queued.
+ using (var registered = await editor.PostAsJsonAsync("/api/v1/nodes/register",
+ new RegisterNodeRequest("studio-pc", [new NodeEncoder("hevc", "NVENC HEVC", true, true, 8192, 8192)], 8192, 8192), ProtocolJson.Default.RegisterNodeRequest))
+ await registered.ExpectAsync(HttpStatusCode.OK);
+ clock.Advance(TimeSpan.FromSeconds(61));
+ var node = (await server.Database.RenderNodes.ListAsync()).Single();
+ Assert.True(await server.Database.RenderNodes.HeartbeatAsync(node.Id, "idle", clock.GetUtcNow()));
+ engine.Wake();
+ await Task.Delay(1500);
+ Assert.Equal("queued", (await JobApiTests.GetAsync(editor, job.Id)).State);
+
+ // The node goes silent: the server renders the job itself in a managed format.
+ clock.Advance(TimeSpan.FromSeconds(61));
+ engine.Wake();
+ var done = await JobApiTests.WaitForAsync(editor, job.Id, "done");
+ Assert.Equal(JobEngineHost.WorkerId, done.NodeId?.Split('#')[0]);
+ var render = (await server.Database.Renders.ListBySequenceAsync(sequence.Id)).Single();
+ Assert.Equal(($"{sequence.Folder}/exports/clip-MJPEG.avi", "Mjpeg", 96, 64), (render.OutputPath, render.Codec, render.Width, render.Height));
+ Assert.Contains(Loc.L("Export.Log.NoRenderNode", Loc.L("Export.Preset.Custom"), "HEVC", "MJPEG"), done.LogTail);
+ }
+
+ [Test]
+ public async Task APostedBatchBecomesOneJobPerPreset()
+ {
+ await using var server = await TestServer.StartAsync(context, services: Production);
+ var (editor, _, _) = await server.UserAsync("alberto", "editor");
+ var sequence = (await server.Database.Sequences.GetAsync(await UploadSceneAsync(editor)))!;
+ var batch = new ExportSettings
+ {
+ Preset = new Auto().WithManual("mjpeg-avi"),
+ Overrides = new ExportOverrides { Width = 96, Height = 64 },
+ NameTemplate = "{title} - {codec}",
+ Batch = ["gif-preview", "1080p-h264"],
+ };
+
+ var main = await JobApiTests.CreateAsync(editor, "render", sequence.Id, ProcessingJobs.Render(sequence, batch, 96, 64).ParametersJson);
+ var jobs = (await server.Database.Jobs.ListAsync(null, JobKind.Render)).Items;
+ Assert.Count(3, jobs);
+ var mp4 = jobs.Single(j => j.TargetLabel!.EndsWith(Loc.L("Export.Preset.1080pShare"), StringComparison.Ordinal));
+ var gif = jobs.Single(j => j.TargetLabel!.EndsWith(Loc.L("Export.Preset.Gif"), StringComparison.Ordinal));
+ await JobApiTests.WaitForAsync(editor, main.Id, "done");
+ await JobApiTests.WaitForAsync(editor, gif.Id, "done");
+
+ // The server renders the managed presets; the MP4 one waits for a render node, at the preset's size.
+ Assert.SequenceEqual(["Gif", "Mjpeg"], (await server.Database.Renders.ListBySequenceAsync(sequence.Id)).Select(r => r.Codec!).Order(StringComparer.Ordinal));
+ Assert.Equal("queued", (await JobApiTests.GetAsync(editor, mp4.Id)).State);
+ var parameters = JsonSerializer.Deserialize(mp4.ParametersJson!, ProtocolJson.Default.RenderJobParameters)!;
+ Assert.Equal(("h264", 1920, 1080), (parameters.Codec, parameters.Width, parameters.Height));
+ }
+
+ [Test]
+ public async Task RenderJobsThatCannotBeReadNeverStopTheEngine()
+ {
+ await using var server = await TestServer.StartAsync(context, services: Production);
+ var (editor, user, _) = await server.UserAsync("alberto", "editor");
+ var sequence = (await server.Database.Sequences.GetAsync(await UploadSceneAsync(editor)))!;
+ const string mjpeg = """{"preset":{"isAuto":false,"manual":"mjpeg-avi"},"overrides":{"width":96,"height":64}""";
+
+ // The API refuses a preset that gives a member twice; one already queued fails with its reason.
+ using (var refused = await editor.PostAsJsonAsync("/api/v1/jobs",
+ new CreateJobRequest("render", [sequence.Id], Parameters(mjpeg + ""","Preset":{}}""")), ProtocolJson.Default.CreateJobRequest))
+ await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_parameters");
+ var engine = server.Services.GetRequiredService().Engine;
+ var broken = await engine.EnqueueAsync(JobKind.Render, [sequence.Id], "broken", Parameters(mjpeg + ""","Preset":{}}"""), JobPriority.User, user.Id);
+ var failed = await JobApiTests.WaitForAsync(editor, broken.Id, "failed");
+ Assert.Equal(Loc.L("Errors.Render.Parameters"), failed.Error);
+
+ // The workers carry on: a null batch is no batch.
+ var fine = await JobApiTests.CreateAsync(editor, "render", sequence.Id, Parameters(mjpeg + ""","batch":null}"""));
+ await JobApiTests.WaitForAsync(editor, fine.Id, "done");
+ }
+
+ private static string Parameters(string presetJson) =>
+ JsonSerializer.Serialize(new RenderJobParameters("MJPEG", presetJson, "mjpeg", 96, 64, false, null), ProtocolJson.Default.RenderJobParameters);
+
+ private static List Drain(EventHub.Subscription events)
+ {
+ var drained = new List();
+ while (events.Reader.TryRead(out var e)) drained.Add(e);
+ return drained;
+ }
+
+ /// Uploads a synthetic scene with Exif into one new sequence; returns its id.
+ private static async Task UploadSceneAsync(HttpClient editor)
+ {
+ var scene = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 });
+ Guid sequenceId = default;
+ for (var i = 0; i < scene.Count; i++)
+ {
+ using var image = scene.Render(i);
+ var exif = ExifWriter.BuildJpegApp1(scene.Metadata[i]);
+ var photo = JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] });
+ sequenceId = (await Uploads.UploadAsync(editor, photo, $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
+ }
+ return sequenceId;
}
}