E3: prove di codec, rimuxaggio, fotogrammi, copie e conversione

Le prove del nucleo della tappa E3 (WP6a), con i media costruiti dalle
prove: il controllo delle foto (stesso formato, HEIC/AVIF/raw, animate,
CMYK e oltre 8 bit, budget di pixel), metadati nei blocchi giusti e
perdite annotate, pixel identici in WEBP senza perdita; il rimuxaggio
da MOV (nuovo TestVideos.Mov) e Matroska a MP4 con campioni, date,
rotazione, lingua ed edit; i fotogrammi H.264 e H.265 all'istante, ogni
k secondi e N in tutto; i suffissi protetti dal taglio a 240; le copie
convertite, com'è con nota, adozione, «già copiato» in ogni forma,
«Copia di nuovo» esatta, spazio sul convertito, fotogrammi nella
cartella delle copie (FrameOnly, una copia per campione, lotti su più
pagine, tetto); la conversione della libreria (perdite, rimuxaggio,
doppioni, importazione delle copie convertite).

Servono a fissare il comportamento di E3 prima dell'unione. Nessun
codice del prodotto cambia; un limite trovato (istanti a meno di 1 ms
in «N in tutto») è annotato per Alberto.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-28 11:00:40 +01:00
1 parent d06b587806
commit f5e12c5d74
9 files changed
+1408 -4

No files matched your search

@@ -0,0 +1,268 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Tests.Codecs.Containers;
using Febe.Tests.Export.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
/// <summary>
/// «Fotogrammi…» → «Nella cartella delle copie» (tappa E3, D4 and D12-D14): frames go to the destination of each
/// account with their suffix, one copy per frame shown, never making the video «Copiato»; photos, accounts that are not
/// exported and videos without frames are skipped; the job waits for engine sessions; a removed frame is written again
/// on request; a request over the cap is refused before anything is recorded. The videos are built by the tests.
/// </summary>
[TestClass]
public sealed class ExportFramesTests
{
private static readonly ElementaryStream Stream = ElementaryStream.Load("BA1_Sony_D");
private static readonly byte[] Mp4 = TestVideos.Mp4(Stream);
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task FramesGoToTheDestinationWithTheirSuffixes()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var duration = TimeSpan.FromMilliseconds((long)Duration(Mp4).TotalMilliseconds); // as the library keeps it
var video = (await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "990", Make.T0.AddDays(-2)), [
new TestFile(Make.Video(1) with { Duration = duration }, Mp4, ".mp4"),
])).Media[0];
var usb = await bed.GeneralAsync(ct: ct);
// «N in tutto»: _f001…_f003, PNG.
var count = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.Count, null, null, 3, ExportFormat.Png)), ct);
Assert.AreEqual((1, 3, 3), (count.Plan.Videos, count.Plan.Frames, count.Plan.Files));
Assert.AreEqual(0L, count.Plan.Bytes, "frames have no size before they are made");
var items = await bed.ItemsAsync(count.Runs.Single().Id, ct);
Assert.IsTrue(items.All(i => i.State == ExportItemState.Copied && i.Variant == ExportVariant.Frame && i.Format == ExportFormat.Png));
CollectionAssert.AreEqual(
ExportFrames.Spread(duration, 3).Select(t => (TimeSpan?)TimeSpan.FromMilliseconds((long)t.TotalMilliseconds)).ToArray(),
items.Select(i => i.FrameAt).ToArray(),
"the item keeps the instant asked (in milliseconds)");
var stem = Path.ChangeExtension(video.RelativePath!, null);
CollectionAssert.AreEqual(
new[] { "_f001", "_f002", "_f003" }.Select(s => "marta.demo/" + stem + s + ".png").ToArray(),
items.Select(i => i.RelativePath).ToArray());
// «Uno ogni k secondi»: the actual instant of the frame shown, rounded up to the millisecond, in the name and the row.
var every = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.Every, null, TimeSpan.FromMilliseconds(250), null, ExportFormat.Jpg)), ct);
var shown = Locate(Mp4, ExportFrames.Every(duration, TimeSpan.FromMilliseconds(250)));
var frames = await bed.ItemsAsync(every.Runs.Single().Id, ct);
Assert.HasCount(shown.Count, frames);
for (var i = 0; i < shown.Count; i++)
{
var copy = (await bed.Db.Exports.GetCopyAsync(frames[i].CopyId!.Value, ct))!;
Assert.AreEqual((ExportVariant.Frame, ExportFormat.Jpg, video.Sha256), (copy.Variant, copy.Format, copy.SourceSha256));
Assert.AreEqual(TimeSpan.FromMilliseconds(ExportFrames.ActualMs(shown[i].Actual)), copy.FrameAt);
Assert.AreEqual("marta.demo/" + stem + ExportFrames.Suffix(FrameMode.Every, shown[i].Actual, i, shown.Count) + ".jpg", copy.RelativePath);
var bytes = await File.ReadAllBytesAsync(Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!)), ct);
CollectionAssert.AreEqual(new byte[] { 0xFF, 0xD8, 0xFF }, bytes[..3]);
}
StringAssert.EndsWith(frames[0].RelativePath, "_t0m00s000.jpg");
Assert.HasCount(3 + shown.Count, Fingerprint.Of(bed.Usb));
Assert.IsTrue(every.Plan.Lossy, "JPG frames are «con perdita»");
Assert.IsFalse(count.Plan.Lossy);
Assert.IsTrue(File.Exists(bed.LibraryFile(bed.Marta, video)));
Assert.HasCount(3 + shown.Count, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct));
}
[TestMethod]
public async Task TheSameFrameShownIsCopiedOnceAndABatchSpansPages()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var still = TestVideos.Mp4(Stream.FirstPictureRepeated(30)); // one second, 30 samples
var video = (await SaveVideoAsync(bed, bed.Marta, "991", still, ".mp4")).Media[0];
await bed.GeneralAsync(ct: ct);
// 600 instants (more than a page of the copier, at least a millisecond apart) on 30 frames: each frame shown once.
const int N = 600;
var targets = Locate(still, ExportFrames.Spread(Duration(still), N));
var leaders = targets.Select((t, i) => (t.Sample, i)).GroupBy(x => x.Sample).Select(g => g.First().i).ToList();
Assert.HasCount(30, leaders);
var start = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.Count, null, null, N, ExportFormat.Png)), ct);
var items = await bed.ItemsAsync(start.Runs.Single().Id, ct);
Assert.HasCount(N, items);
Assert.AreEqual(leaders.Count, items.Count(i => i.State == ExportItemState.Copied));
Assert.AreEqual(N - leaders.Count, items.Count(i => i.State == ExportItemState.AlreadyCopied));
Assert.HasCount(leaders.Count, Fingerprint.Of(bed.Usb));
var stem = Path.ChangeExtension(video.RelativePath!, null);
foreach (var k in leaders)
{
Assert.AreEqual("marta.demo/" + stem + ExportFrames.Suffix(FrameMode.Count, targets[k].Actual, k, N) + ".png", items[k].RelativePath, $"frame {k}");
}
// A follower points at its leader's copy.
for (var k = 0; k < N; k++)
{
Assert.AreEqual(items[leaders.First(l => targets[l].Sample == targets[k].Sample)].CopyId, items[k].CopyId, $"item {k}");
}
}
[TestMethod]
public async Task FramesDoNotMakeTheFileCopied()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "992", Make.T0.AddDays(-2)), [
new TestFile(Make.Video(1) with { Duration = null }, Mp4, ".mp4"),
new TestFile(Make.Video(2) with { Duration = null }, TestVideos.Mov(Stream), ".mov"),
]);
var (first, second) = (post.Media[0], post.Media[1]);
await bed.GeneralAsync(ct: ct);
await bed.CopyAsync(Frames(first, new ExportFramesRequest(FrameMode.At, TimeSpan.FromMilliseconds(300), null, null, ExportFormat.Png)), ct);
Assert.AreEqual(new ExportEntryCopies(2, 0, 1), (await bed.Db.Exports.GetEntryCopyCountsAsync([post.Entry.Id], ct))[post.Entry.Id]);
Assert.AreEqual(ExportMark.FrameOnly, (await bed.Db.Exports.GetEntryMarksAsync([post.Entry.Id], ct))[post.Entry.Id]);
var files = await bed.Db.Exports.GetFileMarksAsync([first.Id, second.Id], ct);
Assert.AreEqual((ExportMark.FrameOnly, ExportMark.None), (files[first.Id], files[second.Id]));
Assert.IsTrue((await EntriesAsync(bed, LibraryCopiesFilter.NotCopied, ct)).Contains(post.Entry.Id), "still «Non ancora copiato»");
Assert.IsFalse((await EntriesAsync(bed, LibraryCopiesFilter.Copied, ct)).Contains(post.Entry.Id));
Assert.AreEqual(2, (await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct)).NotCopied);
// The second video copied whole: «Copiato in parte», the first one is still not copied.
await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([second.Id])), ct);
Assert.AreEqual(new ExportEntryCopies(2, 1, 1), (await bed.Db.Exports.GetEntryCopyCountsAsync([post.Entry.Id], ct))[post.Entry.Id]);
Assert.AreEqual(ExportMark.Partly, (await bed.Db.Exports.GetEntryMarksAsync([post.Entry.Id], ct))[post.Entry.Id]);
Assert.AreEqual(1, (await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct)).NotCopied);
// «Copia in…» of the entry copies the first video whole (the frame does not count) and nothing else.
var whole = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Entries([post.Entry.Id])), ct);
Assert.AreEqual((1, 1), (whole.Plan.Files, whole.Plan.AlreadyCopied));
Assert.AreEqual(ExportMark.Copied, (await bed.Db.Exports.GetEntryMarksAsync([post.Entry.Id], ct))[post.Entry.Id]);
Assert.HasCount(3, Fingerprint.Of(bed.Usb));
}
[TestMethod]
public async Task PhotosAccountsNotExportedAndVideosWithoutFramesAreSkipped()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var mixed = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "993", Make.T0.AddDays(-2)), [
ExportTestBed.Photo(1, 50),
new TestFile(Make.Video(2) with { Duration = null }, Mp4, ".mp4"),
]);
var noise = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "994", Make.T0.AddDays(-3)), [TestFile.Video(1, 4000)]);
var luca = await SaveVideoAsync(bed, bed.Luca, "995", TestVideos.Mov(Stream), ".mov");
await bed.GeneralAsync(ct: ct);
await bed.Service.Destinations.SetAccountEnabledAsync(bed.Luca.Id, false, ct);
var request = new ExportJobRequest(
new ExportSelection.Entries([mixed.Entry.Id, noise.Entry.Id, luca.Entry.Id]),
Frames: new ExportFramesRequest(FrameMode.At, TimeSpan.Zero, null, null, ExportFormat.Png));
var start = await bed.CopyAsync(request, ct);
Assert.AreEqual((1, 1, 2), (start.Plan.PhotosSkipped, start.Plan.NotExported, start.Plan.Videos));
var items = await bed.ItemsAsync(start.Runs.Single().Id, ct);
Assert.HasCount(2, items, "no item for the photo, nor for the account that is not exported");
Assert.AreEqual(ExportItemState.Copied, items.Single(i => i.MediaId == mixed.Media[1].Id).State);
var unavailable = items.Single(i => i.MediaId == noise.Media[0].Id);
Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.FrameNotAvailable, (long?)null), (unavailable.State, unavailable.Note, unavailable.CopyId));
Assert.AreEqual("Fotogramma non disponibile per questo video", ExportText.Note(unavailable.Note));
Assert.HasCount(1, Fingerprint.Of(bed.Usb));
Assert.HasCount(1, await bed.Db.Exports.ListCopiesAsync(start.Runs.Single().DestinationId, ct: ct), "no copy row for a frame that is not there");
}
[TestMethod]
public async Task AFramesJobWaitsForTheEngineSession()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync(env => env with { Session = new CountedSession(3) });
var video = (await SaveVideoAsync(bed, bed.Marta, "996", Mp4, ".mp4")).Media[0];
await bed.GeneralAsync(ct: ct);
var before = bed.Clock.Now;
var start = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.Count, null, null, 2, ExportFormat.Png)), ct);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(start.Runs.Single().Id, ct)).State);
Assert.IsGreaterThanOrEqualTo(before + TimeSpan.FromSeconds(10), bed.Clock.Now, "polled while the session ran");
Assert.HasCount(2, Fingerprint.Of(bed.Usb));
}
[TestMethod]
public async Task ARemovedFrameIsWrittenAgainOnRequest()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var video = (await SaveVideoAsync(bed, bed.Marta, "997", Mp4, ".mp4")).Media[0];
var usb = await bed.GeneralAsync(ct: ct);
var request = Frames(video, new ExportFramesRequest(FrameMode.At, TimeSpan.FromMilliseconds(400), null, null, ExportFormat.WebpLossless));
var first = (await bed.ItemsAsync((await bed.CopyAsync(request, ct)).Runs.Single().Id, ct)).Single();
var path = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(first.RelativePath!));
var bytes = await File.ReadAllBytesAsync(path, ct);
File.Delete(path);
await bed.Service.CheckCopiesAsync(usb.Id, ct);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(first.CopyId!.Value, ct))!.State);
// An explicit frames request writes it again (D14), without «Copia di nuovo»: the same bytes, a new row.
var second = (await bed.ItemsAsync((await bed.CopyAsync(request, ct)).Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.Copied, first.RelativePath), (second.State, second.RelativePath));
Assert.AreNotEqual(first.CopyId, second.CopyId);
CollectionAssert.AreEqual(bytes, await File.ReadAllBytesAsync(path, ct), "the same frame gives the same bytes");
Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(first.CopyId!.Value, ct))!.State);
// Asked once more while it is there: «Già copiato».
var third = (await bed.ItemsAsync((await bed.CopyAsync(request, ct)).Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.AlreadyCopied, second.CopyId), (third.State, third.CopyId));
}
[TestMethod]
public async Task OverTheCapIsRefusedBeforeAnythingIsRecorded()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var video = (await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "998", Make.T0.AddDays(-2)), [
new TestFile(Make.Video(1) with { Duration = TimeSpan.FromSeconds(200) }, Mp4, ".mp4"),
])).Media[0];
await bed.GeneralAsync(ct: ct);
var request = Frames(video, new ExportFramesRequest(FrameMode.Every, null, TimeSpan.FromMilliseconds(100), null, ExportFormat.Png));
Assert.AreEqual(1, (await bed.Service.PlanAsync(request, ct)).OverCap);
var refused = await Assert.ThrowsExactlyAsync<ArgumentException>(() => bed.Service.StartAsync(request, ct));
StringAssert.StartsWith(refused.Message, ExportFrames.OverCapMessage);
Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
Assert.IsEmpty(Fingerprint.Of(bed.Usb));
}
private static ExportJobRequest Frames(Media video, ExportFramesRequest frames) => new(new ExportSelection.Media([video.Id]), Frames: frames);
/// <summary>A video whose length the library does not know (it is read when the job is recorded).</summary>
private static Task<EntryWithMedia> SaveVideoAsync(ExportTestBed bed, Account account, string code, byte[] bytes, string extension) =>
bed.Library.SaveAsync(account, Make.Entry(account.Id, code, Make.T0.AddDays(-2)), [new TestFile(Make.Video(1) with { Duration = null }, bytes, extension)]);
private static TimeSpan Duration(byte[] video)
{
using var stream = new MemoryStream(video);
using var reader = VideoFrameReader.Open(stream, out var info);
Assert.IsTrue(info.Available);
return info.Duration;
}
private static IReadOnlyList<VideoFrameTarget> Locate(byte[] video, IReadOnlyList<TimeSpan> instants)
{
using var stream = new MemoryStream(video);
using var reader = VideoFrameReader.Open(stream, out _);
return reader.Locate(instants);
}
private static async Task<List<long>> EntriesAsync(ExportTestBed bed, LibraryCopiesFilter filter, CancellationToken ct) =>
[.. (await bed.Db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = new LibraryFilter { Copies = filter } }, ct)).Tiles.Select(t => t.EntryId)];
/// <summary>An engine session for the first <paramref name="polls"/> looks, then none.</summary>
private sealed class CountedSession(int polls) : IEngineSessionState
{
private int _left = polls;
public bool InSession => Interlocked.Decrement(ref _left) >= 0;
}
}