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)); } [TestMethod] public async Task TheFrameOfAStillVideoKeepsItsNameAcrossAPause() { // «Salva il fotogramma» to the folder of the copies (tappa E4, D9): the run says «Fermo», so a job resumed after a // pause (or after Febe closed) names the frame «…_fotogramma» as it would have done, at the instant recorded. var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); var video = (await SaveVideoAsync(bed, bed.Marta, "981", Mp4, ".mp4")).Media[0]; var usb = await bed.GeneralAsync(ct: ct); var at = TimeSpan.FromMilliseconds(400); await bed.Db.VideoAnalyses.SetAsync(new VideoAnalysis(video.Sha256!, 1, VideoAnalysisOutcome.Still, Make.T0, at), ct); var request = Frames(video, new ExportFramesRequest(FrameMode.Still, null, null, null, ExportFormat.Png)); bed.Disk.Free = 0; var start = await bed.CopyAsync(request, ct); var run = await bed.RunAsync(start.Runs.Single().Id, ct); Assert.AreEqual(ExportRunState.Paused, run.State, run.LastError); Assert.IsEmpty(Fingerprint.Of(bed.Usb)); bed.Disk.Free = null; await bed.Service.ResumeAsync([run.Id], ct); await bed.Service.WaitAsync(ct); Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State); var copy = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single(); Assert.AreEqual("marta.demo/" + Path.ChangeExtension(video.RelativePath!, null) + "_fotogramma.png", copy.RelativePath); Assert.AreEqual((ExportVariant.Frame, ExportFormat.Png), (copy.Variant, copy.Format)); Assert.AreEqual(TimeSpan.FromMilliseconds(ExportFrames.ActualMs(Locate(Mp4, [at]).Single().Actual)), copy.FrameAt); Assert.HasCount(1, Fingerprint.Of(bed.Usb)); // «Questo istante» at the same instant shows the same frame: «Già copiato», not another file. var same = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.At, at, null, null, ExportFormat.Png)), ct); var item = (await bed.ItemsAsync(same.Runs.Single().Id, ct)).Single(); Assert.AreEqual((ExportItemState.AlreadyCopied, (long?)copy.Id), (item.State, item.CopyId)); Assert.HasCount(1, Fingerprint.Of(bed.Usb)); } [TestMethod] [DataRow(null, false, false)] [DataRow(VideoAnalysisOutcome.Moving, false, false)] [DataRow(VideoAnalysisOutcome.Still, false, false)] [DataRow(VideoAnalysisOutcome.Still, true, false)] [DataRow(VideoAnalysisOutcome.Still, false, true)] [DataRow(VideoAnalysisOutcome.Still, true, true)] [DataRow(VideoAnalysisOutcome.Moving, true, true)] public async Task AFrameWaitingForAFileThatChangedIsTheOneOfTheNewAnalysisOrNone(VideoAnalysisOutcome? now, bool pausedWhileWriting, bool changedTwice) { // The job waited (disk full) while the file was replaced: the instant was chosen on the old one, so it would save // any frame of the new one, whatever it is. Then the disk may go in the middle of the writing, once the item is // recorded again: resumed, the job must still know that the file changed (and it may change once more). var ct = TestContext.CancellationToken; var files = new AwayWhileHashing(); await using var bed = await ExportTestBed.CreateAsync(e => e with { FileSystem = files }); var video = (await SaveVideoAsync(bed, bed.Marta, "984", Mp4, ".mp4")).Media[0]; var usb = await bed.GeneralAsync(ct: ct); await bed.Db.VideoAnalyses.SetAsync(new VideoAnalysis(video.Sha256!, 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.FromMilliseconds(400)), ct); bed.Disk.Free = 0; var start = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.Still, null, null, null, ExportFormat.Png)), ct); async Task ReplaceAsync(byte[] file, VideoAnalysisOutcome? outcome, TimeSpan instant) { var hash = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(file)); await File.WriteAllBytesAsync(bed.Library.Layout.FullPath(bed.Marta, video.RelativePath!), file, ct); await bed.Db.Media.UpdateAsync((await bed.Db.Media.GetAsync(video.Id, ct))! with { Sha256 = hash, Bytes = file.Length }, ct); if (outcome is { } found) { await bed.Db.VideoAnalyses.SetAsync(new VideoAnalysis(hash, 1, found, Make.T0, found == VideoAnalysisOutcome.Still ? instant : null), ct); } return hash; } byte[] other = [.. Mp4, 0, 0, 0, 8, (byte)'f', (byte)'r', (byte)'e', (byte)'e']; var at = TimeSpan.FromMilliseconds(100); var sha = await ReplaceAsync(other, pausedWhileWriting ? VideoAnalysisOutcome.Still : now, at); bed.Disk.Free = null; var runId = start.Runs.Single().Id; if (pausedWhileWriting) { files.OnHash = () => Directory.Move(bed.Usb, bed.Usb + "-via"); await bed.Service.ResumeAsync([runId], ct); await bed.Service.WaitAsync(ct); files.OnHash = null; Directory.Move(bed.Usb + "-via", bed.Usb); Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(runId, ct)).State); var waiting = (await bed.ItemsAsync(runId, ct)).Single(); Assert.AreEqual(ExportItemState.Pending, waiting.State); Assert.IsNotNull(waiting.RelativePath, "fermo dopo l'annuncio del file da scrivere"); } if (changedTwice) { other = [.. other, 0, 0, 0, 8, (byte)'f', (byte)'r', (byte)'e', (byte)'e']; at = TimeSpan.FromMilliseconds(200); sha = await ReplaceAsync(other, now, at); } await bed.Service.ResumeAsync([runId], ct); await bed.Service.WaitAsync(ct); var run = await bed.RunAsync(runId, ct); Assert.AreEqual(ExportRunState.Completed, run.State, run.LastError); var item = (await bed.ItemsAsync(runId, ct)).Single(); if (now == VideoAnalysisOutcome.Still) { var copy = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single(); Assert.AreEqual((ExportItemState.Copied, sha), (item.State, copy.SourceSha256), item.LastError); Assert.AreEqual(TimeSpan.FromMilliseconds(ExportFrames.ActualMs(Locate(other, [at]).Single().Actual)), copy.FrameAt); StringAssert.EndsWith(copy.RelativePath, "_fotogramma.png"); } else { Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.NotStill), (item.State, item.Note)); StringAssert.Contains(ExportText.Note(item.Note), "Il video è cambiato"); Assert.IsEmpty(Fingerprint.Of(bed.Usb)); } } [TestMethod] public async Task OnlyAStillVideoGivesItsFrameAndACopyIsAlwaysTheWholeVideo() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); var video = (await SaveVideoAsync(bed, bed.Marta, "982", Mp4, ".mp4")).Media[0]; var other = (await SaveVideoAsync(bed, bed.Marta, "983", TestVideos.Mov(Stream), ".mov")).Media[0]; var usb = await bed.GeneralAsync(ct: ct); ExportFramesRequest Still(TimeSpan? at = null, TimeSpan? every = null, int? count = null) => new(FrameMode.Still, at, every, count, ExportFormat.Png); // No analysis, «In movimento», «Non analizzabile»: nothing is recorded. foreach (var analysis in new[] { null, new VideoAnalysis(video.Sha256!, 1, VideoAnalysisOutcome.Moving, Make.T0), new VideoAnalysis(video.Sha256!, 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, null, VideoAnalysisNotes.AllDark), }) { if (analysis is not null) { await bed.Db.VideoAnalyses.SetAsync(analysis, ct); } var none = await bed.Service.PlanAsync(Frames(video, Still()), ct); Assert.AreEqual((0, 1), (none.Frames, none.NotStill), analysis?.Outcome.ToString()); Assert.IsEmpty((await bed.CopyAsync(Frames(video, Still()), ct)).Runs); } // One video, nothing but the format (answer 46). await bed.Db.VideoAnalyses.SetAsync(new VideoAnalysis(video.Sha256!, 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.Zero), ct); foreach (var wrong in new[] { Frames(video, Still(at: TimeSpan.Zero)), Frames(video, Still(every: TimeSpan.FromSeconds(1))), Frames(video, Still(count: 1)), new ExportJobRequest(new ExportSelection.Media([video.Id, other.Id]), Frames: Still()), new ExportJobRequest(new ExportSelection.Entries([video.EntryId]), Frames: Still()), new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id), Frames: Still()), }) { await Assert.ThrowsExactlyAsync(() => bed.Service.PlanAsync(wrong, ct)); await Assert.ThrowsExactlyAsync(() => bed.Service.StartAsync(wrong, ct)); } Assert.IsEmpty(Fingerprint.Of(bed.Usb)); Assert.IsEmpty(await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)); // «Copia in…» of a still video copies the whole video and nothing else, byte for byte (answer 39). await bed.CopyAccountAsync(bed.Marta, ct: ct); var copies = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct); Assert.HasCount(2, copies); Assert.IsTrue(copies.All(c => c.Variant == ExportVariant.Whole && c.FrameAt is null), string.Join(", ", copies)); CollectionAssert.AreEqual(Mp4, await File.ReadAllBytesAsync(bed.GeneralCopy(bed.Marta, video), ct)); Assert.HasCount(2, Fingerprint.Of(bed.Usb)); } /// 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; } /// The real files, telling when a file is hashed: the moment the disk of the copies goes. private sealed class AwayWhileHashing : IExportFileSystem { public Action? OnHash { get; set; } public Stream OpenRead(string path) => ExportFileSystem.Instance.OpenRead(path); public Stream OpenRandomAccess(string path) => ExportFileSystem.Instance.OpenRandomAccess(path); public Task ComputeSha256Async(string path, CancellationToken ct) { OnHash?.Invoke(); return ExportFileSystem.Instance.ComputeSha256Async(path, ct); } public bool FileExists(string path) => ExportFileSystem.Instance.FileExists(path); public long? FileLength(string path) => ExportFileSystem.Instance.FileLength(path); } }