Files
Chronos/src/Chronos.Core/Export/ExportNaming.cs
T
Alby96andClaude Opus 5.5 3c2cce8031 feat(P1): output program with direction, loops, hold and fades; still frames
Completes the Core side of owner review 1 phase 5 (R8): OutputProgram turns the plan into the emitted entries (reverse, boomerang without a doubled turn, loops, a hold of whole periods, fades split per period over held frames and shortened with a warning when longer than half the program). The render follows the program: star trails accumulate in program order, median/mean windows stay per plan frame in either direction, a boomerang with trails plays forward with a warning, and the fade gain is the last FrameFinish step. Workload and estimates come from the program, so loops and holds show in time and size.

A still target (RenderTarget.StillFrame) renders one source frame with every correction and no playback into one PNG, JPEG or TIFF 16-bit file (EncodeSettings.SingleImage, StillImageSession), named by ExportNaming.StillPath and recorded with kind still, fps 0 and duration 0.

Refs #21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:07:58 +01:00

186 lines
8.5 KiB
C#

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