Files
Chronos/src/Chronos.Data/Processing/ProcessingJobs.cs
T
Alby96andClaude Opus 5.5 728ffa35cb
CI / Build and test (push) Successful in 9m41s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 9s
Release / Build, test and publish (push) Successful in 14m49s
CI / PostgreSQL 16 integration (push) Successful in 8m51s
CI / PostgreSQL 17 integration (push) Successful in 9m48s
CI / Docker image (push) Successful in 54s
Release / Server image (push) Successful in 1m39s
feat: export panel and Render menu, playback options, videos library (owner review 1 phase 5) (#27)
Owner review 1 R3, R8, R9. A grouped Export step and Render menu; encoding, playback (reverse, boomerang, loops, fades, hold) and still frames; one videos library on the desktop and the server with a verified trash and copies to a videos folder.

Closes #21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-11-05 09:18:40 +01:00

340 lines
20 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using Chronos.Core.Export;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Video;
using Chronos.Data.Archiving.Jobs;
using Chronos.Protocol;
namespace Chronos.Data.Processing;
/// <summary>
/// Builds the analysis and render jobs; enqueue them with <see cref="Archiving.ArchiveJobs.EnqueueAsync"/> (local
/// engine) or post the same kind, targets and parameters to <c>/api/v1/jobs</c> (server).
/// </summary>
public static class ProcessingJobs
{
/// <summary><see cref="JobKind.LightAnalyse"/>: targets = sequences; no parameters.</summary>
public static ArchiveJobRequest LightAnalysis(IReadOnlyList<Guid> sequenceIds, string? label = null) =>
new(JobKind.LightAnalyse, sequenceIds, label, null, JobPriority.Background);
/// <summary><see cref="JobKind.DeepAnalyse"/>: targets = sequences; no parameters.</summary>
public static ArchiveJobRequest DeepAnalysis(IReadOnlyList<Guid> sequenceIds, string? label = null) =>
new(JobKind.DeepAnalyse, sequenceIds, label, null, JobPriority.User);
/// <summary>
/// <see cref="JobKind.Render"/> of one sequence. <paramref name="export"/> (preset, overrides, name template,
/// folder, batch) replaces the project's export section; <paramref name="project"/> embeds the settings to render,
/// null renders the sequence's current project. <paramref name="sourceWidth"/>×<paramref name="sourceHeight"/> (the
/// frames' Exif-oriented size) gives the output size of the settings rendered (<see cref="RenderSize"/>; the sequence's
/// own when <paramref name="project"/> is null), so render nodes can match the job by resolution, and the settings
/// format the render needs (<see cref="RenderRules.RequiredFormat"/>).
/// </summary>
public static ArchiveJobRequest Render(Sequence sequence, ExportSettings export, int sourceWidth, int sourceHeight, ProjectSettings? project = null,
bool useProxies = false)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentNullException.ThrowIfNull(export);
var parameters = Parameters(export, sourceWidth, sourceHeight, project?.ToJson(), useProxies, project ?? ReadSettings(sequence.SettingsJson));
return new ArchiveJobRequest(JobKind.Render, [sequence.Id], RenderLabel(sequence.DisplayTitle, parameters.PresetName),
JsonSerializer.Serialize(parameters, ProtocolJson.Default.RenderJobParameters), JobPriority.User);
}
/// <summary>
/// <see cref="JobKind.Render"/> of one frame saved as an image (owner review 1, R8, "Save frame"): frame
/// <paramref name="frameIndex"/> of the sequence (its photo <paramref name="photoSha256"/> wins when both are given and the
/// frames moved since) with <paramref name="codec"/>, one of <see cref="RenderRules.StillCodecs"/>, at the output size of
/// <paramref name="export"/>, with every correction and no playback. <paramref name="project"/> embeds the settings to
/// render, as <see cref="Render"/>. The job needs settings format <see cref="RenderRules.StillFormat"/>, so an older node,
/// which would render the whole video, never claims it.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="codec"/> is not a still codec, or <paramref name="frameIndex"/> is negative.</exception>
public static ArchiveJobRequest Still(Sequence sequence, ExportSettings export, VideoCodec codec, int frameIndex, string? photoSha256, int sourceWidth,
int sourceHeight, ProjectSettings? project = null)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentNullException.ThrowIfNull(export);
if (!RenderRules.StillCodecs.Contains(codec)) throw new ArgumentOutOfRangeException(nameof(codec), codec, "Not a still codec.");
ArgumentOutOfRangeException.ThrowIfNegative(frameIndex);
var still = export with { Batch = [], Playback = null, Overrides = export.Overrides with { Codec = CodecName(codec), Container = null } };
var parameters = Parameters(still, sourceWidth, sourceHeight, project?.ToJson(), false, project ?? ReadSettings(sequence.SettingsJson));
parameters = parameters with
{
StillFrame = frameIndex,
StillPhoto = string.IsNullOrEmpty(photoSha256) ? null : photoSha256.ToLowerInvariant(),
RequiredSettingsFormat = int.Max(parameters.RequiredSettingsFormat, RenderRules.StillFormat),
};
return new ArchiveJobRequest(JobKind.Render, [sequence.Id], RenderLabel(sequence.DisplayTitle, parameters.PresetName),
JsonSerializer.Serialize(parameters, ProtocolJson.Default.RenderJobParameters), JobPriority.User);
}
/// <summary>
/// <see cref="JobKind.Render"/> of a project version (owner review 2, R8) on the sequence's home: the version's portable
/// settings, placed on the sequence's frames by the render, with <paramref name="export"/> as their export section; the
/// render records the project and the version. One job per preset, as <see cref="RenderEach"/>.
/// </summary>
public static IReadOnlyList<ArchiveJobRequest> RenderVersion(Sequence sequence, ProjectVersion version, ExportSettings export, int sourceWidth, int sourceHeight,
bool useProxies = false)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentNullException.ThrowIfNull(version);
ArgumentNullException.ThrowIfNull(export);
return
[
VersionJob(sequence, version, export with { Batch = [] }, sourceWidth, sourceHeight, useProxies),
.. BatchPresets(export).Select(id => VersionJob(sequence, version, BatchExport(export, id), sourceWidth, sourceHeight, useProxies)),
];
}
private static ArchiveJobRequest VersionJob(Sequence sequence, ProjectVersion version, ExportSettings export, int sourceWidth, int sourceHeight, bool useProxies)
{
var parameters = Parameters(export, sourceWidth, sourceHeight, version.SettingsJson, useProxies) with
{
ProjectId = version.ProjectId,
ProjectVersionId = version.Id,
};
return new ArchiveJobRequest(JobKind.Render, [sequence.Id], RenderLabel(sequence.DisplayTitle, parameters.PresetName),
JsonSerializer.Serialize(parameters, ProtocolJson.Default.RenderJobParameters), JobPriority.User);
}
/// <summary>
/// The label of a render job, "Harbour sunset → 4K HEVC". It is stored as written, in the language of the moment like
/// the preset name: its arrow points from the sequence to the preset in that language's reading direction.
/// </summary>
public static string RenderLabel(string title, string presetName) =>
Loc.L(Loc.IsRightToLeft ? "Jobs.Target.RenderRtl" : "Jobs.Target.Render", title, presetName);
/// <summary>
/// A posted render job as one job per preset, as <see cref="RenderEach"/> 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. <paramref name="sourceWidth"/>×<paramref name="sourceHeight"/> (the
/// frames' Exif-oriented size) stands in for a batch preset without a fixed size. With the <paramref name="settings"/>
/// the job renders, every job gets the output size and the settings format its render needs (<see cref="Routed"/>);
/// without them, the job keeps the size it was posted with and each batch preset its preset's.
/// </summary>
/// <exception cref="InvalidDataException">The preset JSON is not an export section.</exception>
public static IReadOnlyList<RenderJobParameters> Split(RenderJobParameters parameters, int sourceWidth, int sourceHeight, ProjectSettings? settings = null)
{
ArgumentNullException.ThrowIfNull(parameters);
var export = ReadExport(parameters.PresetJson);
var batch = BatchPresets(export).ToList();
var own = batch.Count == 0 ? parameters : parameters with { PresetJson = JsonSerializer.Serialize(export with { Batch = [] }, ProcessingJson.Default.ExportSettings) };
return
[
settings is null ? own : Routed(own, settings, sourceWidth, sourceHeight),
.. batch.Select(id => Parameters(BatchExport(export, id), sourceWidth, sourceHeight, parameters.SettingsJson, parameters.UseProxies, settings) with
{
ProjectId = parameters.ProjectId,
ProjectVersionId = parameters.ProjectVersionId,
}),
];
}
/// <summary>
/// A render job's parameters with the output size and the settings format a render of <paramref name="settings"/> needs
/// (owner review 1, phase 4: the chosen proportions win over a fixed-size preset, a quarter turn swaps a source-sized
/// output). The size comes from the job's preset, as the render does: never from the size the job was posted with,
/// which a newer client already adapted to the settings of the moment (a long edge kept for 1:1 cannot be adapted back
/// to 16:9 once the sequence's settings change). Other presets are sized on the source. The format is at least the one
/// the job was posted with.
/// </summary>
/// <exception cref="InvalidDataException">The preset JSON is not an export section.</exception>
public static RenderJobParameters Routed(RenderJobParameters parameters, ProjectSettings settings, int sourceWidth, int sourceHeight)
{
ArgumentNullException.ThrowIfNull(parameters);
ArgumentNullException.ThrowIfNull(settings);
var resolved = ExportResolver.Resolve(ReadExport(parameters.PresetJson));
var (width, height) = Size(settings, resolved, sourceWidth, sourceHeight) ?? (parameters.Width, parameters.Height);
return parameters with
{
Width = width,
Height = height,
// The job's own export (playback included) is what renders, not the export the settings carry; but a node parses
// the settings text as it is, so never less than the format that text is written in.
RequiredSettingsFormat = int.Max(parameters.RequiredSettingsFormat, int.Max(TextFormat(settings),
RequiredFormat(settings with { Export = ReadExport(parameters.PresetJson) }, resolved, sourceWidth, sourceHeight))),
};
}
/// <summary>
/// The format of the settings text a node parses: the version it was read with, or the one <see cref="ProjectSettings.ToJson"/>
/// writes for it. A node that reads less refuses that text, whatever export the job renders.
/// </summary>
private static int TextFormat(ProjectSettings settings) => int.Max(settings.Version, settings.WrittenFormat);
/// <summary>
/// The settings format a render of <paramref name="settings"/> with <paramref name="export"/> and each of its batch
/// presets needs (the highest <see cref="RenderRules.RequiredFormat"/> of them): what a server or a render node must read
/// to render it as this Chronos would.
/// </summary>
public static int RequiredFormat(ProjectSettings settings, ExportSettings export, int sourceWidth, int sourceHeight)
{
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(export);
return BatchPresets(export).Select(id => BatchExport(export, id)).Prepend(export)
.Max(each => RequiredFormat(settings with { Export = each }, ExportResolver.Resolve(each), sourceWidth, sourceHeight));
}
/// <summary>
/// Project settings read for their output size and format, a newer Chronos's too (its format stands); null when there
/// are none or the text is not a project.
/// </summary>
public static ProjectSettings? ReadSettings(string? settingsJson)
{
if (string.IsNullOrWhiteSpace(settingsJson)) return null;
try
{
return ProjectSettings.FromJson(settingsJson, allowNewer: true);
}
catch (JsonException)
{
return null;
}
}
/// <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 (blank entries of a hand-written batch are skipped).</summary>
internal static IEnumerable<string> 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));
}
/// <summary>
/// A batch preset rendered with its own values, named, placed and played like the export it belongs to: its playback
/// (owner review 1, R8: direction, loops, fades, hold) lives in the export, so every batch preset inherits it.
/// </summary>
internal static ExportSettings BatchExport(ExportSettings export, string presetId) =>
new() { Preset = new Auto<string>().WithManual(presetId), NameTemplate = export.NameTemplate, Folder = export.Folder, Playback = export.Playback };
/// <param name="settings">The settings rendered, for the output size and the format (else read from <paramref name="settingsJson"/>); unknown, the preset's size.</param>
private static RenderJobParameters Parameters(ExportSettings export, int sourceWidth, int sourceHeight, string? settingsJson, bool useProxies,
ProjectSettings? settings = null)
{
var resolved = ExportResolver.Resolve(export);
settings ??= ReadSettings(settingsJson);
var (width, height) = (settings is null ? null : Size(settings, resolved, sourceWidth, sourceHeight))
?? (resolved.Width > 0 ? resolved.Width : sourceWidth, resolved.Height > 0 ? resolved.Height : sourceHeight);
// The format of what renders: the settings with this export in place of their own (its playback raises it to 3), and
// never less than the format of the settings text the node parses.
var format = settings is null
? new ProjectSettings { Export = export }.RequiredFormat
: int.Max(TextFormat(settings), RequiredFormat(settings with { Export = export }, resolved, sourceWidth, sourceHeight));
return new RenderJobParameters(PresetName(resolved), JsonSerializer.Serialize(export, ProcessingJson.Default.ExportSettings), CodecName(resolved.Codec),
width, height, useProxies, settingsJson, RequiredSettingsFormat: format);
}
/// <summary>The output size of <paramref name="settings"/> with <paramref name="export"/> (<see cref="RenderSize.Of"/>); null without a source size.</summary>
private static (int Width, int Height)? Size(ProjectSettings settings, ResolvedExport export, int sourceWidth, int sourceHeight) =>
sourceWidth > 0 && sourceHeight > 0 ? RenderSize.Of(settings.Camera, export, sourceWidth, sourceHeight) : null;
/// <summary><see cref="RenderRules.RequiredFormat"/>; without a source size, the format the settings are written in.</summary>
private static int RequiredFormat(ProjectSettings settings, ResolvedExport export, int sourceWidth, int sourceHeight) =>
sourceWidth > 0 && sourceHeight > 0 ? RenderRules.RequiredFormat(settings, export, sourceWidth, sourceHeight) : settings.WrittenFormat;
/// <summary>Codec name in job parameters and render-node capabilities ("h264", "hevc", "mjpeg", "pngsequence"…).</summary>
public static string CodecName(VideoCodec codec) => codec.ToString().ToLowerInvariant();
/// <summary>Display name of an export's preset in the current language ("Custom" when the values match none).</summary>
public static string PresetName(ResolvedExport export)
{
ArgumentNullException.ThrowIfNull(export);
return Loc.L(export.NameKey ?? "Export.Preset.Custom");
}
/// <summary>The parameters of a render job and the export they select.</summary>
/// <exception cref="InvalidDataException">The job has no valid render parameters.</exception>
public 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 { PresetName.Length: > 0, PresetJson.Length: > 0, Codec.Length: > 0 } parameters)
return parameters;
}
catch (JsonException ex)
{
throw new InvalidDataException(Loc.L("Errors.Render.Parameters"), ex);
}
throw new InvalidDataException(Loc.L("Errors.Render.Parameters"));
}
/// <summary>The export section in a render job's preset JSON; values it leaves out take their defaults.</summary>
/// <exception cref="InvalidDataException">The JSON is not an export section.</exception>
internal static ExportSettings ReadExport(string? presetJson)
{
try
{
// Read as the export section of a project, so missing values keep their defaults (ProjectSettings.FromJson).
var project = new JsonObject { ["export"] = JsonNode.Parse(presetJson ?? string.Empty) };
return ProjectSettings.FromJson(project.ToJsonString()).Export;
}
catch (JsonException ex)
{
throw new InvalidDataException(Loc.L("Errors.Render.Parameters"), ex);
}
}
}
/// <summary>
/// Resume point of a render job: the batch targets already recorded, and the output a crashed attempt was writing
/// (its leftovers are removed before that target renders again) with the sequence's archive-relative folder when it
/// chose that output (null in checkpoints written before it was kept), so the leftovers are found after a Reorganize.
/// </summary>
internal sealed record RenderCheckpoint(IReadOnlyList<int> Done, int? Pending, string? PendingOutput, string? Folder = null)
{
public static RenderCheckpoint Empty { get; } = new([], null, null);
public static RenderCheckpoint Parse(string? json)
{
if (string.IsNullOrEmpty(json)) return Empty;
try
{
return JsonSerializer.Deserialize(json, ProcessingJson.Default.RenderCheckpoint) ?? Empty;
}
catch (JsonException)
{
return Empty;
}
}
public string ToJson() => JsonSerializer.Serialize(this, ProcessingJson.Default.RenderCheckpoint);
}
/// <summary>JSON written into render jobs: presets (the export section of <c>project.json</c>) and checkpoints.</summary>
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true,
PropertyNameCaseInsensitive = true)]
[JsonSerializable(typeof(ExportSettings))]
[JsonSerializable(typeof(RenderCheckpoint))]
internal sealed partial class ProcessingJson : JsonSerializerContext;