feat(server): render MP4 jobs no render node can take as MJPEG, and say so

BRIEF §14.7: the server falls back to managed formats when no node is
available and says so in the job log. An MP4 job waits for render nodes at
least the node timeout, then as long as an online node can encode its codec
at its size; after that the server's engine takes it and writes each output
it cannot encode as MJPEG in AVI at the same size and frame rate, with a job
log line. A job the server started resumes there. Selective acceptance is
asynchronous for that; when node availability cannot be read the job keeps
waiting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-03 09:39:17 +00:00
1 parent 1e255fb075
commit 4007293833
15 files changed
+247 -48

No files matched your search

+4 -4
View File
@@ -242,7 +242,7 @@ public sealed class JobEngine : IAsyncDisposable
Job? candidate = null;
foreach (var queued in await _db.Jobs.ListQueuedAsync(_selective.Keys, SelectiveWindow, cancellationToken).ConfigureAwait(false))
{
if (!Accepts(queued)) continue;
if (!await AcceptsAsync(queued, cancellationToken).ConfigureAwait(false)) continue;
candidate = queued;
break;
}
@@ -261,13 +261,13 @@ public sealed class JobEngine : IAsyncDisposable
}
/// <summary>A job its handler cannot judge is taken, so it fails here with its reason instead of blocking the queue.</summary>
private bool Accepts(Job job)
private async ValueTask<bool> AcceptsAsync(Job job, CancellationToken cancellationToken)
{
try
{
return _selective[job.Kind].Accepts(job);
return await _selective[job.Kind].AcceptsAsync(job, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
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;
+5 -4
View File
@@ -14,13 +14,14 @@ public interface IJobHandler
}
/// <summary>
/// A handler that runs only some jobs of its kind, decided from the job alone (its parameters never change). The engine
/// leaves the others queued for other claimers: the server renders what its managed encoders produce and leaves the
/// rest to render nodes (BRIEF §14.5, §14.7).
/// 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).
/// </summary>
public interface ISelectiveJobHandler : IJobHandler
{
bool Accepts(Job job);
/// <summary>Whether this handler takes <paramref name="job"/> now. A job it cannot read should be taken, so it fails with its reason.</summary>
ValueTask<bool> AcceptsAsync(Job job, CancellationToken cancellationToken);
}
/// <summary>A component that brings several handlers (the archive engine: scan, rebuild, verify, import, images, maintenance).</summary>
@@ -1,39 +1,87 @@
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;
/// <summary>
/// <see cref="JobKind.Render"/> on the server (BRIEF §4.4, §14.5): it takes only 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) stay queued for render nodes (§14.7). Jobs whose parameters cannot be read are taken, so they fail with their
/// reason instead of waiting for a claimer that never comes.
/// <see cref="JobKind.Render"/> 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 <see cref="ProcessingOptions.AwaitsRenderNode"/> 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.
/// </summary>
internal sealed class ManagedRenderJobHandler(RenderJobHandler render, IReadOnlyList<IVideoEncoderProvider> encoders) : ISelectiveJobHandler
internal sealed class ManagedRenderJobHandler(RenderJobHandler render, ProcessingOptions options) : ISelectiveJobHandler
{
private readonly EncoderCapability[] _capabilities = [.. encoders.SelectMany(e => e.Capabilities)];
/// <summary>The managed preset whose values stand in for an output only a render node could make.</summary>
private const string FallbackPresetId = "mjpeg-avi";
private readonly EncoderCapability[] _capabilities = [.. options.Encoders.SelectMany(e => e.Capabilities)];
public JobKind Kind => JobKind.Render;
public bool Accepts(Job job)
public async ValueTask<bool> AcceptsAsync(Job job, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(job);
RenderJobParameters parameters;
try
{
var parameters = ProcessingJobs.ReadParameters(job.ParametersJson);
// Most declined jobs are decided by the main codec, before the export is read.
return _capabilities.Any(c => string.Equals(ProcessingJobs.CodecName(c.Codec), parameters.Codec, StringComparison.OrdinalIgnoreCase))
&& RenderJobHandler.Targets(ProcessingJobs.ReadExport(parameters.PresetJson), parameters.PresetName).All(t => Produces(t.Export));
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 (InvalidDataException)
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);
public Task RunAsync(JobContext context) =>
render.RunAsync(context, target => Produces(target.Export) ? target : Fallback(context, target));
/// <summary>The output as MJPEG in AVI with the managed preset's quality, at the size and frame rate asked for.</summary>
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);
@@ -25,7 +25,10 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
{
public JobKind Kind => JobKind.Render;
public async Task RunAsync(JobContext context)
public Task RunAsync(JobContext context) => RunAsync(context, target => target);
/// <summary>Runs the job with each output still to render passed through <paramref name="adapt"/> (the server's managed stand-ins).</summary>
internal async Task RunAsync(JobContext context, Func<ExportTarget, ExportTarget> adapt)
{
var cancellation = context.Cancellation;
var (parameters, export) = ProcessingJobs.ReadRender(context.Job.ParametersJson);
@@ -56,7 +59,7 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
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)).ToList();
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);
@@ -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;
@@ -40,9 +42,16 @@ public sealed record ProcessingOptions
/// </summary>
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
/// <summary>The server delegates platform codecs to render nodes and never runs them itself.</summary>
/// <summary>The server delegates platform codecs to render nodes (<see cref="AwaitsRenderNode"/>).</summary>
public EncoderHost Host { get; init; } = EncoderHost.Client;
/// <summary>
/// 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.
/// </summary>
public Func<Job, RenderJobParameters, CancellationToken, Task<bool>>? AwaitsRenderNode { get; init; }
/// <summary>Recorded with every render this host produces (client or server name).</summary>
public string ProducedBy { get; init; } = Environment.MachineName;
@@ -10,8 +10,8 @@ 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 (<see cref="ProcessingOptions"/>).
/// Register it on the <see cref="JobEngine"/> next to the archive engine. A client renders every job it is given; a
/// server takes only the renders its managed encoders produce and leaves the others to render nodes. Create jobs with
/// <see cref="ProcessingJobs"/>.
/// server takes the renders its managed encoders produce and leaves the others to render nodes until none can take them
/// (<see cref="ProcessingOptions.AwaitsRenderNode"/>). Create jobs with <see cref="ProcessingJobs"/>.
/// </summary>
public sealed class ProcessingService : IJobHandlerProvider
{
@@ -37,7 +37,7 @@ public sealed class ProcessingService : IJobHandlerProvider
[
new AnalyseJobHandler(_db, _analyser, JobKind.LightAnalyse),
new AnalyseJobHandler(_db, _analyser, JobKind.DeepAnalyse),
Options.Host == EncoderHost.Server ? new ManagedRenderJobHandler(render, Options.Encoders) : render,
Options.Host == EncoderHost.Server ? new ManagedRenderJobHandler(render, Options) : render,
];
}
}
+2 -2
View File
@@ -13,8 +13,8 @@ namespace Titano.Server.Jobs;
/// Hosts the server's <see cref="JobEngine"/> (BRIEF §14.6) with the <see cref="IJobHandler"/>s registered in DI (directly or
/// through <see cref="IJobHandlerProvider"/>s) and
/// relays its state changes and progress as WebSocket events. Render jobs run here only when the registered render
/// handler accepts them (managed formats, <see cref="ISelectiveJobHandler"/>); 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.
/// handler accepts them (<see cref="ISelectiveJobHandler"/>: 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.
/// </summary>
public sealed class JobEngineHost : IHostedService
{
@@ -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;
/// <summary>
/// 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
/// (<see cref="ServerOptions.NodeTimeoutSeconds"/>), 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.
/// </summary>
public sealed class RenderNodeAvailability(TitanoDatabase db, ServerOptions options, TimeProvider time)
{
private static readonly TimeSpan SnapshotAge = TimeSpan.FromSeconds(1);
private Snapshot? _snapshot;
public async Task<bool> 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<RegisterNodeRequest>()]);
Volatile.Write(ref _snapshot, snapshot);
}
return snapshot.Nodes.Any(node => RenderNodeService.CanEncode(node, parameters));
}
/// <summary>What the online nodes announced, and when it was read (a <see cref="Stopwatch"/> timestamp).</summary>
private sealed record Snapshot(long Read, IReadOnlyList<RegisterNodeRequest> Nodes);
}
@@ -8,20 +8,23 @@ using Titano.Data.Processing;
using Titano.Protocol;
using Titano.Server.Configuration;
using Titano.Server.Events;
using Titano.Server.Jobs;
namespace Titano.Server.Storage;
/// <summary>
/// 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 just the jobs whose every output a managed encoder produces (AVI MJPEG, image sequences, GIF, APNG);
/// MP4 jobs stay queued for render nodes (BRIEF §14.7). Renders recorded and Auto values changed here reach connected
/// 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 (<see cref="RenderNodeAvailability"/>), 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 <c>sequenceChanged</c> events (§14.3).
/// </summary>
public static class ProcessingModule
{
public static void Register(IServiceCollection services)
{
services.AddSingleton<RenderNodeAvailability>();
services.AddSingleton(sp =>
{
var db = sp.GetRequiredService<TitanoDatabase>();
@@ -31,6 +34,7 @@ public static class ProcessingModule
Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner },
Encoders = [new ManagedEncoderProvider()],
Host = EncoderHost.Server,
AwaitsRenderNode = sp.GetRequiredService<RenderNodeAvailability>().AwaitsNodeAsync,
ProducedBy = sp.GetRequiredService<ServerOptions>().ServerName,
SequenceChanged = async (id, change, ct) =>
{