using Febe.Core.Abstractions; using Febe.Core.Codecs.Containers; 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; /// /// «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. /// [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(() => 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)); } [TestMethod] public async Task NInAllOnAVideoShorterThanNMillisecondsNamesEachFrameByItsPosition() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); var still = TestVideos.Mp4(Stream.FirstPictureRepeated(18)); // 0,6 s: 1.000 instants cannot all be a millisecond apart var video = (await SaveVideoAsync(bed, bed.Marta, "993", still, ".mp4")).Media[0]; await bed.GeneralAsync(ct: ct); const int N = 1000; // The instants are whole milliseconds (the item, the preview and the download locate the same one); the first of // those on one millisecond is the item, the others are counted as already there. var instants = ExportFrames.Spread(Duration(still), N); Assert.IsTrue(instants.All(t => t.Ticks % TimeSpan.TicksPerMillisecond == 0)); var firsts = instants.Select((t, i) => (Ms: (long)t.TotalMilliseconds, Index: i)).GroupBy(x => x.Ms).Select(g => g.First()).ToList(); Assert.IsLessThan(N, firsts.Count); var start = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.Count, null, null, N, ExportFormat.Png)), ct); Assert.AreEqual((firsts.Count, N - firsts.Count), (start.Plan.Frames, start.Plan.AlreadyCopied), "the plan says what is recorded"); var items = await bed.ItemsAsync(start.Runs.Single().Id, ct); CollectionAssert.AreEqual(firsts.Select(f => (TimeSpan?)TimeSpan.FromMilliseconds(f.Ms)).ToArray(), items.Select(i => i.FrameAt).ToArray()); // Each frame written is named by its position among the N instants, as «Scarica» names it, not by its row. var targets = Locate(still, [.. firsts.Select(f => TimeSpan.FromMilliseconds(f.Ms))]); var stem = Path.ChangeExtension(video.RelativePath!, null); var leaders = targets.Select((t, k) => (t.Sample, k)).GroupBy(x => x.Sample).Select(g => g.First().k).ToList(); Assert.HasCount(leaders.Count, Fingerprint.Of(bed.Usb)); foreach (var k in leaders) { Assert.AreEqual(ExportItemState.Copied, items[k].State); Assert.AreEqual("marta.demo/" + stem + ExportFrames.Suffix(FrameMode.Count, targets[k].Actual, firsts[k].Index, N) + ".png", items[k].RelativePath, $"frame {k}"); } Assert.AreNotEqual(leaders.Count - 1, firsts[leaders[^1]].Index, "the positions skip the instants on one millisecond"); } [TestMethod] public async Task VideosOfUnknownLengthCountAgainstTheCapsBeforeAnythingIsRecorded() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); await bed.GeneralAsync(ct: ct); // One video of 200 s the library has no length for, one every 0,1 s: 2.000 frames, refused before any run. var long200 = (await SaveVideoAsync(bed, bed.Marta, "980", LongStill(200), ".mp4")).Media[0]; var every = Frames(long200, new ExportFramesRequest(FrameMode.Every, null, TimeSpan.FromMilliseconds(100), null, ExportFormat.Png)); var overCap = await Assert.ThrowsExactlyAsync(() => bed.Service.StartAsync(every, ct)); StringAssert.StartsWith(overCap.Message, ExportFrames.OverCapMessage); Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct)); // 21 videos of a second without a length, 1.000 each: 21.000 frames, over the 20.000 of a request. var still = Stream.FirstPictureRepeated(30); var ids = new List(); for (var i = 0; i < 21; i++) { ids.Add((await SaveVideoAsync(bed, bed.Marta, $"96{i:D2}", TestVideos.Mp4(still, Make.T0.AddDays(-i)), ".mp4")).Media[0].Id); } var many = new ExportJobRequest(new ExportSelection.Media(ids), Frames: new ExportFramesRequest(FrameMode.Count, null, null, 1000, ExportFormat.Png)); var tooMany = await Assert.ThrowsExactlyAsync(() => bed.Service.StartAsync(many, ct)); StringAssert.StartsWith(tooMany.Message, ExportService.TooManyFramesText); Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct)); Assert.IsEmpty(Fingerprint.Of(bed.Usb)); Assert.AreEqual(21, (await bed.Service.PlanAsync(many, ct)).Frames, "the dialog does not read the files: «circa» one a video"); // Two of them, 3 each: measured when the job is recorded, the plan of the start says what was recorded. var two = new ExportJobRequest(new ExportSelection.Media(ids.Take(2).ToList()), Frames: new ExportFramesRequest(FrameMode.Count, null, null, 3, ExportFormat.Png)); var started = await bed.CopyAsync(two, ct); Assert.AreEqual((2, 6), (started.Plan.Videos, started.Plan.Frames)); Assert.HasCount(6, await bed.ItemsAsync(started.Runs.Single().Id, ct)); } /// A video of one still picture shown for . private static byte[] LongStill(int seconds) { var es = Stream.FirstPictureRepeated(1); var bytes = es.LengthPrefixed(0); var track = new Mp4OutputTrack { IsVideo = true, Timescale = TestVideos.Timescale, Samples = [new Mp4OutputSample(bytes.Length, 0, 0, true)], WriteSample = (_, s) => s.Write(bytes), Width = es.Width, Height = es.Height, AvcConfiguration = es.AvcC, LastSampleDuration = (long)seconds * TestVideos.Timescale, }; using var output = new MemoryStream(); Mp4Writer.Write(output, [track]); return output.ToArray(); } private static ExportJobRequest Frames(Media video, ExportFramesRequest frames) => new(new ExportSelection.Media([video.Id]), Frames: frames); /// A video whose length the library does not know (it is read when the job is recorded). private static Task 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 Locate(byte[] video, IReadOnlyList instants) { using var stream = new MemoryStream(video); using var reader = VideoFrameReader.Open(stream, out _); return reader.Locate(instants); } private static async Task> 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)]; /// An engine session for the first looks, then none. private sealed class CountedSession(int polls) : IEngineSessionState { private int _left = polls; public bool InSession => Interlocked.Decrement(ref _left) >= 0; } }