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,122 @@
using System.Security.Cryptography;
using Febe.Core.Codecs.Images;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Library.Conversion;
using Febe.Tests.Codecs.Containers;
namespace Febe.Tests.Export;
/// <summary>
/// Instants, suffixes and labels of frames (tappa E3, D12 and D13), the protected suffix of the shortening and of the
/// numbered names (WP1.8), and the environment-free media conversion (WP1.6b).
/// </summary>
[TestClass]
public sealed class ExportFrameNamesTests
{
[TestMethod]
public void EveryKSecondsStartsAtZeroAndStopsBeforeTheEnd()
{
var instants = ExportFrames.Every(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(500));
CollectionAssert.AreEqual(
new[] { 0, 500, 1000, 1500 }.Select(ms => TimeSpan.FromMilliseconds(ms)).ToArray(),
instants.ToArray());
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => ExportFrames.Every(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(50)));
var over = Assert.ThrowsExactly<ArgumentException>(() => ExportFrames.Every(TimeSpan.FromHours(1), TimeSpan.FromSeconds(1)));
StringAssert.StartsWith(over.Message, ExportFrames.OverCapMessage);
}
[TestMethod]
public void NInAllAreCentred()
{
var instants = ExportFrames.Spread(TimeSpan.FromSeconds(4), 4);
CollectionAssert.AreEqual(
new[] { 500, 1500, 2500, 3500 }.Select(ms => TimeSpan.FromMilliseconds(ms)).ToArray(),
instants.ToArray());
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => ExportFrames.Spread(TimeSpan.FromSeconds(4), 1001));
}
[TestMethod]
public void SuffixesAndLabels()
{
var actual = TimeSpan.FromTicks((12_340 * TimeSpan.TicksPerMillisecond) - 3); // rounded up to 12.340 s
Assert.AreEqual("_t0m12s340", ExportFrames.Suffix(FrameMode.At, actual, 0, 1));
Assert.AreEqual("_t1m05s000", ExportFrames.Suffix(FrameMode.Every, TimeSpan.FromSeconds(65), 3, 9));
Assert.AreEqual("_f001", ExportFrames.Suffix(FrameMode.Count, actual, 0, 12));
Assert.AreEqual("_f0042", ExportFrames.Suffix(FrameMode.Count, actual, 41, 1000));
Assert.AreEqual("0:01", ExportFrames.Label(TimeSpan.FromSeconds(1)));
Assert.AreEqual("0:01,25", ExportFrames.Label(TimeSpan.FromMilliseconds(1250)));
Assert.AreEqual("2:03,007", ExportFrames.Label(TimeSpan.FromMilliseconds(123_007)));
}
[TestMethod]
public void AKeptSuffixIsNotCutAndNumberingComesAfterIt()
{
var root = "/destinazione/" + new string('d', 120);
var name = new string('n', 200) + "_t0m12s340.png";
var fitted = WindowsFileNames.FitPath(root, ["post", name], keepSuffix: "_t0m12s340");
Assert.EndsWith("_t0m12s340.png", fitted[^1]);
Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, root.Length + fitted.Sum(s => s.Length + 1));
CollectionAssert.AreEqual(
WindowsFileNames.FitPath(root, ["post", name]).ToArray(),
WindowsFileNames.FitPath(root, ["post", name], keepSuffix: null).ToArray(),
"Senza suffisso nulla cambia.");
var numbered = ExportPaths.NumberedName(root, "post/" + name, 2, keepSuffix: "_t0m12s340");
Assert.EndsWith("_t0m12s340 (2).png", numbered);
Assert.AreEqual("post/a_f001 (3).png", ExportPaths.NumberedName("/d", "post/a_f001.png", 3, keepSuffix: "_f001"));
}
[TestMethod]
public async Task APhotoIsConvertedWithItsShaAndAChangedSourceIsRefused()
{
using var picture = Imaging.TestImages.Gradient(40, 30, seed: 5);
var png = ImageConverter.Encode(picture, ImageFormat.Png, null);
var sha = Convert.ToHexStringLower(SHA256.HashData(png));
using var jpg = await MediaConverter.PrepareAsync(() => new MemoryStream(png), "a/b.png", MediaKind.Photo,
ExportFormat.Jpg, sha, new ConversionThrottle(), CancellationToken.None);
using var output = new MemoryStream();
await jpg.Produce(output, CancellationToken.None);
Assert.AreEqual(ExportVariant.Converted, jpg.Variant);
Assert.AreEqual(".jpg", jpg.Extension);
Assert.AreEqual(jpg.Length, output.Length);
Assert.AreEqual(jpg.Sha256, Convert.ToHexStringLower(SHA256.HashData(output.ToArray())));
CollectionAssert.Contains(jpg.Notes.ToList(), ImageConversionLosses.TransparencyWhite);
using var same = await MediaConverter.PrepareAsync(() => new MemoryStream(png), "a/b.png", MediaKind.Photo,
ExportFormat.Png, sha, ConversionThrottle.Shared, CancellationToken.None);
Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original, sha, ".png"), (same.Variant, same.Format, same.Sha256, same.Extension));
await Assert.ThrowsExactlyAsync<ContentChangedException>(() => MediaConverter.PrepareAsync(() => new MemoryStream(png),
"a/b.png", MediaKind.Photo, ExportFormat.Jpg, new string('0', 64), ConversionThrottle.Shared, CancellationToken.None));
}
[TestMethod]
public async Task AVideoIsRemuxedOrCopiedWithTheReason()
{
var es = ElementaryStream.Load("BA1_Sony_D");
var mkv = TestVideos.Matroska(es);
var sha = Convert.ToHexStringLower(SHA256.HashData(mkv));
using var remux = await MediaConverter.PrepareAsync(() => new MemoryStream(mkv), "v.mkv", MediaKind.Video,
ExportFormat.Mp4, sha, ConversionThrottle.Shared, CancellationToken.None);
using var output = new MemoryStream();
await remux.Produce(output, CancellationToken.None);
Assert.AreEqual((ExportVariant.Converted, ".mp4", (string?)null), (remux.Variant, remux.Extension, remux.Sha256));
Assert.AreEqual(remux.Length, output.Length);
var garbage = new byte[2048];
using var asIs = await MediaConverter.PrepareAsync(() => new MemoryStream(garbage), "v.mov", MediaKind.Video,
ExportFormat.Mp4, sha, ConversionThrottle.Shared, CancellationToken.None);
Assert.AreEqual(ExportVariant.Whole, asIs.Variant);
Assert.HasCount(1, asIs.Notes);
StringAssert.StartsWith(asIs.Notes[0], MediaConversionResult.AsIsNotRemuxable + ":");
}
}
@@ -0,0 +1,90 @@
using System.Security.Cryptography;
using Febe.Core.Codecs.Images;
using static Febe.Tests.Imaging.TestImages;
namespace Febe.Tests.Imaging;
/// <summary>
/// The photo conversion of tappa E3: what is copied as it is and why (D5, D6), what a conversion reports instead of
/// throwing, and that converting the same picture twice gives the same bytes (D9).
/// </summary>
[TestClass]
public sealed class ImageConversionTests
{
private static readonly byte[] Palette4 = [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255];
[TestMethod]
[DataRow(ImageFormat.Jpeg)]
[DataRow(ImageFormat.Png)]
[DataRow(ImageFormat.WebP)]
public void ConvertingTwiceGivesTheSameBytes(ImageFormat target)
{
using var picture = Gradient(97, 61, seed: 7);
var source = ImageConverter.Encode(picture, target == ImageFormat.Png ? ImageFormat.Jpeg : ImageFormat.Png, null);
var first = ImageConverter.Convert(source, target);
var second = ImageConverter.Convert(source, target);
Assert.AreEqual(target, ImageFormatSniffer.Detect(first.Data));
CollectionAssert.AreEqual(SHA256.HashData(first.Data), SHA256.HashData(second.Data));
Assert.AreEqual(target == ImageFormat.Jpeg, first.Lossy);
}
[TestMethod]
public void WebpCostsUseNoFloatingPointLog()
{
// The fixed-point log2 of the VP8L cost estimates is exact on powers of two and monotonic.
var previous = -1L;
for (ulong v = 1; v < 70_000; v += 13)
{
var log = Vp8LEncoder.Log2Fixed(v);
Assert.IsGreaterThanOrEqualTo(previous, log);
previous = log;
}
Assert.AreEqual(10L << 16, Vp8LEncoder.Log2Fixed(1024));
Assert.AreEqual(20L << 16, Vp8LEncoder.Log2Fixed(1UL << 20));
Assert.AreEqual(0L, Vp8LEncoder.Log2Fixed(1));
}
[TestMethod]
public void TheSameFormatIsCopiedAsItIs()
{
using var picture = Gradient(16, 16, seed: 3);
var png = ImageConverter.Encode(picture, ImageFormat.Png, null);
var check = ImageConverter.Check(png, ImageFormat.Png);
Assert.AreEqual(ImageConversionAction.CopyAsIs, check.Action);
Assert.IsNull(check.NoteCode);
Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(png, ImageFormat.Jpeg).Action);
}
[TestMethod]
public void AnimationsAndDamagedFilesAreCopiedWithTheirReason()
{
byte[] indices = [0, 1];
var animated = Gif(2, 1, Palette4, GifFrame(0, 0, 2, 1, indices, 2), GifControl(1), GifFrame(0, 0, 2, 1, indices, 2));
var still = Gif(2, 1, Palette4, GifFrame(0, 0, 2, 1, indices, 2));
Assert.AreEqual(ImageConversionLosses.AsIsAnimated, ImageConverter.Check(animated, ImageFormat.Png).NoteCode);
Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(still, ImageFormat.Png).Action);
var damaged = ImageConverter.Check(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, ImageFormat.Jpeg);
Assert.AreEqual(ImageConversionAction.CopyOriginal, damaged.Action);
Assert.AreEqual(ImageConversionLosses.AsIsNotDecodable, damaged.NoteCode);
}
[TestMethod]
public void TransparencyToJpgIsAnnouncedAndTheImageIsLeftAlone()
{
using var picture = Random(8, 8, seed: 11);
var before = picture.ToArray();
var png = ImageConverter.Encode(picture, ImageFormat.Png, null);
var result = ImageConverter.Convert(png, ImageFormat.Jpeg);
_ = ImageConverter.Encode(picture, ImageFormat.Jpeg, null);
CollectionAssert.Contains(result.Losses.ToList(), ImageConversionLosses.TransparencyWhite);
CollectionAssert.AreEqual(before, picture.ToArray(), "Encode lavora su una copia.");
}
}
@@ -14,6 +14,36 @@ public sealed class SafeFileWriterTests
return bytes;
}
[TestMethod]
public async Task ProducedContentIsHashedAndATakenNameIsNumberedAfterTheKeptSuffix()
{
using var temp = new TempFolder();
var content = Content(3000, 7);
Directory.CreateDirectory(Path.Combine(temp.Path, "post"));
File.WriteAllBytes(Path.Combine(temp.Path, "post", "a_f001.png"), [1, 2, 3]);
var tempDirectory = Path.Combine(temp.Path, ".tmp");
Directory.CreateDirectory(tempDirectory);
FileDigest? seen = null;
var saved = await new SafeFileWriter().SaveAsync(
(output, token) => output.WriteAsync(content, token).AsTask(),
temp.Path,
tempDirectory,
(digest, _) =>
{
seen = digest;
return ValueTask.FromResult<string?>("post/a_f001.png");
},
new SafeWriteOptions { KeepSuffix = "_f001" });
Assert.IsNotNull(saved);
Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(content)), seen!.Value.Sha256);
Assert.AreEqual(3000L, seen.Value.Bytes);
Assert.AreEqual("post/a_f001 (2).png", saved.RelativePath);
CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, File.ReadAllBytes(Path.Combine(temp.Path, "post", "a_f001.png")), "Il file che c'era non è toccato.");
CollectionAssert.AreEqual(content, File.ReadAllBytes(saved.FullPath));
}
[TestMethod]
public async Task WritesTheFileWithItsHashAndPublicationTime()
{
@@ -0,0 +1,153 @@
using System.Security.Cryptography;
using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.H264;
using Febe.Core.Export;
using Febe.Core.Library;
namespace Febe.Tests.Codecs.Containers;
/// <summary>
/// Frames at chosen instants (tappa E3, D12): the sample shown at an instant, exact decoding at full size, rotation,
/// and the remux into MP4 (D9: the same bytes every time).
/// </summary>
[TestClass]
public sealed class VideoFramesTests
{
[TestMethod]
[DataRow("mp4")]
[DataRow("mkv")]
public void TheFrameAtAnInstantIsTheOneShown(string kind)
{
var es = ElementaryStream.Load("CABA3_SVA_B");
var data = kind == "mkv" ? TestVideos.Matroska(es) : TestVideos.Mp4(es);
using var stream = new MemoryStream(data);
using var reader = VideoFrameReader.Open(stream, out var info);
Assert.IsTrue(info.Available);
Assert.AreEqual((es.Width, es.Height), (info.Width, info.Height));
// 30 frames per second: 0.51 s shows frame 15 (shown at 0.5 s), 0.499 s still frame 14. The Matroska file starts
// showing later by the reordering delay of its B frames (its block times are presentation times as written).
var shift = kind == "mkv" ? Enumerable.Range(0, es.Count).Max(i => i - es.Rank[i]) : 0;
var targets = reader.Locate([TimeSpan.FromMilliseconds(510), TimeSpan.FromMilliseconds(499)]);
Assert.AreEqual(TimeSpan.FromMilliseconds(500), targets[0].Actual);
Assert.AreEqual(500L, ExportFrames.ActualMs(targets[0].Actual));
Assert.IsLessThan(TimeSpan.FromMilliseconds(500), targets[1].Actual);
var frames = reader.Decode(targets, CancellationToken.None).ToList();
try
{
Assert.HasCount(2, frames);
foreach (var (frame, rank) in new[] { (frames.Single(f => f.Index == 0), 15 - shift), (frames.Single(f => f.Index == 1), 14 - shift) })
{
var expected = VideoFrameDecoder.ToImage(ShownFrame(es, rank), 0, 0);
Assert.AreEqual((expected.Width, expected.Height), (frame.Image.Width, frame.Image.Height));
var pixels = frame.Image.ToArray();
for (var i = 0; i < expected.Width * expected.Height; i++)
{
Assert.AreEqual(expected.Rgb[i * 3], pixels[i * 4]);
Assert.AreEqual(expected.Rgb[(i * 3) + 1], pixels[(i * 4) + 1]);
Assert.AreEqual(expected.Rgb[(i * 3) + 2], pixels[(i * 4) + 2]);
Assert.AreEqual((byte)255, pixels[(i * 4) + 3]);
}
}
}
finally
{
frames.ForEach(f => f.Dispose());
}
}
[TestMethod]
public void BeforeTheStartAndPastTheEndGiveTheFirstAndLastFrames()
{
var es = ElementaryStream.Load("CABA3_SVA_B");
using var stream = new MemoryStream(TestVideos.Mp4(es));
using var reader = VideoFrameReader.Open(stream, out var info);
var targets = reader.Locate([TimeSpan.Zero, TimeSpan.FromHours(1), info.Duration]);
Assert.AreEqual(Array.IndexOf(es.Rank, 0), targets[0].Sample);
Assert.AreEqual(Array.IndexOf(es.Rank, es.Count - 1), targets[1].Sample);
Assert.AreEqual(targets[1].Sample, targets[2].Sample);
}
[TestMethod]
public void ReRequestingTheActualMsGivesTheSameFrame()
{
var es = ElementaryStream.Load("CABA3_SVA_B");
using var stream = new MemoryStream(TestVideos.Matroska(es));
using var reader = VideoFrameReader.Open(stream, out var info);
var instants = ExportFrames.Spread(info.Duration, 7);
var first = reader.Locate(instants);
var again = reader.Locate([.. first.Select(t => TimeSpan.FromMilliseconds(ExportFrames.ActualMs(t.Actual)))]);
CollectionAssert.AreEqual(first.Select(t => t.Sample).ToArray(), again.Select(t => t.Sample).ToArray());
}
[TestMethod]
public void RotationIsApplied()
{
var es = ElementaryStream.Load("BA1_Sony_D");
using var stream = new MemoryStream(TestVideos.Mp4(es, rotation: 90));
using var reader = VideoFrameReader.Open(stream, out var info);
Assert.AreEqual((es.Height, es.Width), (info.Width, info.Height));
using var frame = reader.Decode(reader.Locate([TimeSpan.Zero]), CancellationToken.None).Single();
Assert.AreEqual((es.Height, es.Width), (frame.Image.Width, frame.Image.Height));
}
[TestMethod]
public void AnUnreadableVideoSaysNotAvailable()
{
using var stream = new MemoryStream(new byte[4096]);
using var reader = VideoFrameReader.Open(stream, out var info);
Assert.IsFalse(info.Available);
Assert.AreEqual(VideoFrameReader.NotAvailableMessage, info.Unavailable);
Assert.IsEmpty(reader.Locate([TimeSpan.Zero]));
}
[TestMethod]
public void RemuxingTwiceGivesTheSameBytesOfThePlannedLength()
{
var es = ElementaryStream.Load("CABA3_SVA_B");
var mkv = TestVideos.Matroska(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero));
using var source = new MemoryStream(mkv);
Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "video.mkv", out var plan, CancellationToken.None));
using var first = new MemoryStream();
using var second = new MemoryStream();
Mp4Remuxer.Write(plan!, source, first, CancellationToken.None);
Mp4Remuxer.Write(plan!, source, second, CancellationToken.None);
Assert.AreEqual(plan!.OutputLength, first.Length);
CollectionAssert.AreEqual(SHA256.HashData(first.ToArray()), SHA256.HashData(second.ToArray()));
// The MP4 shows the same frames at the same instants as the Matroska file.
first.Position = 0;
using var remuxed = VideoFrameReader.Open(first, out var info);
Assert.IsTrue(info.Available);
using var original = VideoFrameReader.Open(source, out _);
var instants = ExportFrames.Every(info.Duration, TimeSpan.FromMilliseconds(250));
CollectionAssert.AreEqual(
original.Locate(instants).Select(t => t.Actual).ToArray(),
remuxed.Locate(instants).Select(t => t.Actual).ToArray());
// An MP4 named .mp4 is already what was asked.
using var mp4 = new MemoryStream(TestVideos.Mp4(es));
Assert.AreEqual(RemuxRefusal.AlreadyMp4, Mp4Remuxer.Check(mp4, "video.mp4", out _, CancellationToken.None));
}
/// <summary>The frame shown at position <paramref name="rank"/>, decoded straight from the stream.</summary>
private static H264Frame ShownFrame(ElementaryStream es, int rank)
{
var decoder = new H264Decoder();
var frames = new List<H264Frame>();
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(ElementaryStream.AnnexB(es.Name));
var index = Array.IndexOf(es.Rank, rank);
return frames.Single(f => f.DecodeIndex == index);
}
}