E3: conversione delle foto, rimux in MP4 e fotogrammi esatti nel nucleo

Prima parte della tappa E3 (formati e fotogrammi), solo nel nucleo: il
pianificatore, il copiatore e l'archivio delle esportazioni restano alla
parte successiva.

- Foto: ImageConverter.Check dice prima che cosa succede (copia identica,
  conversione, copia così com'è con il motivo: HEIC, AVIF, raw, animazioni,
  file danneggiati, CMYK e oltre 8 bit verso PNG/WEBP, oltre il limite di
  pixel); la conversione riporta come note ciò che non può portare invece
  di fermarsi, e la trasparenza verso JPG diventa bianco. I lettori
  segnalano animazioni, CMYK e segmenti non letti. VP8L usa un logaritmo
  in virgola fissa, così lo stesso file dà gli stessi byte su ogni sistema.
- Video: i lettori ISO e Matroska leggono elenco dei montaggi, lingue,
  tipo di AAC, MP3 e i vecchi codici AAC di Matroska; Mp4Writer prepara
  la disposizione e ne conosce la lunghezza prima di scrivere; il nuovo
  Mp4Remuxer porta in MP4 senza ricodificare, sempre con gli stessi byte.
- Fotogrammi: VideoFrameReader trova il campione mostrato a un istante
  come lo mostra il lettore, lo decodifica esatto a piena risoluzione e lo
  raddrizza; ExportFrames calcola istanti, suffissi e etichette.
- Nomi: il suffisso del fotogramma non si accorcia mai e la numerazione
  dei nomi liberi viene dopo di lui; SafeFileWriter scrive anche contenuti
  prodotti mentre li scrive.
- MediaConverter e ConversionThrottle preparano una conversione senza
  sapere dove andrà, una alla volta in tutto il processo.

Nuove prove per determinismo, istanti, rotazione, rimux e nomi; tutte le
prove di Febe.Tests passano.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-27 22:30:23 +01:00
1 parent 7faf92e667
commit 704c1ed9cf
28 files changed
+2830 -144

No files matched your search

+145
View File
@@ -0,0 +1,145 @@
using System.Globalization;
namespace Febe.Core.Export;
/// <summary>
/// The instants, names and labels of frames (spec §4.10 «Fotogrammi», decisions D12 and D13 of tappa E3): which instants
/// a request asks for, the suffix a frame file gets, and how an instant is shown.
/// </summary>
public static class ExportFrames
{
/// <summary>The shortest step of «Uno ogni k secondi».</summary>
public static readonly TimeSpan MinEvery = TimeSpan.FromMilliseconds(100);
/// <summary>The most frames of «N in tutto».</summary>
public const int MaxCount = 1000;
/// <summary>The most frames taken from one video.</summary>
public const int MaxPerVideo = 1000;
/// <summary>The most frames of one request.</summary>
public const int MaxPerRequest = 20000;
/// <summary>Why a request over <see cref="MaxPerVideo"/> is refused.</summary>
public const string OverCapMessage = "Più di 1.000 fotogrammi per un video: scegli un intervallo più lungo";
/// <summary>The suffix of the single frame of «Salva il fotogramma» (tappa E4).</summary>
public const string SingleSuffix = "_fotogramma";
/// <summary>How many frames <paramref name="request"/> asks of a video of <paramref name="duration"/>.</summary>
public static long FrameCount(TimeSpan duration, ExportFramesRequest request)
{
ArgumentNullException.ThrowIfNull(request);
return request.Mode switch
{
FrameMode.At => 1,
FrameMode.Every => EveryCount(duration, request.Every ?? throw new ArgumentException("Manca l'intervallo dei fotogrammi.", nameof(request))),
FrameMode.Count => request.Count ?? throw new ArgumentException("Manca il numero dei fotogrammi.", nameof(request)),
_ => throw new ArgumentOutOfRangeException(nameof(request)),
};
}
/// <summary>
/// The instants <paramref name="request"/> asks of a video of <paramref name="duration"/>, in increasing order.
/// Refused (<see cref="ArgumentException"/> with <see cref="OverCapMessage"/>) over <see cref="MaxPerVideo"/>.
/// </summary>
public static IReadOnlyList<TimeSpan> Instants(TimeSpan duration, ExportFramesRequest request)
{
ArgumentNullException.ThrowIfNull(request);
return request.Mode switch
{
FrameMode.At => [request.At is { } at && at > TimeSpan.Zero ? at : TimeSpan.Zero],
FrameMode.Every => Every(duration, request.Every ?? throw new ArgumentException("Manca l'intervallo dei fotogrammi.", nameof(request))),
FrameMode.Count => Spread(duration, request.Count ?? throw new ArgumentException("Manca il numero dei fotogrammi.", nameof(request))),
_ => throw new ArgumentOutOfRangeException(nameof(request)),
};
}
/// <summary>«Uno ogni k secondi»: 0, k, 2k… before <paramref name="duration"/> (only 0 for a video without length).</summary>
public static IReadOnlyList<TimeSpan> Every(TimeSpan duration, TimeSpan step)
{
if (step < MinEvery)
{
throw new ArgumentOutOfRangeException(nameof(step), "L'intervallo minimo è 0,1 secondi.");
}
var count = EveryCount(duration, step);
if (count > MaxPerVideo)
{
throw new ArgumentException(OverCapMessage, nameof(step));
}
var instants = new TimeSpan[count];
for (var i = 0; i < count; i++)
{
instants[i] = TimeSpan.FromTicks(step.Ticks * i);
}
return instants;
}
/// <summary>«N in tutto»: (i + ½) · duration / N for i = 0…N − 1, in 100 ns ticks rounded down.</summary>
public static IReadOnlyList<TimeSpan> Spread(TimeSpan duration, int count)
{
if (count is < 1 or > MaxCount)
{
throw new ArgumentOutOfRangeException(nameof(count), "Da 1 a 1.000 fotogrammi.");
}
var length = (Int128)Math.Max(0, duration.Ticks);
var instants = new TimeSpan[count];
for (var i = 0; i < count; i++)
{
instants[i] = TimeSpan.FromTicks((long)(((2 * i) + 1) * length / (2 * (Int128)count)));
}
return instants;
}
/// <summary>
/// The suffix of a frame file, appended to the stem: <c>_t0m12s340</c> (the actual instant: minutes, seconds on two
/// digits, milliseconds on three) for «Questo istante» and «Uno ogni k secondi»; <c>_f001</c> (the position among
/// the <paramref name="count"/> instants, at least three digits) for «N in tutto».
/// </summary>
/// <param name="index">0-based position of the instant in the request.</param>
public static string Suffix(FrameMode mode, TimeSpan actual, int index, int count)
{
if (mode == FrameMode.Count)
{
var digits = Math.Max(3, Math.Max(1, count).ToString(CultureInfo.InvariantCulture).Length);
return "_f" + (index + 1).ToString("D" + digits.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
}
var ms = ActualMs(actual);
return string.Create(CultureInfo.InvariantCulture, $"_t{ms / 60000}m{ms / 1000 % 60:D2}s{ms % 1000:D3}");
}
/// <summary>
/// An instant as the viewer and the dialog show it: <c>m:ss</c> («0:01»), followed by a comma and the milliseconds
/// without trailing zeros only when it is not a whole second («0:01,25»).
/// </summary>
public static string Label(TimeSpan actual)
{
var ms = ActualMs(actual);
var label = string.Create(CultureInfo.InvariantCulture, $"{ms / 60000}:{ms / 1000 % 60:D2}");
var fraction = ms % 1000;
return fraction == 0
? label
: label + "," + fraction.ToString("D3", CultureInfo.InvariantCulture).TrimEnd('0');
}
/// <summary>The identity of a frame's instant: its shown time in milliseconds, rounded up.</summary>
public static long ActualMs(TimeSpan shown) =>
shown <= TimeSpan.Zero ? 0 : (shown.Ticks + TimeSpan.TicksPerMillisecond - 1) / TimeSpan.TicksPerMillisecond;
private static long EveryCount(TimeSpan duration, TimeSpan step)
{
if (step <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(step));
}
// 0, k, 2k… strictly before the end: ceil(duration / k), and at least the frame at 0.
return duration <= TimeSpan.Zero ? 1 : Math.Max(1, (duration.Ticks + step.Ticks - 1) / step.Ticks);
}
}
+16
View File
@@ -23,6 +23,22 @@ public abstract record ExportSelection
public sealed record Account(long AccountId) : ExportSelection;
}
/// <summary>How the instants of «Fotogrammi» are chosen (spec §4.10 «Fotogrammi»).</summary>
public enum FrameMode
{
/// <summary>«Questo istante»: one frame at <see cref="ExportFramesRequest.At"/>.</summary>
At,
/// <summary>«Uno ogni k secondi»: at 0, k, 2k… before the end.</summary>
Every,
/// <summary>«N in tutto»: N frames spread over the video, each in the middle of its share.</summary>
Count,
}
/// <summary>A request of frames of videos, in a photo format (Jpg, Png or WebpLossless).</summary>
public sealed record ExportFramesRequest(FrameMode Mode, TimeSpan? At, TimeSpan? Every, int? Count, ExportFormat Format);
/// <summary>A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked.</summary>
public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain = false, ExportRunOrigin Origin = ExportRunOrigin.Manual);
+34 -6
View File
@@ -4,6 +4,12 @@ using Febe.Core.Library;
namespace Febe.Core.Export;
/// <summary>
/// How the file name of a copy differs from the library's (tappa E3): the extension of the effective format
/// («.jpg»; null keeps the source's) and the suffix of a frame («_t0m12s340»; null for none), appended to the stem.
/// </summary>
public sealed record ExportNameOptions(string? Extension, string? Suffix);
/// <summary>Paths and content types of the export (spec §4.10).</summary>
public static class ExportPaths
{
@@ -63,7 +69,8 @@ public static class ExportPaths
Media media,
string? highlightTitle,
bool inHighlight,
TimeZoneInfo zone)
TimeZoneInfo zone,
ExportNameOptions? name = null)
{
ArgumentNullException.ThrowIfNull(d);
ArgumentNullException.ThrowIfNull(library);
@@ -106,22 +113,42 @@ public static class ExportPaths
segments = scheme.Render(values, zone);
}
segments = Renamed(segments, name);
return d.Scope == ExportScope.General ? [WindowsFileNames.SanitizeSegment(account.Username), .. segments] : segments;
}
/// <summary>The last segment with the suffix appended to its stem and the extension of <paramref name="name"/>.</summary>
private static IReadOnlyList<string> Renamed(IReadOnlyList<string> segments, ExportNameOptions? name)
{
if (name is null || segments.Count == 0 || (name.Extension is null && string.IsNullOrEmpty(name.Suffix)))
{
return segments;
}
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
var fileName = WindowsFileNames.SanitizeSegment(stem + (name.Suffix ?? string.Empty) + (name.Extension ?? extension));
return [.. segments.Take(segments.Count - 1), fileName];
}
/// <summary>The relative path ('/' separated) of a copy: the segments fitted to the length limit under the root.</summary>
/// <param name="d">The destination.</param>
/// <param name="segments">The segments of <see cref="Segments"/>.</param>
/// <param name="maxPath">The longest full path.</param>
/// <param name="keepSuffix">The frame suffix of the file name, never cut by the shortening.</param>
/// <exception cref="PathTooLongException">Even shortened, the path does not fit.</exception>
public static string RelativePathFor(ExportDestination d, IReadOnlyList<string> segments, int maxPath = WindowsFileNames.MaxPathLength)
public static string RelativePathFor(ExportDestination d, IReadOnlyList<string> segments, int maxPath = WindowsFileNames.MaxPathLength, string? keepSuffix = null)
{
ArgumentNullException.ThrowIfNull(d);
return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath));
return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath, keepSuffix));
}
/// <summary>
/// The name the safe writer gives a file at its <paramref name="attempt"/>-th try when the planned name is taken
/// («nome (2).jpg», «nome (3).jpg», …), so a resumed copy finds a file it renamed before a crash.
/// («nome (2).jpg», «nome (3).jpg», …), so a resumed copy finds a file it renamed before a crash. With
/// <paramref name="keepSuffix"/> (a frame suffix, <see cref="SafeWriteOptions.KeepSuffix"/>) the number comes after
/// it and both survive the shortening: «x_f001 (2).png».
/// </summary>
public static string NumberedName(string root, string relativePath, int attempt, int maxPath = WindowsFileNames.MaxPathLength)
public static string NumberedName(string root, string relativePath, int attempt, int maxPath = WindowsFileNames.MaxPathLength, string? keepSuffix = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(relativePath);
var segments = LibraryLayout.ToStored(relativePath).Split('/', StringSplitOptions.RemoveEmptyEntries);
@@ -132,7 +159,8 @@ public static class ExportPaths
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
var name = WindowsFileNames.SanitizeSegment(string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}"));
return string.Join('/', WindowsFileNames.FitPath(root, [.. segments[..^1], name], maxPath));
var keep = keepSuffix is null ? null : string.Create(CultureInfo.InvariantCulture, $"{keepSuffix} ({attempt})");
return string.Join('/', WindowsFileNames.FitPath(root, [.. segments[..^1], name], maxPath, keep));
}
/// <summary>The scheme that names an entry kind.</summary>