Files
Chronos/src/Titano.Core/Render/RenderPipeline.cs
T
Claude 3e146c9f9f feat(settings): make every Settings row real; archive settings, index backups and restore
Settings (UI-01, UI-02, UI-03, UI-09, RF-4):
- New Import, Analysis and Formats pages, in the order of Settings.html. Import holds
  the defaults of new cards (session rules, subfolders, verification, duplicates,
  after-import actions); Analysis the deep-analysis width cap, night and star-field
  thresholds and deep analysis after import or scan; Formats the decode tier of every
  format on this PC with a notice and Store install link per missing codec extension.
- Archive gains thumbnail size and rescan interval; its templates, proxy size and
  thumbnail size are the open archive's own (archive.json) and new archives' defaults.
- Rendering quality, parallelism and background priority now drive the jobs: quality
  maps to preparation size, read-ahead and default flow quality; parallelism sets the
  engine's workers live and caps per-job threads; background priority raises the UI
  thread while Titano is in front.
- Advanced gains Restore (daily backups, dry-run summary, destructive confirmation,
  staged for the next start) and Reset all.
- The naming preview's sample title is a catalog string.

Engine (ENG-03, ENG-04, ENG-06):
- ArchiveService.GetSettingsAsync/UpdateSettingsAsync rewrite archive.json atomically
  under a lease, then the index row; the server endpoint and the desktop use them, and
  the desktop creates archives with Settings › Archive. ThumbnailPolicy in archive.json
  sizes the thumbnails.
- DatabaseBackups: daily VACUUM INTO copies kept x3 on the desktop and on a server on
  SQLite (DatabaseBackupService), staged restore checked and preceded by a fresh copy.
- Maintenance vacuums the SQLite index when 10 % or more is free (dry run reports it).
- JobEngine.SetWorkers; ProcessingOptions.Tune applies host tuning per job.

Archive setup toasts say why in a localized sentence (RF-1).

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

462 lines
21 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.Diagnostics;
using Titano.Core.Export;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Geometry;
using Titano.Core.Motion;
using Titano.Core.Project;
using Titano.Core.Video;
namespace Titano.Core.Render;
/// <summary>
/// Renders sequences (BRIEF §11). For every planned output frame: source frames come from the
/// <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 highlight knee come last, then the encoder. 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>
public sealed class RenderPipeline(IReadOnlyList<IVideoEncoderProvider> encoders, EncoderHost host = EncoderHost.Client)
{
internal const string LogCategory = "Render";
/// <summary>Encoder providers in priority order (client: Media Foundation, then managed; server: managed).</summary>
public IReadOnlyList<IVideoEncoderProvider> Encoders { get; } = encoders ?? throw new ArgumentNullException(nameof(encoders));
public EncoderHost Host { get; } = host;
/// <summary>Geometry, encoder and plan of a target without rendering (Export tab, estimates).</summary>
public RenderSetup Setup(RenderInput input, RenderTarget target, RenderOptions? options = null, RenderCorrections? corrections = null) =>
RenderSetup.Create(input, target, Encoders, Host, options, corrections);
/// <summary>Prepares the sequence and renders one target.</summary>
public async Task<RenderResult> RenderAsync(RenderInput input, RenderTarget target, RenderOptions? options = null, IProgress<RenderProgress>? progress = null,
CancellationToken cancellationToken = default)
{
var corrections = await RenderPreparation.PrepareAsync(input, options, progress, cancellationToken).ConfigureAwait(false);
return await RenderAsync(input, corrections, target, options, progress, cancellationToken).ConfigureAwait(false);
}
/// <summary>Renders one target with corrections prepared earlier (shared by a batch).</summary>
/// <exception cref="RenderException">No encoder can produce the target, or every frame is excluded.</exception>
public async Task<RenderResult> RenderAsync(RenderInput input, RenderCorrections corrections, RenderTarget target, RenderOptions? options = null,
IProgress<RenderProgress>? progress = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(corrections);
ArgumentNullException.ThrowIfNull(target);
options ??= RenderOptions.Default;
if (corrections.FrameCount != input.Source.FrameCount) throw new ArgumentException("The corrections belong to another sequence.", nameof(corrections));
await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding);
cancellationToken.ThrowIfCancellationRequested();
var setup = Setup(input, target, options, corrections);
if (!setup.Encoder.IsReady)
{
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.");
using var run = new RenderRun(input, corrections, setup, options, progress);
return await run.ExecuteAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Renders several targets of one sequence one after the other, preparing the sequence once. A failing target is
/// reported and the batch continues; cancellation stops the batch.
/// </summary>
public async Task<IReadOnlyList<BatchItemResult>> RenderBatchAsync(RenderInput input, IReadOnlyList<RenderTarget> targets, RenderOptions? options = null,
IProgress<RenderProgress>? progress = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(targets);
var corrections = await RenderPreparation.PrepareAsync(input, options, progress, cancellationToken).ConfigureAwait(false);
var results = new List<BatchItemResult>(targets.Count);
foreach (var target in targets)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
results.Add(new BatchItemResult(target, await RenderAsync(input, corrections, target, options, progress, cancellationToken).ConfigureAwait(false), null));
}
catch (Exception ex) when (!(ex is OperationCanceledException && cancellationToken.IsCancellationRequested))
{
Log.Warning(LogCategory, $"Batch target {target.OutputPath} failed", ex);
results.Add(new BatchItemResult(target, null, ex));
}
}
return results;
}
}
/// <summary>State of one render: caches, flow, stacking, the encoder session and the encode in flight.</summary>
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;
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 RenderGeometry _geometry;
private readonly PreparedFrameCache _prepared;
private readonly FlowCache _flows = new(2);
private readonly MotionBlurRenderer _blur = new();
private readonly List<RenderWarning> _warnings = [];
private readonly Stopwatch _clock = new();
private readonly int _workingEdge;
private readonly float? _knee;
private readonly double _targetShutter;
private readonly FlowQuality _flowQuality;
private OpticalFlowEngine? _flowEngine;
private RegionMask? _mask;
private IVideoEncoderSession? _session;
private Task? _encoding;
private int _done;
public RenderRun(RenderInput input, RenderCorrections corrections, RenderSetup setup, RenderOptions options, IProgress<RenderProgress>? progress)
{
_input = input;
_corrections = corrections;
_setup = setup;
_options = options;
_progress = progress;
_plan = setup.Plan;
_geometry = setup.Geometry;
_prepared = new PreparedFrameCache(int.Max(3, options.CacheFrames));
_workingEdge = _geometry.WorkingLongEdge;
var exposure = input.Project.Exposure;
if (exposure.HighlightKnee is { } knee)
{
if (knee is > 0 and < 1) _knee = (float)knee;
else _warnings.Add(new RenderWarning("Export.Render.KneeIgnored", knee.ToString(CultureInfo.InvariantCulture)));
}
var motion = input.Project.Motion;
_targetShutter = double.Clamp(motion.TargetShutterAngle.Resolve(180.0), 0, 360);
_flowQuality = motion.FlowQuality.Resolve(options.DefaultFlowQuality) switch
{
FlowQualitySetting.Draft => FlowQuality.Draft,
FlowQualitySetting.Best => FlowQuality.Best,
_ => FlowQuality.Balanced,
};
}
public async Task<RenderResult> ExecuteAsync(CancellationToken cancellationToken)
{
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}");
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));
session.Complete();
}
catch
{
await ObserveEncodingAsync().ConfigureAwait(false);
throw;
}
finally
{
session.Dispose();
}
_clock.Stop();
var warnings = new List<RenderWarning>(_setup.Warnings);
warnings.AddRange(_corrections.Report.Warnings);
warnings.AddRange(_warnings);
var result = new RenderResult
{
OutputPath = settings.OutputPath,
PresetId = _setup.Target.Export.PresetId,
Codec = settings.Codec,
Width = settings.Width,
Height = settings.Height,
FrameRate = settings.FrameRate,
DurationSeconds = _plan.DurationSeconds,
FrameCount = _plan.Frames.Count,
Bytes = RenderResult.SizeOf(settings.OutputPath),
EncoderName = session.EncoderName,
Hardware = session.IsHardware,
Elapsed = _clock.Elapsed,
Warnings = warnings,
};
Log.Info(RenderPipeline.LogCategory, $"Rendered {result.FrameCount} frames in {result.Elapsed.TotalSeconds:F1} s with {result.EncoderName}: {result.Bytes} bytes");
return result;
}
public void Dispose()
{
_prepared.Dispose();
_flows.Dispose();
_flowEngine?.Dispose();
}
private async Task RenderFramesAsync(CancellationToken cancellationToken)
{
var stack = _input.Project.Stack;
switch (stack.Mode)
{
case StackSetting.Median or StackSetting.Mean:
await RenderWindowStackAsync(stack, cancellationToken).ConfigureAwait(false);
break;
case StackSetting.StarTrails:
using (var trails = new StarTrailStacker(StarTrailStacker.DecayForTrailLength(stack.Length > 0 ? stack.Length : double.PositiveInfinity)))
{
foreach (var planned in _plan.Frames)
{
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);
}
}
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);
}
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>
private async Task RenderWindowStackAsync(StackSettings stack, CancellationToken cancellationToken)
{
var window = int.Max(1, stack.Length);
var half = (window - 1) / 2;
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)
{
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);
}
private async Task EmitStackAsync(TemporalStacker stacker, PlannedFrame planned, CancellationToken cancellationToken)
{
var output = new ImageBuffer(_geometry.OutputWidth, _geometry.OutputHeight, 3, clear: false);
try
{
stacker.Render(output, cancellationToken);
}
catch
{
output.Dispose();
throw;
}
await EmitAsync(output, planned.Duration90k).ConfigureAwait(false);
}
/// <summary>The picture of one planned frame at the output size (a new buffer owned by the caller).</summary>
private async Task<ImageBuffer> RenderFrameAsync(PlannedFrame planned, bool blur, CancellationToken cancellationToken)
{
if (planned.Fraction == 0)
{
var frame = await PreparedAsync(planned.From, cancellationToken).ConfigureAwait(false);
if (blur && BlurPair(planned.From) is { } pair && BlurFraction(pair.From, pair.To, planned.Speed) is var fraction and > 0)
{
var flows = await FlowAsync(pair.From, pair.To, needBackward: false, cancellationToken).ConfigureAwait(false);
frame = await PreparedAsync(planned.From, cancellationToken).ConfigureAwait(false);
return Blurred(frame, flows.Forward, fraction, cancellationToken);
}
return frame.Clone();
}
var pairFlows = await FlowAsync(planned.From, planned.To, needBackward: true, cancellationToken).ConfigureAwait(false);
var a = await PreparedAsync(planned.From, cancellationToken).ConfigureAwait(false);
var b = await PreparedAsync(planned.To, cancellationToken).ConfigureAwait(false);
var synthesised = new ImageBuffer(a.Width, a.Height, a.Channels, clear: false);
try
{
FrameInterpolator.Synthesize(a, b, pairFlows.Forward, pairFlows.Backward!, planned.Fraction, synthesised, cancellationToken: cancellationToken);
var fraction = blur ? BlurFraction(planned.From, planned.To, planned.Speed) : 0;
if (fraction <= 0) return synthesised;
using (synthesised) return Blurred(synthesised, pairFlows.Forward, fraction, cancellationToken);
}
catch
{
synthesised.Dispose();
throw;
}
}
private ImageBuffer Blurred(ImageBuffer source, MotionField flow, double fraction, CancellationToken cancellationToken)
{
var output = new ImageBuffer(source.Width, source.Height, source.Channels, clear: false);
try
{
_blur.Render(source, flow, fraction, output, cancellationToken);
return output;
}
catch
{
output.Dispose();
throw;
}
}
/// <summary>Continuous neighbours whose flow describes the motion at <paramref name="index"/>.</summary>
private (int From, int To)? BlurPair(int index)
{
var next = _plan.NextContinuous(index);
if (next >= 0) return (index, next);
var previous = _plan.PreviousContinuous(index);
return previous >= 0 ? (previous, index) : null;
}
/// <summary>
/// Fraction of the <paramref name="from"/>→<paramref name="to"/> flow to smear: the target shutter is relative to the
/// output period, which spans <paramref name="speed"/> source intervals, and the camera's own exposure already
/// blurred <see cref="ShutterAngle.FromExposure"/> of one interval (√(target² − real²) composition, §11.1).
/// </summary>
private double BlurFraction(int from, int to, double speed)
{
var steps = to - from;
if (steps <= 0) return 0;
var real = 0.0;
var info = _input.Frames[from];
if (info.ExposureTime is > 0 and var exposure && info.CapturedAt is { } t0 && _input.Frames[to].CapturedAt is { } t1 && t1 > t0)
real = double.Min(360, ShutterAngle.FromExposure(exposure, (t1 - t0).TotalSeconds / steps));
return ShutterAngle.BlurFraction(_targetShutter * double.Clamp(double.Abs(speed), 0, MaxBlurSpeed), real) / steps;
}
private async Task<FlowPair> FlowAsync(int from, int to, bool needBackward, CancellationToken cancellationToken)
{
if (_flows.TryGet(from, to, needBackward, out var cached)) return cached;
var a = await PreparedAsync(from, cancellationToken).ConfigureAwait(false);
var b = await PreparedAsync(to, cancellationToken).ConfigureAwait(false);
_flowEngine ??= new OpticalFlowEngine(_flowQuality);
FlowPair flows;
if (needBackward)
{
var (forward, backward) = _flowEngine.ComputeBidirectional(a, b, cancellationToken);
flows = new FlowPair(forward, backward);
}
else
{
flows = new FlowPair(_flowEngine.Compute(a, b, cancellationToken), null);
}
_flows.Add(from, to, flows);
return flows;
}
/// <summary>Source frame <paramref name="index"/> decoded, exposure-corrected and warped to the output size (cached).</summary>
private async Task<ImageBuffer> PreparedAsync(int index, CancellationToken cancellationToken)
{
if (_prepared.TryGet(index, out var cached)) return cached;
var raw = await _input.Source.GetFrameAsync(index, _workingEdge, DecodePurpose.Render, cancellationToken).ConfigureAwait(false);
ImageBuffer prepared;
try
{
raw = Rgb(raw);
ApplyExposure(raw, index);
var settings = _geometry.For(raw.Width, raw.Height, index, _corrections.StabilizationAt(index, raw.Width, raw.Height));
prepared = GeometryStage.Apply(raw, settings, cancellationToken);
}
finally
{
raw.Dispose();
}
_prepared.Add(index, prepared);
return prepared;
}
/// <summary>Gray sources become RGB and alpha is dropped, so every stage and encoder sees three channels.</summary>
private static ImageBuffer Rgb(ImageBuffer frame)
{
if (frame.Channels == 3) return frame;
using (frame)
{
if (frame.Channels == 1) return PixelConvert.GrayToRgb(frame);
var rgb = new ImageBuffer(frame.Width, frame.Height, 3, clear: false);
frame.Data[..(3 * frame.PlaneLength)].CopyTo(rgb.Data);
return rgb;
}
}
private void ApplyExposure(ImageBuffer frame, int index)
{
var gains = _corrections.WhiteBalance?[index];
if (_corrections is { Regions: { } mask, SkyEv: { } sky, LandEv: { } land })
{
if (_mask is null || _mask.Width != frame.Width || _mask.Height != frame.Height) _mask = mask.Resample(frame.Width, frame.Height);
ExposureProcessor.ApplyRegion(frame, _mask.Sky, sky[index], land[index], gains);
return;
}
var ev = _corrections.ExposureEv[index];
if (ev != 0 || (gains is { } g && g != ChannelGains.Identity)) ExposureProcessor.Apply(frame, ev, gains);
}
/// <summary>Applies the knee and hands the frame to the encoder once the previous frame is encoded; owns <paramref name="frame"/>.</summary>
private async Task EmitAsync(ImageBuffer frame, long duration90k)
{
ImageBuffer? preview = null;
try
{
await FlushEncodingAsync().ConfigureAwait(false);
if (_knee is { } knee) ExposureProcessor.Apply(frame, 0, null, knee);
_done++;
if (_options.PreviewInterval > 0 && (_done - 1) % _options.PreviewInterval == 0) preview = Resampler.Thumbnail(frame, _options.PreviewLongEdge);
}
catch
{
frame.Dispose();
throw;
}
var session = _session!;
_encoding = Task.Run(() =>
{
using (frame) session.WriteFrame(frame, duration90k);
}, CancellationToken.None);
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));
}
else
{
preview?.Dispose();
}
}
private double Fps() => _done / double.Max(_clock.Elapsed.TotalSeconds, 1e-6);
/// <summary>Waits for the encode in flight; its failure propagates here (once).</summary>
private async Task FlushEncodingAsync()
{
var encoding = _encoding;
_encoding = null;
if (encoding is not null) await encoding.ConfigureAwait(false);
}
/// <summary>After a failure: waits for the encode in flight and logs (never throws) a second error.</summary>
private async Task ObserveEncodingAsync()
{
try
{
await FlushEncodingAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
Log.Warning(RenderPipeline.LogCategory, "The encoder also failed while the render was stopping", ex);
}
}
}