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;
/// Diagnostics of for the editor's measuring tools and the render log.
public sealed record RenderPreparationReport
{
/// Frames decoded by the preparation pass (0 when cached analysis covered everything needed).
public int MeasuredFrames { get; init; }
public DeflickerDiagnostics? Deflicker { get; init; }
/// Holy-grail transitions (received and ignored steps).
public IReadOnlyList Transitions { get; init; } = [];
/// Largest frame-to-frame change of the holy-grail target, in EV.
public double? MaxTargetStepEv { get; init; }
public double? ShakeRms { get; init; }
public RegionMethod? RegionMethod { get; init; }
public IReadOnlyList Warnings { get; init; } = [];
}
/// Per-source-frame corrections computed once per render (every array has one entry per source frame).
public sealed record RenderCorrections
{
public required int FrameCount { get; init; }
/// Measured log2 luminance (NaN where not measured): the amber curve of the Exposure chart.
public required double[] MeasuredLogLuminance { get; init; }
/// Global exposure correction in EV, including the project's exposure offset.
public required double[] ExposureEv { get; init; }
/// White-balance gains; null when smoothing is off.
public ChannelGains[]? WhiteBalance { get; init; }
/// Sky/land mask; when set, and replace .
public RegionMask? Regions { get; init; }
public double[]? SkyEv { get; init; }
public double[]? LandEv { get; init; }
/// Stabiliser corrections (source → stabilised) in pixels of a -wide frame.
public Affine2D[]? Stabilization { get; init; }
public int StabilizationWidth { get; init; }
public int StabilizationHeight { get; init; }
/// Zoom applied about the centre so stabilisation borders stay outside the picture (1 = none).
public double StabilizationZoom { get; init; } = 1;
public RenderPreparationReport Report { get; init; } = new();
/// Target log2 luminance (measured + correction): the accent curve of the Exposure chart.
public double[] TargetLogLuminance()
{
var target = new double[FrameCount];
for (var i = 0; i < FrameCount; i++) target[i] = MeasuredLogLuminance[i] + ExposureEv[i];
return target;
}
/// The stabiliser correction of frame for a frame of ×.
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();
}
}
///
/// 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 provides are reused; the rest is measured on frames decoded at
/// one at a time (memory does not grow with the sequence).
///
/// - Modules switch on only when their setting resolves to true; Auto without advice changes nothing.
/// - 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.
/// - Stabilisation analyses the included frames only and zooms in by 1 / crop scale (at most 1 / 0.75) to hide borders.
///
///
public static class RenderPreparation
{
/// Smallest stabilisation crop scale compensated by zooming; below it borders may show.
public const double MinimumCropScale = 0.75;
/// Region masks below this confidence are not used when the region mode is Auto.
public const double MinimumRegionConfidence = 0.3;
public static async Task PrepareAsync(RenderInput input, RenderOptions? options = null, IProgress? 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();
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 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,
},
};
}
/// Corrections for every source frame (identity for excluded ones) with the frame size they are measured in.
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 Included(IReadOnlyList 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(n);
for (var i = 0; i < n; i++)
{
if (!skip[i]) result.Add(i);
}
return result;
}
/// A copy of a cached series with excluded frames marked unusable, or null when it does not fit the sequence.
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 SegmentAsync(IRenderFrameSource source, List 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(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();
}
}
/// Resizes to the given size (disposing it) when a source returns frames of varying size.
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();
}
}
/// One sequential pass that measures whatever the cache did not provide.
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 included, int longEdge, IProgress? 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;
}
}
/// False when the frames are too small to stabilise.
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 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 values)
{
double sum = 0;
foreach (var v in values) sum += v;
return sum;
}
}
}