using System.Globalization; using System.Text; using Chronos.Core.Naming; using Chronos.Core.Project; using Chronos.Core.Video; namespace Chronos.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 and the paths /// says are being written. /// public static string OutputPath(string folder, string template, ExportNameContext context, Func? taken = null) { 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, taken); } /// /// Output path of a project's export: or, when unset, the sequence's exports folder, /// named by . /// public static string OutputPath(ExportSettings settings, string sequenceExportsFolder, ExportNameContext context, Func? taken = null) { ArgumentNullException.ThrowIfNull(settings); return OutputPath(string.IsNullOrWhiteSpace(settings.Folder) ? sequenceExportsFolder : settings.Folder, settings.NameTemplate, context, taken); } /// /// The name of a still (owner review 1, R8, "Save frame"): the expanded , " - " and the 1-based /// number of source frame in at least four digits, "2026-09-28 Harbour - 4K HEVC - 0123". /// public static string StillName(string template, ExportNameContext context, int frameIndex) { ArgumentOutOfRangeException.ThrowIfNegative(frameIndex); var name = Expand(template, context).Name; return PathTemplate.SanitizeSegment(string.Create(CultureInfo.InvariantCulture, $"{name} - {frameIndex + 1:D4}")); } /// /// Full path of a still inside : plus the image extension of the codec /// (one file, never a folder), made unique like . /// public static string StillPath(string folder, string template, ExportNameContext context, int frameIndex, Func? taken = null) { ArgumentException.ThrowIfNullOrWhiteSpace(folder); return Unique(folder, StillName(template, context, frameIndex), VideoCodecInfo.FileExtension(context.Codec), taken); } /// /// Path of a still of a project's export: or, when unset, the sequence's exports /// folder, named by and the frame number. /// public static string StillPath(ExportSettings settings, string sequenceExportsFolder, ExportNameContext context, int frameIndex, Func? taken = null) { ArgumentNullException.ThrowIfNull(settings); return StillPath(string.IsNullOrWhiteSpace(settings.Folder) ? sequenceExportsFolder : settings.Folder, settings.NameTemplate, context, frameIndex, taken); } /// "name.ext", or "name (2).ext", "name (3).ext"… when a file or folder of that name exists or is . public static string Unique(string folder, string name, string extension, Func? taken = null) { 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) && taken?.Invoke(candidate) != true) 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, }; } }