using Chronos.Core.Analysis;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
namespace Chronos.Data.Processing;
/// One output of a render job: the resolved export values and the preset name recorded with the render.
internal sealed record ExportTarget(ResolvedExport Export, string PresetName);
/// How one target of ended: a result, or the localised reason it failed.
internal sealed record TargetOutcome(ExportTarget Target, RenderResult? Result, string? Error);
///
/// The render of one sequence (BRIEF §11): the frame source, the clock-corrected capture metadata, the project with the
/// 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. 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 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.
/// The frames' files are the archive's originals (no proxies), so describes them.
/// The JPEG of each GPR frame kept in another sequence, by frame id ().
public SequenceRender(SequenceFrames frames, ProjectSettings project, DeepAnalysisReport? analysis, ProcessingOptions options, bool originals = false,
IReadOnlyDictionary? companions = null)
{
// The host's tuning as it is now (memory budget, quality profile): a change applies from the next render.
options = options.Current;
var metadata = frames.LightFrames();
var planned = project with { ExcludedFrames = [.. project.ExcludedFrames.Union(frames.NotRenderable()).Order()] };
// A frame that turns out not to decode is shown as its nearest planned neighbour instead of failing the render.
_source = new SequenceFrameSource(frames, metadata, options.Archive.Decoder, options.FrameWindow)
{
Originals = originals,
RenderExcluded = planned.ExcludedFrames.ToHashSet(),
Companions = companions,
};
_processing = options;
_options = options.Render;
Input = new RenderInput
{
Source = _source,
Frames = SourceFrameInfo.From(frames.Frames, LightAnalyzer.Analyze(metadata).AdjustedTimes),
Project = planned,
Analysis = analysis?.FrameCount == frames.Count ? new PrecomputedAnalysis { LogLuminance = Luminance(analysis.Frames) } : null,
};
}
public RenderInput Input { get; }
/// Positions that did not decode during the render; a neighbour stood in for each (ascending).
public IReadOnlyList StandIns => _source.StandIns;
/// The decode tier each frame was read at so far (unavailable when it did not decode); originals only.
public IReadOnlyDictionary Decoded => _source.Observed;
/// Encoder, geometry and plan of an export before its output is named.
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
/// from its setup; runs before a target writes anything (checkpoints),
/// after its output is complete (record it, upload it). Progress counts measured and
/// rendered frames over the whole call.
///
public async Task> RenderAllAsync(
IReadOnlyList<(int Index, ExportTarget Target)> targets,
Func name,
Func starting,
Func finished,
Func progress,
CancellationToken cancellationToken)
{
var outcomes = new List(targets.Count);
var ready = new List<(int Index, ExportTarget Target, RenderSetup Setup)>();
foreach (var (index, target) in targets)
{
RenderSetup setup;
try
{
setup = Setup(target.Export);
}
catch (RenderException ex)
{
// The source size could not be measured (no renderable frame decodes).
outcomes.Add(new TargetOutcome(target, null, Reason(ex)));
continue;
}
if (setup.Encoder.IsReady && setup.Program.Count > 0) ready.Add((index, target, setup));
else outcomes.Add(new TargetOutcome(target, null, Reason(setup)));
}
if (ready.Count == 0) return outcomes;
var preparing = ready[0].Setup.NeedsPreparation ? ready[0].Setup.Plan.IncludedFrames.Count : 0;
// Rendered pictures are counted in the output program's entries (loops, a boomerang and fades add to the plan's).
var total = preparing + ready.Sum(r => (long)r.Setup.Program.Count);
var stage = Loc.L("Export.Job.Preparing");
var chain = new ProgressChain(progress);
var corrections = await RenderPreparation.PrepareAsync(Input, _options, Stage(chain, 0, preparing, total, stage), cancellationToken).ConfigureAwait(false);
await chain.FlushAsync().ConfigureAwait(false);
long done = preparing;
foreach (var (index, target, setup) in ready)
{
cancellationToken.ThrowIfCancellationRequested();
var output = name(target, setup);
await starting(index, output).ConfigureAwait(false);
try
{
var result = await Pipeline(target.Export).RenderAsync(Input, corrections, new RenderTarget(target.Export, output), _options,
Stage(chain, done, setup.Program.Count, total, target.PresetName), cancellationToken).ConfigureAwait(false);
await chain.FlushAsync().ConfigureAwait(false);
await finished(index, target, result).ConfigureAwait(false);
outcomes.Add(new TargetOutcome(target, result, null));
}
catch (Exception ex) when (!(ex is OperationCanceledException && cancellationToken.IsCancellationRequested))
{
Core.Diagnostics.Log.Warning("processing", $"Render of {target.PresetName} to {output} failed", ex);
outcomes.Add(new TargetOutcome(target, null, Reason(ex)));
}
done += setup.Program.Count;
}
return outcomes;
}
///
/// Saves frame as one image ("Save frame", owner review 1, R8): the sequence prepared whole
/// as for a video (so its exposure, colour and stabilisation corrections are the ones the video gives that frame), then
/// that frame rendered by the pipeline's still path () at the export's output size
/// with every correction and the look, without stacking, interpolation, motion blur or playback, through the image
/// encoder of 's codec (PNG, JPEG or TIFF 16-bit). The encoder writes a temporary name and
/// renames it once complete, so a cancelled or failed still leaves nothing behind.
///
/// The output path of the still from its setup.
/// Runs with that path before anything is written (checkpoints).
/// The frame is not one of the sequence's, or no encoder writes the codec.
public async Task RenderStillAsync(ExportTarget target, int frameIndex, Func name, Func starting,
Func progress, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(target);
ArgumentNullException.ThrowIfNull(name);
var pipeline = Pipeline(target.Export);
var setup = pipeline.Setup(Input, new RenderTarget(target.Export, ExportNaming.FallbackName, frameIndex), _options);
if (!setup.Encoder.IsReady)
{
var notice = setup.Encoder.Notices.LastOrDefault() ?? new EncoderNotice(EncoderNotices.NoEncoder, setup.Encoder.Settings.Codec.ToString());
throw new RenderException(notice.Key, $"No encoder can save {target.Export.Codec} here ({setup.Encoder.Status})", notice.Args);
}
var output = name(setup);
await starting(output).ConfigureAwait(false);
var chain = new ProgressChain(progress);
var preparing = setup.NeedsPreparation ? setup.Plan.IncludedFrames.Count : 0;
var total = preparing + 1L;
// The corrections of the whole sequence, indexed by source frame: the frame gets what the video gives it.
var corrections = await RenderPreparation.PrepareAsync(Input, _options, Stage(chain, 0, preparing, total, Loc.L("Export.Job.Preparing")), cancellationToken)
.ConfigureAwait(false);
await chain.FlushAsync().ConfigureAwait(false);
var result = await pipeline.RenderAsync(Input, corrections, new RenderTarget(target.Export, output, frameIndex), _options,
Stage(chain, preparing, 1, total, target.PresetName), cancellationToken).ConfigureAwait(false);
await chain.FlushAsync().ConfigureAwait(false);
return result;
}
///
/// The path of a still of frame (0-based) in (or the export's own
/// folder): ,
/// "2026-09-28 Harbour sunset - PNG - 0124.png"; " (2)" and so on when taken.
///
public static string StillPath(ExportSettings export, string folder, ExportNameContext context, int frameIndex, Func? taken = null) =>
ExportNaming.StillPath(export, folder, context, frameIndex, taken);
///
/// The frame a still job saves (, ):
/// the frame holding the photo when its SHA-256 is given (the frames may have moved since), null when that photo is no
/// longer in the sequence (the index would name another photo now); without a hash (a photo not hashed yet) the index.
/// Null when neither names a frame of the sequence.
///
public static int? StillIndex(SequenceFrames frames, int? frameIndex, string? photoSha256)
{
ArgumentNullException.ThrowIfNull(frames);
if (photoSha256 is { Length: > 0 } sha)
{
for (var i = 0; i < frames.Frames.Count; i++)
{
if (string.Equals(frames.Frames[i].Sha256, sha, StringComparison.OrdinalIgnoreCase)) return i;
}
return null;
}
return frameIndex is { } index && (uint)index < (uint)frames.Frames.Count ? index : null;
}
/// Values of the output name tokens: the shoot date and title of the sequence, the codec and size the encoder will use.
public static ExportNameContext NameContext(Sequence sequence, ExportTarget target, RenderSetup setup) => new()
{
Date = sequence.FirstCapture ?? DateTime.Now,
Title = sequence.DisplayTitle,
PresetName = target.PresetName,
Width = setup.Encoder.Settings.Width,
Height = setup.Encoder.Settings.Height,
FrameRate = setup.Encoder.Settings.FrameRate,
Codec = setup.Encoder.Settings.Codec,
};
/// Localised text of a render failure.
public static string Reason(Exception exception) =>
exception is RenderException render ? Loc.L(render.ReasonKey, [.. render.Args]) : exception.Message;
/// Localised remarks of a finished render (encoder fallbacks, ignored settings…), without repeats.
public static IEnumerable Remarks(RenderResult result) => result.Warnings.Select(w => Loc.L(w.Key, [.. w.Args])).Distinct();
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.Program.Count == 0) return Loc.L("Export.Render.NoFrames");
var notice = setup.Encoder.Notices.LastOrDefault() ?? new EncoderNotice(EncoderNotices.NoEncoder, setup.Encoder.Settings.Codec.ToString());
return Loc.L(notice.Key, [.. notice.Args]);
}
private static double[] Luminance(DeepFrameColumns columns) => [.. columns.LogLuminance.Select(v => v ?? double.NaN)];
/// One stage's progress (frames measured, or rendered for one target) as frames of the whole call.
private static IProgress Stage(ProgressChain chain, long offset, long length, long total, string message) =>
chain.For(p => (offset + long.Min(length, p.Done), total, message));
}