feat(P1): output program with direction, loops, hold and fades; still frames
Completes the Core side of owner review 1 phase 5 (R8): OutputProgram turns the plan into the emitted entries (reverse, boomerang without a doubled turn, loops, a hold of whole periods, fades split per period over held frames and shortened with a warning when longer than half the program). The render follows the program: star trails accumulate in program order, median/mean windows stay per plan frame in either direction, a boomerang with trails plays forward with a warning, and the fade gain is the last FrameFinish step. Workload and estimates come from the program, so loops and holds show in time and size. A still target (RenderTarget.StillFrame) renders one source frame with every correction and no playback into one PNG, JPEG or TIFF 16-bit file (EncodeSettings.SingleImage, StillImageSession), named by ExportNaming.StillPath and recorded with kind still, fps 0 and duration 0. Refs #21 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d472dfdec1
commit
3c2cce8031
13 files changed
+803
-69
No files matched your search
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
|
||||
@@ -21,8 +22,9 @@ public readonly record struct ProgramEntry(int PlanIndex, long Duration90k, doub
|
||||
/// time grows with <see cref="Count"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Phase 5 groundwork: the API is final; <see cref="Build(IReadOnlyList{PlannedFrame}, PlaybackSettings?, Rational)"/> emits
|
||||
/// the plan forward once, without fades or hold, until the output program parcel completes it.
|
||||
/// 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
|
||||
{
|
||||
@@ -73,9 +75,96 @@ public sealed class OutputProgram
|
||||
ArgumentNullException.ThrowIfNull(frames);
|
||||
if (frameRate.Numerator <= 0 || frameRate.Denominator <= 0) throw new ArgumentOutOfRangeException(nameof(frameRate));
|
||||
var warnings = new List<RenderWarning>();
|
||||
if (playback?.Direction is { } direction && !PlaybackDirection.IsKnown(direction)) warnings.Add(new RenderWarning(DirectionUnknownWarning, direction));
|
||||
var entries = new ProgramEntry[frames.Count];
|
||||
for (var i = 0; i < frames.Count; i++) entries[i] = new ProgramEntry(i, frames[i].Duration90k, 1);
|
||||
return new OutputProgram(entries, warnings);
|
||||
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));
|
||||
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));
|
||||
for (var i = frames.Count - 2; i >= 0; i--) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1));
|
||||
break;
|
||||
default:
|
||||
for (var i = 0; i < frames.Count; i++) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1));
|
||||
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(new ProgramEntry(entry.PlanIndex, boundary - previous, 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));
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -104,6 +106,7 @@ internal sealed class RenderRun : IDisposable
|
||||
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 +132,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,13 +152,16 @@ 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();
|
||||
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();
|
||||
}
|
||||
catch
|
||||
@@ -178,8 +185,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 +207,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 +221,117 @@ internal sealed class RenderRun : IDisposable
|
||||
await RenderWindowStackAsync(stack, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
case StackSetting.StarTrails:
|
||||
// The trails accumulate in program order: a reversed video grows its trails from the end.
|
||||
using (var trails = new StarTrailStacker(StarTrailStacker.DecayForTrailLength(stack.Length > 0 ? stack.Length : double.PositiveInfinity)))
|
||||
{
|
||||
foreach (var planned in _plan.Frames)
|
||||
await RenderProgramAsync(async (index, 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);
|
||||
}
|
||||
using (var frame = await RenderFrameAsync(_plan.Frames[index], blur: false, token).ConfigureAwait(false)) trails.Add(frame);
|
||||
return trails.Result!.Clone();
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
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((index, token) => RenderFrameAsync(_plan.Frames[index], _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 (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<int, 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.PlanIndex, cancellationToken).ConfigureAwait(false);
|
||||
kept = null;
|
||||
if (i + 1 < entries.Count && entries[i + 1].PlanIndex == entry.PlanIndex)
|
||||
{
|
||||
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 (index, 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 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 +474,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 +503,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
|
||||
{
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -29,11 +29,22 @@ public static class RenderRules
|
||||
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)
|
||||
{
|
||||
|
||||
@@ -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("Tooltips.Export.StillNeedsFrame", $"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>
|
||||
|
||||
@@ -107,6 +107,12 @@ public sealed record EncodeSettings
|
||||
|
||||
/// <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>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -201,6 +201,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><folder name>_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
|
||||
|
||||
Reference in new issue
Block a user