From 262a0455dbb268f716652c033ddb23d2d548b542 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:48:34 +0000 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Export/ExportEstimate.cs | 145 +++++++++++ src/Titano.Core/Export/ExportNaming.cs | 142 +++++++++++ src/Titano.Core/Export/ExportResolver.cs | 229 ++++++++++++++++++ .../Export/ExportEstimateTests.cs | 61 +++++ .../Export/ExportNamingTests.cs | 71 ++++++ .../Export/ExportResolverTests.cs | 131 ++++++++++ 6 files changed, 779 insertions(+) create mode 100644 src/Titano.Core/Export/ExportEstimate.cs create mode 100644 src/Titano.Core/Export/ExportNaming.cs create mode 100644 src/Titano.Core/Export/ExportResolver.cs create mode 100644 tests/Titano.Core.Tests/Export/ExportEstimateTests.cs create mode 100644 tests/Titano.Core.Tests/Export/ExportNamingTests.cs create mode 100644 tests/Titano.Core.Tests/Export/ExportResolverTests.cs diff --git a/src/Titano.Core/Export/ExportEstimate.cs b/src/Titano.Core/Export/ExportEstimate.cs new file mode 100644 index 00000000..bcd09ba0 --- /dev/null +++ b/src/Titano.Core/Export/ExportEstimate.cs @@ -0,0 +1,145 @@ +using Titano.Core.Video; + +namespace Titano.Core.Export; + +/// What a render will do, in the units the estimates need. +/// Distinct output pictures (planned frames). +/// Output frame periods (pictures repeated on constant-rate outputs). +/// Video duration. +/// Output width. +/// Output height. +/// Pixels of each decoded source frame. +/// Output frames that need optical flow (synthesised or motion-blurred). +/// Frames read by the preparation pass (0 when cached analysis covers everything). +/// True when a hardware encoder is expected. +public sealed record ExportWorkload( + int OutputFrames, + int OutputPeriods, + double DurationSeconds, + int Width, + int Height, + long WorkingPixels, + int FlowFrames, + int AnalysisFrames, + bool HardwareEncoder); + +/// Estimated output size and render time. +public sealed record ExportEstimate(long Bytes, TimeSpan Time); + +/// +/// Throughput of the stages on this machine, in megapixels (or frames) per second. Defaults are conservative figures +/// for a 4-core desktop; folds the measured time of a finished render into . +/// +public sealed record ThroughputModel +{ + public static ThroughputModel Default { get; } = new(); + + public double DecodeMegapixelsPerSecond { get; init; } = 80; + + /// Exposure, geometry and stacking per working-size pixel. + public double ProcessMegapixelsPerSecond { get; init; } = 60; + + /// Optical flow plus synthesis or blur per output pixel. + 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; + + /// Machine factor learnt from finished renders (2 = twice as fast as the defaults). + public double Scale { get; init; } = 1; + + /// Moves towards the ratio of a predicted to an actual render time. + /// 0 keeps the old scale, 1 adopts the new measurement entirely. + 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, + }; +} + +/// +/// 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). +/// +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); + } + + /// Typical JPEG bits per pixel at an IJG quality, piecewise linear between measured points. + 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; + } +} diff --git a/src/Titano.Core/Export/ExportNaming.cs b/src/Titano.Core/Export/ExportNaming.cs new file mode 100644 index 00000000..29fdb9f1 --- /dev/null +++ b/src/Titano.Core/Export/ExportNaming.cs @@ -0,0 +1,142 @@ +using System.Globalization; +using System.Text; +using Titano.Core.Naming; +using Titano.Core.Video; + +namespace Titano.Core.Export; + +/// Values of the export name tokens. +public sealed record ExportNameContext +{ + /// Shoot date of the sequence (first capture), or the render date when unknown. + public required DateTime Date { get; init; } + + public string? Title { get; init; } + + /// Display name of the preset in the user's language ("Custom" for custom values). + 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; } +} + +/// An expanded export name and any template problems. +public sealed record ExportName(string Name, IReadOnlyList Errors) +{ + public bool IsValid => Errors.Count == 0; +} + +/// +/// Output names from (BRIEF §11.5). Tokens: {date} (optionally +/// {date:yyyyMMdd}), {title}, {preset}, {width}, {height}, {fps}, {codec}; +/// {{/}} are literal braces. The result is sanitised like ; an existing file or +/// folder gets a " (2)", " (3)"… suffix. +/// +public static class ExportNaming +{ + public static IReadOnlyList Tokens { get; } = ["date", "title", "preset", "width", "height", "fps", "codec"]; + + /// Name used when a template expands to nothing. + public const string FallbackName = "Render"; + + /// Short, file-name safe codec label ("H.264", "HEVC", "PNG"…). + 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(), + }; + + /// Expands into a sanitised name without extension. + public static ExportName Expand(string template, ExportNameContext context) + { + ArgumentNullException.ThrowIfNull(template); + ArgumentNullException.ThrowIfNull(context); + var errors = new List(); + 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); + } + + /// + /// Full output path inside : the expanded name plus the codec's extension, or the bare name + /// for image sequences (a folder), made unique against existing files and folders. + /// + 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); + } + + /// "name.ext", or "name (2).ext", "name (3).ext"… when a file or folder of that name exists. + 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, + }; + } +} diff --git a/src/Titano.Core/Export/ExportResolver.cs b/src/Titano.Core/Export/ExportResolver.cs new file mode 100644 index 00000000..36be3b54 --- /dev/null +++ b/src/Titano.Core/Export/ExportResolver.cs @@ -0,0 +1,229 @@ +using Titano.Core.Project; +using Titano.Core.Video; + +namespace Titano.Core.Export; + +/// Export values after applying a project's overrides to its preset (BRIEF §11.4). +public sealed record ResolvedExport +{ + /// Id of the preset whose values these are, or . + public required string PresetId { get; init; } + + /// Id of the preset the overrides were applied to. + public required string BasePresetId { get; init; } + + /// Localisation key of the effective preset's name; null when custom. + 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; + + /// Output width; 0 derives it from the height and the aspect, or from the source. + public int Width { get; init; } + + /// Output height; 0 derives it from the width and the aspect, or from the source. + public int Height { get; init; } + + public Rational FrameRate { get; init; } = new(30, 1); + + /// Fixed bit rate in bit/s; 0 = at the render size. + public long BitRate { get; init; } + + public double BitsPerPixel { get; init; } + + /// Key-frame distance in frames. + public int GopFrames { get; init; } + + public int BFrames { get; init; } + + public int Quality { get; init; } = 92; + + public RateControl RateControl { get; init; } = RateControl.Vbr; + + /// Specific encoder name requested by the user, or null. + public string? Encoder { get; init; } + + /// Localisation keys of ignored or invalid override values. + public IReadOnlyList Warnings { get; init; } = []; + + /// Average bit rate for a render of ×. + 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, + }; +} + +/// +/// Applies to the selected preset and names the result: the preset's id when the values +/// equal it (or equal another preset), 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. +/// +public static class ExportResolver +{ + public const string CustomId = "custom"; + + /// Preset used when none is selected, the stored id is unknown or the selection is "custom". + public const string DefaultPresetId = "1080p-h264"; + + public static ResolvedExport Resolve(ExportSettings settings, IReadOnlyList? presets = null) + { + ArgumentNullException.ThrowIfNull(settings); + presets ??= ExportPresets.BuiltIn; + var warnings = new List(); + 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, + }; + } + + /// The preset's own values (no overrides). + 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, + }; + } + + /// Parses a codec name or alias ("h264", "H.265", "hevc", "png", "tiff16", "dng"…). + 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 presets, string id) => + presets.FirstOrDefault(p => p.Id.Equals(id, StringComparison.OrdinalIgnoreCase)); + + private static ResolvedExport Apply(ResolvedExport v, ExportOverrides o, List 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(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(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(text, ignoreCase: true, out var parsed) && parsed == container; + + /// Equal export values; bit rates compare as effective rates when the size is fixed. + 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; + } +} diff --git a/tests/Titano.Core.Tests/Export/ExportEstimateTests.cs b/tests/Titano.Core.Tests/Export/ExportEstimateTests.cs new file mode 100644 index 00000000..7da50b5e --- /dev/null +++ b/tests/Titano.Core.Tests/Export/ExportEstimateTests.cs @@ -0,0 +1,61 @@ +using Titano.Core.Export; +using Titano.Core.Video; +using Titano.Testing; + +namespace Titano.Core.Tests.Export; + +public sealed class ExportEstimateTests +{ + private static ExportWorkload Workload(int frames = 600, int width = 3840, int height = 2160, int flow = 0, int analysis = 0, bool hardware = true) => + new(frames, frames, frames / 24.0, width, height, (long)width * height, flow, analysis, hardware); + + private static ResolvedExport Preset(string id) => ExportResolver.FromPreset(ExportPresets.Find(id)!); + + [Test] + public void VideoSizeIsBitRateTimesDuration() + { + var export = Preset("4k-h264"); + var bytes = ExportEstimator.EstimateBytes(export, Workload()); + var expected = 0.10 * 3840 * 2160 * 24 * 25 / 8 * 1.01; + Assert.Approximately(expected, bytes, 1); + Assert.InRange(bytes / 1e6, 60, 70); // ≈ 63 MB for 25 s of 4K at 19.9 Mb/s + } + + [Test] + public void FrameBasedSizesScaleWithPicturesAndDepth() + { + var png8 = ExportResolver.FromPreset(ExportPresets.Find("png-sequence")!) with { Width = 1920, Height = 1080 }; + var png16 = png8 with { BitDepth = 16 }; + var w = Workload(240, 1920, 1080) with { OutputPeriods = 480 }; + Assert.Equal(2 * ExportEstimator.EstimateBytes(png8, Workload(240, 1920, 1080)), ExportEstimator.EstimateBytes(png8, w)); + Assert.Greater(ExportEstimator.EstimateBytes(png16, w), 2 * ExportEstimator.EstimateBytes(png8, w)); + var gif = Preset("gif-preview"); + Assert.Less(ExportEstimator.EstimateBytes(gif, Workload(240, 480, 270)), ExportEstimator.EstimateBytes(Preset("apng"), Workload(240, 480, 270))); + Assert.Monotonic(Enumerable.Range(1, 100).Select(q => ExportEstimator.JpegBitsPerPixel(q)), strict: true); + Assert.Approximately(2.8, ExportEstimator.JpegBitsPerPixel(90), 1e-12); + var mjpeg = Preset("mjpeg-avi"); + Assert.Greater(ExportEstimator.EstimateBytes(mjpeg, Workload()), ExportEstimator.EstimateBytes(Preset("4k-hevc10-archive"), Workload())); + } + + [Test] + public void TimeGrowsWithWorkAndCalibrationRescalesIt() + { + var export = Preset("4k-hevc"); + var model = ThroughputModel.Default; + var plain = ExportEstimator.EstimateTime(export.Codec, Workload(), model); + Assert.Greater(ExportEstimator.EstimateTime(export.Codec, Workload(flow: 600), model).TotalSeconds, 2 * plain.TotalSeconds); + Assert.Greater(ExportEstimator.EstimateTime(export.Codec, Workload(analysis: 600), model).TotalSeconds, plain.TotalSeconds); + Assert.Greater(ExportEstimator.EstimateTime(export.Codec, Workload(hardware: false), model).TotalSeconds, plain.TotalSeconds); + Assert.InRange(plain.TotalSeconds, 30, 600); // ≈ 4 frames per second of 4K on the default model + + var faster = model.Calibrate(plain, plain / 2, weight: 1); + Assert.Approximately(2.0, faster.Scale, 1e-9); + Assert.Approximately(plain.TotalSeconds / 2, ExportEstimator.EstimateTime(export.Codec, Workload(), faster).TotalSeconds, 1e-6); + Assert.Approximately(Math.Sqrt(2), model.Calibrate(plain, plain / 2).Scale, 1e-9); + Assert.Same(model, model.Calibrate(TimeSpan.Zero, plain)); + + var estimate = ExportEstimator.Estimate(export, Workload()); + Assert.Equal(ExportEstimator.EstimateBytes(export, Workload()), estimate.Bytes); + Assert.Equal(plain, estimate.Time); + } +} diff --git a/tests/Titano.Core.Tests/Export/ExportNamingTests.cs b/tests/Titano.Core.Tests/Export/ExportNamingTests.cs new file mode 100644 index 00000000..c4c69054 --- /dev/null +++ b/tests/Titano.Core.Tests/Export/ExportNamingTests.cs @@ -0,0 +1,71 @@ +using Titano.Core.Export; +using Titano.Core.Video; +using Titano.Testing; + +namespace Titano.Core.Tests.Export; + +public sealed class ExportNamingTests +{ + private readonly TestContext _context; + + public ExportNamingTests(TestContext context) => _context = context; + + private static ExportNameContext Context(VideoCodec codec = VideoCodec.Hevc, string? title = "Harbour sunset") => new() + { + Date = new DateTime(2024, 6, 21, 19, 30, 0), + Title = title, + PresetName = "4K UHD HEVC", + Width = 3840, + Height = 2160, + FrameRate = Rational.Fps2997, + Codec = codec, + }; + + [Test] + public void DefaultTemplateNamesTheRender() + { + var name = ExportNaming.Expand("{date} {title} - {preset}", Context()); + Assert.Equal("2024-06-21 Harbour sunset - 4K UHD HEVC", name.Name); + Assert.True(name.IsValid); + } + + [Test] + public void EveryTokenExpands() + { + var name = ExportNaming.Expand("{date:yyyyMMdd}_{width}x{height}_{fps}fps_{codec}_{{raw}}", Context()); + Assert.Equal("20240621_3840x2160_29.97fps_HEVC_{raw}", name.Name); + Assert.Equal("PNG", ExportNaming.CodecLabel(VideoCodec.PngSequence)); + Assert.Equal("H.264", ExportNaming.CodecLabel(VideoCodec.H264)); + } + + [Test] + public void IllegalCharactersAndProblemsAreReported() + { + var name = ExportNaming.Expand("{title} {bogus} {", Context(title: "a/b:c*d?")); + Assert.Equal("a-b_c_d_ {", name.Name); + Assert.Count(2, name.Errors); + Assert.Equal("UnknownToken", name.Errors[0].Code); + Assert.Equal("UnclosedBrace", name.Errors[1].Code); + Assert.Equal(ExportNaming.FallbackName, ExportNaming.Expand("{title}", Context(title: null)).Name); + Assert.Equal("2024-06-21 - 4K UHD HEVC", ExportNaming.Expand("{date} {title} - {preset}", Context(title: null)).Name); + } + + [Test] + public void CollisionsGetANumberedSuffix() + { + var dir = _context.CreateTempDirectory(); + var first = ExportNaming.OutputPath(dir, "{title}", Context()); + Assert.Equal(Path.Combine(dir, "Harbour sunset.mp4"), first); + File.WriteAllBytes(first, [1]); + var second = ExportNaming.OutputPath(dir, "{title}", Context()); + Assert.Equal(Path.Combine(dir, "Harbour sunset (2).mp4"), second); + File.WriteAllBytes(second, [1]); + Assert.Equal(Path.Combine(dir, "Harbour sunset (3).mp4"), ExportNaming.OutputPath(dir, "{title}", Context())); + + var sequence = ExportNaming.OutputPath(dir, "{title}", Context(VideoCodec.PngSequence)); + Assert.Equal(Path.Combine(dir, "Harbour sunset"), sequence); + Directory.CreateDirectory(sequence); + Assert.Equal(Path.Combine(dir, "Harbour sunset (2)"), ExportNaming.OutputPath(dir, "{title}", Context(VideoCodec.PngSequence))); + Assert.Equal(Path.Combine(dir, "Harbour sunset.gif"), ExportNaming.OutputPath(dir, "{title}", Context(VideoCodec.Gif))); + } +} diff --git a/tests/Titano.Core.Tests/Export/ExportResolverTests.cs b/tests/Titano.Core.Tests/Export/ExportResolverTests.cs new file mode 100644 index 00000000..c934f4be --- /dev/null +++ b/tests/Titano.Core.Tests/Export/ExportResolverTests.cs @@ -0,0 +1,131 @@ +using Titano.Core.Export; +using Titano.Core.Project; +using Titano.Core.Video; +using Titano.Testing; + +namespace Titano.Core.Tests.Export; + +public sealed class ExportResolverTests +{ + private static ExportSettings Export(string preset, ExportOverrides? overrides = null) => + new() { Preset = new Auto().WithManual(preset), Overrides = overrides ?? new ExportOverrides() }; + + [Test] + public void EveryBuiltInPresetResolvesToItself() + { + foreach (var preset in ExportPresets.BuiltIn) + { + var resolved = ExportResolver.Resolve(Export(preset.Id)); + Assert.Equal(preset.Id, resolved.PresetId); + Assert.False(resolved.IsCustom); + Assert.Equal(preset.NameKey, resolved.NameKey); + Assert.Equal(preset.Codec, resolved.Codec); + Assert.Empty(resolved.Warnings); + } + } + + [Test] + public void EditingAValueMakesTheExportCustom() + { + var resolved = ExportResolver.Resolve(Export("4k-hevc", new ExportOverrides { BitRate = 50_000_000 })); + Assert.True(resolved.IsCustom); + Assert.Equal(ExportResolver.CustomId, resolved.PresetId); + Assert.Equal("4k-hevc", resolved.BasePresetId); + Assert.Null(resolved.NameKey); + Assert.Equal(50_000_000L, resolved.EffectiveBitRate(3840, 2160)); + Assert.Equal(3840, resolved.Width); + } + + [Test] + public void ValuesEqualToThePresetRestoreItsName() + { + var resolved = ExportResolver.Resolve(Export("1080p-h264", new ExportOverrides + { + Codec = "h.264", + Container = "mp4", + Width = 1920, + Height = 1080, + FrameRate = "30", + BitRate = 6_220_800, // the preset's 0.10 bpp at 1920×1080×30 + GopFrames = 30, + Profile = "H264High", + RateControl = "vbr", + })); + Assert.Equal("1080p-h264", resolved.PresetId); + Assert.Empty(resolved.Warnings); + } + + [Test] + public void ValuesEqualToAnotherPresetTakeItsName() + { + var resolved = ExportResolver.Resolve(Export("1080p-h264", new ExportOverrides { FrameRate = "60" })); + Assert.Equal("1080p60", resolved.PresetId); + Assert.Equal(60, resolved.GopFrames); + Assert.Equal("1080p-h264", resolved.BasePresetId); + } + + [Test] + public void FractionalRatesAndGopFollowTheOverride() + { + var resolved = ExportResolver.Resolve(Export("4k-h264", new ExportOverrides { FrameRate = "24000/1001" })); + Assert.True(resolved.IsCustom); + Assert.Equal(Rational.Fps23976, resolved.FrameRate); + Assert.Equal(24, resolved.GopFrames); + var settings = resolved.ToEncodeSettings("x.mp4", 3840, 2160); + Assert.Equal(24, settings.GopLength); + Assert.Equal((long)Math.Round(0.10 * 3840 * 2160 * 24000 / 1001.0), settings.BitRate); + Assert.Equal(CodecProfile.H264High, settings.Profile); + } + + [Test] + public void BadOverridesAreIgnoredWithWarnings() + { + var resolved = ExportResolver.Resolve(Export("1080p-h264", new ExportOverrides { Codec = "divx", FrameRate = "fast", Container = "avi", Profile = "ultra", RateControl = "magic" })); + Assert.Equal("1080p-h264", resolved.PresetId); + Assert.SequenceEqual(new[] { "Export.Warning.UnknownCodec", "Export.Warning.ContainerIgnored", "Export.Warning.UnknownProfile", "Export.Warning.UnknownFrameRate", "Export.Warning.UnknownRateControl" }, resolved.Warnings); + } + + [Test] + public void UnknownOrCustomSelectionsStartFromTheDefaultPreset() + { + var unknown = ExportResolver.Resolve(Export("deleted-user-preset")); + Assert.Equal(ExportResolver.DefaultPresetId, unknown.PresetId); + Assert.Contains("Export.Warning.UnknownPreset", unknown.Warnings); + + var custom = ExportResolver.Resolve(Export("custom", new ExportOverrides { Codec = "png", Width = 0, Height = 0, BitDepth = 16, FrameRate = "30", GopFrames = 30, BFrames = 0, Quality = 92 })); + Assert.Empty(custom.Warnings); + Assert.Equal(VideoCodec.PngSequence, custom.Codec); + Assert.True(custom.IsCustom); + + var auto = ExportResolver.Resolve(new ExportSettings()); + Assert.Equal(ExportResolver.DefaultPresetId, auto.PresetId); + } + + [Test] + public void ChangingTheCodecResetsCodecSpecificValues() + { + var resolved = ExportResolver.Resolve(Export("1080p-h264", new ExportOverrides { Codec = "HEVC" })); + Assert.Equal(VideoCodec.Hevc, resolved.Codec); + Assert.Equal(CodecProfile.Auto, resolved.Profile); + Assert.Equal((long)Math.Round(0.07 * 1920 * 1080 * 30), resolved.EffectiveBitRate(1920, 1080)); + Assert.True(resolved.IsCustom); + Assert.True(ExportResolver.TryParseCodec("TIFF-16", out var tiff) && tiff == VideoCodec.Tiff16Sequence); + Assert.False(ExportResolver.TryParseCodec("", out _)); + } + + [Test] + public void FrameRateTextRoundTrips() + { + Assert.True(FrameRateText.TryParse("30000/1001", out var ntsc)); + Assert.Equal(Rational.Fps2997, ntsc); + Assert.True(FrameRateText.TryParse("29.97", out var decimalNtsc)); + Assert.Equal(Rational.Fps2997, decimalNtsc); + Assert.True(FrameRateText.TryParse(" 25 ", out var pal)); + Assert.Equal("25", FrameRateText.Format(pal)); + Assert.Equal("24000/1001", FrameRateText.Format(Rational.Fps23976)); + Assert.True(FrameRateText.AreEqual(new Rational(48000, 2002), Rational.Fps23976)); + Assert.False(FrameRateText.TryParse("0", out _)); + Assert.False(FrameRateText.TryParse("1/0", out _)); + Assert.False(FrameRateText.TryParse(null, out _)); + } +}