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

+31
View File
@@ -126,6 +126,37 @@ public static class ExportNaming
return OutputPath(string.IsNullOrWhiteSpace(settings.Folder) ? sequenceExportsFolder : settings.Folder, settings.NameTemplate, context, taken);
}
/// <summary>
/// The name of a still (owner review 1, R8, "Save frame"): the expanded <paramref name="template"/>, " - " and the 1-based
/// number of source frame <paramref name="frameIndex"/> in at least four digits, "2026-09-28 Harbour - 4K HEVC - 0123".
/// </summary>
public static string StillName(string template, ExportNameContext context, int frameIndex)
{
ArgumentOutOfRangeException.ThrowIfNegative(frameIndex);
var name = Expand(template, context).Name;
return PathTemplate.SanitizeSegment(string.Create(CultureInfo.InvariantCulture, $"{name} - {frameIndex + 1:D4}"));
}
/// <summary>
/// Full path of a still inside <paramref name="folder"/>: <see cref="StillName"/> plus the image extension of the codec
/// (one file, never a folder), made unique like <see cref="OutputPath(string, string, ExportNameContext, Func{string, bool}?)"/>.
/// </summary>
public static string StillPath(string folder, string template, ExportNameContext context, int frameIndex, Func<string, bool>? taken = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
return Unique(folder, StillName(template, context, frameIndex), VideoCodecInfo.FileExtension(context.Codec), taken);
}
/// <summary>
/// Path of a still of a project's export: <see cref="ExportSettings.Folder"/> or, when unset, the sequence's exports
/// folder, named by <see cref="ExportSettings.NameTemplate"/> and the frame number.
/// </summary>
public static string StillPath(ExportSettings settings, string sequenceExportsFolder, ExportNameContext context, int frameIndex, Func<string, bool>? taken = null)
{
ArgumentNullException.ThrowIfNull(settings);
return StillPath(string.IsNullOrWhiteSpace(settings.Folder) ? sequenceExportsFolder : settings.Folder, settings.NameTemplate, context, frameIndex, taken);
}
/// <summary>"name.ext", or "name (2).ext", "name (3).ext"… when a file or folder of that name exists or is <paramref name="taken"/>.</summary>
public static string Unique(string folder, string name, string extension, Func<string, bool>? taken = null)
{
+12
View File
@@ -93,6 +93,18 @@ public static class AtomicFile
Replace(tempPath, path);
}
/// <summary>
/// Commits an already-written temporary file as <paramref name="path"/>, which must not exist: an output whose free name
/// something else took meanwhile (a restore, another program) is never overwritten.
/// </summary>
/// <exception cref="IOException"><paramref name="path"/> exists (the temporary file stays for the caller to discard).</exception>
public static void CommitNew(string tempPath, string path)
{
using (var fs = new FileStream(tempPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
fs.Flush(flushToDisk: true);
File.Move(tempPath, path, overwrite: false);
}
public static string TempPathFor(string path)
{
var dir = Path.GetDirectoryName(Path.GetFullPath(path)) ?? ".";
+80
View File
@@ -164,6 +164,86 @@ public sealed record Render
/// <summary>The project version rendered; null for a render of the sequence's settings.</summary>
public Guid? ProjectVersionId { get; init; }
/// <summary>
/// Lower-case hex SHA-256 of a single-file render (owner review 1, R9), hashed when it is recorded; null for an image
/// sequence's folder (verified file by file when copied) and for a render recorded before migration 0010, hashed the
/// first time it is copied, deleted or restored.
/// </summary>
public string? Sha256 { get; init; }
/// <summary>
/// What the render is beyond its codec (<see cref="RenderKind"/>): null for a video or an image sequence (told apart by
/// <see cref="Codec"/>), <see cref="RenderKind.Still"/> for one frame saved as an image. A text, so a newer Chronos can add
/// kinds.
/// </summary>
public string? Kind { get; init; }
}
/// <summary>The values of <see cref="Render.Kind"/> and of the videos library's kinds (owner review 1, R9).</summary>
public static class RenderKind
{
/// <summary>A video file (MP4, AVI, GIF, APNG): <see cref="Render.Kind"/> null and a video codec.</summary>
public const string Video = "video";
/// <summary>A folder of numbered images: <see cref="Render.Kind"/> null and an image-sequence codec.</summary>
public const string Sequence = "sequence";
/// <summary>One frame saved as one image ("Save frame"): fps 0 and duration 0.</summary>
public const string Still = "still";
/// <summary>
/// The library kind of a render: its <see cref="Render.Kind"/> when set (a kind of a newer Chronos as it is), else
/// <see cref="Sequence"/> for an image-sequence codec and <see cref="Video"/> otherwise.
/// </summary>
public static string Of(string? kind, string? codec) =>
kind is { Length: > 0 } ? kind
: codec is { } c && c.EndsWith("sequence", StringComparison.OrdinalIgnoreCase) ? Sequence
: Video;
/// <summary>
/// <see cref="Of(string?, string?)"/>, telling a still apart when its kind was lost (one uploaded to a server of before
/// phase 5, which does not record it): an image-sequence codec with fps 0 and duration 0, which every still records and
/// no image sequence has.
/// </summary>
public static string Of(string? kind, string? codec, double fps, double durationSeconds)
{
var of = Of(kind, codec);
return of == Sequence && fps <= 0 && durationSeconds <= 0 ? Still : of;
}
/// <inheritdoc cref="Of(string?, string?, double, double)"/>
public static string Of(Render render)
{
ArgumentNullException.ThrowIfNull(render);
return Of(render.Kind, render.Codec, render.Fps, render.DurationSeconds);
}
}
/// <summary>
/// A verified copy of a render in a videos folder (owner review 1, R9; <c>render_copies</c>): recorded once the copy matched
/// its render. There is no link to <c>renders</c>, so the copy of a server render downloaded to a PC is recorded too, and a
/// copy outlives its render's deletion (copies are the user's files; Chronos never deletes them).
/// </summary>
public sealed record RenderCopy
{
public required Guid Id { get; init; }
/// <summary>The render copied (of this index, or of the server it was downloaded from).</summary>
public required Guid RenderId { get; init; }
/// <summary>Absolute path of the copy (a file, or a folder for an image sequence).</summary>
public required string Path { get; init; }
/// <summary>Lower-case hex SHA-256 the copy was verified against; null for an image sequence's folder (verified per file).</summary>
public string? Sha256 { get; init; }
public long Bytes { get; init; }
public DateTimeOffset CopiedAt { get; init; }
/// <summary>The user (server) or the PC (desktop) that copied it.</summary>
public string? CopiedBy { get; init; }
}
/// <summary>
+6
View File
@@ -123,6 +123,12 @@ public enum JobKind
/// source kept until every file is verified (owner review 2, R8, phase 5c); stored as 23.
/// </summary>
WorkspaceMove = 23,
/// <summary>
/// Copies renders into the videos folder (owner review 1, R9), each copy hash-verified against its render before it takes
/// its name, the render itself never touched; on the desktop a server-only render is downloaded into it; stored as 24.
/// </summary>
VideoCopy = 24,
}
/// <summary>Why a photo left a sequence (its tombstone, owner review 2, R6); stored as a number.</summary>
+128 -5
View File
@@ -278,6 +278,116 @@ public sealed record ExportSettings
/// </summary>
public bool SyncToServer { get; init; }
/// <summary>
/// How the rendered frames play (owner review 1, R8): direction, loops, fades and a hold at the end, applied by
/// <c>OutputProgram</c> between the plan and the encoder. Null at the default (forward, once, no fades, no hold), which
/// <see cref="ProjectSettings.ToJson"/> writes whenever <see cref="PlaybackSettings.IsDefault"/>. Settings format 3. It
/// lives in the export, so the batch presets of the export inherit it.
/// </summary>
public PlaybackSettings? Playback { get; init; }
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
/// <summary>The directions of <see cref="PlaybackSettings.Direction"/>: texts, not an enum, so a newer Chronos can add one.</summary>
public static class PlaybackDirection
{
/// <summary>The plan as it is (the default, never written).</summary>
public const string Forward = "forward";
/// <summary>The plan from its last frame to its first.</summary>
public const string Reverse = "reverse";
/// <summary>Forward, then backward without repeating the turning frame.</summary>
public const string Boomerang = "boomerang";
/// <summary>The directions this Chronos renders, in the order the editor offers them.</summary>
public static IReadOnlyList<string> All { get; } = [Forward, Reverse, Boomerang];
/// <summary>Whether this Chronos renders <paramref name="direction"/> (null is forward); the comparison ignores case.</summary>
public static bool IsKnown(string? direction) =>
direction is null || All.Contains(direction, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// The playback of an export (owner review 1, R8; settings format 3): each member null at its default and omitted then, so
/// a project that sets nothing here keeps its text. Values out of range are clamped when rendered
/// (<see cref="EffectiveLoops"/> and the other effective values); a direction this Chronos does not know renders forward
/// with the warning <c>Export.Render.DirectionUnknown</c>.
/// </summary>
public sealed record PlaybackSettings
{
/// <summary>The most passes a video plays (<see cref="Loops"/>).</summary>
public const int MaxLoops = 10;
/// <summary>The longest fade in or out, in seconds.</summary>
public const double MaxFadeSeconds = 30;
/// <summary>The longest hold of the last frame, in seconds.</summary>
public const double MaxHoldSeconds = 60;
/// <summary><see cref="PlaybackDirection"/>: null for forward; "reverse" or "boomerang".</summary>
public string? Direction { get; init; }
/// <summary>Passes of the whole video, 1..<see cref="MaxLoops"/>; null for 1.</summary>
public int? Loops { get; init; }
/// <summary>Seconds of fade from black at the start, 0..<see cref="MaxFadeSeconds"/>; null for 0.</summary>
public double? FadeIn { get; init; }
/// <summary>Seconds of fade to black at the end, 0..<see cref="MaxFadeSeconds"/>; null for 0.</summary>
public double? FadeOut { get; init; }
/// <summary>Seconds the last frame stays on screen after the last pass, 0..<see cref="MaxHoldSeconds"/>; null for 0.</summary>
public double? HoldEnd { get; init; }
/// <summary>The direction rendered: forward for null and for a direction this Chronos does not know.</summary>
[JsonIgnore]
public string EffectiveDirection => Direction is { } d && PlaybackDirection.IsKnown(d) ? d.ToLowerInvariant() : PlaybackDirection.Forward;
/// <summary>The passes rendered, clamped to 1..<see cref="MaxLoops"/>.</summary>
[JsonIgnore]
public int EffectiveLoops => Math.Clamp(Loops ?? 1, 1, MaxLoops);
/// <summary>The fade in rendered, in seconds, clamped (a value that is not finite counts as 0).</summary>
[JsonIgnore]
public double EffectiveFadeIn => Seconds(FadeIn, MaxFadeSeconds);
/// <summary>The fade out rendered, in seconds, clamped (a value that is not finite counts as 0).</summary>
[JsonIgnore]
public double EffectiveFadeOut => Seconds(FadeOut, MaxFadeSeconds);
/// <summary>The hold rendered, in seconds, clamped (a value that is not finite counts as 0).</summary>
[JsonIgnore]
public double EffectiveHoldEnd => Seconds(HoldEnd, MaxHoldSeconds);
/// <summary>
/// The playback renders as the default (forward, once, no fades, no hold) and holds nothing a newer Chronos wrote: the
/// export then writes no playback at all. A direction this Chronos does not know is not the default (it is a newer
/// Chronos's), so it is kept and raises the format.
/// </summary>
[JsonIgnore]
public bool IsDefault =>
(Direction is null || string.Equals(Direction, PlaybackDirection.Forward, StringComparison.OrdinalIgnoreCase))
&& EffectiveLoops == 1 && EffectiveFadeIn == 0 && EffectiveFadeOut == 0 && EffectiveHoldEnd == 0 && Extra is not { Count: > 0 };
/// <summary>
/// The same playback with each member at its default (forward, 1, 0) set to null, so it is not written; values out of
/// range and unknown directions stay as they are. <see cref="ProjectSettings.ToJson"/> writes the playback this way.
/// </summary>
public PlaybackSettings Normalized() => this with
{
Direction = string.Equals(Direction, PlaybackDirection.Forward, StringComparison.OrdinalIgnoreCase) ? null : Direction,
Loops = Loops == 1 ? null : Loops,
FadeIn = FadeIn == 0 ? null : FadeIn,
FadeOut = FadeOut == 0 ? null : FadeOut,
HoldEnd = HoldEnd == 0 ? null : HoldEnd,
};
private static double Seconds(double? value, double max) => value is { } v && double.IsFinite(v) ? Math.Clamp(v, 0, max) : 0;
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
@@ -323,7 +433,10 @@ public sealed record LookSettings
public sealed record ProjectSettings
{
/// <summary>The highest settings format this Chronos reads; a project of a higher one opens read-only (<see cref="IsNewerFormat"/>).</summary>
public const int CurrentVersion = 2;
public const int CurrentVersion = 3;
/// <summary>The format of a project whose export plays other than forward once without fades (<see cref="ExportSettings.Playback"/>).</summary>
public const int PlaybackVersion = 3;
/// <summary>The format of a project that uses nothing added since the first one, which most projects are written as.</summary>
public const int BaseVersion = 1;
@@ -377,11 +490,13 @@ public sealed record ProjectSettings
public bool IsNewerFormat => Version > CurrentVersion;
/// <summary>
/// The lowest settings format that renders these settings the same: 2 while a turn, mirror, flip or straighten
/// The lowest settings format that renders these settings the same: 3 while the export's playback is not the default
/// (<see cref="PlaybackSettings.IsDefault"/>), 2 while a turn, mirror, flip or straighten
/// (<see cref="CameraSettings.IsOriented"/>) or a look other than the identity is set, otherwise <see cref="BaseVersion"/>.
/// </summary>
[JsonIgnore]
public int RequiredFormat => Camera.IsOriented || Look is { IsIdentity: false } ? 2 : BaseVersion;
public int RequiredFormat =>
Export.Playback is { IsDefault: false } ? PlaybackVersion : Camera.IsOriented || Look is { IsIdentity: false } ? 2 : BaseVersion;
/// <summary>The format <see cref="ToJson"/> writes: <see cref="RequiredFormat"/>, or a newer format read, kept as it is.</summary>
[JsonIgnore]
@@ -389,9 +504,16 @@ public sealed record ProjectSettings
/// <summary>
/// The settings as JSON, stamped with <see cref="WrittenFormat"/>. Every serialisation of a project goes through here,
/// so the version written always matches the members used.
/// so the version written always matches the members used; a playback at its default is written as none, and each of
/// its members at its default is left out (<see cref="PlaybackSettings.Normalized"/>).
/// </summary>
public string ToJson() => JsonSerializer.Serialize(Version == WrittenFormat ? this : this with { Version = WrittenFormat }, ProjectJson.Default.ProjectSettings);
public string ToJson()
{
var written = Export.Playback is { } playback
? this with { Export = Export with { Playback = playback.IsDefault ? null : playback.Normalized() } }
: this;
return JsonSerializer.Serialize(written.Version == WrittenFormat ? written : written with { Version = WrittenFormat }, ProjectJson.Default.ProjectSettings);
}
/// <summary>
/// Reads a project; members missing from <paramref name="json"/> (an API client's partial settings, an older file)
@@ -821,4 +943,5 @@ public sealed record ProjectSettings
UseStringEnumConverter = true,
PropertyNameCaseInsensitive = true)]
[JsonSerializable(typeof(ProjectSettings))]
[JsonSerializable(typeof(PlaybackSettings))]
internal sealed partial class ProjectJson : JsonSerializerContext;
+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>
+27 -1
View File
@@ -102,11 +102,21 @@ public sealed record EncodeSettings
/// <summary>Distance between key frames in frames; 0 = encoder default (≈ 1 s).</summary>
public int GopLength { get; init; }
public int BFrames { get; init; } = 2;
public int BFrames { get; init; } = DefaultBFrames;
/// <summary>The B-frames an encode asks for unless told otherwise.</summary>
public const int DefaultBFrames = 2;
public bool PreferHardware { get; init; } = true;
/// <summary>Optional specific encoder name from <see cref="EncoderCapability.Name"/>.</summary>
public string? EncoderName { get; init; }
/// <summary>
/// One frame saved as one image file at <see cref="OutputPath"/> (owner review 1, R8, "Save frame") instead of a numbered
/// sequence in a folder: the image-sequence codecs PNG, JPEG and TIFF only, and exactly one frame.
/// </summary>
public bool SingleImage { get; init; }
}
/// <summary>One open encode. Frames are linear-light buffers at the output size.</summary>
@@ -122,6 +132,22 @@ public interface IVideoEncoderSession : IDisposable
/// <summary>Flushes and closes the output. Without it, <see cref="IDisposable.Dispose"/> deletes the partial file.</summary>
void Complete();
/// <summary>
/// The settings asked for that the encoder does not support or refused, so the output was encoded with its own instead;
/// empty when it took every one (the managed encoders, which have none of them to refuse).
/// </summary>
IReadOnlyList<EncoderSetting> Ignored => [];
}
/// <summary>An encoding setting an encoder may refuse (<see cref="IVideoEncoderSession.Ignored"/>).</summary>
public enum EncoderSetting
{
RateControl,
Quality,
BitRate,
KeyframeInterval,
BFrames,
}
/// <summary>A family of encoders (Media Foundation on Windows, managed everywhere).</summary>
@@ -2,7 +2,8 @@ namespace Chronos.Core.Video.Managed;
/// <summary>
/// The encoders every platform has (BRIEF §11.3): MJPEG in AVI, JPEG / PNG (8 or 16-bit) / TIFF-16 / linear DNG image
/// sequences, animated GIF and APNG, all written by the in-house codecs. Frames are linear-light buffers at the output
/// sequences, animated GIF and APNG, and one PNG, JPEG or TIFF still (<see cref="EncodeSettings.SingleImage"/>), all
/// written by the in-house codecs. Frames are linear-light buffers at the output
/// size. Single files are written to a temporary sibling and renamed on <see cref="IVideoEncoderSession.Complete"/>;
/// sequences go to a temporary folder renamed the same way, so a cancelled or failed encode leaves nothing behind.
/// AVI and image sequences are constant frame rate: a frame lasting several periods is repeated.
@@ -44,6 +45,7 @@ public sealed class ManagedEncoderProvider : IVideoEncoderProvider
ArgumentNullException.ThrowIfNull(settings);
if (Problem(settings) is { } problem) throw new NotSupportedException(problem);
var name = Capabilities.First(c => c.Codec == settings.Codec).Name;
if (settings.SingleImage) return new StillImageSession(settings, name);
return settings.Codec switch
{
VideoCodec.Mjpeg => new AviMjpegSession(settings, name),
@@ -59,6 +61,7 @@ public sealed class ManagedEncoderProvider : IVideoEncoderProvider
if (s.Width is <= 0 or > MaxDimension || s.Height is <= 0 or > MaxDimension) return $"{s.Width}×{s.Height} is outside 1–{MaxDimension}";
if (s.FrameRate.Numerator <= 0 || s.FrameRate.Denominator <= 0) return "The frame rate must be positive";
if (!BitDepths(s.Codec).Contains(s.BitDepth)) return $"{s.Codec} cannot be written with {s.BitDepth}-bit samples";
if (s.SingleImage && !StillImageSession.Takes(s.Codec)) return $"{s.Codec} cannot be saved as a single image";
return string.IsNullOrWhiteSpace(s.OutputPath) ? "No output path" : null;
}
}
@@ -108,7 +108,8 @@ internal abstract class SingleFileSession : ManagedSession
Finish();
File.Flush(flushToDisk: true);
File.Dispose();
AtomicFile.Commit(_tempPath, Settings.OutputPath);
// The render picked a free name: something that took it meanwhile (a restore) is never overwritten.
AtomicFile.CommitNew(_tempPath, Settings.OutputPath);
}
protected override void Discard()
@@ -201,6 +202,37 @@ internal sealed class ApngSession : SingleFileSession
protected override void Finish() => _encoder.Complete();
}
/// <summary>
/// One frame saved as one image file (owner review 1, R8, "Save frame"; <see cref="EncodeSettings.SingleImage"/>): PNG (8 or
/// 16-bit), JPEG or TIFF (16 or 8-bit) at <see cref="EncodeSettings.OutputPath"/>, written to a temporary sibling and renamed
/// into place on completion like the other single files. A second frame is refused.
/// </summary>
internal sealed class StillImageSession(EncodeSettings settings, string encoderName) : SingleFileSession(settings, encoderName)
{
private bool _written;
/// <summary>The codecs a still is saved with.</summary>
public static bool Takes(VideoCodec codec) => codec is VideoCodec.PngSequence or VideoCodec.JpegSequence or VideoCodec.Tiff16Sequence;
protected override void Write(ImageBuffer frame, long duration90k)
{
if (_written) throw new InvalidOperationException("A still holds one frame");
var bytes = Settings.Codec switch
{
VideoCodec.JpegSequence => JpegEncoder.Encode(frame, JpegOptions(Settings.Quality)),
VideoCodec.PngSequence => PngEncoder.Encode(frame, Settings.BitDepth == 16 ? 16 : 8, CompressionLevel.Optimal),
VideoCodec.Tiff16Sequence => TiffWriter.Write(frame, new TiffWriteOptions { BitsPerSample = Settings.BitDepth == 8 ? 8 : 16 }),
_ => throw new NotSupportedException($"{Settings.Codec} cannot be saved as a single image"),
};
File.Write(bytes);
_written = true;
}
protected override void Finish()
{
}
}
/// <summary>
/// Numbered image files (<c>&lt;folder name&gt;_000001.ext</c>, 1-based, six digits) in the output folder. Files are written
/// (and flushed) into a hidden temporary sibling folder that is renamed to the output folder on completion. Frames are