feat: export panel and Render menu, playback options, videos library (owner review 1 phase 5) (#27)
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

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>
This commit was merged in pull request #27.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-05 09:18:40 +01:00
1 parent 188b2c2e55
commit 728ffa35cb
729 files changed
+26954 -1652

No files matched your search

+25
View File
@@ -1,4 +1,6 @@
using System.Globalization;
using System.Numerics;
using System.Runtime.InteropServices;
using Chronos.Core.Analysis;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Color;
@@ -58,4 +60,27 @@ public static class FrameFinish
if (look is { IsIdentity: false } && LookFilter.IsKnown(look.Filter)) LookFilter.Apply(frame, look.Filter, Strength(look));
if (knee is > 0 and < 1 and var k) ExposureProcessor.Apply(frame, 0, null, k);
}
/// <summary>
/// The fade to and from black of the output program (owner review 1, R8; <see cref="ProgramEntry.Gain"/>): every sample
/// of the finished linear-light <paramref name="frame"/> multiplied by <paramref name="gain"/>, in place. It runs after
/// <see cref="Apply"/>, so neither the look nor the knee sees a darkened frame. A gain of 1 or more (or not finite)
/// leaves the frame as it is; 0 or less makes it black.
/// </summary>
public static void Fade(ImageBuffer frame, double gain)
{
ArgumentNullException.ThrowIfNull(frame);
if (!double.IsFinite(gain) || gain >= 1) return;
var data = frame.Data;
if (gain <= 0)
{
data.Clear();
return;
}
var factor = (float)gain;
var vectors = MemoryMarshal.Cast<float, Vector<float>>(data);
var scale = new Vector<float>(factor);
for (var i = 0; i < vectors.Length; i++) vectors[i] *= scale;
for (var i = vectors.Length * Vector<float>.Count; i < data.Length; i++) data[i] *= factor;
}
}
+172
View File
@@ -0,0 +1,172 @@
using Chronos.Core.Imaging;
using Chronos.Core.Project;
using Chronos.Core.Video;
namespace Chronos.Core.Render;
/// <summary>One frame the encoder receives, in emission order (<see cref="OutputProgram"/>).</summary>
/// <param name="PlanIndex">The frame of <see cref="RenderPlan.Frames"/> rendered for it.</param>
/// <param name="Duration90k">How long it shows, on the 90 kHz clock: the planned frame's duration, a share of it (a held
/// frame split per slot inside a fade), or longer (the hold at the end).</param>
/// <param name="Gain">The linear-light multiplier of the fade to and from black, applied after the look and the knee
/// (<c>FrameFinish</c>): 1 leaves the frame as it is, 0 is black. Already in linear light (the sRGB ramp converted), so a
/// fade looks even.</param>
/// <param name="Pass">The pass of the playback it belongs to (0 for the first; each loop is one more): a star-trail stack
/// starts again at each pass, so every loop plays the trails growing.</param>
public readonly record struct ProgramEntry(int PlanIndex, long Duration90k, double Gain, int Pass = 0);
/// <summary>
/// The output program of a render (owner review 1, R8): the plan's frames in the order and for the time they are emitted,
/// with the fade gain of each, from the export's <see cref="PlaybackSettings"/>. Reverse is the plan backwards; a boomerang
/// is forward then backward without repeating the turning frame; loops repeat the pass (a boomerang's later passes start at
/// its second frame, so the joint is not doubled); the hold extends the last emitted frame; fades longer than half of the
/// program are scaled to fit (warning <see cref="FadesShortenedWarning"/>). Every pass is rendered again, so the render
/// time grows with <see cref="Count"/>.
/// </summary>
/// <remarks>
/// Durations stay on the plan's 90 kHz values: a pass sums to the plan's duration and the hold is a whole number of output
/// periods, so constant-rate outputs keep their grid. The fade gain of an entry is taken at its start inside the fade in and
/// at its end inside the fade out, so the first and the last emitted frames are black.
/// </remarks>
public sealed class OutputProgram
{
/// <summary>Warning key: the fades were longer than half of the program and were scaled to fit.</summary>
public const string FadesShortenedWarning = "Export.Render.FadesShortened";
/// <summary>Warning key: the playback names a direction this Chronos does not know ({0}); the video plays forward.</summary>
public const string DirectionUnknownWarning = "Export.Render.DirectionUnknown";
/// <summary>Warning key: a boomerang is not rendered with star trails; the video plays forward.</summary>
public const string BoomerangStackWarning = "Export.Render.BoomerangStack";
private OutputProgram(IReadOnlyList<ProgramEntry> entries, IReadOnlyList<RenderWarning> warnings)
{
Entries = entries;
Warnings = warnings;
long total = 0;
foreach (var entry in entries) total += entry.Duration90k;
Duration90k = total;
}
/// <summary>The emitted frames, in order.</summary>
public IReadOnlyList<ProgramEntry> Entries { get; }
/// <summary>Frames the encoder receives (and the render renders).</summary>
public int Count => Entries.Count;
/// <summary>Exact total duration on the 90 kHz clock, holds included.</summary>
public long Duration90k { get; }
/// <summary>The duration in seconds.</summary>
public double DurationSeconds => Duration90k / 90000.0;
/// <summary>What the program changed of the playback asked for (fades shortened, an unknown direction played forward).</summary>
public IReadOnlyList<RenderWarning> Warnings { get; }
/// <summary>The program of <paramref name="plan"/>'s frames played as <paramref name="playback"/> says (null: forward once).</summary>
public static OutputProgram Build(RenderPlan plan, PlaybackSettings? playback, Rational frameRate)
{
ArgumentNullException.ThrowIfNull(plan);
return Build(plan.Frames, playback, frameRate);
}
/// <summary>The program of the planned <paramref name="frames"/> played as <paramref name="playback"/> says (null: forward once).</summary>
/// <param name="frameRate">The output frame rate: the grid a held frame is split on inside a fade.</param>
public static OutputProgram Build(IReadOnlyList<PlannedFrame> frames, PlaybackSettings? playback, Rational frameRate)
{
ArgumentNullException.ThrowIfNull(frames);
if (frameRate.Numerator <= 0 || frameRate.Denominator <= 0) throw new ArgumentOutOfRangeException(nameof(frameRate));
var warnings = new List<RenderWarning>();
if (playback?.Direction is { } unknown && !PlaybackDirection.IsKnown(unknown)) warnings.Add(new RenderWarning(DirectionUnknownWarning, unknown));
if (frames.Count == 0) return new OutputProgram([], warnings);
playback ??= new PlaybackSettings();
// The passes: plan indices in emission order, each frame for its planned duration.
var entries = new List<ProgramEntry>(frames.Count * playback.EffectiveLoops);
var direction = frames.Count == 1 ? PlaybackDirection.Forward : playback.EffectiveDirection;
for (var pass = 0; pass < playback.EffectiveLoops; pass++)
{
switch (direction)
{
case PlaybackDirection.Reverse:
for (var i = frames.Count - 1; i >= 0; i--) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1, pass));
break;
case PlaybackDirection.Boomerang:
// The turning frame plays once, and a later pass starts after the first frame the previous one ended on.
for (var i = pass == 0 ? 0 : 1; i < frames.Count; i++) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1, pass));
for (var i = frames.Count - 2; i >= 0; i--) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1, pass));
break;
default:
for (var i = 0; i < frames.Count; i++) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1, pass));
break;
}
}
// The hold: whole output periods added to the last frame.
if (playback.EffectiveHoldEnd > 0)
{
var periods = long.Max(1, (long)double.Round(playback.EffectiveHoldEnd * frameRate.Value));
var last = entries[^1];
entries[^1] = last with { Duration90k = last.Duration90k + RenderPlan.TicksAt(frameRate, periods) };
}
long total = 0;
foreach (var entry in entries) total += entry.Duration90k;
var fadeIn = (long)double.Round(playback.EffectiveFadeIn * 90000);
var fadeOut = (long)double.Round(playback.EffectiveFadeOut * 90000);
if (fadeIn + fadeOut == 0) return new OutputProgram(entries, warnings);
if (fadeIn + fadeOut > total / 2)
{
// Both fades shrink by the same factor until together they take half of the program.
var scale = (double)(total / 2) / (fadeIn + fadeOut);
fadeIn = (long)double.Floor(fadeIn * scale);
fadeOut = (long)double.Floor(fadeOut * scale);
warnings.Add(new RenderWarning(FadesShortenedWarning));
}
return new OutputProgram(Faded(entries, total, fadeIn, fadeOut, frameRate), warnings);
}
/// <summary>
/// The entries with the fade gains: an entry that reaches into a fade is split into its output periods (a held frame
/// otherwise keeps one gain for its whole time), and each part takes the gain of its own time.
/// </summary>
private static List<ProgramEntry> Faded(List<ProgramEntry> entries, long total, long fadeIn, long fadeOut, Rational frameRate)
{
var period = 90000.0 * frameRate.Denominator / frameRate.Numerator;
var faded = new List<ProgramEntry>(entries.Count);
long start = 0;
foreach (var entry in entries)
{
var end = start + entry.Duration90k;
if (start >= fadeIn && end <= total - fadeOut)
{
faded.Add(entry);
start = end;
continue;
}
var parts = int.Max(1, (int)double.Round(entry.Duration90k / period));
long previous = 0;
for (var part = 1; part <= parts; part++)
{
var boundary = (long)double.Round((double)entry.Duration90k * part / parts);
if (boundary == previous) continue;
faded.Add(entry with { Duration90k = boundary - previous, Gain = Gain(start + previous, start + boundary, total, fadeIn, fadeOut) });
previous = boundary;
}
start = end;
}
return faded;
}
/// <summary>
/// The linear gain of the time from <paramref name="start"/> to <paramref name="end"/>: the fade in at its start, the fade
/// out at its end, the darker of the two, through the sRGB curve so the ramp looks even.
/// </summary>
private static double Gain(long start, long end, long total, long fadeIn, long fadeOut)
{
var level = 1.0;
if (fadeIn > 0 && start < fadeIn) level = double.Min(level, (double)start / fadeIn);
if (fadeOut > 0 && end > total - fadeOut) level = double.Min(level, (double)(total - end) / fadeOut);
return level >= 1 ? 1 : ColorSpace.SrgbToLinear(double.Clamp(level, 0, 1));
}
}
+12 -2
View File
@@ -21,8 +21,18 @@ public sealed record RenderInput
}
/// <summary>One output of a render: the resolved export values and where the file (or sequence folder) goes.</summary>
/// <param name="OutputPath">Full path of the file, or of the folder for image sequences (see <see cref="ExportNaming.OutputPath"/>).</param>
public sealed record RenderTarget(ResolvedExport Export, string OutputPath);
/// <param name="OutputPath">Full path of the file, or of the folder for image sequences (see <see cref="ExportNaming.OutputPath"/>);
/// for a still, the image file (<see cref="ExportNaming.StillPath(string, string, ExportNameContext, int, Func{string, bool}?)"/>).</param>
/// <param name="StillFrame">
/// Owner review 1, R8, "Save frame": the source frame saved as one image (PNG, JPEG or TIFF, <see cref="RenderRules.StillCodecs"/>)
/// at the export's output size, with every correction and look, without stacking, interpolation, motion blur or playback;
/// null renders the video.
/// </param>
public sealed record RenderTarget(ResolvedExport Export, string OutputPath, int? StillFrame = null)
{
/// <summary>The target saves one frame as an image (<see cref="StillFrame"/>).</summary>
public bool IsStill => StillFrame is not null;
}
/// <summary>Tuning of a render that is not part of the project.</summary>
public sealed record RenderOptions
+143 -42
View File
@@ -16,7 +16,9 @@ namespace Chronos.Core.Render;
/// <see cref="IRenderFrameSource"/> at the working size; per-frame exposure corrections (deflicker, holy grail, white
/// balance, regions) are applied; stabilisation, virtual camera and crop are resampled once to the output size;
/// fractional positions are synthesised from the bidirectional flow; motion blur follows the flow with shutter-angle
/// composition; stacking (median, mean, star trails) and the finish (look, then highlight knee: <see cref="FrameFinish"/>) come last, then the encoder. Encoding of a
/// composition; stacking (median, mean, star trails) and the finish (look, then highlight knee, then the fade:
/// <see cref="FrameFinish"/>) come last, then the encoder. Frames are rendered in the order of the <see cref="OutputProgram"/>
/// (direction, loops, hold, fades); a still target renders one source frame into one image. Encoding of a
/// frame overlaps the processing of the next. Cancellation and failures leave no output behind (sessions delete their
/// partial files on dispose) and every background task is awaited, so exceptions surface exactly once.
/// </summary>
@@ -60,7 +62,7 @@ public sealed class RenderPipeline(IReadOnlyList<IVideoEncoderProvider> encoders
var notice = setup.Encoder.Notices.LastOrDefault() ?? new EncoderNotice(EncoderNotices.NoEncoder, setup.Encoder.Settings.Codec.ToString());
throw new RenderException(notice.Key, $"No encoder can produce {target.Export.Codec} here ({setup.Encoder.Status})", notice.Args);
}
if (setup.Plan.Frames.Count == 0) throw new RenderException("Export.Render.NoFrames", "Every frame is excluded.");
if (setup.Still is null && setup.Program.Count == 0) throw new RenderException("Export.Render.NoFrames", "Every frame is excluded.");
using var run = new RenderRun(input, corrections, setup, options, progress);
return await run.ExecuteAsync(cancellationToken).ConfigureAwait(false);
}
@@ -98,12 +100,16 @@ internal sealed class RenderRun : IDisposable
/// <summary>Largest speed (source frames per output period) that scales motion blur; faster plans blur no further.</summary>
private const double MaxBlurSpeed = 4;
/// <summary>Warning key prefix of a setting the encoder refused (<see cref="IVideoEncoderSession.Ignored"/>), followed by its <see cref="EncoderSetting"/>.</summary>
internal const string IgnoredWarningPrefix = "Export.Encoder.Ignored.";
private readonly RenderInput _input;
private readonly RenderCorrections _corrections;
private readonly RenderSetup _setup;
private readonly RenderOptions _options;
private readonly IProgress<RenderProgress>? _progress;
private readonly RenderPlan _plan;
private readonly OutputProgram _program;
private readonly RenderGeometry _geometry;
private readonly PreparedFrameCache _prepared;
private readonly FlowCache _flows = new(2);
@@ -129,6 +135,7 @@ internal sealed class RenderRun : IDisposable
_options = options;
_progress = progress;
_plan = setup.Plan;
_program = setup.Program;
_geometry = setup.Geometry;
_prepared = new PreparedFrameCache(int.Max(3, options.CacheFrames));
_workingEdge = _geometry.WorkingLongEdge;
@@ -148,14 +155,19 @@ internal sealed class RenderRun : IDisposable
{
var settings = _setup.Encoder.Settings;
_clock.Start();
Log.Info(RenderPipeline.LogCategory, $"Rendering {_plan.Frames.Count} frames ({_plan.SlotCount} periods) to {settings.Codec} {settings.Width}×{settings.Height} @ {settings.FrameRate}: {settings.OutputPath}");
if (_setup.Still is { } still)
Log.Info(RenderPipeline.LogCategory, $"Saving frame {still.From} as {settings.Codec} {settings.Width}×{settings.Height}: {settings.OutputPath}");
else
Log.Info(RenderPipeline.LogCategory, $"Rendering {_program.Count} frames of a {_plan.Frames.Count}-frame plan ({_plan.SlotCount} periods) to {settings.Codec} {settings.Width}×{settings.Height} @ {settings.FrameRate}: {settings.OutputPath}");
var session = _session = _setup.Encoder.Open();
IReadOnlyList<EncoderSetting> ignored;
try
{
await RenderFramesAsync(cancellationToken).ConfigureAwait(false);
await FlushEncodingAsync().ConfigureAwait(false);
_progress?.Report(new RenderProgress(RenderStage.Finishing, _done, _plan.Frames.Count, Fps(), _clock.Elapsed, TimeSpan.Zero));
_progress?.Report(new RenderProgress(RenderStage.Finishing, _done, _program.Count, Fps(), _clock.Elapsed, TimeSpan.Zero));
session.Complete();
ignored = [.. session.Ignored];
}
catch
{
@@ -170,6 +182,8 @@ internal sealed class RenderRun : IDisposable
var warnings = new List<RenderWarning>(_setup.Warnings);
warnings.AddRange(_corrections.Report.Warnings);
warnings.AddRange(_warnings);
// What the encoder did not take: the output was encoded with its own value, which the job's log says.
warnings.AddRange(ignored.Select(s => new RenderWarning(IgnoredWarningPrefix + s)));
var result = new RenderResult
{
OutputPath = settings.OutputPath,
@@ -178,8 +192,9 @@ internal sealed class RenderRun : IDisposable
Width = settings.Width,
Height = settings.Height,
FrameRate = settings.FrameRate,
DurationSeconds = _plan.DurationSeconds,
FrameCount = _plan.Frames.Count,
DurationSeconds = _setup.Still is null ? _program.DurationSeconds : 0,
FrameCount = _program.Count,
Kind = _setup.Still is null ? null : Model.RenderKind.Still,
Bytes = RenderResult.SizeOf(settings.OutputPath),
EncoderName = session.EncoderName,
Hardware = session.IsHardware,
@@ -199,6 +214,13 @@ internal sealed class RenderRun : IDisposable
private async Task RenderFramesAsync(CancellationToken cancellationToken)
{
if (_setup.Still is { } still)
{
// Save frame: the one source frame, whole, with every correction and the finish; no stacking and no playback.
var picture = await RenderFrameAsync(still, blur: false, cancellationToken).ConfigureAwait(false);
await EmitAsync(picture, new ProgramEntry(0, still.Duration90k, 1)).ConfigureAwait(false);
return;
}
var stack = _input.Project.Stack;
switch (stack.Mode)
{
@@ -206,58 +228,132 @@ internal sealed class RenderRun : IDisposable
await RenderWindowStackAsync(stack, cancellationToken).ConfigureAwait(false);
break;
case StackSetting.StarTrails:
using (var trails = new StarTrailStacker(StarTrailStacker.DecayForTrailLength(stack.Length > 0 ? stack.Length : double.PositiveInfinity)))
// The trails accumulate in program order: a reversed video grows its trails from the end, and each loop grows
// them again from nothing (a stacker carried over would freeze on the trails the first pass finished).
var decay = StarTrailStacker.DecayForTrailLength(stack.Length > 0 ? stack.Length : double.PositiveInfinity);
StarTrailStacker? trails = null;
var pass = -1;
try
{
foreach (var planned in _plan.Frames)
await RenderProgramAsync(async (entry, token) =>
{
cancellationToken.ThrowIfCancellationRequested();
using (var frame = await RenderFrameAsync(planned, blur: false, cancellationToken).ConfigureAwait(false)) trails.Add(frame);
await EmitAsync(trails.Result!.Clone(), planned.Duration90k).ConfigureAwait(false);
}
if (entry.Pass != pass || trails is null)
{
trails?.Dispose();
trails = new StarTrailStacker(decay);
pass = entry.Pass;
}
using (var frame = await RenderFrameAsync(_plan.Frames[entry.PlanIndex], blur: false, token).ConfigureAwait(false)) trails.Add(frame);
return trails.Result!.Clone();
}, cancellationToken).ConfigureAwait(false);
}
finally
{
trails?.Dispose();
}
break;
default:
foreach (var planned in _plan.Frames)
{
cancellationToken.ThrowIfCancellationRequested();
var frame = await RenderFrameAsync(planned, _setup.MotionBlur, cancellationToken).ConfigureAwait(false);
await EmitAsync(frame, planned.Duration90k).ConfigureAwait(false);
}
await RenderProgramAsync((entry, token) => RenderFrameAsync(_plan.Frames[entry.PlanIndex], _setup.MotionBlur, token), cancellationToken).ConfigureAwait(false);
break;
}
}
/// <summary>Centred median/mean window: output k is emitted once frame k + half has been pushed (the tail reuses the
/// last full window).</summary>
/// <summary>
/// Emits the program's entries in order, each rendered by <paramref name="render"/> from its plan index. Consecutive
/// entries of one plan frame and one pass (a held frame split over the periods of a fade) share one rendering, so a
/// stack folds it in once; every other entry is rendered again (a boomerang's way back, each loop).
/// </summary>
private async Task RenderProgramAsync(Func<ProgramEntry, CancellationToken, Task<ImageBuffer>> render, CancellationToken cancellationToken)
{
var entries = _program.Entries;
ImageBuffer? kept = null;
try
{
for (var i = 0; i < entries.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var entry = entries[i];
var frame = kept ?? await render(entry, cancellationToken).ConfigureAwait(false);
kept = null;
if (i + 1 < entries.Count && entries[i + 1].PlanIndex == entry.PlanIndex && entries[i + 1].Pass == entry.Pass)
{
try
{
kept = frame.Clone();
}
catch
{
frame.Dispose();
throw;
}
}
await EmitAsync(frame, entry).ConfigureAwait(false);
}
}
finally
{
kept?.Dispose();
}
}
/// <summary>
/// Median/mean stacks, one centred window per plan frame whatever the program's order: frame k combines plan frames
/// k − half … k + half, cut to the plan at the start and shifted inside it at the end (as a forward render always did).
/// Stepping to the next frame in the direction the program travels pushes one frame; a turn or the shrinking window at the
/// plan's start fills the window again.
/// </summary>
private async Task RenderWindowStackAsync(StackSettings stack, CancellationToken cancellationToken)
{
var window = int.Max(1, stack.Length);
var half = (window - 1) / 2;
var last = _plan.Frames.Count - 1;
using var stacker = new TemporalStacker(window, stack.Mode == StackSetting.Median ? StackMode.Median : StackMode.Mean);
var pending = new Queue<PlannedFrame>();
foreach (var planned in _plan.Frames)
// Plan indices in the stacker, oldest (the next evicted) first.
var held = new List<int>(window + 1);
var previous = -1;
await RenderProgramAsync(async (entry, token) =>
{
cancellationToken.ThrowIfCancellationRequested();
using (var frame = await RenderFrameAsync(planned, blur: false, cancellationToken).ConfigureAwait(false)) stacker.Push(frame);
pending.Enqueue(planned);
if (pending.Count > half) await EmitStackAsync(stacker, pending.Dequeue(), cancellationToken).ConfigureAwait(false);
}
while (pending.Count > 0) await EmitStackAsync(stacker, pending.Dequeue(), cancellationToken).ConfigureAwait(false);
var index = entry.PlanIndex;
var hi = int.Min(index + half, last);
var lo = int.Max(0, hi - window + 1);
await WindowAsync(stacker, held, lo, hi, index >= previous, token).ConfigureAwait(false);
previous = index;
var output = new ImageBuffer(_geometry.OutputWidth, _geometry.OutputHeight, 3, clear: false);
try
{
stacker.Render(output, token);
return output;
}
catch
{
output.Dispose();
throw;
}
}, cancellationToken).ConfigureAwait(false);
}
private async Task EmitStackAsync(TemporalStacker stacker, PlannedFrame planned, CancellationToken cancellationToken)
/// <summary>Makes the stacker hold exactly plan frames <paramref name="lo"/>…<paramref name="hi"/>.</summary>
private async Task WindowAsync(TemporalStacker stacker, List<int> held, int lo, int hi, bool forward, CancellationToken cancellationToken)
{
var output = new ImageBuffer(_geometry.OutputWidth, _geometry.OutputHeight, 3, clear: false);
try
bool Holds(IEnumerable<int> frames) => frames.Count() == hi - lo + 1 && frames.All(i => i >= lo && i <= hi);
if (Holds(held)) return;
var missing = Enumerable.Range(lo, hi - lo + 1).Where(i => !held.Contains(i)).ToList();
if (missing.Count == 1 && Holds(held.Skip(held.Count == stacker.Window ? 1 : 0).Append(missing[0])))
{
stacker.Render(output, cancellationToken);
await PushAsync(stacker, held, missing[0], cancellationToken).ConfigureAwait(false);
return;
}
catch
{
output.Dispose();
throw;
}
await EmitAsync(output, planned.Duration90k).ConfigureAwait(false);
stacker.Clear();
held.Clear();
// Pushed in the direction of travel, so the next step evicts the frame it leaves behind.
for (var k = 0; k <= hi - lo; k++) await PushAsync(stacker, held, forward ? lo + k : hi - k, cancellationToken).ConfigureAwait(false);
}
private async Task PushAsync(TemporalStacker stacker, List<int> held, int index, CancellationToken cancellationToken)
{
using (var frame = await RenderFrameAsync(_plan.Frames[index], blur: false, cancellationToken).ConfigureAwait(false)) stacker.Push(frame);
held.Add(index);
if (held.Count > stacker.Window) held.RemoveAt(0);
}
/// <summary>The picture of one planned frame at the output size (a new buffer owned by the caller).</summary>
@@ -400,14 +496,19 @@ internal sealed class RenderRun : IDisposable
if (ev != 0 || (gains is { } g && g != ChannelGains.Identity)) ExposureProcessor.Apply(frame, ev, gains);
}
/// <summary>Finishes the frame (look, then knee) and hands it to the encoder once the previous frame is encoded; owns <paramref name="frame"/>.</summary>
private async Task EmitAsync(ImageBuffer frame, long duration90k)
/// <summary>
/// Finishes the frame (look, then knee, then the entry's fade) and hands it to the encoder for the entry's duration once
/// the previous frame is encoded; owns <paramref name="frame"/>.
/// </summary>
private async Task EmitAsync(ImageBuffer frame, ProgramEntry entry)
{
ImageBuffer? preview = null;
var duration90k = entry.Duration90k;
try
{
await FlushEncodingAsync().ConfigureAwait(false);
FrameFinish.Apply(frame, _look, _knee);
if (entry.Gain < 1) FrameFinish.Fade(frame, entry.Gain);
_done++;
if (_options.PreviewInterval > 0 && (_done - 1) % _options.PreviewInterval == 0) preview = Resampler.Thumbnail(frame, _options.PreviewLongEdge);
}
@@ -424,8 +525,8 @@ internal sealed class RenderRun : IDisposable
if (_progress is not null)
{
var fps = Fps();
_progress.Report(new RenderProgress(RenderStage.Rendering, _done, _plan.Frames.Count, fps, _clock.Elapsed,
fps > 0 ? TimeSpan.FromSeconds((_plan.Frames.Count - _done) / fps) : null, preview));
_progress.Report(new RenderProgress(RenderStage.Rendering, _done, _program.Count, fps, _clock.Elapsed,
fps > 0 ? TimeSpan.FromSeconds((_program.Count - _done) / fps) : null, preview));
}
else
{
+13 -3
View File
@@ -17,11 +17,19 @@ public sealed record RenderResult
public required int Width { get; init; }
public required int Height { get; init; }
public required Rational FrameRate { get; init; }
/// <summary>The video's duration, holds included (<see cref="OutputProgram.DurationSeconds"/>); 0 for a still.</summary>
public required double DurationSeconds { get; init; }
/// <summary>Output pictures rendered (held frames count once).</summary>
/// <summary>
/// Pictures the encoder received (<see cref="OutputProgram.Count"/>): every pass and loop, a held frame once, or once per
/// output period inside a fade; 1 for a still.
/// </summary>
public required int FrameCount { get; init; }
/// <summary><see cref="Model.Render.Kind"/>: <see cref="Model.RenderKind.Still"/> for one frame saved as an image, else null.</summary>
public string? Kind { get; init; }
/// <summary>Size of the file, or of every file of a sequence.</summary>
public required long Bytes { get; init; }
@@ -46,11 +54,13 @@ public sealed record RenderResult
Codec = Codec.ToString(),
Width = Width,
Height = Height,
Fps = FrameRate.Value,
DurationSeconds = DurationSeconds,
// A still is recorded with no frame rate and no duration (DECISIONS 2026-11-05, phase 5 (12)).
Fps = Kind == Model.RenderKind.Still ? 0 : FrameRate.Value,
DurationSeconds = Kind == Model.RenderKind.Still ? 0 : DurationSeconds,
Bytes = Bytes,
Created = DateTimeOffset.UtcNow,
ProducedBy = producedBy,
Kind = Kind,
};
/// <summary>Bytes of a file, or the total of the files in a folder.</summary>
+34 -3
View File
@@ -1,5 +1,6 @@
using Chronos.Core.Export;
using Chronos.Core.Project;
using Chronos.Core.Video;
namespace Chronos.Core.Render;
@@ -9,11 +10,41 @@ namespace Chronos.Core.Render;
/// </summary>
public static class RenderRules
{
/// <summary>
/// The settings format a still job needs (owner review 1, R8, "Save frame"): an older program reads the job as a render
/// of the whole video, so it must never claim one.
/// </summary>
public const int StillFormat = 3;
/// <summary>The codecs a still frame is saved with, in the order "Save frame" offers them: PNG, JPEG and TIFF 16-bit.</summary>
public static IReadOnlyList<VideoCodec> StillCodecs { get; } = [VideoCodec.PngSequence, VideoCodec.JpegSequence, VideoCodec.Tiff16Sequence];
/// <summary>
/// <see cref="RequiredFormat(ProjectSettings, ResolvedExport, int, int)"/>, and at least <see cref="StillFormat"/> for a
/// still job (<paramref name="still"/>: one frame saved as an image).
/// </summary>
public static int RequiredFormat(ProjectSettings settings, ResolvedExport export, int sourceWidth, int sourceHeight, bool still)
{
var format = RequiredFormat(settings, export, sourceWidth, sourceHeight);
return still ? int.Max(format, StillFormat) : format;
}
/// <summary>
/// The settings format a render of <paramref name="target"/> needs: <see cref="RequiredFormat(ProjectSettings, ResolvedExport, int, int, bool)"/>
/// for its export, a still when <see cref="RenderTarget.StillFrame"/> is set.
/// </summary>
public static int RequiredFormat(ProjectSettings settings, RenderTarget target, int sourceWidth, int sourceHeight)
{
ArgumentNullException.ThrowIfNull(target);
return RequiredFormat(settings, target.Export, sourceWidth, sourceHeight, target.IsStill);
}
/// <summary>
/// The settings format a render of <paramref name="settings"/> with <paramref name="export"/> on a source of the given
/// (Exif-oriented) size needs: the format the settings are written in (<see cref="ProjectSettings.WrittenFormat"/>), and
/// at least 2 when the chosen proportions change a fixed-size preset's size (<see cref="RenderSize"/>), which a format-1
/// program would render at the preset's own ratio.
/// (Exif-oriented) size needs: the format the settings are written in (<see cref="ProjectSettings.WrittenFormat"/>, 3 when
/// <see cref="ExportSettings.Playback"/> plays other than forward once, so the settings must carry the export the job
/// renders), and at least 2 when the chosen proportions change a fixed-size preset's size (<see cref="RenderSize"/>), which
/// a format-1 program would render at the preset's own ratio.
/// </summary>
public static int RequiredFormat(ProjectSettings settings, ResolvedExport export, int sourceWidth, int sourceHeight)
{
+76 -13
View File
@@ -5,27 +5,44 @@ using Chronos.Core.Video;
namespace Chronos.Core.Render;
/// <summary>
/// What a render will do, decided before its first frame: output geometry, encoder (with its adjustments) and plan.
/// The Export tab uses it for the output size, encoder notices, plan chart and estimates.
/// What a render will do, decided before its first frame: output geometry, encoder (with its adjustments), plan and output
/// program. The Export tab uses it for the output size, encoder notices, plan chart and estimates; <see cref="Program"/> is
/// what the encoder receives (owner review 1, R8).
/// </summary>
public sealed record RenderSetup
{
private readonly OutputProgram? _program;
public required RenderTarget Target { get; init; }
public required RenderGeometry Geometry { get; init; }
public required EncoderSelection Encoder { get; init; }
public required RenderPlan Plan { get; init; }
/// <summary>
/// The frames in the order and for the time they are emitted (owner review 1, R8): the plan played as the export's
/// <see cref="ExportSettings.Playback"/> says. A still's program is its one frame. Defaults to the plan forward once.
/// </summary>
public OutputProgram Program
{
get => _program ?? OutputProgram.Build(Plan, null, Plan.FrameRate);
init => _program = value;
}
/// <summary>The frame a still target saves (<see cref="RenderTarget.StillFrame"/>): whole, never interpolated; null for a video.</summary>
public PlannedFrame? Still { get; init; }
/// <summary>Synthetic motion blur applies (it is off while stacking).</summary>
public bool MotionBlur { get; init; }
/// <summary>The preparation pass decodes frames (no corrections were supplied and a module needs measurements).</summary>
public bool NeedsPreparation { get; init; }
/// <summary>Geometry, plan and encoder remarks.</summary>
/// <summary>Geometry, plan, program and encoder remarks.</summary>
public IReadOnlyList<RenderWarning> Warnings { get; init; } = [];
/// <summary>Decides geometry, encoder and plan for one target.</summary>
/// <summary>Decides geometry, encoder, plan and program for one target.</summary>
/// <param name="corrections">Prepared corrections when available (their stabilisation zoom affects the decode size).</param>
/// <exception cref="RenderException">A still target names a frame the sequence does not have.</exception>
public static RenderSetup Create(RenderInput input, RenderTarget target, IReadOnlyList<IVideoEncoderProvider> encoders, EncoderHost host,
RenderOptions? options = null, RenderCorrections? corrections = null)
{
@@ -34,21 +51,49 @@ public sealed record RenderSetup
ArgumentNullException.ThrowIfNull(encoders);
options ??= RenderOptions.Default;
if (input.Frames.Count != input.Source.FrameCount) throw new ArgumentException("One metadata entry per source frame is required.", nameof(input));
if (target.StillFrame is { } wanted && (wanted < 0 || wanted >= input.Source.FrameCount))
throw new RenderException("Export.Render.StillMissing", $"Frame {wanted} is not in the sequence of {input.Source.FrameCount} frames.");
var project = input.Project;
var geometry = RenderGeometry.Create(project.Camera, target.Export, input.Source.Width, input.Source.Height,
corrections?.StabilizationZoom ?? 1, options.MaxWorkingLongEdge);
var selection = EncoderSelector.Select(target.Export.ToEncodeSettings(target.OutputPath, geometry.OutputWidth, geometry.OutputHeight), encoders, host);
var requested = target.Export.ToEncodeSettings(target.OutputPath, geometry.OutputWidth, geometry.OutputHeight);
// "TIFF 16-bit" is what Save frame offers, whatever depth the export's video has.
if (target.IsStill) requested = requested with { SingleImage = true, BitDepth = requested.Codec == VideoCodec.Tiff16Sequence ? 16 : requested.BitDepth };
var selection = EncoderSelector.Select(requested, encoders, host);
geometry = geometry.WithOutputSize(selection.Settings.Width, selection.Settings.Height);
var times = new DateTime?[input.Frames.Count];
for (var i = 0; i < times.Length; i++) times[i] = input.Frames[i].CapturedAt;
var plan = RenderPlan.Build(times, project, selection.Settings.FrameRate, options.Plan);
var rate = selection.Settings.FrameRate;
var plan = RenderPlan.Build(times, project, rate, options.Plan);
var warnings = new List<RenderWarning>(geometry.Warnings);
warnings.AddRange(plan.Warnings.Select(k => new RenderWarning(k)));
warnings.AddRange(selection.Notices.Select(n => new RenderWarning(n.Key, n.Args)));
var stacking = project.Stack.Mode != StackSetting.None;
var blur = project.Motion.MotionBlur.Resolve(false);
if (blur && stacking) warnings.Add(new RenderWarning("Export.Render.BlurOffWhileStacking"));
OutputProgram program;
PlannedFrame? still = null;
if (target.StillFrame is { } index)
{
// One source frame, whole: no stacking, interpolation, blur or playback, so no plan remark applies.
still = new PlannedFrame(index, index, index, 0, 0, RenderPlan.TicksAt(rate, 1), 0, 1, 0, PlannedFrameFlags.None);
program = OutputProgram.Build([still.Value], null, rate);
warnings.AddRange(selection.Notices.Select(n => new RenderWarning(n.Key, n.Args)));
blur = false;
}
else
{
warnings.AddRange(plan.Warnings.Select(k => new RenderWarning(k)));
warnings.AddRange(selection.Notices.Select(n => new RenderWarning(n.Key, n.Args)));
if (blur && stacking) warnings.Add(new RenderWarning("Export.Render.BlurOffWhileStacking"));
var playback = project.Export.Playback;
if (project.Stack.Mode == StackSetting.StarTrails && playback?.EffectiveDirection == PlaybackDirection.Boomerang)
{
// Trails cannot shrink on the way back, so the video plays forward (DECISIONS 2026-11-05, phase 5 (11)).
warnings.Add(new RenderWarning(OutputProgram.BoomerangStackWarning));
playback = playback with { Direction = null };
}
program = OutputProgram.Build(plan, playback, rate);
warnings.AddRange(program.Warnings);
}
var exposure = project.Exposure;
var measuring = exposure.Deflicker.Resolve(false) || exposure.HolyGrail.Resolve(false)
|| exposure.WhiteBalanceSmoothing.Resolve(false) || project.Motion.Stabilize.Resolve(false);
@@ -58,20 +103,38 @@ public sealed record RenderSetup
Geometry = geometry,
Encoder = selection,
Plan = plan,
Program = program,
Still = still,
MotionBlur = blur && !stacking,
NeedsPreparation = corrections is null && measuring,
Warnings = warnings,
};
}
/// <summary>The render's workload in the units of <see cref="ExportEstimator"/>.</summary>
/// <summary>
/// The render's workload in the units of <see cref="ExportEstimator"/>, from the output program: every pass and loop is
/// rendered again, so the time grows with them, and the duration includes the hold. A still is one picture of no duration.
/// </summary>
public ExportWorkload Workload()
{
var edge = Geometry.WorkingLongEdge;
var shortEdge = (long)double.Round(edge * (double)int.Min(Geometry.SourceWidth, Geometry.SourceHeight) / int.Max(Geometry.SourceWidth, Geometry.SourceHeight));
var flowFrames = MotionBlur ? Plan.Frames.Count : Plan.Statistics.InterpolatedFrames;
return new ExportWorkload(Plan.Frames.Count, Plan.SlotCount, Plan.DurationSeconds, Geometry.OutputWidth, Geometry.OutputHeight, edge * shortEdge,
flowFrames, NeedsPreparation ? Plan.IncludedFrames.Count : 0, Encoder.Capability?.Hardware ?? false);
var program = Program;
var flowFrames = 0;
if (Still is null)
{
// A frame split over the periods of a fade is rendered once; every other entry is rendered again.
for (var i = 0; i < program.Count; i++)
{
var entry = program.Entries[i];
if (i > 0 && program.Entries[i - 1].PlanIndex == entry.PlanIndex) continue;
if (MotionBlur || Plan.Frames[entry.PlanIndex].IsInterpolated) flowFrames++;
}
}
var rate = Encoder.Settings.FrameRate;
var periods = Still is null ? (int)double.Round(program.Duration90k * (double)rate.Numerator / (90000.0 * rate.Denominator)) : 1;
return new ExportWorkload(program.Count, periods, Still is null ? program.DurationSeconds : 0, Geometry.OutputWidth, Geometry.OutputHeight,
edge * shortEdge, flowFrames, NeedsPreparation ? Plan.IncludedFrames.Count : 0, Encoder.Capability?.Hardware ?? false);
}
/// <summary>Size and time estimates for the values the encoder will actually use.</summary>