feat(export): preset resolution with the Custom rule, output naming and estimates

ExportResolver applies overrides and names the result after the preset
it equals (or custom); ExportNaming expands the name template with
collision suffixes; ExportEstimator predicts size and time from a
calibratable throughput model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 10:48:34 +00:00
1 parent b3801961aa
commit 262a0455db
6 files changed
+779

No files matched your search

+145
View File
@@ -0,0 +1,145 @@
using Titano.Core.Video;
namespace Titano.Core.Export;
/// <summary>What a render will do, in the units the estimates need.</summary>
/// <param name="OutputFrames">Distinct output pictures (planned frames).</param>
/// <param name="OutputPeriods">Output frame periods (pictures repeated on constant-rate outputs).</param>
/// <param name="DurationSeconds">Video duration.</param>
/// <param name="Width">Output width.</param>
/// <param name="Height">Output height.</param>
/// <param name="WorkingPixels">Pixels of each decoded source frame.</param>
/// <param name="FlowFrames">Output frames that need optical flow (synthesised or motion-blurred).</param>
/// <param name="AnalysisFrames">Frames read by the preparation pass (0 when cached analysis covers everything).</param>
/// <param name="HardwareEncoder">True when a hardware encoder is expected.</param>
public sealed record ExportWorkload(
int OutputFrames,
int OutputPeriods,
double DurationSeconds,
int Width,
int Height,
long WorkingPixels,
int FlowFrames,
int AnalysisFrames,
bool HardwareEncoder);
/// <summary>Estimated output size and render time.</summary>
public sealed record ExportEstimate(long Bytes, TimeSpan Time);
/// <summary>
/// Throughput of the stages on this machine, in megapixels (or frames) per second. Defaults are conservative figures
/// for a 4-core desktop; <see cref="Calibrate"/> folds the measured time of a finished render into <see cref="Scale"/>.
/// </summary>
public sealed record ThroughputModel
{
public static ThroughputModel Default { get; } = new();
public double DecodeMegapixelsPerSecond { get; init; } = 80;
/// <summary>Exposure, geometry and stacking per working-size pixel.</summary>
public double ProcessMegapixelsPerSecond { get; init; } = 60;
/// <summary>Optical flow plus synthesis or blur per output pixel.</summary>
public double FlowMegapixelsPerSecond { get; init; } = 5;
public double AnalysisFramesPerSecond { get; init; } = 40;
public double HardwareEncodeMegapixelsPerSecond { get; init; } = 400;
public double SoftwareVideoEncodeMegapixelsPerSecond { get; init; } = 50;
public double JpegEncodeMegapixelsPerSecond { get; init; } = 60;
public double PngEncodeMegapixelsPerSecond { get; init; } = 12;
public double TiffEncodeMegapixelsPerSecond { get; init; } = 25;
public double GifEncodeMegapixelsPerSecond { get; init; } = 20;
/// <summary>Machine factor learnt from finished renders (2 = twice as fast as the defaults).</summary>
public double Scale { get; init; } = 1;
/// <summary>Moves <see cref="Scale"/> towards the ratio of a predicted to an actual render time.</summary>
/// <param name="weight">0 keeps the old scale, 1 adopts the new measurement entirely.</param>
public ThroughputModel Calibrate(TimeSpan predicted, TimeSpan actual, double weight = 0.5)
{
if (predicted <= TimeSpan.Zero || actual <= TimeSpan.Zero) return this;
var ratio = predicted.TotalSeconds / actual.TotalSeconds;
return this with { Scale = double.Clamp(Scale * double.Pow(ratio, double.Clamp(weight, 0, 1)), 0.02, 50) };
}
internal double EncodeMegapixelsPerSecond(VideoCodec codec, bool hardware) => codec switch
{
VideoCodec.H264 or VideoCodec.Hevc or VideoCodec.Av1 => hardware ? HardwareEncodeMegapixelsPerSecond : SoftwareVideoEncodeMegapixelsPerSecond,
VideoCodec.Mjpeg or VideoCodec.JpegSequence => JpegEncodeMegapixelsPerSecond,
VideoCodec.PngSequence or VideoCodec.Apng => PngEncodeMegapixelsPerSecond,
VideoCodec.Gif => GifEncodeMegapixelsPerSecond,
_ => TiffEncodeMegapixelsPerSecond,
};
}
/// <summary>
/// Output size and render time estimates for the Export tab. Video codecs: bit rate × duration plus 1 % container
/// overhead. Frame-based outputs: bits per pixel typical of photographic time-lapse content — JPEG by quality
/// (≈1 bpp at 50 to ≈9 bpp at 100), PNG 12/30 bpp (8/16-bit), TIFF-16 30 bpp, DNG 26 bpp, GIF 2.5 bpp for the first
/// frame and 1.2 bpp per difference frame, APNG 10 and 6 bpp — times the pictures written (constant-rate outputs repeat
/// held pictures).
/// </summary>
public static class ExportEstimator
{
private static readonly (int Quality, double Bpp)[] JpegBits = [(1, 0.3), (50, 1.0), (75, 1.6), (85, 2.2), (90, 2.8), (95, 4.0), (100, 9.0)];
public static ExportEstimate Estimate(ResolvedExport export, ExportWorkload workload, ThroughputModel? model = null)
{
ArgumentNullException.ThrowIfNull(export);
ArgumentNullException.ThrowIfNull(workload);
return new ExportEstimate(EstimateBytes(export, workload), EstimateTime(export.Codec, workload, model ?? ThroughputModel.Default));
}
public static long EstimateBytes(ResolvedExport export, ExportWorkload w)
{
ArgumentNullException.ThrowIfNull(export);
ArgumentNullException.ThrowIfNull(w);
double pixels = (double)w.Width * w.Height;
var bits = export.Codec switch
{
VideoCodec.H264 or VideoCodec.Hevc or VideoCodec.Av1 => export.EffectiveBitRate(w.Width, w.Height) * w.DurationSeconds * 1.01,
VideoCodec.Mjpeg => (JpegBitsPerPixel(export.Quality) * pixels + 24 * 8) * w.OutputPeriods,
VideoCodec.JpegSequence => JpegBitsPerPixel(export.Quality) * pixels * w.OutputPeriods,
VideoCodec.PngSequence => (export.BitDepth > 8 ? 30 : 12) * pixels * w.OutputPeriods,
VideoCodec.Tiff16Sequence => (export.BitDepth > 8 ? 30 : 12) * pixels * w.OutputPeriods,
VideoCodec.LinearDngSequence => 26 * pixels * w.OutputPeriods,
VideoCodec.Gif => w.OutputFrames > 0 ? (2.5 + 1.2 * (w.OutputFrames - 1)) * pixels : 0,
VideoCodec.Apng => w.OutputFrames > 0 ? (10 + 6.0 * (w.OutputFrames - 1)) * pixels : 0,
_ => 0,
};
return (long)double.Ceiling(bits / 8);
}
public static TimeSpan EstimateTime(VideoCodec codec, ExportWorkload w, ThroughputModel model)
{
ArgumentNullException.ThrowIfNull(w);
ArgumentNullException.ThrowIfNull(model);
var outputMp = (double)w.Width * w.Height / 1e6;
var workingMp = w.WorkingPixels / 1e6;
var seconds = w.AnalysisFrames / model.AnalysisFramesPerSecond
+ w.OutputFrames * (workingMp / model.DecodeMegapixelsPerSecond + workingMp / model.ProcessMegapixelsPerSecond
+ outputMp / model.EncodeMegapixelsPerSecond(codec, w.HardwareEncoder))
+ w.FlowFrames * outputMp / model.FlowMegapixelsPerSecond;
return TimeSpan.FromSeconds(seconds / model.Scale);
}
/// <summary>Typical JPEG bits per pixel at an IJG quality, piecewise linear between measured points.</summary>
public static double JpegBitsPerPixel(int quality)
{
quality = int.Clamp(quality, 1, 100);
for (var i = 1; i < JpegBits.Length; i++)
{
var (q1, b1) = JpegBits[i];
if (quality > q1) continue;
var (q0, b0) = JpegBits[i - 1];
return b0 + (b1 - b0) * (quality - q0) / (q1 - q0);
}
return JpegBits[^1].Bpp;
}
}
+142
View File
@@ -0,0 +1,142 @@
using System.Globalization;
using System.Text;
using Titano.Core.Naming;
using Titano.Core.Video;
namespace Titano.Core.Export;
/// <summary>Values of the export name tokens.</summary>
public sealed record ExportNameContext
{
/// <summary>Shoot date of the sequence (first capture), or the render date when unknown.</summary>
public required DateTime Date { get; init; }
public string? Title { get; init; }
/// <summary>Display name of the preset in the user's language ("Custom" for custom values).</summary>
public required string PresetName { get; init; }
public int Width { get; init; }
public int Height { get; init; }
public Rational FrameRate { get; init; } = new(30, 1);
public required VideoCodec Codec { get; init; }
}
/// <summary>An expanded export name and any template problems.</summary>
public sealed record ExportName(string Name, IReadOnlyList<TemplateError> Errors)
{
public bool IsValid => Errors.Count == 0;
}
/// <summary>
/// Output names from <see cref="Project.ExportSettings.NameTemplate"/> (BRIEF §11.5). Tokens: <c>{date}</c> (optionally
/// <c>{date:yyyyMMdd}</c>), <c>{title}</c>, <c>{preset}</c>, <c>{width}</c>, <c>{height}</c>, <c>{fps}</c>, <c>{codec}</c>;
/// <c>{{</c>/<c>}}</c> are literal braces. The result is sanitised like <see cref="PathTemplate"/>; an existing file or
/// folder gets a " (2)", " (3)"… suffix.
/// </summary>
public static class ExportNaming
{
public static IReadOnlyList<string> Tokens { get; } = ["date", "title", "preset", "width", "height", "fps", "codec"];
/// <summary>Name used when a template expands to nothing.</summary>
public const string FallbackName = "Render";
/// <summary>Short, file-name safe codec label ("H.264", "HEVC", "PNG"…).</summary>
public static string CodecLabel(VideoCodec codec) => codec switch
{
VideoCodec.H264 => "H.264",
VideoCodec.Hevc => "HEVC",
VideoCodec.Av1 => "AV1",
VideoCodec.Mjpeg => "MJPEG",
VideoCodec.JpegSequence => "JPEG",
VideoCodec.PngSequence => "PNG",
VideoCodec.Tiff16Sequence => "TIFF",
VideoCodec.LinearDngSequence => "DNG",
VideoCodec.Gif => "GIF",
VideoCodec.Apng => "APNG",
_ => codec.ToString(),
};
/// <summary>Expands <paramref name="template"/> into a sanitised name without extension.</summary>
public static ExportName Expand(string template, ExportNameContext context)
{
ArgumentNullException.ThrowIfNull(template);
ArgumentNullException.ThrowIfNull(context);
var errors = new List<TemplateError>();
var sb = new StringBuilder();
for (var i = 0; i < template.Length; i++)
{
var c = template[i];
if ((c == '{' || c == '}') && i + 1 < template.Length && template[i + 1] == c)
{
sb.Append(c);
i++;
continue;
}
if (c == '}')
{
errors.Add(new TemplateError(i, "UnopenedBrace", null));
continue;
}
if (c != '{')
{
sb.Append(c);
continue;
}
var close = template.IndexOf('}', i + 1);
if (close < 0)
{
errors.Add(new TemplateError(i, "UnclosedBrace", null));
sb.Append(template, i, template.Length - i);
break;
}
var body = template[(i + 1)..close];
var colon = body.IndexOf(':', StringComparison.Ordinal);
var name = (colon < 0 ? body : body[..colon]).Trim().ToLowerInvariant();
var format = colon < 0 ? null : body[(colon + 1)..];
if (Value(name, format, context) is { } value) sb.Append(value.Replace('/', '-').Replace('\\', '-'));
else errors.Add(new TemplateError(i, name.Length == 0 ? "EmptyToken" : "UnknownToken", name));
i = close;
}
var result = PathTemplate.SanitizeSegment(sb.ToString());
return new ExportName(result.Length == 0 ? FallbackName : result, errors);
}
/// <summary>
/// Full output path inside <paramref name="folder"/>: the expanded name plus the codec's extension, or the bare name
/// for image sequences (a folder), made unique against existing files and folders.
/// </summary>
public static string OutputPath(string folder, string template, ExportNameContext context)
{
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
var name = Expand(template, context).Name;
var extension = VideoCodecInfo.DefaultContainer(context.Codec) == ContainerFormat.ImageSequence ? string.Empty : VideoCodecInfo.FileExtension(context.Codec);
return Unique(folder, name, extension);
}
/// <summary>"name.ext", or "name (2).ext", "name (3).ext"… when a file or folder of that name exists.</summary>
public static string Unique(string folder, string name, string extension)
{
for (var n = 1; ; n++)
{
var candidate = Path.Combine(folder, (n == 1 ? name : string.Create(CultureInfo.InvariantCulture, $"{name} ({n})")) + extension);
if (!File.Exists(candidate) && !Directory.Exists(candidate)) return candidate;
}
}
private static string? Value(string token, string? format, ExportNameContext c)
{
var inv = CultureInfo.InvariantCulture;
return token switch
{
"date" => c.Date.ToString(format ?? "yyyy-MM-dd", inv),
"title" => c.Title ?? string.Empty,
"preset" => c.PresetName,
"width" => c.Width.ToString(format, inv),
"height" => c.Height.ToString(format, inv),
"fps" => c.FrameRate.ToString(),
"codec" => CodecLabel(c.Codec),
_ => null,
};
}
}
+229
View File
@@ -0,0 +1,229 @@
using Titano.Core.Project;
using Titano.Core.Video;
namespace Titano.Core.Export;
/// <summary>Export values after applying a project's overrides to its preset (BRIEF §11.4).</summary>
public sealed record ResolvedExport
{
/// <summary>Id of the preset whose values these are, or <see cref="ExportResolver.CustomId"/>.</summary>
public required string PresetId { get; init; }
/// <summary>Id of the preset the overrides were applied to.</summary>
public required string BasePresetId { get; init; }
/// <summary>Localisation key of the effective preset's name; null when custom.</summary>
public string? NameKey { get; init; }
public bool IsCustom => PresetId == ExportResolver.CustomId;
public required VideoCodec Codec { get; init; }
public ContainerFormat Container => VideoCodecInfo.DefaultContainer(Codec);
public CodecProfile Profile { get; init; }
public int BitDepth { get; init; } = 8;
/// <summary>Output width; 0 derives it from the height and the aspect, or from the source.</summary>
public int Width { get; init; }
/// <summary>Output height; 0 derives it from the width and the aspect, or from the source.</summary>
public int Height { get; init; }
public Rational FrameRate { get; init; } = new(30, 1);
/// <summary>Fixed bit rate in bit/s; 0 = <see cref="BitsPerPixel"/> at the render size.</summary>
public long BitRate { get; init; }
public double BitsPerPixel { get; init; }
/// <summary>Key-frame distance in frames.</summary>
public int GopFrames { get; init; }
public int BFrames { get; init; }
public int Quality { get; init; } = 92;
public RateControl RateControl { get; init; } = RateControl.Vbr;
/// <summary>Specific encoder name requested by the user, or null.</summary>
public string? Encoder { get; init; }
/// <summary>Localisation keys of ignored or invalid override values.</summary>
public IReadOnlyList<string> Warnings { get; init; } = [];
/// <summary>Average bit rate for a render of <paramref name="width"/>×<paramref name="height"/>.</summary>
public long EffectiveBitRate(int width, int height)
{
if (BitRate > 0) return BitRate;
var bpp = BitsPerPixel > 0 ? BitsPerPixel : ExportPreset.DefaultBitsPerPixel(Codec);
return (long)double.Round(bpp * width * height * FrameRate.Value);
}
public EncodeSettings ToEncodeSettings(string outputPath, int width, int height) => new()
{
OutputPath = outputPath,
Codec = Codec,
Width = width,
Height = height,
FrameRate = FrameRate,
Profile = Profile,
BitDepth = BitDepth,
RateControl = RateControl,
BitRate = EffectiveBitRate(width, height),
Quality = Quality,
GopLength = GopFrames,
BFrames = BFrames,
EncoderName = Encoder,
};
}
/// <summary>
/// Applies <see cref="ExportOverrides"/> to the selected preset and names the result: the preset's id when the values
/// equal it (or equal another preset), <see cref="CustomId"/> otherwise. Editing any value therefore flips the name to
/// "Custom" and editing it back restores the preset name. Unknown or contradictory override values are ignored with a
/// warning key.
/// </summary>
public static class ExportResolver
{
public const string CustomId = "custom";
/// <summary>Preset used when none is selected, the stored id is unknown or the selection is "custom".</summary>
public const string DefaultPresetId = "1080p-h264";
public static ResolvedExport Resolve(ExportSettings settings, IReadOnlyList<ExportPreset>? presets = null)
{
ArgumentNullException.ThrowIfNull(settings);
presets ??= ExportPresets.BuiltIn;
var warnings = new List<string>();
var id = settings.Preset.Resolve(DefaultPresetId);
var basePreset = Find(presets, id) ?? Find(presets, DefaultPresetId) ?? presets.FirstOrDefault()
?? throw new ArgumentException("No presets", nameof(presets));
if (!basePreset.Id.Equals(id, StringComparison.OrdinalIgnoreCase) && !id.Equals(CustomId, StringComparison.OrdinalIgnoreCase))
warnings.Add("Export.Warning.UnknownPreset");
var values = Apply(FromPreset(basePreset), settings.Overrides, warnings);
var match = Matches(values, FromPreset(basePreset)) ? basePreset : presets.FirstOrDefault(p => Matches(values, FromPreset(p)));
return values with
{
PresetId = match?.Id ?? CustomId,
BasePresetId = basePreset.Id,
NameKey = match?.NameKey,
Warnings = warnings,
};
}
/// <summary>The preset's own values (no overrides).</summary>
public static ResolvedExport FromPreset(ExportPreset preset)
{
ArgumentNullException.ThrowIfNull(preset);
return new ResolvedExport
{
PresetId = preset.Id,
BasePresetId = preset.Id,
NameKey = preset.NameKey,
Codec = preset.Codec,
Profile = preset.Profile,
BitDepth = preset.BitDepth,
Width = preset.Width,
Height = preset.Height,
FrameRate = preset.FrameRate,
BitRate = preset.BitRate,
BitsPerPixel = preset.BitsPerPixel,
GopFrames = int.Max(1, (int)double.Round(preset.GopSeconds * preset.FrameRate.Value)),
BFrames = preset.BFrames,
Quality = preset.Quality,
};
}
/// <summary>Parses a codec name or alias ("h264", "H.265", "hevc", "png", "tiff16", "dng"…).</summary>
public static bool TryParseCodec(string? text, out VideoCodec codec)
{
codec = default;
if (string.IsNullOrWhiteSpace(text)) return false;
var key = text.Trim().ToLowerInvariant().Replace(".", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal).Replace(" ", string.Empty, StringComparison.Ordinal);
VideoCodec? parsed = key switch
{
"h264" or "avc" => VideoCodec.H264,
"h265" or "hevc" => VideoCodec.Hevc,
"av1" => VideoCodec.Av1,
"mjpeg" or "mjpg" => VideoCodec.Mjpeg,
"jpeg" or "jpg" or "jpegsequence" => VideoCodec.JpegSequence,
"png" or "pngsequence" => VideoCodec.PngSequence,
"tiff" or "tif" or "tiff16" or "tiff16sequence" => VideoCodec.Tiff16Sequence,
"dng" or "lineardng" or "lineardngsequence" => VideoCodec.LinearDngSequence,
"gif" => VideoCodec.Gif,
"apng" => VideoCodec.Apng,
_ => null,
};
if (parsed is null) return false;
codec = parsed.Value;
return true;
}
private static ExportPreset? Find(IReadOnlyList<ExportPreset> presets, string id) =>
presets.FirstOrDefault(p => p.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
private static ResolvedExport Apply(ResolvedExport v, ExportOverrides o, List<string> warnings)
{
if (o.Codec is not null)
{
if (TryParseCodec(o.Codec, out var codec))
{
if (codec != v.Codec) v = v with { Codec = codec, Profile = CodecProfile.Auto, BitRate = 0, BitsPerPixel = 0 };
}
else
{
warnings.Add("Export.Warning.UnknownCodec");
}
}
if (o.Container is not null && !ContainerMatches(o.Container, v.Container)) warnings.Add("Export.Warning.ContainerIgnored");
if (o.Profile is not null)
{
if (Enum.TryParse<CodecProfile>(o.Profile, ignoreCase: true, out var profile) && Enum.IsDefined(profile)) v = v with { Profile = profile };
else warnings.Add("Export.Warning.UnknownProfile");
}
if (o.BitDepth is { } depth) v = v with { BitDepth = depth };
if (o.Width is { } width) v = v with { Width = int.Max(0, width) };
if (o.Height is { } height) v = v with { Height = int.Max(0, height) };
if (o.FrameRate is not null)
{
if (FrameRateText.TryParse(o.FrameRate, out var rate))
{
// A preset's GOP is defined in seconds: keep its duration at the new rate unless the GOP is overridden too.
var seconds = v.GopFrames / v.FrameRate.Value;
v = v with { FrameRate = rate, GopFrames = int.Max(1, (int)double.Round(seconds * rate.Value)) };
}
else
{
warnings.Add("Export.Warning.UnknownFrameRate");
}
}
if (o.BitRate is { } bitRate) v = v with { BitRate = long.Max(0, bitRate) };
if (o.GopFrames is { } gop) v = v with { GopFrames = int.Max(1, gop) };
if (o.BFrames is { } bFrames) v = v with { BFrames = int.Max(0, bFrames) };
if (o.Quality is { } quality) v = v with { Quality = int.Clamp(quality, 1, 100) };
if (o.RateControl is not null)
{
if (Enum.TryParse<RateControl>(o.RateControl, ignoreCase: true, out var rc) && Enum.IsDefined(rc)) v = v with { RateControl = rc };
else warnings.Add("Export.Warning.UnknownRateControl");
}
if (o.Encoder is not null) v = v with { Encoder = string.IsNullOrWhiteSpace(o.Encoder) ? null : o.Encoder };
return v;
}
private static bool ContainerMatches(string text, ContainerFormat container) =>
Enum.TryParse<ContainerFormat>(text, ignoreCase: true, out var parsed) && parsed == container;
/// <summary>Equal export values; bit rates compare as effective rates when the size is fixed.</summary>
private static bool Matches(ResolvedExport a, ResolvedExport b)
{
if (a.Codec != b.Codec || a.Profile != b.Profile || a.BitDepth != b.BitDepth || a.Width != b.Width || a.Height != b.Height
|| !FrameRateText.AreEqual(a.FrameRate, b.FrameRate) || a.GopFrames != b.GopFrames || a.BFrames != b.BFrames
|| a.Quality != b.Quality || a.RateControl != b.RateControl || a.Encoder != b.Encoder) return false;
return a.Width > 0 && a.Height > 0
? a.EffectiveBitRate(a.Width, a.Height) == b.EffectiveBitRate(b.Width, b.Height)
: a.BitRate == b.BitRate && a.BitsPerPixel == b.BitsPerPixel;
}
}