feat(processing): selective render claims, analysis follow-ups, per-sequence failures
- JobEngine: ISelectiveJobHandler lets a host decline jobs of a kind it runs; declined jobs stay queued for other claimers without holding up the rest. JobContext.EnqueueFollowUpAsync queues follow-up work on the same engine. - Server renders the jobs whose every output a managed encoder produces (ManagedRenderJobHandler); MP4 jobs stay for render nodes. Program.cs registers ProcessingModule next to ArchiveModule. Server renders ignore a client's export folder. - Light analysis is queued after imports and after scans that indexed new sequences, so the advisor's Auto values exist without user action. - Analysis jobs log a failing sequence and go on; the job then fails and a retry analyses only the failed ones. The advised frame rate follows the user's fit-to duration. - ProcessingJobs.RenderEach splits a batch into one job per preset for servers; render nodes say which batch presets they did not render, fetch each content once and stop on a changed certificate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
30 files changed
+572
-85
No files matched your search
@@ -0,0 +1,36 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Repositories;
|
||||
|
||||
namespace Titano.Data.Processing;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static class AnalysisFollowUp
|
||||
{
|
||||
/// <summary>Queues one light analysis of <paramref name="sequenceIds"/> (labelled like the job that found them).</summary>
|
||||
public static async Task QueueAsync(JobContext context, IReadOnlyCollection<Guid> sequenceIds)
|
||||
{
|
||||
if (sequenceIds.Count == 0) return;
|
||||
var request = ProcessingJobs.LightAnalysis([.. sequenceIds], context.Job.TargetLabel);
|
||||
await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Sequences of <paramref name="archiveId"/> that were never light-analysed (new or adopted ones).</summary>
|
||||
public static async Task<List<Guid>> UnanalysedAsync(TitanoDatabase db, Guid archiveId, CancellationToken cancellationToken)
|
||||
{
|
||||
var ids = new List<Guid>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.LightAnalyse"/> and <see cref="JobKind.DeepAnalyse"/> 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 <c>analysis.partial</c>.
|
||||
/// 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 (<c>next[;i,j…]</c>). A deep pass interrupted inside a
|
||||
/// sequence resumes from that sequence's <c>analysis.partial</c>.
|
||||
/// </summary>
|
||||
internal sealed class AnalyseJobHandler(TitanoDatabase db, SequenceAnalyser analyser, JobKind kind) : IJobHandler
|
||||
{
|
||||
@@ -19,29 +22,47 @@ 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<int>();
|
||||
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<AnalysisProgress>(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);
|
||||
context.Log(Loc.L("Advisor.Log.Failed", await TitleAsync(targets[i], context.Cancellation).ConfigureAwait(false), ex.Message));
|
||||
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);
|
||||
}
|
||||
if (failed.Count > 0) throw new InvalidOperationException(Loc.L("Errors.Analysis.Failed", failed.Count, targets.Count));
|
||||
}
|
||||
|
||||
private async Task<string> 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 +71,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()))));
|
||||
}
|
||||
|
||||
/// <summary>Next target and the failed targets to retry first; a missing or unreadable checkpoint starts over.</summary>
|
||||
internal static (int Next, IReadOnlyList<int> 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<int>();
|
||||
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<int> failed) =>
|
||||
failed.Count == 0
|
||||
? next.ToString(CultureInfo.InvariantCulture)
|
||||
: string.Create(CultureInfo.InvariantCulture, $"{next};{string.Join(',', failed.Order())}");
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Video;
|
||||
using Titano.Data.Jobs;
|
||||
|
||||
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.
|
||||
/// </summary>
|
||||
internal sealed class ManagedRenderJobHandler(RenderJobHandler render, IReadOnlyList<IVideoEncoderProvider> encoders) : ISelectiveJobHandler
|
||||
{
|
||||
private readonly EncoderCapability[] _capabilities = [.. encoders.SelectMany(e => e.Capabilities)];
|
||||
|
||||
public JobKind Kind => JobKind.Render;
|
||||
|
||||
public bool Accepts(Job job)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
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));
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public Task RunAsync(JobContext context) => render.RunAsync(context);
|
||||
|
||||
private bool Produces(ResolvedExport export) =>
|
||||
_capabilities.Any(c => c.Codec == export.Codec && export.Width <= c.MaxWidth && export.Height <= c.MaxHeight);
|
||||
}
|
||||
@@ -13,7 +13,7 @@ namespace Titano.Data.Processing.Jobs;
|
||||
/// <c>RenderJobParameters</c> 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
|
||||
/// <c>exports/</c> (or the export folder), named by the template, and each finished output is recorded at once.
|
||||
/// <c>exports/</c> (or the export folder, never on a server), 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.
|
||||
/// </summary>
|
||||
@@ -31,6 +31,8 @@ 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();
|
||||
|
||||
@@ -74,18 +76,12 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
|
||||
}
|
||||
|
||||
/// <summary>The job's preset, then every other preset of the batch with its own values.</summary>
|
||||
internal static List<ExportTarget> Targets(ExportSettings export, string presetName)
|
||||
{
|
||||
var main = ExportResolver.Resolve(export);
|
||||
var targets = new List<ExportTarget> { 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<string>().WithManual(id) });
|
||||
targets.Add(new ExportTarget(resolved, ProcessingJobs.PresetName(resolved)));
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
internal static List<ExportTarget> 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))),
|
||||
];
|
||||
|
||||
/// <summary>Archive-relative for outputs inside the archive (like the server's renders), absolute otherwise.</summary>
|
||||
private static string Stored(ArchivePaths paths, string output)
|
||||
|
||||
@@ -44,6 +44,32 @@ public static class ProcessingJobs
|
||||
JsonSerializer.Serialize(parameters, ProtocolJson.Default.RenderJobParameters), JobPriority.User);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One <see cref="Render"/> job per preset of <paramref name="export"/>: 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.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<ArchiveJobRequest> 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)),
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>The batch presets of an export besides its own, each once.</summary>
|
||||
internal static IEnumerable<string> BatchPresets(ExportSettings export)
|
||||
{
|
||||
var main = ExportResolver.Resolve(export).BasePresetId;
|
||||
return export.Batch.Distinct(StringComparer.OrdinalIgnoreCase).Where(id => !id.Equals(main, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>A batch preset rendered with its own values, named and placed like the export it belongs to.</summary>
|
||||
internal static ExportSettings BatchExport(ExportSettings export, string presetId) =>
|
||||
new() { Preset = new Auto<string>().WithManual(presetId), NameTemplate = export.NameTemplate, Folder = export.Folder };
|
||||
|
||||
/// <summary>Codec name in job parameters and render-node capabilities ("h264", "hevc", "mjpeg", "pngsequence"…).</summary>
|
||||
public static string CodecName(VideoCodec codec) => codec.ToString().ToLowerInvariant();
|
||||
|
||||
@@ -57,11 +83,20 @@ public static class ProcessingJobs
|
||||
/// <summary>The parameters of a render job and the export they select.</summary>
|
||||
/// <exception cref="InvalidDataException">The job has no valid render parameters.</exception>
|
||||
internal static (RenderJobParameters Parameters, ExportSettings Export) ReadRender(string? parametersJson)
|
||||
{
|
||||
var parameters = ReadParameters(parametersJson);
|
||||
return (parameters, ReadExport(parameters.PresetJson));
|
||||
}
|
||||
|
||||
/// <summary>The protocol record of a render job, without reading its export.</summary>
|
||||
/// <exception cref="InvalidDataException">The job has no valid render parameters.</exception>
|
||||
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)
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
/// <summary>
|
||||
/// 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 server engine leaves render jobs to render
|
||||
/// nodes. Create jobs with <see cref="ProcessingJobs"/>.
|
||||
/// 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"/>.
|
||||
/// </summary>
|
||||
public sealed class ProcessingService : IJobHandlerProvider
|
||||
{
|
||||
@@ -28,10 +30,14 @@ public sealed class ProcessingService : IJobHandlerProvider
|
||||
public ProcessingOptions Options { get; }
|
||||
|
||||
/// <summary>Handlers for <see cref="JobKind.LightAnalyse"/>, <see cref="JobKind.DeepAnalyse"/> and <see cref="JobKind.Render"/>.</summary>
|
||||
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
|
||||
[
|
||||
new AnalyseJobHandler(_db, _analyser, JobKind.LightAnalyse),
|
||||
new AnalyseJobHandler(_db, _analyser, JobKind.DeepAnalyse),
|
||||
new RenderJobHandler(_db, Options),
|
||||
];
|
||||
public IReadOnlyList<IJobHandler> 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.Encoders) : render,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Render;
|
||||
using Titano.Core.Video;
|
||||
using Titano.Data.Processing.Jobs;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
@@ -148,9 +149,9 @@ 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;
|
||||
}
|
||||
@@ -193,8 +194,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);
|
||||
}
|
||||
}
|
||||
@@ -211,6 +213,9 @@ public sealed class RenderNodeClient : IAsyncDisposable
|
||||
var target = new ExportTarget(resolved, ProcessingJobs.PresetName(resolved));
|
||||
if (target.Export.Container == ContainerFormat.ImageSequence) throw new InvalidOperationException(Loc.L("Errors.Render.NodeSequence"));
|
||||
var project = ProjectStore.Parse(claimed.SettingsJson) with { Export = export };
|
||||
// One output per job: batch presets were meant for separate jobs (ProcessingJobs.RenderEach).
|
||||
if (RenderJobHandler.Targets(export, target.PresetName).Skip(1).Select(t => t.PresetName).ToList() is { Count: > 0 } skipped)
|
||||
await reporter.ReportAsync(0, claimed.Frames.Count, Loc.L("Export.Log.NodeBatch", string.Join(", ", skipped))).ConfigureAwait(false);
|
||||
|
||||
var sequence = ToSequence(await _client.GetSequenceAsync(claimed.SequenceId, cancellationToken).ConfigureAwait(false));
|
||||
var frames = await ListFramesAsync(claimed.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
@@ -257,21 +262,28 @@ public sealed class RenderNodeClient : IAsyncDisposable
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private async Task<Dictionary<Guid, string>> DownloadAsync(ClaimedJob claimed, string work, NodeReporter reporter, CancellationToken cancellationToken)
|
||||
{
|
||||
var files = new Dictionary<Guid, string>();
|
||||
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;
|
||||
}
|
||||
@@ -309,8 +321,12 @@ 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))
|
||||
// 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 using var file = new FileStream(part, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
|
||||
await _client.DownloadFrameAsync(frame.Id, "original", file, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
if (await TitanoClient.HashFileAsync(part, cancellationToken).ConfigureAwait(false) == sha)
|
||||
{
|
||||
File.Move(part, path, overwrite: true);
|
||||
@@ -406,7 +422,7 @@ public sealed class RenderNodeClient : IAsyncDisposable
|
||||
|
||||
/// <summary>
|
||||
/// 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: <see cref="Lost"/> is set and the job's token cancelled.
|
||||
/// job was cancelled or given to another node: the job's token is cancelled.
|
||||
/// </summary>
|
||||
private sealed class NodeReporter(TitanoClient client, Guid nodeId, Guid jobId, TimeSpan interval, CancellationTokenSource job)
|
||||
{
|
||||
@@ -418,8 +434,6 @@ public sealed class RenderNodeClient : IAsyncDisposable
|
||||
|
||||
public Guid NodeId => nodeId;
|
||||
|
||||
public bool Lost { get; private set; }
|
||||
|
||||
public async ValueTask ReportAsync(long done, long total, string? message)
|
||||
{
|
||||
await _gate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
@@ -435,7 +449,6 @@ public sealed class RenderNodeClient : IAsyncDisposable
|
||||
}
|
||||
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)
|
||||
|
||||
@@ -44,13 +44,15 @@ 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);
|
||||
var warnings = Advisor.Recommend(light, report, context).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)
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user