Files
Chronos/src/Titano.Core/Render/RenderPreparation.cs
T
Claude f78a76513c fix(core): tell value-type Auto settings without advice from an advised default
Auto<T>.Resolve returned default instead of the fallback for value types
because AutoValue cannot be null there. Auto<T> now records HasAdvice;
the render pipeline's ProjectValues workaround and the advisor's
ReasonKey heuristic are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-02 12:26:17 +00:00

460 lines
22 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Diagnostics;
using System.Globalization;
using Titano.Core.Analysis;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Geometry;
using Titano.Core.Motion;
using Titano.Core.Project;
namespace Titano.Core.Render;
/// <summary>Diagnostics of <see cref="RenderPreparation"/> for the editor's measuring tools and the render log.</summary>
public sealed record RenderPreparationReport
{
/// <summary>Frames decoded by the preparation pass (0 when cached analysis covered everything needed).</summary>
public int MeasuredFrames { get; init; }
public DeflickerDiagnostics? Deflicker { get; init; }
/// <summary>Holy-grail transitions (received and ignored steps).</summary>
public IReadOnlyList<ExposureTransition> Transitions { get; init; } = [];
/// <summary>Largest frame-to-frame change of the holy-grail target, in EV.</summary>
public double? MaxTargetStepEv { get; init; }
public double? ShakeRms { get; init; }
public RegionMethod? RegionMethod { get; init; }
public IReadOnlyList<RenderWarning> Warnings { get; init; } = [];
}
/// <summary>Per-source-frame corrections computed once per render (every array has one entry per source frame).</summary>
public sealed record RenderCorrections
{
public required int FrameCount { get; init; }
/// <summary>Measured log2 luminance (NaN where not measured): the amber curve of the Exposure chart.</summary>
public required double[] MeasuredLogLuminance { get; init; }
/// <summary>Global exposure correction in EV, including the project's exposure offset.</summary>
public required double[] ExposureEv { get; init; }
/// <summary>White-balance gains; null when smoothing is off.</summary>
public ChannelGains[]? WhiteBalance { get; init; }
/// <summary>Sky/land mask; when set, <see cref="SkyEv"/> and <see cref="LandEv"/> replace <see cref="ExposureEv"/>.</summary>
public RegionMask? Regions { get; init; }
public double[]? SkyEv { get; init; }
public double[]? LandEv { get; init; }
/// <summary>Stabiliser corrections (source → stabilised) in pixels of a <see cref="StabilizationWidth"/>-wide frame.</summary>
public Affine2D[]? Stabilization { get; init; }
public int StabilizationWidth { get; init; }
public int StabilizationHeight { get; init; }
/// <summary>Zoom applied about the centre so stabilisation borders stay outside the picture (1 = none).</summary>
public double StabilizationZoom { get; init; } = 1;
public RenderPreparationReport Report { get; init; } = new();
/// <summary>Target log2 luminance (measured + correction): the accent curve of the Exposure chart.</summary>
public double[] TargetLogLuminance()
{
var target = new double[FrameCount];
for (var i = 0; i < FrameCount; i++) target[i] = MeasuredLogLuminance[i] + ExposureEv[i];
return target;
}
/// <summary>The stabiliser correction of frame <paramref name="index"/> for a frame of <paramref name="width"/>×<paramref name="height"/>.</summary>
public Affine2D StabilizationAt(int index, int width, int height)
{
if (Stabilization is null) return Affine2D.Identity;
var c = Stabilization[index];
if (c.IsIdentity() || (width == StabilizationWidth && height == StabilizationHeight)) return c;
// Pixel-centre scaling between the two frame sizes: x' = (x + ½)·s − ½.
double sx = (double)width / StabilizationWidth, sy = (double)height / StabilizationHeight;
var toFrame = new Affine2D(sx, 0, 0, sy, (sx - 1) / 2, (sy - 1) / 2);
return toFrame * c * toFrame.Invert();
}
}
/// <summary>
/// The pass over the sequence that a render needs before its first frame (BRIEF §11.1–§11.2): luminance, colour and
/// region series for deflicker / holy grail / white balance / region deflicker, and the stabilisation path. Values the
/// cached <see cref="PrecomputedAnalysis"/> provides are reused; the rest is measured on frames decoded at
/// <see cref="RenderOptions.AnalysisLongEdge"/> one at a time (memory does not grow with the sequence).
/// <list type="bullet">
/// <item>Modules switch on only when their setting resolves to true; Auto without advice changes nothing.</item>
/// <item>Deflicker keeps metadata exposure steps (as intentional offsets); holy grail turns the received steps into
/// ramps (alone, or on top of deflicker); region deflicker gives sky and land their own curves.</item>
/// <item>Stabilisation analyses the included frames only and zooms in by 1 / crop scale (at most 1 / 0.75) to hide borders.</item>
/// </list>
/// </summary>
public static class RenderPreparation
{
/// <summary>Smallest stabilisation crop scale compensated by zooming; below it borders may show.</summary>
public const double MinimumCropScale = 0.75;
/// <summary>Region masks below this confidence are not used when the region mode is Auto.</summary>
public const double MinimumRegionConfidence = 0.3;
public static async Task<RenderCorrections> PrepareAsync(RenderInput input, RenderOptions? options = null, IProgress<RenderProgress>? progress = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(input);
options ??= RenderOptions.Default;
await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding);
var n = input.Source.FrameCount;
if (input.Frames.Count != n) throw new ArgumentException("One metadata entry per source frame is required.", nameof(input));
var exposure = input.Project.Exposure;
var motion = input.Project.Motion;
var cached = input.Analysis;
var warnings = new List<RenderWarning>();
var included = Included(input.Project.ExcludedFrames, n);
var excluded = new bool[n];
Array.Fill(excluded, true);
foreach (var i in included) excluded[i] = false;
var deflicker = exposure.Deflicker.Resolve(false);
var holyGrail = exposure.HolyGrail.Resolve(false);
var regionMode = deflicker ? exposure.Regions.Resolve(RegionMode.Off) : RegionMode.Off;
var whiteBalance = exposure.WhiteBalanceSmoothing.Resolve(false);
var stabilize = motion.Stabilize.Resolve(false);
var smoothing = motion.StabilizeSmoothing.Resolve(new StabilizerOptions().SmoothingSigma);
var luminance = deflicker || holyGrail ? Valid(cached?.LogLuminance, excluded) : null;
var measureLuminance = (deflicker || holyGrail) && luminance is null;
double[]? red = null, green = null, blue = null;
if (whiteBalance && Valid(cached?.MeanRed, excluded) is { } r && Valid(cached?.MeanGreen, excluded) is { } g && Valid(cached?.MeanBlue, excluded) is { } b)
(red, green, blue) = (r, g, b);
var measureColour = whiteBalance && red is null;
RegionMask? mask = null;
double[]? sky = null, land = null;
if (regionMode != RegionMode.Off && cached?.Regions is { } m && Valid(cached.SkyLogLuminance, excluded) is { } s && Valid(cached.LandLogLuminance, excluded) is { } l)
(mask, sky, land) = (m, s, l);
var stabilization = stabilize ? CachedStabilization(cached, n, smoothing) : null;
var measureStabilization = stabilize && stabilization is null;
if (regionMode != RegionMode.Off && mask is null && included.Count > 0)
{
mask = await SegmentAsync(input.Source, included, regionMode, options.AnalysisLongEdge, cancellationToken).ConfigureAwait(false);
if (mask is null) warnings.Add(new RenderWarning("Export.Render.RegionsUnavailable"));
else if (regionMode == RegionMode.Auto && mask.Confidence < MinimumRegionConfidence)
{
warnings.Add(new RenderWarning("Export.Render.RegionsUnreliable", mask.Confidence.ToString("0.00", CultureInfo.InvariantCulture)));
mask = null;
}
}
var measureRegions = mask is not null && sky is null;
var pass = new MeasurementPass(n, measureLuminance, measureColour, measureRegions ? mask : null, measureStabilization, smoothing);
if (pass.Needed)
{
await pass.RunAsync(input.Source, included, options.AnalysisLongEdge, progress, cancellationToken).ConfigureAwait(false);
luminance ??= pass.Luminance;
red ??= pass.Red;
green ??= pass.Green;
blue ??= pass.Blue;
sky ??= pass.Sky;
land ??= pass.Land;
if (measureStabilization)
{
stabilization = pass.SolveStabilization(included, n);
if (stabilization is null) warnings.Add(new RenderWarning("Export.Render.StabilizationUnavailable"));
}
}
return Combine(input, excluded, luminance, red, green, blue, mask, sky, land, stabilization, deflicker, holyGrail, pass.MeasuredFrames, warnings);
}
private static RenderCorrections Combine(RenderInput input, bool[] excluded, double[]? luminance, double[]? red, double[]? green, double[]? blue, RegionMask? mask,
double[]? sky, double[]? land, StabilizationData? stabilization, bool deflicker, bool holyGrail, int measured, List<RenderWarning> warnings)
{
var n = input.Source.FrameCount;
var exposure = input.Project.Exposure;
var ev = new double[n];
double[]? skyEv = null, landEv = null;
DeflickerDiagnostics? diagnostics = null;
HolyGrailResult? hg = null;
if (luminance is not null)
{
var options = new DeflickerOptions
{
Window = int.Max(3, exposure.DeflickerWindow.Resolve(0) is var w and > 0 ? w : RecommendedWindow(luminance)),
Strength = double.Clamp(exposure.DeflickerStrength.Resolve(1.0), 0, 1),
};
var evs = new double?[n];
// Excluded frames (test shots, bumps) must not create exposure steps.
for (var i = 0; i < n; i++) evs[i] = excluded[i] ? null : input.Frames[i].ExposureValue;
if (holyGrail)
{
var transition = exposure.TransitionLength.Resolve(0);
hg = HolyGrailEngine.Compute(luminance, evs, new HolyGrailOptions { TransitionFrames = transition > 0 ? transition : null, Deflicker = options });
}
var offsets = hg?.StepOffsets ?? DeflickerEngine.OffsetsFromExposure(evs);
if (deflicker && hg is not null)
{
Array.Copy(hg.CorrectionEv, ev, n);
diagnostics = hg.Deflicker.Diagnostics;
}
else if (deflicker)
{
var result = DeflickerEngine.Compute(luminance, options, offsets);
Array.Copy(result.CorrectionEv, ev, n);
diagnostics = result.Diagnostics;
}
else if (hg is not null)
{
for (var i = 0; i < n; i++) ev[i] = hg.SmoothedOffsets[i] - hg.StepOffsets[i];
}
if (mask is not null && sky is not null && land is not null)
{
var regions = RegionDeflicker.Compute(sky, land, options, offsets);
skyEv = new double[n];
landEv = new double[n];
for (var i = 0; i < n; i++)
{
var ramp = hg is null ? 0 : hg.SmoothedOffsets[i] - hg.StepOffsets[i];
skyEv[i] = regions.Sky.CorrectionEv[i] + ramp + exposure.ExposureOffsetEv;
landEv[i] = regions.Land.CorrectionEv[i] + ramp + exposure.ExposureOffsetEv;
}
}
}
for (var i = 0; i < n; i++) ev[i] += exposure.ExposureOffsetEv;
ChannelGains[]? gains = red is not null && green is not null && blue is not null ? WhiteBalanceSmoother.Smooth(red, green, blue).Gains : null;
var zoom = 1.0;
if (stabilization is not null)
{
zoom = 1 / double.Max(stabilization.CropScale, MinimumCropScale);
if (stabilization.CropScale < MinimumCropScale)
warnings.Add(new RenderWarning("Export.Render.StabilizationBorders", stabilization.CropScale.ToString("0.00", CultureInfo.InvariantCulture)));
}
var measuredLuminance = luminance ?? NaNs(n);
return new RenderCorrections
{
FrameCount = n,
MeasuredLogLuminance = measuredLuminance,
ExposureEv = ev,
WhiteBalance = gains,
Regions = skyEv is null ? null : mask,
SkyEv = skyEv,
LandEv = landEv,
Stabilization = stabilization?.Corrections,
StabilizationWidth = stabilization?.Width ?? 0,
StabilizationHeight = stabilization?.Height ?? 0,
StabilizationZoom = zoom,
Report = new RenderPreparationReport
{
MeasuredFrames = measured,
Deflicker = diagnostics,
Transitions = hg?.Transitions ?? [],
MaxTargetStepEv = hg?.MaxFrameStepEv,
ShakeRms = stabilization?.ShakeRms,
RegionMethod = skyEv is null ? null : mask!.Method,
Warnings = warnings,
},
};
}
/// <summary>Corrections for every source frame (identity for excluded ones) with the frame size they are measured in.</summary>
private sealed record StabilizationData(Affine2D[] Corrections, int Width, int Height, double CropScale, double ShakeRms);
private static StabilizationData? CachedStabilization(PrecomputedAnalysis? cached, int n, double smoothing)
{
if (cached?.Stabilization is not { } result || result.Corrections.Count != n || cached.StabilizationWidth <= 0 || cached.StabilizationHeight <= 0
|| double.Abs(cached.StabilizationSmoothing - smoothing) > 1e-9) return null;
return new StabilizationData([.. result.Corrections], cached.StabilizationWidth, cached.StabilizationHeight, result.CropScale, result.ShakeRms);
}
private static int RecommendedWindow(double[] luminance)
{
var finite = luminance.Where(double.IsFinite).ToArray();
return finite.Length >= 16 ? FlickerSpectrum.Analyze(finite).RecommendedWindow : DeflickerOptions.Default.Window;
}
private static List<int> Included(IReadOnlyList<int> excluded, int n)
{
var skip = new bool[n];
foreach (var i in excluded)
{
if ((uint)i < (uint)n) skip[i] = true;
}
var result = new List<int>(n);
for (var i = 0; i < n; i++)
{
if (!skip[i]) result.Add(i);
}
return result;
}
/// <summary>A copy of a cached series with excluded frames marked unusable, or null when it does not fit the sequence.</summary>
private static double[]? Valid(double[]? values, bool[] excluded)
{
if (values is null || values.Length != excluded.Length) return null;
var copy = (double[])values.Clone();
for (var i = 0; i < copy.Length; i++)
{
if (excluded[i]) copy[i] = double.NaN;
}
return copy;
}
private static double[] NaNs(int n)
{
var values = new double[n];
Array.Fill(values, double.NaN);
return values;
}
private static async Task<RegionMask?> SegmentAsync(IRenderFrameSource source, List<int> included, RegionMode mode, int longEdge, CancellationToken cancellationToken)
{
var options = new RegionSegmenterOptions
{
// Horizon mode accepts any detected horizon; Luminance mode lets the horizon win only when it is more confident.
MinimumHorizonConfidence = mode switch { RegionMode.Horizon => 0, RegionMode.Luminance => 2, _ => RegionSegmenterOptions.Default.MinimumHorizonConfidence },
};
var count = int.Min(options.MaxFrames, included.Count);
var frames = new List<ImageBuffer>(count);
try
{
for (var k = 0; k < count; k++)
{
var index = included[(int)((long)k * (included.Count - 1) / int.Max(1, count - 1))];
var frame = await source.GetFrameAsync(index, longEdge, DecodePurpose.Analysis, cancellationToken).ConfigureAwait(false);
frames.Add(frames.Count == 0 ? frame : Conform(frame, frames[0].Width, frames[0].Height));
}
return frames[0].Height < 8 ? null : RegionSegmenter.Segment(frames, options);
}
finally
{
foreach (var f in frames) f.Dispose();
}
}
/// <summary>Resizes <paramref name="frame"/> to the given size (disposing it) when a source returns frames of varying size.</summary>
internal static ImageBuffer Conform(ImageBuffer frame, int width, int height)
{
if (frame.Width == width && frame.Height == height) return frame;
try
{
return Resampler.Resize(frame, width, height);
}
finally
{
frame.Dispose();
}
}
/// <summary>One sequential pass that measures whatever the cache did not provide.</summary>
private sealed class MeasurementPass(int n, bool luminance, bool colour, RegionMask? regions, bool stabilization, double smoothing)
{
public bool Needed => luminance || colour || regions is not null || stabilization;
public int MeasuredFrames { get; private set; }
public double[]? Luminance { get; } = luminance ? NaNs(n) : null;
public double[]? Red { get; } = colour ? NaNs(n) : null;
public double[]? Green { get; } = colour ? NaNs(n) : null;
public double[]? Blue { get; } = colour ? NaNs(n) : null;
public double[]? Sky { get; } = regions is not null ? NaNs(n) : null;
public double[]? Land { get; } = regions is not null ? NaNs(n) : null;
private Stabilizer? _stabilizer;
public async Task RunAsync(IRenderFrameSource source, List<int> included, int longEdge, IProgress<RenderProgress>? progress, CancellationToken cancellationToken)
{
var clock = Stopwatch.StartNew();
RegionMask? fitted = null;
var stabilize = stabilization;
try
{
foreach (var index in included)
{
cancellationToken.ThrowIfCancellationRequested();
var frame = await source.GetFrameAsync(index, longEdge, DecodePurpose.Analysis, cancellationToken).ConfigureAwait(false);
using (frame)
{
if (Luminance is not null) Luminance[index] = FrameStatistics.MeasureLogLuminance(frame);
if (Red is not null) (Red[index], Green![index], Blue![index]) = Means(frame);
if (regions is not null && Sky is not null)
{
if (fitted is null || fitted.Width != frame.Width || fitted.Height != frame.Height) fitted = regions.Resample(frame.Width, frame.Height);
(Sky[index], Land![index]) = RegionDeflicker.Measure(frame, fitted);
}
if (stabilize) stabilize = AddToStabilizer(frame);
}
MeasuredFrames++;
if (progress is not null)
{
var elapsed = clock.Elapsed;
var fps = MeasuredFrames / double.Max(elapsed.TotalSeconds, 1e-6);
progress.Report(new RenderProgress(RenderStage.Preparing, MeasuredFrames, included.Count, fps, elapsed,
TimeSpan.FromSeconds((included.Count - MeasuredFrames) / fps)));
}
}
}
catch
{
_stabilizer?.Dispose();
_stabilizer = null;
throw;
}
if (!stabilize)
{
_stabilizer?.Dispose();
_stabilizer = null;
}
}
/// <summary>False when the frames are too small to stabilise.</summary>
private bool AddToStabilizer(ImageBuffer frame)
{
if (_stabilizer is null)
{
if (frame.Width < 16 || frame.Height < 16) return false;
_stabilizer = new Stabilizer(frame.Width, frame.Height, new StabilizerOptions { SmoothingSigma = smoothing });
}
if (frame.Width == _stabilizer.Width && frame.Height == _stabilizer.Height)
{
_stabilizer.AddFrame(frame);
return true;
}
using var resized = Resampler.Resize(frame, _stabilizer.Width, _stabilizer.Height);
_stabilizer.AddFrame(resized);
return true;
}
public StabilizationData? SolveStabilization(List<int> included, int frameCount)
{
var stabilizer = _stabilizer;
_stabilizer = null;
if (stabilizer is null) return null;
using (stabilizer)
{
if (stabilizer.FrameCount == 0) return null;
var result = stabilizer.Solve();
var corrections = new Affine2D[frameCount];
Array.Fill(corrections, Affine2D.Identity);
for (var k = 0; k < included.Count; k++) corrections[included[k]] = result.Corrections[k];
return new StabilizationData(corrections, stabilizer.Width, stabilizer.Height, result.CropScale, result.ShakeRms);
}
}
private static (double R, double G, double B) Means(ImageBuffer image)
{
var count = image.PlaneLength;
var r = Sum(image.Plane(0)) / count;
if (image.Channels < 3) return (r, r, r);
return (r, Sum(image.Plane(1)) / count, Sum(image.Plane(2)) / count);
}
private static double Sum(ReadOnlySpan<float> values)
{
double sum = 0;
foreach (var v in values) sum += v;
return sum;
}
}
}