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

@@ -0,0 +1,29 @@
namespace Febe.Core.Library.Conversion;
/// <summary>
/// One conversion at a time across the process (tappa E3, decision D16): a photo conversion holds a decoded picture
/// and its encoder state (up to about a gigabyte for 40 megapixels), so the export and the library conversion take
/// turns, each off the calling thread.
/// </summary>
public sealed class ConversionThrottle
{
private readonly SemaphoreSlim gate = new(1, 1);
/// <summary>The throttle every conversion of the process shares.</summary>
public static ConversionThrottle Shared { get; } = new();
/// <summary>Runs <paramref name="work"/> on the thread pool once no other conversion runs.</summary>
public async Task<T> RunAsync<T>(Func<CancellationToken, T> work, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(work);
await gate.WaitAsync(ct).ConfigureAwait(false);
try
{
return await Task.Run(() => work(ct), ct).ConfigureAwait(false);
}
finally
{
gate.Release();
}
}
}
@@ -0,0 +1,213 @@
using System.Security.Cryptography;
using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.Images;
using Febe.Core.Domain;
namespace Febe.Core.Library.Conversion;
/// <summary>
/// A library file ready to be written in a format (tappa E3, spec §4.10 «Conversione del formato»): what will be
/// written and how. Dispose it once written or given up.
/// </summary>
/// <param name="Variant"><see cref="ExportVariant.Whole"/> (the file byte for byte) or <see cref="ExportVariant.Converted"/>.</param>
/// <param name="Format">The effective format: <see cref="ExportFormat.Original"/> for a whole file.</param>
/// <param name="Extension">The extension of the file written, with its dot («.jpg»; a whole file keeps its own).</param>
/// <param name="Length">The bytes <see cref="Produce"/> writes.</param>
/// <param name="Sha256">
/// The SHA-256 (lowercase hex) of what <see cref="Produce"/> writes; null for a remux, known once written.
/// </param>
/// <param name="Notes">Note codes: why the file is copied as it is, or what the conversion could not carry.</param>
/// <param name="Produce">Writes the file into the stream given.</param>
public sealed record MediaConversionResult(ExportVariant Variant, ExportFormat Format, string Extension,
long Length, string? Sha256, IReadOnlyList<string> Notes, Func<Stream, CancellationToken, Task> Produce) : IDisposable
{
/// <summary>The note prefix of a video that cannot be remuxed; the <see cref="RemuxRefusal"/> follows the colon.</summary>
public const string AsIsNotRemuxable = "AsIsNotRemuxable";
/// <summary>Converted bytes or a remux plan, released on <see cref="Dispose"/>.</summary>
internal object? Held { get; set; }
/// <inheritdoc />
public void Dispose() => Held = null;
}
/// <summary>
/// Prepares a library file in a target format, independent of where it goes (an export destination, the library):
/// photos are converted in memory under the <see cref="ConversionThrottle"/>, videos are remuxed into MP4 while being
/// written. The source is never changed.
/// </summary>
public static class MediaConverter
{
/// <summary>The raw camera formats, copied as they are (spec §4.10).</summary>
private static readonly HashSet<string> RawExtensions = new(StringComparer.OrdinalIgnoreCase)
{
".dng", ".cr2", ".cr3", ".nef", ".arw", ".raf", ".orf", ".rw2", ".pef", ".srw",
};
/// <summary>
/// Prepares <paramref name="relativePath"/> (only its name is used) in <paramref name="target"/>.
/// <paramref name="openRandomAccess"/> opens the source for reading, seekable; it may be called more than once.
/// </summary>
/// <exception cref="ContentChangedException">A photo's bytes do not have <paramref name="expectedSourceSha256"/>.</exception>
/// <exception cref="ArgumentException">The target does not belong to the kind of file.</exception>
public static async Task<MediaConversionResult> PrepareAsync(Func<Stream> openRandomAccess, string relativePath,
MediaKind kind, ExportFormat target, string expectedSourceSha256, ConversionThrottle throttle, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(openRandomAccess);
ArgumentException.ThrowIfNullOrEmpty(relativePath);
ArgumentException.ThrowIfNullOrEmpty(expectedSourceSha256);
ArgumentNullException.ThrowIfNull(throttle);
var valid = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(target) : ExportFormats.IsVideoFormat(target);
if (!valid)
{
throw new ArgumentException("Il formato non è adatto a questo tipo di file.", nameof(target));
}
return kind == MediaKind.Photo
? await PreparePhotoAsync(openRandomAccess, relativePath, target, expectedSourceSha256.ToLowerInvariant(), throttle, ct).ConfigureAwait(false)
: await PrepareVideoAsync(openRandomAccess, relativePath, target, expectedSourceSha256.ToLowerInvariant(), throttle, ct).ConfigureAwait(false);
}
/// <summary>The image format written for an export format; null for Original and MP4.</summary>
public static ImageFormat? ImageFormatOf(ExportFormat format) => format switch
{
ExportFormat.Jpg => ImageFormat.Jpeg,
ExportFormat.Png => ImageFormat.Png,
ExportFormat.WebpLossless => ImageFormat.WebP,
_ => null,
};
/// <summary>The extension of a converted file, with its dot.</summary>
public static string ExtensionOf(ExportFormat format) => format switch
{
ExportFormat.Jpg => ".jpg",
ExportFormat.Png => ".png",
ExportFormat.WebpLossless => ".webp",
ExportFormat.Mp4 => ".mp4",
_ => throw new ArgumentOutOfRangeException(nameof(format)),
};
private static async Task<MediaConversionResult> PreparePhotoAsync(Func<Stream> open, string relativePath,
ExportFormat target, string expected, ConversionThrottle throttle, CancellationToken ct)
{
var extension = Path.GetExtension(relativePath);
long length;
byte[]? bytes = null;
await using (var source = open())
{
length = source.Length;
if (target != ExportFormat.Original && length <= ImageConverter.MaxSourceBytes)
{
bytes = new byte[length];
await source.ReadExactlyAsync(bytes, ct).ConfigureAwait(false);
}
}
if (bytes is null)
{
// Original, or too large to hold: the file byte for byte, checked against its SHA while written.
return Whole(open, extension, length, expected, target == ExportFormat.Original ? [] : [ImageConversionLosses.AsIsTooLarge]);
}
var sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
if (!string.Equals(sha, expected, StringComparison.Ordinal))
{
throw new ContentChangedException("Il file della libreria è cambiato durante la copia.");
}
if (RawExtensions.Contains(extension))
{
return Whole(bytes, extension, sha, [ImageConversionLosses.AsIsRaw]);
}
var format = ImageFormatOf(target)!.Value;
var check = ImageConverter.Check(bytes, format);
switch (check.Action)
{
case ImageConversionAction.CopyAsIs:
return Whole(bytes, extension, sha, []);
case ImageConversionAction.CopyOriginal:
return Whole(bytes, extension, sha, check.NoteCode is { } note ? [note] : []);
}
var converted = await throttle.RunAsync(token =>
{
token.ThrowIfCancellationRequested();
try
{
return ImageConverter.Convert(bytes, format);
}
catch (ImageLimitException)
{
return null;
}
catch (ImageDecodeException)
{
return null;
}
}, ct).ConfigureAwait(false);
if (converted is null)
{
return Whole(bytes, extension, sha, [ImageConversionLosses.AsIsNotDecodable]);
}
var data = converted.Data;
return new MediaConversionResult(ExportVariant.Converted, target, ExtensionOf(target), data.Length,
Convert.ToHexStringLower(SHA256.HashData(data)), converted.Losses, Writer(data))
{
Held = data,
};
}
private static async Task<MediaConversionResult> PrepareVideoAsync(Func<Stream> open, string relativePath,
ExportFormat target, string expected, ConversionThrottle throttle, CancellationToken ct)
{
var extension = Path.GetExtension(relativePath);
var fileName = Path.GetFileName(relativePath);
var (length, refusal, plan) = await throttle.RunAsync(token =>
{
using var source = open();
var size = source.Length;
if (target == ExportFormat.Original)
{
return (size, RemuxRefusal.AlreadyMp4, (RemuxPlan?)null);
}
var outcome = Mp4Remuxer.Check(source, fileName, out var made, token);
return (size, outcome, made);
}, ct).ConfigureAwait(false);
if (refusal == RemuxRefusal.None && plan is not null)
{
return new MediaConversionResult(ExportVariant.Converted, ExportFormat.Mp4, ".mp4", plan.OutputLength, null,
plan.Losses, (output, token) => Task.Run(
() =>
{
using var source = open();
Mp4Remuxer.Write(plan, source, output, token);
},
token))
{
Held = plan,
};
}
string[] notes = refusal == RemuxRefusal.AlreadyMp4 ? [] : [$"{MediaConversionResult.AsIsNotRemuxable}:{refusal}"];
return Whole(open, extension, length, expected, notes);
}
/// <summary>A whole file streamed from the source (a video, or a photo not read into memory).</summary>
private static MediaConversionResult Whole(Func<Stream> open, string extension, long length, string sha, IReadOnlyList<string> notes) =>
new(ExportVariant.Whole, ExportFormat.Original, extension, length, sha, notes, async (output, token) =>
{
await using var source = open();
await source.CopyToAsync(output, token).ConfigureAwait(false);
});
/// <summary>A whole photo from the bytes already read and checked.</summary>
private static MediaConversionResult Whole(byte[] bytes, string extension, string sha, IReadOnlyList<string> notes) =>
new(ExportVariant.Whole, ExportFormat.Original, extension, bytes.Length, sha, notes, Writer(bytes)) { Held = bytes };
private static Func<Stream, CancellationToken, Task> Writer(byte[] data) =>
(output, token) => output.WriteAsync(data, token).AsTask();
}
+130 -4
View File
@@ -42,6 +42,12 @@ public sealed record SafeWriteOptions
/// is removed and an <see cref="IOException"/> says so.
/// </summary>
public bool VerifyFromDisk { get; init; }
/// <summary>
/// The end of the stem of the file name that a shortening or a free name never cuts (the frame suffix of tappa
/// E3, «_t0m12s340»): a free name is «nome_t0m12s340 (2).png», as <c>ExportPaths.NumberedName</c> gives it.
/// </summary>
public string? KeepSuffix { get; init; }
}
/// <summary>The content exceeded <see cref="SafeWriteOptions.MaxBytes"/>; nothing was kept.</summary>
@@ -164,6 +170,38 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(source);
return await SaveCoreAsync((path, o, token) => WriteTempAsync(source, path, o, token), rootFolder, tempDirectory, decide, options, ct)
.ConfigureAwait(false);
}
/// <summary>
/// As <see cref="SaveAsync(Stream, string, string, Func{FileDigest, CancellationToken, ValueTask{string}}, SafeWriteOptions, CancellationToken)"/>,
/// for content that is made while it is written (a converted photo, a remuxed video, a frame): <paramref name="produce"/>
/// writes it into the temporary file, through a stream that hashes and counts it (and honours
/// <see cref="SafeWriteOptions.MaxBytes"/> and <see cref="SafeWriteOptions.Progress"/>); then the same checks,
/// <paramref name="decide"/> and the free-name rename. Our own temporary file is removed on any failure.
/// </summary>
public async Task<SavedFile?> SaveAsync(
Func<Stream, CancellationToken, Task> produce,
string rootFolder,
string tempDirectory,
Func<FileDigest, CancellationToken, ValueTask<string?>> decide,
SafeWriteOptions? options = null,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(produce);
return await SaveCoreAsync((path, o, token) => ProduceTempAsync(produce, path, o, token), rootFolder, tempDirectory, decide, options, ct)
.ConfigureAwait(false);
}
private async Task<SavedFile?> SaveCoreAsync(
Func<string, SafeWriteOptions, CancellationToken, Task<FileDigest>> write,
string rootFolder,
string tempDirectory,
Func<FileDigest, CancellationToken, ValueTask<string?>> decide,
SafeWriteOptions? options,
CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(rootFolder);
ArgumentNullException.ThrowIfNull(decide);
options ??= new SafeWriteOptions();
@@ -180,7 +218,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
try
{
var digest = await WriteTempAsync(source, tempPath, options, ct).ConfigureAwait(false);
var digest = await write(tempPath, options, ct).ConfigureAwait(false);
ct.ThrowIfCancellationRequested();
if (options.VerifyFromDisk)
{
@@ -194,7 +232,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
}
ct.ThrowIfCancellationRequested();
var finalPath = MoveToFreeName(tempPath, root, desired, out var relative);
var finalPath = MoveToFreeName(tempPath, root, desired, options.KeepSuffix, out var relative);
var timeSet = true;
if (options.LastWriteTime is { } time)
{
@@ -289,6 +327,93 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
}
private static async Task<FileDigest> ProduceTempAsync(Func<Stream, CancellationToken, Task> produce, string tempPath, SafeWriteOptions options, CancellationToken ct)
{
await using var target = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize, FileOptions.Asynchronous);
using var hashing = new HashingStream(target, options);
await produce(hashing, ct).ConfigureAwait(false);
ct.ThrowIfCancellationRequested();
await target.FlushAsync(ct).ConfigureAwait(false);
target.Flush(flushToDisk: true);
return hashing.Digest();
}
/// <summary>A write-only stream that hashes and counts what goes through it into the temporary file.</summary>
private sealed class HashingStream(Stream inner, SafeWriteOptions options) : Stream
{
private readonly IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
private long total;
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => total;
public override long Position
{
get => total;
set => throw new NotSupportedException();
}
public FileDigest Digest() => new(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
public override void Flush() => inner.Flush();
public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken);
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
public override void Write(ReadOnlySpan<byte> buffer)
{
Count(buffer);
inner.Write(buffer);
options.Progress?.Report(total);
}
public override void WriteByte(byte value) => Write([value]);
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
Count(buffer.Span);
await inner.WriteAsync(buffer, cancellationToken).ConfigureAwait(false);
options.Progress?.Report(total);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
hash.Dispose();
}
base.Dispose(disposing);
}
private void Count(ReadOnlySpan<byte> buffer)
{
total += buffer.Length;
if (options.MaxBytes is { } max && total > max)
{
throw new FileTooLargeException(
string.Create(CultureInfo.InvariantCulture, $"Il file supera il limite di {max} byte: non viene salvato."));
}
hash.AppendData(buffer);
}
}
/// <summary>Reads the temporary file back and compares its SHA-256 with the one computed while writing.</summary>
private static async Task VerifyFromDiskAsync(string tempPath, FileDigest digest, CancellationToken ct)
{
@@ -316,7 +441,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
return segments.Count == 0 ? throw new ArgumentException("Il nome del file è vuoto.", nameof(relativePath)) : segments;
}
private string MoveToFreeName(string tempPath, string root, string desiredRelativePath, out string relative)
private string MoveToFreeName(string tempPath, string root, string desiredRelativePath, string? keepSuffix, out string relative)
{
var segments = Segments(desiredRelativePath);
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
@@ -324,7 +449,8 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
{
var name = attempt == 1 ? segments[^1] : string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}");
var candidate = segments.Take(segments.Count - 1).Append(WindowsFileNames.SanitizeSegment(name)).ToList();
var fitted = WindowsFileNames.FitPath(root, candidate, maxPathLength);
var keep = keepSuffix is null ? null : attempt == 1 ? keepSuffix : string.Create(CultureInfo.InvariantCulture, $"{keepSuffix} ({attempt})");
var fitted = WindowsFileNames.FitPath(root, candidate, maxPathLength, keep);
relative = string.Join('/', fitted);
var finalPath = LibraryLayout.FullPath(root, relative);
Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!);
+114 -28
View File
@@ -58,7 +58,7 @@ public sealed record VideoStillness(bool IsStill, int SampledFrames, double Diff
/// (<see cref="H264Decoder"/>, <see cref="H265Decoder"/>). Videos in other codecs (VP9, AV1, ...) give no frame: the
/// interface shows the neutral tile.
/// </summary>
public sealed class VideoFrameDecoder
public sealed partial class VideoFrameDecoder
{
/// <summary>Differences up to this value (0–255) count as compression noise of a still picture.</summary>
public const double StillThreshold = 3.0;
@@ -77,8 +77,6 @@ public sealed class VideoFrameDecoder
/// <summary>How far back from a sample flagged as key the decoder looks for one it can really start from.</summary>
private const int MaxRunStartSearch = 2000;
private static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero);
private readonly TimeSpan budget;
private readonly int maxRun;
@@ -184,10 +182,10 @@ public sealed class VideoFrameDecoder
// The frame where the run starts comes along: it stands for a target that gives no picture (a RASL picture
// of the HEVC CRA picture decoding starts from, a damaged sample).
var frames = decoding.Decode(start < target ? [start, target] : [target], ct);
var frames = decoding.DecodeAll(start < target ? [start, target] : [target], ct);
if (!frames.TryGetValue(target, out var frame) && !frames.TryGetValue(start, out frame) && target != 0)
{
frames = new Decoding(stream, video, maxRun).Decode([0], ct);
frames = new Decoding(stream, video, maxRun).DecodeAll([0], ct);
frames.TryGetValue(0, out frame);
}
@@ -248,7 +246,7 @@ public sealed class VideoFrameDecoder
return null;
}
var frames = decoding.Decode([.. targets], ct);
var frames = decoding.DecodeAll([.. targets], ct);
if (frames.Count < 2)
{
return null;
@@ -295,7 +293,7 @@ public sealed class VideoFrameDecoder
private static VideoTrack? Open(Stream stream)
{
// The creation time does not matter here: any date is accepted (the readers add a day to «now»).
var container = ContainerReader.Read(stream, AnyDate, samples: true);
var container = ContainerReader.Read(stream, ContainerReader.AnyDate, samples: true);
return container?.Video is { Samples.Count: > 0 } video && video.Codec switch
{
VideoCodec.H264 => video.AnnexB || video.AvcConfiguration is not null,
@@ -362,6 +360,13 @@ public sealed class VideoFrameDecoder
/// <summary>Exact: an H.264 IDR picture, an HEVC IDR or BLA picture.</summary>
Idr,
/// <summary>
/// Exact for the pictures shown from it on: an HEVC CRA picture (only its RASL pictures, shown before it, are
/// lost), an H.264 I picture with a recovery point SEI whose recovery_frame_cnt is 0. Elsewhere close, as
/// <see cref="Intra"/>.
/// </summary>
Recovery,
}
/// <summary>Size of the NAL length fields of the samples (0: Annex B), from the configuration record.</summary>
@@ -436,9 +441,11 @@ public sealed class VideoFrameDecoder
/// <summary>
/// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it.
/// </summary>
private sealed class Decoding(Stream stream, VideoTrack video, int maxRun)
private sealed class Decoding(Stream stream, VideoTrack video, int maxRun, bool exact = false)
{
private readonly Dictionary<int, Frame> found = [];
private readonly HashSet<int> produced = [];
private readonly List<(int Sample, Frame Frame)> pending = [];
private readonly HashSet<int> wanted = [];
private readonly int[] keys = KeyIndices(video);
private readonly Dictionary<int, StartPoint> accessPoints = [];
@@ -458,6 +465,11 @@ public sealed class VideoFrameDecoder
/// </summary>
internal int RunStart(int index)
{
if (exact)
{
return ExactStart(index);
}
var position = Array.BinarySearch(keys, index);
position = position >= 0 ? position : Math.Max(0, ~position - 1);
var intra = -1;
@@ -475,7 +487,7 @@ public sealed class VideoFrameDecoder
return index - candidate <= maxRun || intra < 0 ? candidate : intra;
}
if (point == StartPoint.Intra && intra < 0)
if (point is StartPoint.Intra or StartPoint.Recovery && intra < 0)
{
intra = candidate;
}
@@ -490,6 +502,34 @@ public sealed class VideoFrameDecoder
return index <= maxRun || intra < 0 ? 0 : intra;
}
/// <summary>
/// The nearest start from which <paramref name="index"/> comes out exact, however far: an IDR picture, or a
/// recovery point shown no later than it; otherwise the first sample.
/// </summary>
private int ExactStart(int index)
{
var position = Array.BinarySearch(keys, index);
position = position >= 0 ? position : Math.Max(0, ~position - 1);
var shown = video.Samples[index].PresentationTime;
for (var tried = 0; position > 0 && tried < MaxRunStartSearch; position--, tried++)
{
var candidate = keys[position];
if (!accessPoints.TryGetValue(candidate, out var point))
{
point = AccessPointOf(candidate);
accessPoints[candidate] = point;
}
if (point == StartPoint.Idr
|| (point == StartPoint.Recovery && shown >= video.Samples[candidate].PresentationTime))
{
return candidate;
}
}
return 0;
}
private StartPoint AccessPointOf(int index)
{
try
@@ -500,7 +540,7 @@ public sealed class VideoFrameDecoder
return H265Decoder.AccessPoint(sample, lengthSize) switch
{
H265AccessPoint.Idr => StartPoint.Idr,
H265AccessPoint.Cra => StartPoint.Intra,
H265AccessPoint.Cra => StartPoint.Recovery,
_ => StartPoint.None,
};
}
@@ -508,6 +548,7 @@ public sealed class VideoFrameDecoder
return H264Decoder.AccessPoint(sample, lengthSize) switch
{
H264AccessPoint.Idr => StartPoint.Idr,
H264AccessPoint.IntraPicture when H264Decoder.HasExactRecoveryPoint(sample, lengthSize) => StartPoint.Recovery,
H264AccessPoint.IntraPicture => StartPoint.Intra,
_ => StartPoint.None,
};
@@ -518,7 +559,25 @@ public sealed class VideoFrameDecoder
}
}
internal Dictionary<int, Frame> Decode(int[] targets, CancellationToken ct)
/// <summary>
/// Decodes the targets (sample indices in ascending order) and keeps every frame: the few a thumbnail or a
/// stillness check asks for.
/// </summary>
internal Dictionary<int, Frame> DecodeAll(int[] targets, CancellationToken ct)
{
foreach (var (sample, frame) in Decode(targets, ct))
{
found.TryAdd(sample, frame);
}
return found;
}
/// <summary>
/// Decodes the targets (sample indices in ascending order) and hands out each frame as soon as the sample that
/// finishes it is decoded, in decoding order, once per sample; a target that gives no picture is left out.
/// </summary>
internal IEnumerable<(int Sample, Frame Frame)> Decode(int[] targets, CancellationToken ct)
{
foreach (var t in targets)
{
@@ -536,29 +595,56 @@ public sealed class VideoFrameDecoder
next = key;
}
try
for (; next <= target; next++)
{
// Frames are matched to samples by the sample being decoded, not by the decoder's own count: a
// sample without a picture (only parameter sets, a skipped RASL picture, or damaged) must not shift
// the frames after it.
runner ??= new Runner(video, () => wanted.Contains(current), frame => found.TryAdd(current, frame));
for (; next <= target; next++)
ct.ThrowIfCancellationRequested();
if (!Step(ref runner, next))
{
ct.ThrowIfCancellationRequested();
current = next;
runner.Decode(ContainerReader.ReadSample(stream, video.Samples[next], ref buffer));
// This run is damaged (or its samples lie past the end of a truncated file): the next target
// starts again from its own key frame, and what was decoded so far stands.
runner = null;
}
foreach (var item in pending)
{
yield return item;
}
pending.Clear();
if (runner is null)
{
break;
}
}
catch (Exception ex) when (ex is H264Exception or H265Exception or ContainerException or EndOfStreamException
or IndexOutOfRangeException or ArgumentException or InvalidOperationException)
{
// This run is damaged (or its samples lie past the end of a truncated file): the next target starts
// again from its own key frame, and what was decoded so far stands.
runner = null;
}
}
}
return found;
/// <summary>Decodes one sample; false when the stream is damaged there.</summary>
private bool Step(ref Runner? runner, int sample)
{
try
{
// Frames are matched to samples by the sample being decoded, not by the decoder's own count: a sample
// without a picture (only parameter sets, a skipped RASL picture, or damaged) must not shift the frames
// after it.
runner ??= new Runner(video, () => wanted.Contains(current), Found);
current = sample;
runner.Decode(ContainerReader.ReadSample(stream, video.Samples[sample], ref buffer));
return true;
}
catch (Exception ex) when (ex is H264Exception or H265Exception or ContainerException or EndOfStreamException
or IndexOutOfRangeException or ArgumentException or InvalidOperationException)
{
return false;
}
}
private void Found(Frame frame)
{
if (produced.Add(current))
{
pending.Add((current, frame));
}
}
}
+346
View File
@@ -0,0 +1,346 @@
using Febe.Core.Codecs;
using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.Images;
using YuvToRgb = Febe.Core.Codecs.YuvToRgb;
namespace Febe.Core.Library;
/// <summary>What <see cref="VideoFrameReader.Open"/> found about a video.</summary>
/// <param name="Available">False when no frame can be taken from it: <paramref name="Unavailable"/> says why.</param>
/// <param name="Unavailable">The Italian message shown when frames are not available; null otherwise.</param>
/// <param name="Duration">The presentation length (zero when unknown).</param>
/// <param name="Width">Width of a frame as shown (rotation applied).</param>
/// <param name="Height">Height of a frame as shown (rotation applied).</param>
/// <param name="Rotation">Clockwise rotation of the track: 0, 90, 180 or 270.</param>
/// <param name="Codec">The video codec («H264», «Hevc»), or the container's codec tag of one Febe does not decode.</param>
/// <param name="FrameDuration">The mean time between two frames (zero when unknown).</param>
/// <param name="HasAudio">Whether the container has an audio track.</param>
/// <param name="SampleCount">Samples of the video track.</param>
public sealed record VideoFrameInfo(bool Available, string? Unavailable, TimeSpan Duration, int Width, int Height,
int Rotation, string Codec, TimeSpan FrameDuration, bool HasAudio, int SampleCount);
/// <summary>A frame to take: the instant asked for and the sample really shown then (spec §4.10 «Fotogrammi»).</summary>
/// <param name="Index">Position of the instant in the request (0-based), which names the file.</param>
/// <param name="Requested">The instant asked for.</param>
/// <param name="Actual">
/// When the sample is shown, rounded up to the next 100 ns tick: what the frame's identity and name carry.
/// </param>
/// <param name="Sample">The sample index in decoding order.</param>
public sealed record VideoFrameTarget(int Index, TimeSpan Requested, TimeSpan Actual, int Sample);
/// <summary>A decoded frame, upright, in 8-bit RGBA (alpha 255). Dispose it to give the pixels back.</summary>
public sealed class VideoFrame(int index, TimeSpan requested, TimeSpan actual, RgbaImage image) : IDisposable
{
/// <summary>Position of the instant in the request.</summary>
public int Index { get; } = index;
/// <summary>The instant asked for.</summary>
public TimeSpan Requested { get; } = requested;
/// <summary>When the frame is shown.</summary>
public TimeSpan Actual { get; } = actual;
/// <summary>The pixels, rotated as the video is shown.</summary>
public RgbaImage Image { get; } = image;
/// <inheritdoc />
public void Dispose() => Image.Dispose();
}
/// <summary>
/// Frames of a video at chosen instants, at full resolution and exact (spec §4.10 «Fotogrammi»): instants are the
/// presentation times as a player shows them (ISO edit lists included), each frame decoded from a point the decoder can
/// start from exactly, and turned upright. One frame lives in memory at a time; the stream must stay open and seekable
/// while the reader is used.
/// </summary>
public sealed class VideoFrameReader : IDisposable
{
/// <summary>The message for a video whose frames Febe cannot take.</summary>
public const string NotAvailableMessage = "Fotogramma non disponibile per questo video";
private readonly Stream? stream;
private readonly VideoTrack? video;
/// <summary>Shown time of each sample in track units (presentation time plus the empty edits).</summary>
private readonly long[] shown = [];
/// <summary>The samples that can be chosen, by shown time then decoding order.</summary>
private readonly int[] order = [];
private VideoFrameReader(Stream? stream, VideoTrack? video)
{
this.stream = stream;
this.video = video;
if (video is null)
{
return;
}
var samples = video.Samples;
shown = new long[samples.Count];
for (var i = 0; i < samples.Count; i++)
{
shown[i] = samples[i].PresentationTime + video.EmptyEditDuration;
}
// Samples shown before the start (cut by the edit list) are not chosen, unless nothing else is.
var visible = Enumerable.Range(0, samples.Count).Where(i => shown[i] >= 0).ToArray();
order = visible.Length > 0 ? visible : [.. Enumerable.Range(0, samples.Count)];
Array.Sort(order, (a, b) => shown[a] != shown[b] ? shown[a].CompareTo(shown[b]) : a.CompareTo(b));
}
/// <summary>
/// Opens the video in <paramref name="seekable"/> (left open: the caller disposes it after the reader). Never
/// throws for a video it cannot read: <paramref name="info"/> is then not available, and the reader gives no frame.
/// </summary>
public static VideoFrameReader Open(Stream seekable, out VideoFrameInfo info)
{
ArgumentNullException.ThrowIfNull(seekable);
MediaContainer? container;
VideoTrack? video;
try
{
seekable.Position = 0;
container = ContainerReader.Read(seekable, ContainerReader.AnyDate, samples: true);
video = container is null ? null : VideoFrameDecoder.FrameTrack(container);
}
catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex))
{
container = null;
video = null;
}
if (container?.Video is not { } track || video is null)
{
var v = container?.Video;
info = new VideoFrameInfo(false, NotAvailableMessage, container?.Duration ?? TimeSpan.Zero,
v?.DisplayWidth ?? 0, v?.DisplayHeight ?? 0, v?.Rotation ?? 0, v is null ? string.Empty : Codec(v),
TimeSpan.Zero, container?.Audio is not null, v?.Samples.Count ?? 0);
return new VideoFrameReader(null, null);
}
var reader = new VideoFrameReader(seekable, video);
info = new VideoFrameInfo(true, null, reader.Duration(container), track.DisplayWidth, track.DisplayHeight,
Rotation(track.Rotation), Codec(track), reader.FrameDuration(), container.Audio is not null, track.Samples.Count);
return reader;
}
/// <summary>The length of the video from its headers only (no sample table walked through); null when unreadable.</summary>
public static TimeSpan? ProbeDuration(Stream seekable)
{
ArgumentNullException.ThrowIfNull(seekable);
try
{
seekable.Position = 0;
return ContainerReader.Read(seekable, ContainerReader.AnyDate, samples: false)?.Duration;
}
catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex))
{
return null;
}
}
/// <summary>
/// The sample shown at each instant: the one with the greatest shown time not after it; the first one for an
/// instant before it, the last one for an instant past the end. Empty when the video is not available.
/// </summary>
public IReadOnlyList<VideoFrameTarget> Locate(IReadOnlyList<TimeSpan> instants)
{
ArgumentNullException.ThrowIfNull(instants);
if (video is null || order.Length == 0)
{
return [];
}
var targets = new VideoFrameTarget[instants.Count];
for (var i = 0; i < instants.Count; i++)
{
var sample = SampleAt(instants[i]);
targets[i] = new VideoFrameTarget(i, instants[i], ShownAt(sample), sample);
}
return targets;
}
/// <summary>
/// Decodes the targets lazily, in decoding order (not the order of the instants): each frame comes out as soon as it
/// is decoded and must be disposed by the caller. A target whose sample gives no picture (a damaged stream) is left
/// out; targets on the same sample each get their own copy.
/// </summary>
public IEnumerable<VideoFrame> Decode(IReadOnlyList<VideoFrameTarget> targets, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(targets);
return video is null || stream is null || targets.Count == 0 ? [] : DecodeCore(targets, ct);
}
private IEnumerable<VideoFrame> DecodeCore(IReadOnlyList<VideoFrameTarget> targets, CancellationToken ct)
{
var bySample = targets.Where(t => t.Sample >= 0 && t.Sample < shown.Length)
.GroupBy(t => t.Sample)
.ToDictionary(g => g.Key, g => g.OrderBy(t => t.Index).ToArray());
int[] samples = [.. bySample.Keys.Order()];
foreach (var (sample, image) in VideoFrameDecoder.DecodeExact(stream!, video!, samples, ct))
{
var wanted = bySample[sample];
for (var i = 0; i < wanted.Length; i++)
{
var copy = i == wanted.Length - 1 ? image : new RgbaImage(image.Width, image.Height, image.ToArray());
yield return new VideoFrame(wanted[i].Index, wanted[i].Requested, wanted[i].Actual, copy);
}
}
}
/// <inheritdoc />
public void Dispose()
{
// The stream belongs to the caller; nothing else is held.
}
private int SampleAt(TimeSpan at)
{
// Exact comparison of at (100 ns ticks) with a shown time (track units): at·timescale against shown·10⁷.
var timescale = (Int128)video!.Timescale;
var wanted = (Int128)at.Ticks * timescale;
int low = 0, high = order.Length - 1, best = -1;
while (low <= high)
{
var middle = (low + high) / 2;
if ((Int128)shown[order[middle]] * TimeSpan.TicksPerSecond <= wanted)
{
best = middle;
low = middle + 1;
}
else
{
high = middle - 1;
}
}
if (best < 0)
{
return order[0];
}
// Among samples shown at the same time, the first in decoding order.
while (best > 0 && shown[order[best - 1]] == shown[order[best]])
{
best--;
}
return order[best];
}
/// <summary>The shown time of a sample as a TimeSpan, rounded up to the tick (never before it is shown).</summary>
private TimeSpan ShownAt(int sample)
{
var timescale = (Int128)Math.Max(1, video!.Timescale);
var units = (Int128)Math.Max(0, shown[sample]);
var ticks = ((units * TimeSpan.TicksPerSecond) + timescale - 1) / timescale;
return TimeSpan.FromTicks((long)Int128.Min(ticks, TimeSpan.MaxValue.Ticks));
}
private TimeSpan Duration(MediaContainer container)
{
if (container.Duration is { } d && d > TimeSpan.Zero)
{
return d;
}
if (video!.Duration > 0 && video.Timescale > 0)
{
return TimeSpan.FromTicks((long)((Int128)video.Duration * TimeSpan.TicksPerSecond / video.Timescale));
}
return order.Length == 0 ? TimeSpan.Zero : ShownAt(order[^1]) + FrameDuration();
}
private TimeSpan FrameDuration()
{
if (order.Length < 2 || video!.Timescale <= 0)
{
return TimeSpan.Zero;
}
var span = (Int128)(shown[order[^1]] - shown[order[0]]) * TimeSpan.TicksPerSecond;
return TimeSpan.FromTicks((long)(span / video.Timescale / (order.Length - 1)));
}
private static int Rotation(int rotation) => ((rotation % 360) + 360) % 360 is var r && r is 90 or 180 or 270 ? r : 0;
private static string Codec(VideoTrack video) =>
video.Codec is VideoCodec.H264 or VideoCodec.Hevc ? video.Codec.ToString() : video.CodecTag;
}
/// <summary>The frames part of the decoder: what <see cref="VideoFrameReader"/> needs of its private machinery.</summary>
public sealed partial class VideoFrameDecoder
{
/// <summary>The track frames can be taken from: H.264 or HEVC with its samples and configuration; else null.</summary>
internal static VideoTrack? FrameTrack(MediaContainer container) =>
container.Video is { Samples.Count: > 0, Encoded: false } video && video.Codec switch
{
VideoCodec.H264 => video.AnnexB || video.AvcConfiguration is not null,
VideoCodec.Hevc => video.AnnexB || video.HevcConfiguration is not null,
_ => false,
}
? video
: null;
/// <summary>Whether an exception while reading a video means a file that cannot be read (not a bug).</summary>
internal static bool IsUnreadableFile(Exception ex) => IsUnreadable(ex);
/// <summary>
/// Decodes the samples (ascending indices) exactly, each from an IDR picture or a recovery point shown no later than
/// it (else from the first sample), and gives each frame in RGBA, rotated upright, in decoding order.
/// </summary>
internal static IEnumerable<(int Sample, RgbaImage Image)> DecodeExact(Stream stream, VideoTrack video, int[] samples,
CancellationToken ct)
{
var decoding = new Decoding(stream, video, int.MaxValue, exact: true);
foreach (var (sample, frame) in decoding.Decode(samples, ct))
{
yield return (sample, ToRgba(frame, video.Rotation));
}
}
/// <summary>A frame at full size in RGBA (alpha 255), brought to 8 bits, then turned as the video is shown.</summary>
private static RgbaImage ToRgba(Frame frame, int rotation)
{
RgbaImage image;
if (frame.Hevc is { } h)
{
image = ToRgba(Planes(h), h.MatrixCoefficients, h.FullRange);
}
else
{
var a = frame.Avc!;
image = a.BytesPerSample == 2
? ToRgba(WidePlanes(a), a.MatrixCoefficients, a.FullRange)
: ToRgba(Planes(a), a.MatrixCoefficients, a.FullRange);
}
var orientation = (((rotation % 360) + 360) % 360) switch
{
90 => 6,
180 => 3,
270 => 8,
_ => 1,
};
var upright = ImageOrientation.Apply(image, orientation);
if (!ReferenceEquals(upright, image))
{
image.Dispose();
}
return upright;
}
private static RgbaImage ToRgba<T>(in YuvPlanes<T> planes, int matrix, bool fullRange)
where T : unmanaged, System.Numerics.IBinaryInteger<T>
{
var image = new RgbaImage(planes.Width, planes.Height);
var k = YuvToRgb.For(matrix, fullRange, planes.BitDepthY, planes.BitDepthC, planes.Height);
YuvToRgb.Convert(planes, k, 1, image.Pixels, planes.Width * RgbaImage.BytesPerPixel, RgbaImage.BytesPerPixel,
planes.Width, planes.Height);
return image;
}
}
+25 -6
View File
@@ -89,8 +89,15 @@ public static class WindowsFileNames
/// keeping its extension; then the longest folder segments. A shortened part ends with <c>~</c> and eight hex digits
/// of the SHA-256 of the original, so different names stay different (for example <c>_1</c> and <c>_2</c>).
/// </summary>
/// <param name="baseFolder">The folder the path is below.</param>
/// <param name="segments">The segments.</param>
/// <param name="maxLength">The longest full path.</param>
/// <param name="keepSuffix">
/// When the stem of the file name ends with it (a frame suffix, «_t0m12s340»), the part before it is shortened and the
/// hash goes before it: «nome~1a2b3c4d_t0m12s340.png». Null: the whole stem may be cut, as before tappa E3.
/// </param>
/// <exception cref="PathTooLongException">Even shortened, the path does not fit (the base folder is too long).</exception>
public static IReadOnlyList<string> FitPath(string baseFolder, IReadOnlyList<string> segments, int maxLength = MaxPathLength)
public static IReadOnlyList<string> FitPath(string baseFolder, IReadOnlyList<string> segments, int maxLength = MaxPathLength, string? keepSuffix = null)
{
ArgumentNullException.ThrowIfNull(baseFolder);
ArgumentNullException.ThrowIfNull(segments);
@@ -111,11 +118,11 @@ public static class WindowsFileNames
// 1. The file name, keeping its extension.
var last = parts.Length - 1;
var (stem, extension) = SplitExtension(parts[last]);
var (stem, extension) = SplitKept(parts[last], keepSuffix);
var stemTarget = Math.Max(stem.Length - excess, Math.Min(stem.Length, MinimumStem + HashSuffixLength));
if (stemTarget < stem.Length)
{
parts[last] = Shorten(parts[last], stemTarget + extension.Length, keepExtension: true);
parts[last] = Shorten(parts[last], stemTarget + extension.Length, keepExtension: true, keepSuffix);
excess = Total() - maxLength;
}
@@ -156,10 +163,22 @@ public static class WindowsFileNames
: (fileName[..dot], fileName[dot..]);
}
/// <summary>Shortens a name to at most <paramref name="maxLength"/> characters with a hash suffix of the original.</summary>
private static string Shorten(string name, int maxLength, bool keepExtension)
/// <summary>
/// The stem and the end that is kept of a file name: the extension, preceded by <paramref name="keepSuffix"/> when
/// the stem ends with it.
/// </summary>
private static (string Stem, string Kept) SplitKept(string fileName, string? keepSuffix)
{
var (stem, extension) = keepExtension ? SplitExtension(name) : (name, string.Empty);
var (stem, extension) = SplitExtension(fileName);
return keepSuffix is { Length: > 0 } && stem.Length > keepSuffix.Length && stem.EndsWith(keepSuffix, StringComparison.Ordinal)
? (stem[..^keepSuffix.Length], keepSuffix + extension)
: (stem, extension);
}
/// <summary>Shortens a name to at most <paramref name="maxLength"/> characters with a hash suffix of the original.</summary>
private static string Shorten(string name, int maxLength, bool keepExtension, string? keepSuffix = null)
{
var (stem, extension) = keepExtension ? SplitKept(name, keepSuffix) : (name, string.Empty);
var room = maxLength - extension.Length - HashSuffixLength;
if (room < 1)
{