diff --git a/tests/Febe.Tests/Export/ExportConversionTests.cs b/tests/Febe.Tests/Export/ExportConversionTests.cs index 539fe68..b588040 100644 --- a/tests/Febe.Tests/Export/ExportConversionTests.cs +++ b/tests/Febe.Tests/Export/ExportConversionTests.cs @@ -1,7 +1,9 @@ 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.Core.Storage; using Febe.Tests.Codecs.Containers; using Febe.Tests.Export.Support; @@ -10,8 +12,10 @@ using Febe.Tests.Support; namespace Febe.Tests.Export; /// -/// The copy job of tappa E3 on real folders (WP1.7): a converted copy and a frame copy. The full set of cases is WP6a's; -/// the media are built by the tests. +/// The copy job of tappa E3 on real folders (WP1.7): converted copies, byte copies of the same format, files copied as +/// they are with a note, the format chosen by the request, the destination or the settings (D1), «già copiato» in any +/// form (D3), adoption of a converted file (D10), «Copia di nuovo» of a form (D11), the space of the converted size +/// (D17) and the file time (D18). The media are built by the tests; more frames are in . /// [TestClass] public sealed class ExportConversionTests @@ -92,4 +96,312 @@ public sealed class ExportConversionTests Assert.AreEqual((ExportItemState.AlreadyCopied, copy.Id), (same.State, same.CopyId)); Assert.HasCount(2, Fingerprint.Of(bed.Usb)); } + + [TestMethod] + public async Task JpgToJpgIsAByteCopyAndTheLibraryIsUntouched() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await FormatsAsync(bed, ExportFormat.Jpg, ct); + var post = await bed.PostAsync(bed.Marta, "962", 33); + var media = post.Media[0]; + await bed.GeneralAsync(ct: ct); + var library = Fingerprint.Of(bed.Temp.Combine("libreria")); + + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + + Assert.AreEqual((1, 0, false), (start.Plan.Files, start.Plan.Converted, start.Plan.Lossy), "a JPEG to JPG is not a conversion, nor «con perdita»"); + var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, (string?)null), (item.State, item.Note)); + var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original, media.Sha256), (copy.Variant, copy.Format, copy.CopySha256)); + CollectionAssert.AreEqual(await File.ReadAllBytesAsync(bed.LibraryFile(bed.Marta, media), ct), await File.ReadAllBytesAsync(bed.GeneralCopy(bed.Marta, media), ct)); + Fingerprint.AreEqual(library, Fingerprint.Of(bed.Temp.Combine("libreria")), "the library is never touched"); + } + + [TestMethod] + public async Task APngIsConvertedToTheDestinationFormatWithItsNoteAndTime() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await FormatsAsync(bed, ExportFormat.Png, ct); // the destination's format wins over this one + using var picture = Imaging.TestImages.Gradient(40, 30, seed: 6); // with transparent pixels + var post = await SaveAsync(bed, bed.Marta, "963", ImageConverter.Encode(picture, ImageFormat.Png, null), ".png"); + var media = post.Media[0]; + await bed.Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, bed.Usb, "Disco USB", ContentTypes.All, null, null, null, PhotoFormat: ExportFormat.Jpg), ct); + var library = Fingerprint.Of(bed.Temp.Combine("libreria")); + + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + + Assert.AreEqual((1, 1, true), (start.Plan.Files, start.Plan.Converted, start.Plan.Lossy)); + var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.TransparencyWhite), (item.State, item.Note)); + var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Converted, ExportFormat.Jpg, media.Sha256), (copy.Variant, copy.Format, copy.SourceSha256)); + Assert.AreEqual("marta.demo/" + Path.ChangeExtension(media.RelativePath!, ".jpg"), copy.RelativePath); + var file = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!)); + var bytes = await File.ReadAllBytesAsync(file, ct); + CollectionAssert.AreEqual(new byte[] { 0xFF, 0xD8, 0xFF }, bytes[..3]); + Assert.AreEqual((Convert.ToHexStringLower(SHA256.HashData(bytes)), (long?)bytes.Length), (copy.CopySha256, copy.Bytes)); + Assert.AreEqual(post.Entry.PublishedAt.UtcDateTime, File.GetLastWriteTimeUtc(file), "«libreria.data-file-pubblicazione» is on"); + Fingerprint.AreEqual(library, Fingerprint.Of(bed.Temp.Combine("libreria")), "the original stays as it is"); + + // The report lists the note, in Italian. + var report = await bed.Service.Reports.BuildAsync(start.Runs.Single().Id, ct); + var line = report.Notes.Single(); + Assert.AreEqual((item.Id, ExportItemState.Copied), (line.ItemId, line.State)); + Assert.AreEqual(ExportText.Note(ExportText.Notes.TransparencyWhite), line.Text); + Assert.IsEmpty(report.Accounts.Single().AsIs); + } + + [TestMethod] + public void TheFormatIsTheRequestsThenTheDestinationsThenTheSettings() + { + var settings = ExportSettings.Default with { PhotoFormat = ExportFormat.Png, VideoFormat = ExportFormat.Mp4 }; + var destination = new ExportDestination { Id = 1, Scope = ExportScope.General, RootPath = "/copie", ContentTypes = ContentTypes.All, CreatedAt = Make.T0 }; + var jpgHere = destination with { PhotoFormat = ExportFormat.Jpg, VideoFormat = ExportFormat.Original }; + + Assert.AreEqual(ExportFormat.Png, ExportConversions.Resolve(MediaKind.Photo, null, destination, settings)); + Assert.AreEqual(ExportFormat.Mp4, ExportConversions.Resolve(MediaKind.Video, null, destination, settings)); + Assert.AreEqual(ExportFormat.Jpg, ExportConversions.Resolve(MediaKind.Photo, null, jpgHere, settings)); + Assert.AreEqual(ExportFormat.Original, ExportConversions.Resolve(MediaKind.Video, null, jpgHere, settings)); + Assert.AreEqual(ExportFormat.WebpLossless, ExportConversions.Resolve(MediaKind.Photo, new ExportFormatChoice(ExportFormat.WebpLossless, null), jpgHere, settings)); + Assert.AreEqual(ExportFormat.Mp4, ExportConversions.Resolve(MediaKind.Video, new ExportFormatChoice(null, ExportFormat.Mp4), jpgHere, settings)); + Assert.AreEqual(ExportFormat.Jpg, ExportConversions.Resolve(MediaKind.Photo, new ExportFormatChoice(ExportFormat.Mp4, null), jpgHere, settings), "a video format is not a photo's"); + } + + [TestMethod] + public async Task TheRequestOverridesTheDestination() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "964", 34); + await bed.Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, bed.Usb, "Disco USB", ContentTypes.All, null, null, null, PhotoFormat: ExportFormat.Png), ct); + + var start = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id]), Formats: new ExportFormatChoice(ExportFormat.WebpLossless, null)), ct); + + var copy = (await bed.Db.Exports.GetCopyAsync((await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single().CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Converted, ExportFormat.WebpLossless), (copy.Variant, copy.Format)); + StringAssert.EndsWith(copy.RelativePath, ".webp"); + Assert.AreEqual(ImageFormat.WebP, ImageFormatSniffer.Detect(await File.ReadAllBytesAsync(Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!)), ct))); + } + + [TestMethod] + public async Task HeicIsCopiedAsItIsWithANoteAndTheReportCountsIt() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await FormatsAsync(bed, ExportFormat.Jpg, ct); + byte[] heic = [0, 0, 0, 0x18, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, 0, 0, 0, 8, .. "free"u8, .. new byte[64]]; + var post = await SaveAsync(bed, bed.Marta, "965", heic, ".heic"); + var media = post.Media[0]; + await bed.GeneralAsync(ct: ct); + + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + + Assert.AreEqual(new ExportPlanAsIs("HEIC", 1), start.Plan.AsIs.Single(), "predicted from the name"); + var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.AsIsHeif), (item.State, item.Note)); + var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original, media.Sha256), (copy.Variant, copy.Format, copy.CopySha256)); + CollectionAssert.AreEqual(heic, await File.ReadAllBytesAsync(bed.GeneralCopy(bed.Marta, media), ct)); + + var report = await bed.Service.Reports.BuildAsync(start.Runs.Single().Id, ct); + Assert.AreEqual(1, report.Accounts.Single().AsIs["HEIC"]); + Assert.AreEqual(ExportText.Note(ExportText.Notes.AsIsHeif), report.Notes.Single().Text); + } + + [TestMethod] + public async Task AConvertedFileAtThePathIsAdoptedAndASameSizeDifferentFileIsNot() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await FormatsAsync(bed, ExportFormat.Jpg, ct); + var same = await SavePngAsync(bed, "966", 35); + var other = await SavePngAsync(bed, "967", 36); + await bed.GeneralAsync(ct: ct); + + // An earlier conversion of the same file (the bytes Febe makes), and one of the other file with a byte changed. + var adopted = ConvertedPath(bed, same.Media[0], ".jpg"); + var foreign = ConvertedPath(bed, other.Media[0], ".jpg"); + Directory.CreateDirectory(Path.GetDirectoryName(adopted)!); + Directory.CreateDirectory(Path.GetDirectoryName(foreign)!); + var conversion = await ConvertAsync(bed, same.Media[0], ExportFormat.Jpg, ct); + await File.WriteAllBytesAsync(adopted, conversion, ct); + var handDate = new DateTime(2020, 5, 1, 12, 0, 0, DateTimeKind.Utc); + File.SetLastWriteTimeUtc(adopted, handDate); + var changed = await ConvertAsync(bed, other.Media[0], ExportFormat.Jpg, ct); + changed[^10] ^= 0x01; + await File.WriteAllBytesAsync(foreign, changed, ct); + var before = Fingerprint.Of(bed.Usb); + + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + + var items = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).ToDictionary(i => i.MediaId!.Value); + var adoption = items[same.Media[0].Id]; + Assert.AreEqual(ExportItemState.Adopted, adoption.State); + var copy = (await bed.Db.Exports.GetCopyAsync(adoption.CopyId!.Value, ct))!; + Assert.AreEqual((ExportCopyOrigin.Adopted, ExportVariant.Converted, ExportFormat.Jpg), (copy.Origin, copy.Variant, copy.Format)); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(conversion)), copy.CopySha256); + Assert.AreEqual(handDate, File.GetLastWriteTimeUtc(adopted), "adopted, not written again"); + + var written = items[other.Media[0].Id]; + Assert.AreEqual(ExportItemState.Copied, written.State); + StringAssert.Contains(written.Note, ExportText.Notes.NameTaken); + StringAssert.EndsWith(written.RelativePath, " (2).jpg"); + var after = Fingerprint.Of(bed.Usb); + foreach (var (path, print) in before) + { + Assert.AreEqual(print, after[path], path); + } + + Assert.AreEqual(before.Count + 1, after.Count); + } + + [TestMethod] + public async Task SpaceIsCheckedOnTheConvertedSize() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await FormatsAsync(bed, ExportFormat.Png, ct); + var post = await bed.PostAsync(bed.Marta, "968", 37); + var media = post.Media[0]; + var usb = await bed.GeneralAsync(ct: ct); + long png = (await ConvertAsync(bed, media, ExportFormat.Png, ct)).Length; + Assert.IsGreaterThan(media.Bytes!.Value, png, "the PNG of a small JPEG is bigger"); + + bed.Disk.Free = media.Bytes!.Value + ExportSpace.Margin; // enough for the original, not for its PNG + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var run = await bed.RunAsync(start.Runs.Single().Id, ct); + Assert.AreEqual(ExportRunState.Paused, run.State); + StringAssert.Contains(run.LastError, "margine di 64 MB"); + Assert.IsEmpty(Fingerprint.Of(bed.Usb)); + + bed.Disk.Free = png + ExportSpace.Margin; + await bed.Service.ResumeAsync([run.Id], ct); + await bed.Service.WaitAsync(ct); + Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State); + Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); + Assert.AreEqual(png, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single().Bytes); + } + + [TestMethod] + public async Task ARemovedWholeCopyIsNotCopiedAgainInTheNewFormatUntilAskedAndExactIgnoresOtherForms() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await SavePngAsync(bed, "969", 38); + var media = post.Media[0]; + var usb = await bed.GeneralAsync(ct: ct); + var first = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var whole = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value; + File.Delete(bed.GeneralCopy(bed.Marta, media)); + + // The format changes to JPG: the file was copied («Tolto» now), so it is not copied again by itself (D3). + await FormatsAsync(bed, ExportFormat.Jpg, ct); + var skipped = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var item = (await bed.ItemsAsync(skipped.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.Removed, (long?)whole), (item.State, item.Note, item.CopyId)); + Assert.IsEmpty(Fingerprint.Of(bed.Usb)); + var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct); + Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded)); + + // «Copia di nuovo» from the dialog writes the current form: a JPG. + var again = await bed.CopyAccountAsync(bed.Marta, copyAgain: true, ct: ct); + var converted = (await bed.Db.Exports.GetCopyAsync((await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single().CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Converted, ExportFormat.Jpg, ExportCopyState.Copied), (converted.Variant, converted.Format, converted.State)); + Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(whole, ct))!.State); + + // «Copia di nuovo» of the removed row from the viewer: its own form, whatever else is copied (D11). + var exact = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([media.Id]), CopyAgain: true, Exact: new ExportCopyRequest(ExportVariant.Whole, ExportFormat.Original, null)), ct); + var back = (await bed.ItemsAsync(exact.Runs.Single().Id, ct)).Single(); + Assert.AreEqual(ExportItemState.Copied, back.State); + var restored = (await bed.Db.Exports.GetCopyAsync(back.CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original), (restored.Variant, restored.Format)); + Assert.AreNotEqual(whole, restored.Id); + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, media))); + Assert.HasCount(2, Fingerprint.Of(bed.Usb), "the JPG and the PNG"); + Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.GetCopyAsync(converted.Id, ct))!.State); + + // The JPG asked again exactly: «Già copiato». + var twice = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([media.Id]), CopyAgain: true, Exact: new ExportCopyRequest(ExportVariant.Converted, ExportFormat.Jpg, null)), ct); + var same = (await bed.ItemsAsync(twice.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.AlreadyCopied, (long?)converted.Id), (same.State, same.CopyId)); + Assert.HasCount(3, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)); + } + + [TestMethod] + public async Task OneCopyOnlyIgnoresTheFormat() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await (ExportSettings.Default with { SamePost = SamePostCopies.OneOnly, PhotoFormat = ExportFormat.Jpg }).SaveAsync(bed.Db.Settings, ct); + using var image = TestImages.Scene(39, 64, 48); + var png = TestImages.Png(image); + await SaveAsync(bed, bed.Marta, "970", png, ".png"); + await SaveAsync(bed, bed.Luca, "970", png, ".png"); + await bed.GeneralAsync(ct: ct); + + await bed.CopyAccountAsync(bed.Marta, ct: ct); + var luca = await bed.CopyAccountAsync(bed.Luca, ct: ct); + + var item = (await bed.ItemsAsync(luca.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.AlreadyCopied, ExportText.Notes.CopiedForAnotherAccount), (item.State, item.Note)); + Assert.AreEqual(ExportVariant.Converted, (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!.Variant); + Assert.HasCount(1, Fingerprint.Of(bed.Usb)); + } + + [TestMethod] + public async Task AChangedSourceFailsTheConversionAndAStaleFailedRowIsClearedLater() + { + var ct = TestContext.CancellationToken; + var corrupt = true; + await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = new CorruptingExportFileSystem(path => corrupt && path.EndsWith(".jpg", StringComparison.Ordinal)) }); + await FormatsAsync(bed, ExportFormat.Png, ct); + var post = await bed.PostAsync(bed.Marta, "971", 40); + var usb = await bed.GeneralAsync(ct: ct); + + var failed = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var item = (await bed.ItemsAsync(failed.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Failed, ExportText.Notes.SourceChanged), (item.State, item.Note)); + var row = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single(); + Assert.AreEqual((ExportCopyState.Failed, ExportVariant.Converted, ExportFormat.Png), (row.State, row.Variant, row.Format)); + Assert.IsEmpty(Fingerprint.Of(bed.Usb)); + + // The disk reads well again and the format is back to Originale: the copy is written, the old failure goes. + corrupt = false; + await FormatsAsync(bed, ExportFormat.Original, ct); + var copied = await bed.CopyAccountAsync(bed.Marta, ct: ct); + Assert.AreEqual(ExportItemState.Copied, (await bed.ItemsAsync(copied.Runs.Single().Id, ct)).Single().State); + var copies = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct); + Assert.AreEqual((ExportCopyState.Copied, ExportVariant.Whole), (copies.Single().State, copies.Single().Variant), "the «Non riuscito» row of the other form has no use"); + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0]))); + } + + private static Task FormatsAsync(ExportTestBed bed, ExportFormat photo, CancellationToken ct) => + (ExportSettings.Default with { PhotoFormat = photo }).SaveAsync(bed.Db.Settings, ct); + + private static Task SaveAsync(ExportTestBed bed, Account account, string code, byte[] bytes, string extension) => + bed.Library.SaveAsync(account, Make.Entry(account.Id, code, Make.T0.AddDays(-1)), [new TestFile(Make.Photo(1), bytes, extension)]); + + private static Task SavePngAsync(ExportTestBed bed, string code, int scene) + { + using var image = TestImages.Scene(scene, 64, 48); + return SaveAsync(bed, bed.Marta, code, TestImages.Png(image), ".png"); + } + + /// Where the general folder gets the converted copy of a file of marta.demo. + private static string ConvertedPath(ExportTestBed bed, Media media, string extension) => + Path.Combine(bed.Usb, bed.Marta.Username, LibraryLayout.ToPlatform(Path.ChangeExtension(media.RelativePath!, extension))); + + /// The bytes Febe makes of a library file in a format. + private static async Task ConvertAsync(ExportTestBed bed, Media media, ExportFormat format, CancellationToken ct) + { + var path = bed.LibraryFile(bed.Marta, media); + using var conversion = await MediaConverter.PrepareAsync(() => File.OpenRead(path), media.RelativePath!, media.Kind, format, media.Sha256!, new ConversionThrottle(), ct); + Assert.AreEqual(ExportVariant.Converted, conversion.Variant); + using var output = new MemoryStream(); + await conversion.Produce!(output, ct); + return output.ToArray(); + } } diff --git a/tests/Febe.Tests/Export/ExportFramesTests.cs b/tests/Febe.Tests/Export/ExportFramesTests.cs new file mode 100644 index 0000000..c3231ad --- /dev/null +++ b/tests/Febe.Tests/Export/ExportFramesTests.cs @@ -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; + +/// +/// «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)); + } + + 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; + } +} diff --git a/tests/Febe.Tests/Export/ExportPathsTests.cs b/tests/Febe.Tests/Export/ExportPathsTests.cs index af336df..ba30b4c 100644 --- a/tests/Febe.Tests/Export/ExportPathsTests.cs +++ b/tests/Febe.Tests/Export/ExportPathsTests.cs @@ -150,6 +150,53 @@ public sealed class ExportPathsTests Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, Path.TrimEndingDirectorySeparator(root).Length + 1 + numbered.Length); } + [TestMethod] + public void TheTargetExtensionReplacesTheSourceOneAndAFrameSuffixFollowsTheStem() + { + // Tappa E3 (WP1.8): a converted copy takes the extension of its format, a frame adds its suffix before it. + var asJpg = new ExportNameOptions(".jpg", null); + var png = Photo(1) with { RelativePath = "post/2026/vecchio_1.PNG" }; + CollectionAssert.AreEqual( + new[] { "marta.demo", "post", "2026", "2026-10-13_10-00-00_C500_1.jpg" }, + ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), png, null, false, TestZones.Rome, asJpg).ToArray()); + var frame = new ExportNameOptions(".png", "_t0m01s250"); + CollectionAssert.AreEqual( + new[] { "marta.demo", "post", "2026", "2026-10-13_10-00-00_C500_1_t0m01s250.png" }, + ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), png, null, false, TestZones.Rome, frame).ToArray()); + + // A file of «importati/» keeps its name, with the extension swapped too. + var imported = Photo(1) with { RelativePath = "importati/vacanze/IMG 0001.HEIC.mov" }; + CollectionAssert.AreEqual( + new[] { "marta.demo", "importati", "vacanze", "IMG 0001.HEIC.mp4" }, + ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), imported, null, false, TestZones.Rome, new ExportNameOptions(".mp4", null)).ToArray()); + CollectionAssert.AreEqual( + new[] { "marta.demo", "importati", "vacanze", "IMG 0001.HEIC_f001.png" }, + ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), imported, null, false, TestZones.Rome, new ExportNameOptions(".png", "_f001")).ToArray()); + + // No options: nothing changes. + CollectionAssert.AreEqual( + ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), png, null, false, TestZones.Rome).ToArray(), + ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), png, null, false, TestZones.Rome, new ExportNameOptions(null, null)).ToArray()); + } + + [TestMethod] + public void TheFrameSuffixSurvivesTheShorteningTo240() + { + var root = Path.Combine(Path.GetTempPath(), new string('r', 120)); + var deep = General() with { RootPath = root }; + var segments = new[] { "marta.demo", new string('a', 60), new string('b', 80) + "_t12m05s340.png" }; + + var fitted = ExportPaths.RelativePathFor(deep, segments, keepSuffix: "_t12m05s340"); + Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, Path.TrimEndingDirectorySeparator(root).Length + 1 + fitted.Length); + StringAssert.EndsWith(fitted, "_t12m05s340.png"); + + // The numbered names of the safe writer keep it and put the number after it. + var numbered = ExportPaths.NumberedName(root, fitted, 2, keepSuffix: "_t12m05s340"); + StringAssert.EndsWith(numbered, "_t12m05s340 (2).png"); + Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, Path.TrimEndingDirectorySeparator(root).Length + 1 + numbered.Length); + Assert.AreEqual("marta.demo/x_f001.png", ExportPaths.RelativePathFor(deep, ["marta.demo", "x_f001.png"], keepSuffix: "_f001"), "short paths are not touched"); + } + [TestMethod] public void TheNamingPreviewOfADestinationTakesTheLibrarySchemesWhenNull() { diff --git a/tests/Febe.Tests/Imaging/ImageConversionCheckTests.cs b/tests/Febe.Tests/Imaging/ImageConversionCheckTests.cs new file mode 100644 index 0000000..1fa3f83 --- /dev/null +++ b/tests/Febe.Tests/Imaging/ImageConversionCheckTests.cs @@ -0,0 +1,164 @@ +using System.Security.Cryptography; +using Febe.Core.Codecs.Images; +using Febe.Core.Domain; +using Febe.Core.Library.Conversion; +using static Febe.Tests.Imaging.TestImages; + +namespace Febe.Tests.Imaging; + +/// +/// What a photo conversion of tappa E3 does with a source, from its bytes only (D5, D6): the same format is a byte copy, +/// HEIF, AVIF and raw files, animations, damaged files, CMYK and deep colour to PNG/WEBP and pictures over the budget +/// of the target are copied as they are, each with its reason. The files are built by the test. +/// +[TestClass] +public sealed class ImageConversionCheckTests +{ + private static readonly ImageFormat[] Targets = [ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.WebP]; + + [TestMethod] + public void SameFormatIsACopy() + { + using var picture = Gradient(24, 16, seed: 1); + foreach (var format in Targets) + { + var file = ImageConverter.Encode(picture, format, null); + var check = ImageConverter.Check(file, format); + Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyAsIs, format, null), check, $"{format}"); + } + + // A lossy WebP to «WEBP senza perdita» is copied too: re-encoding it would only make it bigger (Q36). + var lossy = ReferenceImages.Get("webp-perdita-alfa-q80").ReadInput(); + Assert.AreEqual(ImageConversionAction.CopyAsIs, ImageConverter.Check(lossy, ImageFormat.WebP).Action); + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(lossy, ImageFormat.Png).Action); + } + + [TestMethod] + public void HeifAvifAndRawAreCopiedAsTheyAre() + { + byte[] Ftyp(string brand) => [0, 0, 0, 0x18, .. "ftyp"u8, .. System.Text.Encoding.ASCII.GetBytes(brand), 0, 0, 0, 0, .. "mif1"u8, .. System.Text.Encoding.ASCII.GetBytes(brand), 0, 0, 0, 8, .. "free"u8]; + byte[] tiff = [.. "II*\0"u8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + foreach (var target in Targets) + { + Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyOriginal, ImageFormat.Heif, ImageConversionLosses.AsIsHeif), ImageConverter.Check(Ftyp("heic"), target)); + Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyOriginal, ImageFormat.Avif, ImageConversionLosses.AsIsAvif), ImageConverter.Check(Ftyp("avif"), target)); + Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyOriginal, ImageFormat.Tiff, ImageConversionLosses.AsIsRaw), ImageConverter.Check(tiff, target)); + } + + // Raw files go by their name in the library (a DNG is a TIFF inside), and the plan predicts them as they are. + Assert.IsTrue(MediaConverter.IsRawExtension(".dng")); + Assert.IsTrue(MediaConverter.IsRawExtension(".CR3")); + Assert.IsFalse(MediaConverter.IsRawExtension(".jpg")); + } + + [TestMethod] + public void AnimatedGifWebpAndPngAreNeverConverted() + { + // GIF with two images. + byte[] palette = [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255]; + byte[] indices = [0, 1]; + var gif = Gif(2, 1, palette, GifFrame(0, 0, 2, 1, indices, 2), GifControl(1), GifFrame(0, 0, 2, 1, indices, 2)); + + // PNG with an acTL chunk before its image data (an APNG, by the presence of the chunk). + using var picture = Gradient(8, 8, seed: 2); + var chunks = PngChunks(PngEncoder.Encode(picture)); + var actl = new byte[8]; + System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian(actl, 2); + var apng = Png([chunks[0], ("acTL", actl), .. chunks.Skip(1)]); + Assert.IsTrue(ImageDecoder.Identify(apng).IsAnimated); + + // WebP with ANIM and ANMF chunks. + var vp8l = WebPTestFiles.Payload(WebPEncoder.Encode(picture), "VP8L"); + var webp = WebPTestFiles.Riff( + ("VP8X", WebPTestFiles.Vp8X(0x02 | 0x10, 8, 8)), + ("ANIM", WebPTestFiles.Anim()), + ("ANMF", WebPTestFiles.Anmf(0, 0, 8, 8, 0, ("VP8L", vp8l)))); + + foreach (var (file, source) in new[] { (gif, ImageFormat.Gif), (apng, ImageFormat.Png), (webp, ImageFormat.WebP) }) + { + foreach (var target in Targets.Where(t => t != source)) + { + var check = ImageConverter.Check(file, target); + Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyOriginal, source, ImageConversionLosses.AsIsAnimated), check, $"{source} in {target}"); + } + } + + // The same picture without the chunk is converted. + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(PngEncoder.Encode(picture), ImageFormat.WebP).Action); + } + + [TestMethod] + public void CmykAndDeepColorGoToJpgOnly() + { + // An Adobe CMYK JPEG: to PNG and WEBP it is copied as it is; to JPG it is already a JPEG. + const int width = 16; + const int height = 8; + var fine = Enumerable.Repeat((ushort)1, 64).ToArray(); + int[] Plane(int value) => Enumerable.Repeat(value, width * height).ToArray(); + var cmyk = JpegTestEncoder.Write( + JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, Plane(200)), (2, 1, 1, 0, Plane(120)), (3, 1, 1, 0, Plane(60)), (4, 1, 1, 0, Plane(230))], [fine], 0xC1), + new JpegTestOptions { Jfif = false, AdobeTransform = 0 }); + Assert.AreEqual(ImageConversionLosses.AsIsCmyk, ImageConverter.Check(cmyk, ImageFormat.Png).NoteCode); + Assert.AreEqual(ImageConversionLosses.AsIsCmyk, ImageConverter.Check(cmyk, ImageFormat.WebP).NoteCode); + Assert.AreEqual(ImageConversionAction.CopyAsIs, ImageConverter.Check(cmyk, ImageFormat.Jpeg).Action); + + // A 16-bit PNG: to WEBP as it is, to JPG converted (JPG loses anyway). + var raw = new byte[2 * (1 + (2 * 6))]; + var deep = Png(("IHDR", Ihdr(2, 2, 16, 2)), ("IDAT", Zlib(raw)), ("IEND", [])); + Assert.AreEqual(ImageConversionLosses.AsIsDeepColor, ImageConverter.Check(deep, ImageFormat.WebP).NoteCode); + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(deep, ImageFormat.Jpeg).Action); + + // A 12-bit JPEG to PNG. + var twelve = JpegTestEncoder.Write(JpegEncoder.TransformPlanes(8, 8, 12, [(1, 1, 1, 0, new int[64])], [fine], 0xC1), new JpegTestOptions()); + Assert.AreEqual(ImageConversionLosses.AsIsDeepColor, ImageConverter.Check(twelve, ImageFormat.Png).NoteCode); + } + + [TestMethod] + public void AnUndecodableImageIsCopiedAsItIs() + { + var unknown = ImageConverter.Check(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, ImageFormat.Png); + Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyOriginal, null, ImageConversionLosses.AsIsNotDecodable), unknown); + + // A PNG whose header says 0 × 0: recognised, not decodable. + var broken = Png(("IHDR", Ihdr(0, 0, 8, 2)), ("IEND", [])); + var check = ImageConverter.Check(broken, ImageFormat.Jpeg); + Assert.AreEqual((ImageConversionAction.CopyOriginal, ImageConversionLosses.AsIsNotDecodable), (check.Action, check.NoteCode)); + + // A JPEG cut after its signature. + Assert.AreEqual(ImageConversionLosses.AsIsNotDecodable, ImageConverter.Check(new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0, 16 }, ImageFormat.Png).NoteCode); + } + + [TestMethod] + public async Task AJpegNamedPngIsDetectedByItsBytes() + { + using var picture = Gradient(20, 12, seed: 4); + var jpeg = ImageConverter.Encode(picture, ImageFormat.Jpeg, null); + var sha = Convert.ToHexStringLower(SHA256.HashData(jpeg)); + + using var asJpg = await MediaConverter.PrepareAsync(() => new MemoryStream(jpeg), "post/foto.png", MediaKind.Photo, ExportFormat.Jpg, sha, new ConversionThrottle(), CancellationToken.None); + Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original), (asJpg.Variant, asJpg.Format), "a JPEG is already a JPG, whatever its name"); + Assert.IsEmpty(asJpg.Notes); + + using var asPng = await MediaConverter.PrepareAsync(() => new MemoryStream(jpeg), "post/foto.png", MediaKind.Photo, ExportFormat.Png, sha, new ConversionThrottle(), CancellationToken.None); + Assert.AreEqual((ExportVariant.Converted, ExportFormat.Png, ".png"), (asPng.Variant, asPng.Format, asPng.Extension), "its name is not a PNG's bytes"); + } + + [TestMethod] + public void PixelBudgetsCopyAsIs() + { + // Only the header is read: the image data is a single empty row, never decoded by the check. + byte[] Header(int w, int h) => Png(("IHDR", Ihdr(w, h, 8, 2)), ("IDAT", Zlib([0])), ("IEND", [])); + + var big = Header(7000, 7000); // 49 MP: over the 40 MP of WEBP, within the 100 MP of PNG and JPG + Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(big, ImageFormat.WebP).NoteCode); + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(big, ImageFormat.Jpeg).Action); + + var wide = Header(20_000, 2); // a WebP side is at most 16384 + Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(wide, ImageFormat.WebP).NoteCode); + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(wide, ImageFormat.Jpeg).Action); + + var huge = Header(11_000, 11_000); // 121 MP: over every budget + Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(huge, ImageFormat.Jpeg).NoteCode); + Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(huge, ImageFormat.WebP).NoteCode); + } +} diff --git a/tests/Febe.Tests/Imaging/ImageProcessingTests.cs b/tests/Febe.Tests/Imaging/ImageProcessingTests.cs index 17ec59b..630cf8b 100644 --- a/tests/Febe.Tests/Imaging/ImageProcessingTests.cs +++ b/tests/Febe.Tests/Imaging/ImageProcessingTests.cs @@ -452,6 +452,128 @@ public sealed class ImageProcessingTests Assert.ThrowsExactly(() => ImageConverter.Convert(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, ImageFormat.Png)); } + // ---- Conversions of tappa E3 ---- + + [TestMethod] + public void PngWithTransparencyToJpgIsWhite() + { + using var clear = Flat(16, 16, 10, 200, 30, 0); + var png = PngEncoder.Encode(clear); + + var result = ImageConverter.Convert(png, ImageFormat.Jpeg); + + CollectionAssert.AreEqual(new[] { ImageConversionLosses.TransparencyWhite }, result.Losses.ToArray()); + using var back = ImageDecoder.Decode(result.Data); + AssertEveryPixel(back, (255, 255, 255, 255), 2, "trasparente diventa bianco"); + } + + [TestMethod] + public void WebpLosslessHasTheSamePixelsAndPngToWebpAndBackIsIdentical() + { + using var picture = TestImages.Random(37, 23, 71); // random alpha: some 0, some 255, the colour under it too + var png = PngEncoder.Encode(picture); + + var webp = ImageConverter.Convert(png, ImageFormat.WebP); + Assert.IsFalse(webp.Lossy); + Assert.IsEmpty(webp.Losses); + using var fromWebp = ImageDecoder.Decode(webp.Data); + CollectionAssert.AreEqual(picture.ToArray(), fromWebp.ToArray(), "ogni pixel identico"); + + var again = ImageConverter.Convert(webp.Data, ImageFormat.Png); + using var fromPng = ImageDecoder.Decode(again.Data); + CollectionAssert.AreEqual(picture.ToArray(), fromPng.ToArray(), "PNG → WEBP → PNG"); + } + + [TestMethod] + public void MetadataIsCarriedIntoTheRightChunksOfEachFormat() + { + using var scene = Scenes.Scene(11, 64, 40); + var exif = Tiff(orientation: 8); + var icc = Profile(500); + const string xmp = ""; + var jpeg = JpegEncoder.Encode(scene, new JpegEncoderOptions { Quality = 90, Exif = exif, IccProfile = icc, Xmp = xmp }); + + // PNG: eXIf, iCCP and an iTXt «XML:com.adobe.xmp», all before the image data. + var png = ImageConverter.Convert(jpeg, ImageFormat.Png).Data; + var chunks = TestImages.PngChunks(png); + var idat = chunks.FindIndex(c => c.Type == "IDAT"); + CollectionAssert.AreEqual(exif, chunks.Single(c => c.Type == "eXIf").Payload); + Assert.IsLessThan(idat, chunks.FindIndex(c => c.Type == "eXIf")); + Assert.IsLessThan(idat, chunks.FindIndex(c => c.Type == "iCCP")); + var itxt = chunks.Single(c => c.Type == "iTXt").Payload; + StringAssert.StartsWith(Encoding.Latin1.GetString(itxt), "XML:com.adobe.xmp\0"); + StringAssert.EndsWith(Encoding.UTF8.GetString(itxt), xmp); + + // WEBP: VP8X first with its flags, ICCP before the image, EXIF and XMP after it. + var webp = ImageConverter.Convert(jpeg, ImageFormat.WebP).Data; + var riff = WebPTestFiles.Chunks(webp); + CollectionAssert.AreEqual(new[] { "VP8X", "ICCP", "VP8L", "EXIF", "XMP " }, riff.Select(c => c.Type).ToArray()); + Assert.AreEqual(0x20 | 0x08 | 0x04, riff[0].Payload[0] & 0x2C, "flag di ICC, EXIF e XMP"); + CollectionAssert.AreEqual(icc, riff[1].Payload); + CollectionAssert.AreEqual(exif, riff[3].Payload); + Assert.AreEqual(xmp, Encoding.UTF8.GetString(riff[4].Payload)); + + // JPG from the PNG: APP1 «Exif», APP2 «ICC_PROFILE» and APP1 of the XMP namespace. + var back = ImageConverter.Convert(png, ImageFormat.Jpeg).Data; + var segments = JpegSegments(back); + var app1 = segments.Where(s => s.Marker == 0xE1).Select(s => s.Payload).ToList(); + Assert.IsTrue(app1.Any(p => p.AsSpan().StartsWith("Exif\0\0"u8) && p.AsSpan(6).SequenceEqual(exif)), "EXIF in APP1"); + Assert.IsTrue(app1.Any(p => p.AsSpan().StartsWith("http://ns.adobe.com/xap/1.0/\0"u8) && Encoding.UTF8.GetString(p.AsSpan(29)) == xmp), "XMP in APP1"); + var app2 = segments.Single(s => s.Marker == 0xE2).Payload; + Assert.IsTrue(app2.AsSpan().StartsWith("ICC_PROFILE\0"u8)); + CollectionAssert.AreEqual(icc, app2[14..]); + } + + [TestMethod] + public void WhatCannotBeCarriedBecomesANote() + { + // A grey JPEG with a grey profile, to every target: the RGB output cannot carry the profile. + using var scene = Scenes.Scene(12, 32, 24); + var grey = JpegEncoder.Encode(scene, new JpegEncoderOptions { Grayscale = true, IccProfile = Profile(300, "GRAY") }); + foreach (var target in new[] { ImageFormat.Png, ImageFormat.WebP, ImageFormat.Jpeg }) + { + CollectionAssert.AreEqual(new[] { ImageConversionLosses.LostIcc }, ImageConverter.Convert(grey, target).Losses.ToArray(), $"grigio in {target}"); + } + + // A CMYK JPEG with its profile, to JPG: converted (it is a JPEG, so only an explicit conversion), profile left behind. + const int width = 16; + const int height = 8; + var fine = Enumerable.Repeat((ushort)1, 64).ToArray(); + int[] Plane(int value) => Enumerable.Repeat(value, width * height).ToArray(); + var cmyk = WithIcc(JpegTestEncoder.Write( + JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, Plane(200)), (2, 1, 1, 0, Plane(120)), (3, 1, 1, 0, Plane(60)), (4, 1, 1, 0, Plane(230))], [fine], 0xC1), + new JpegTestOptions { Jfif = false, AdobeTransform = 0 }), Profile(400, "CMYK")); + CollectionAssert.AreEqual(new[] { ImageConversionLosses.LostIcc }, ImageConverter.Convert(cmyk, ImageFormat.Jpeg).Losses.ToArray()); + + // A PNG with texts and colour chunks, to WEBP: no texts in WebP, the colour chunks are not written. + using var picture = TestImages.Random(6, 5, 3, opaque: true); + var gamma = new byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(gamma, 45455); + var parts = TestImages.PngChunks(PngEncoder.Encode(picture, new PngEncoderOptions { Texts = [new ImageText("Title", "Lago")] })); + var png = TestImages.Png([parts[0], ("gAMA", gamma), .. parts.Skip(1)]); + var webp = ImageConverter.Convert(png, ImageFormat.WebP); + CollectionAssert.AreEqual(new[] { ImageConversionLosses.LostTexts, ImageConversionLosses.LostColorChunks }, webp.Losses.ToArray(), "in un ordine fisso"); + Assert.HasCount(2, webp.NotCarried); + } + + [TestMethod] + public void ADamagedExifIsDroppedNotThrown() + { + // A WebP keeps whatever its EXIF chunk holds (PNG and JPEG readers already skip a block that is not TIFF). + using var picture = TestImages.Random(6, 5, 4, opaque: true); + var vp8l = WebPTestFiles.Payload(WebPEncoder.Encode(picture), "VP8L"); + var webp = WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x08, 6, 5)), ("VP8L", vp8l), ("EXIF", [1, 2, 3, 4, 5, 6, 7, 8, 9])); + Assert.IsNotNull(ImageDecoder.Identify(webp).Metadata.Exif); + + foreach (var target in new[] { ImageFormat.Jpeg, ImageFormat.Png }) + { + var result = ImageConverter.Convert(webp, target); + Assert.Contains(ImageConversionLosses.LostExifUnreadable, result.Losses, $"{target}"); + Assert.IsNull(result.Metadata.Exif, $"{target}"); + Assert.IsNull(ImageDecoder.Identify(result.Data).Metadata.Exif, $"{target}: il file scritto non ha l'EXIF"); + } + } + // ---- PNG texts ---- [TestMethod] @@ -674,6 +796,21 @@ public sealed class ImageProcessingTests return bytes; } + /// The marker segments of a JPEG up to its first scan: marker (second byte) and payload. + private static List<(int Marker, byte[] Payload)> JpegSegments(byte[] jpeg) + { + var segments = new List<(int, byte[])>(); + var pos = 2; + while (pos + 4 <= jpeg.Length && jpeg[pos] == 0xFF && jpeg[pos + 1] != 0xDA) + { + var length = BinaryPrimitives.ReadUInt16BigEndian(jpeg.AsSpan(pos + 2)); + segments.Add((jpeg[pos + 1], jpeg.AsSpan(pos + 4, length - 2).ToArray())); + pos += 2 + length; + } + + return segments; + } + /// A JPEG with an APP2 ICC_PROFILE segment (one chunk) right after SOI. private static byte[] WithIcc(byte[] jpeg, byte[] profile) { diff --git a/tests/Febe.Tests/Library/LibraryConversionTests.cs b/tests/Febe.Tests/Library/LibraryConversionTests.cs index 46fe864..f77022b 100644 --- a/tests/Febe.Tests/Library/LibraryConversionTests.cs +++ b/tests/Febe.Tests/Library/LibraryConversionTests.cs @@ -413,6 +413,125 @@ public sealed class LibraryConversionTests Assert.AreEqual(0, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import, ct), "never a probable duplicate of its original"); } + [TestMethod] + public async Task WhatWasNotKeptIsRecordedOnTheConvertedRow() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + using var clear = Imaging.TestImages.Gradient(40, 30, seed: 9); // transparent pixels + var (account, entry) = await SaveAsync(library, "1", new TestFile(Make.Photo(1), Core.Codecs.Images.ImageConverter.Encode(clear, Core.Codecs.Images.ImageFormat.Png, null), ".png")); + + Assert.AreEqual(1, (await Worker(library).RunOnceAsync(ct)).Converted); + + var row = (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single(); + Assert.AreEqual((MediaConversionState.Converted, ExportText.Notes.TransparencyWhite), (row.State, row.LastError), "the loss codes of a Converted row (D19)"); + Assert.IsTrue(File.Exists(library.Layout.FullPath(account, row.RelativePath!))); + Assert.IsFalse(LibraryConversionText.IsAsIs(row.LastError)); + } + + [TestMethod] + public async Task AMovIsRemuxedNextToTheOriginal() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await (ExportSettings.Default with { LibraryVideoFormat = ExportFormat.Mp4 }).SaveAsync(library.Db.Settings, ct); + var mov = Codecs.Containers.TestVideos.Mov(Codecs.Containers.ElementaryStream.Load("BA1_Sony_D"), new Codecs.Containers.MovOptions(Audio: true, Language: "ita")); + var (account, entry) = await SaveAsync(library, "1", new TestFile(Make.Video(1), mov, ".mov")); + var media = entry.Media[0]; + var original = library.Layout.FullPath(account, media.RelativePath!); + + Assert.AreEqual(1, (await Worker(library).RunOnceAsync(ct)).Converted); + + var row = (await library.Db.Conversions.ListByMediaAsync(media.Id, ct)).Single(); + Assert.AreEqual((MediaConversionState.Converted, ExportFormat.Mp4, media.Sha256), (row.State, row.Format, row.SourceSha256)); + Assert.AreEqual(Path.ChangeExtension(media.RelativePath!, ".mp4"), row.RelativePath); + var mp4 = await File.ReadAllBytesAsync(library.Layout.FullPath(account, row.RelativePath!), ct); + Assert.AreEqual((Convert.ToHexStringLower(SHA256.HashData(mp4)), (long?)mp4.Length), (row.Sha256, row.Bytes)); + using var stream = new MemoryStream(mp4); + var container = Core.Codecs.Containers.ContainerReader.Read(stream, Core.Codecs.Containers.ContainerReader.AnyDate, samples: false)!; + Assert.AreNotEqual("qt ", container.MajorBrand); + Assert.AreEqual("ita", container.Video!.Language); + CollectionAssert.AreEqual(mov, await File.ReadAllBytesAsync(original, ct), "the MOV stays as it is"); + } + + [TestMethod] + public async Task TheDuplicateLoserTakesItsConversions() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder("doppioni"); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Png); + var account = await library.Db.Accounts.AddAsync(Make.Account("doppie.prova"), ct); + var older = await library.SaveAsync(account, Make.Entry(account.Id, "100", Make.T0 - TimeSpan.FromDays(3)), [TestFile.Photo(1, 41, 320, 400)]); + var series = await library.SaveAsync(account, Make.Entry(account.Id, "200", Make.T0 - TimeSpan.FromDays(2)), [TestFile.Photo(1, 41, 240, 300), TestFile.Photo(2, 77, 320, 320)]); + Assert.AreEqual(3, (await Worker(library).RunOnceAsync(ct)).Converted); + var lost = (await library.Db.Conversions.ListByMediaAsync(series.Media[0].Id, ct)).Single(); + var kept = (await library.Db.Conversions.ListByMediaAsync(series.Media[1].Id, ct)).Single(); + + // «Tieni quello in libreria» for the first file of the series: its PNG goes with it, the second file's stays. + var review = new DownloadDuplicateReview(library.Db, library.Layout, library.Journal, library.Clock, library.Thumbnails, library.Index); + var pair = (await review.ListAsync(ct: ct)).Single(c => c.Candidate.EntryId == series.Entry.Id); + var result = await review.DecideAsync(pair.Pair.Id, DuplicateDecision.KeepExisting, ct: ct); + + Assert.AreEqual(1, result.FilesRemoved); + Assert.AreEqual(MediaConversionState.Removed, (await library.Db.Conversions.GetAsync(lost.Id, ct))!.State); + Assert.IsFalse(File.Exists(library.Layout.FullPath(account, lost.RelativePath!)), "the converted file of the loser goes"); + Assert.AreEqual(MediaConversionState.Converted, (await library.Db.Conversions.GetAsync(kept.Id, ct))!.State); + Assert.IsTrue(File.Exists(library.Layout.FullPath(account, kept.RelativePath!))); + var olderRow = (await library.Db.Conversions.ListByMediaAsync(older.Media[0].Id, ct)).Single(); + Assert.IsTrue(File.Exists(library.Layout.FullPath(account, olderRow.RelativePath!)), "the winner's PNG stays"); + } + + [TestMethod] + public async Task ImportingACopyConvertedForADestinationOrAFrameSaysItIsInTheLibrary() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var (account, saved) = await bed.AccountWithPhotoAsync("luca.demo", "501", TestFile.PhotoBytes(29, 64, 48)); + var media = saved.Media[0]; + + // Two files a destination of Febe got: a PNG copy of the photo and a frame (here any picture: only its SHA counts). + using var picture = TestImages.Scene(29, 64, 48); + var png = TestImages.Png(picture); + using var other = TestImages.Scene(30, 48, 64); + var frame = TestImages.Png(other); + var usb = await bed.Library.Db.Exports.AddDestinationAsync(new ExportDestination { Scope = ExportScope.General, RootPath = temp.Combine("usb"), ContentTypes = ContentTypes.All, CreatedAt = Make.T0 }, ct); + foreach (var (bytes, variant, at, name) in new[] { (png, ExportVariant.Converted, (TimeSpan?)null, "copia.png"), (frame, ExportVariant.Frame, TimeSpan.FromMilliseconds(1250), "fotogramma.png") }) + { + await bed.Library.Db.Exports.AddCopyAsync(new ExportCopy + { + DestinationId = usb.Id, + AccountId = account.Id, + MediaId = media.Id, + SourceSha256 = media.Sha256!, + Variant = variant, + Format = ExportFormat.Png, + FrameAt = at, + State = ExportCopyState.Copied, + RelativePath = "luca.demo/" + name, + Bytes = bytes.Length, + CopySha256 = Convert.ToHexStringLower(SHA256.HashData(bytes)), + CopiedAt = Make.T0, + }, ct); + bed.Write("luca.demo/" + name, bytes); + } + + var run = await bed.AnalyzeAsync(); + + foreach (var name in new[] { "copia.png", "fotogramma.png" }) + { + var file = await bed.FileAsync(run.Id, "luca.demo/" + name); + Assert.AreEqual(ImportOutcome.AlreadyInLibrary, file.Outcome, name); + Assert.AreEqual(Core.Import.ImportText.NoteConvertedCopy, file.LastError, name); + } + + Assert.AreEqual(0, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import, ct), "never a probable duplicate of its original"); + } + private static LibraryConversionEnvironment Environment(TestLibrary library, LongWorkGate? gate = null, ConversionThrottle? throttle = null) => new() { Storage = library.Db, diff --git a/tests/Febe.Tests/Media/Containers/Mp4RemuxerTests.cs b/tests/Febe.Tests/Media/Containers/Mp4RemuxerTests.cs new file mode 100644 index 0000000..49bcc39 --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/Mp4RemuxerTests.cs @@ -0,0 +1,184 @@ +using System.Security.Cryptography; +using Febe.Core.Codecs.Containers; + +namespace Febe.Tests.Codecs.Containers; + +/// +/// «MOV → MP4 solo rimuxaggio» (tappa E3, WP1.4): the samples are copied as they are, with their times, sync samples, +/// edit, rotation, languages and dates; what the MP4 cannot take is refused with its reason, and the same source always +/// gives the same bytes of the length planned. The videos are built by the tests from conformance streams. +/// +[TestClass] +public sealed class Mp4RemuxerTests +{ + private static readonly DateTimeOffset Created = new(2025, 7, 14, 18, 30, 5, TimeSpan.Zero); + private static readonly DateTimeOffset Modified = new(2025, 7, 15, 9, 0, 0, TimeSpan.Zero); + + [TestMethod] + public void MovBecomesMp4WithTheSameSamplesDatesRotationAndLanguage() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); // B frames: composition offsets and an edit + var mov = TestVideos.Mov(es, new MovOptions(Audio: true, Language: "ita", Rotation: 90, Created: Created, Modified: Modified)); + using var source = new MemoryStream(mov); + var before = Read(source); + Assert.AreEqual("qt ", before.MajorBrand); + + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None)); + Assert.IsEmpty(plan!.Losses); + var mp4 = Remux(plan, source); + + Assert.AreEqual(plan.OutputLength, mp4.Length, "the length is known before writing"); + using var output = new MemoryStream(mp4); + var after = Read(output); + Assert.AreNotEqual("qt ", after.MajorBrand); + Assert.AreEqual((Created, Modified), (after.CreatedAt, after.ModifiedAt)); + Assert.AreEqual(2, after.TrackCount); + Assert.AreEqual((90, "ita", "ita"), (after.Video!.Rotation, after.Video.Language, after.Audio!.Language)); + CollectionAssert.AreEqual(before.Video!.AvcConfiguration, after.Video.AvcConfiguration); + CollectionAssert.AreEqual(before.Audio!.AacConfiguration, after.Audio.AacConfiguration); + AssertSameSamples(before.Video, source, after.Video, output, "video"); + AssertSameSamples(before.Audio, source, after.Audio, output, "audio"); + + // The MP4 named .mp4 is what was asked: copied, not remuxed again. + Assert.AreEqual(RemuxRefusal.AlreadyMp4, Mp4Remuxer.Check(output, "clip.mp4", out _, CancellationToken.None)); + } + + [TestMethod] + public void TheStartAndSyncAreKeptByTheEditList() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + var mov = TestVideos.Mov(es, new MovOptions(Audio: true, AudioPriming: 1024, VideoEmptyEdit: TestVideos.Timescale / 2)); + using var source = new MemoryStream(mov); + var before = Read(source); + Assert.AreEqual((1024L, 1), (before.Audio!.EditMediaTime, before.Audio.EditCount), "the priming is hidden by the edit"); + Assert.AreEqual((long)TestVideos.Timescale / 2, before.Video!.EmptyEditDuration, "the video starts half a second later"); + + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None)); + using var output = new MemoryStream(Remux(plan!, source)); + var after = Read(output); + + Assert.AreEqual((before.Audio.EditMediaTime, before.Video.EmptyEditDuration), (after.Audio!.EditMediaTime, after.Video!.EmptyEditDuration)); + Assert.AreEqual(before.Video.EditMediaTime ?? 0, after.Video.EditMediaTime ?? 0); + AssertSameSamples(before.Video, source, after.Video, output, "video"); + AssertSameSamples(before.Audio, source, after.Audio, output, "audio"); + } + + [TestMethod] + public void ExtraTracksAreDroppedAndCountedAndMp3IsKept() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + using var two = new MemoryStream(TestVideos.Mov(es, new MovOptions(Audio: true, ExtraAudioTracks: 1))); + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(two, "clip.mov", out var plan, CancellationToken.None)); + CollectionAssert.AreEqual(new[] { Mp4Remuxer.LostTracks + ":1" }, plan!.Losses.ToArray()); + using (var output = new MemoryStream(Remux(plan, two))) + { + Assert.AreEqual(2, Read(output).TrackCount); + } + + using var mp3 = new MemoryStream(TestVideos.Mov(es, new MovOptions(Audio: true, Mp3: true))); + Assert.AreEqual(AudioCodec.Mp3, Read(mp3).Audio!.Codec); + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(mp3, "clip.mov", out var mp3Plan, CancellationToken.None)); + using var mp3Output = new MemoryStream(Remux(mp3Plan!, mp3)); + Assert.AreEqual(AudioCodec.Mp3, Read(mp3Output).Audio!.Codec); + } + + [TestMethod] + public void HevcAndMatroskaAreRemuxedWithTheirSamples() + { + var hevc = ElementaryStream.LoadHevc("INITQP_A_Sony_1"); + using var mov = new MemoryStream(TestVideos.Mov(hevc)); + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(mov, "clip.mov", out var plan, CancellationToken.None)); + using (var output = new MemoryStream(Remux(plan!, mov))) + { + var after = Read(output); + Assert.AreEqual(VideoCodec.Hevc, after.Video!.Codec); + CollectionAssert.AreEqual(hevc.AvcC, after.Video.HevcConfiguration); + AssertSameSamples(Read(mov).Video!, mov, after.Video, output, "HEVC"); + } + + // Matroska block times are presentation times in milliseconds: the MP4 shows each sample at the same millisecond. + var es = ElementaryStream.Load("CABA3_SVA_B"); + using var mkv = new MemoryStream(TestVideos.Matroska(es)); + var before = Read(mkv).Video!; + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(mkv, "clip.mkv", out var mkvPlan, CancellationToken.None)); + using var remuxed = new MemoryStream(Remux(mkvPlan!, mkv)); + var after2 = Read(remuxed).Video!; + Assert.HasCount(before.Samples.Count, after2.Samples); + var buffer = new byte[1]; + var other = new byte[1]; + for (var i = 0; i < before.Samples.Count; i++) + { + CollectionAssert.AreEqual(ContainerReader.ReadSample(mkv, before.Samples[i], ref buffer).ToArray(), ContainerReader.ReadSample(remuxed, after2.Samples[i], ref other).ToArray(), $"campione {i}"); + Assert.AreEqual(before.Samples[i].Key, after2.Samples[i].Key, $"sincronia {i}"); + Assert.AreEqual( + Math.Round(before.Seconds(before.Samples[i].PresentationTime) * 1000), + Math.Round(after2.Seconds(after2.Samples[i].PresentationTime + after2.EmptyEditDuration) * 1000), + $"istante {i}"); + } + } + + [TestMethod] + public void WhatNeedsReEncodingIsRefusedWithItsReason() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + RemuxRefusal Check(byte[] data, string name) + { + using var stream = new MemoryStream(data); + var refusal = Mp4Remuxer.Check(stream, name, out var plan, CancellationToken.None); + Assert.AreEqual(refusal == RemuxRefusal.None, plan is not null); + return refusal; + } + + Assert.AreEqual(RemuxRefusal.VideoCodec, Check(TestVideos.Matroska(es, codecId: "V_VP9"), "clip.webm")); + Assert.AreEqual(RemuxRefusal.ContainerNotRemuxable, Check(TestVideos.Avi(es), "clip.avi")); + Assert.AreEqual(RemuxRefusal.AlreadyMp4, Check(TestVideos.Mp4(es), "clip.mp4")); + Assert.AreEqual(RemuxRefusal.None, Check(TestVideos.Mp4(es), "clip.m4v"), "an MP4 with another name is remuxed into a true .mp4"); + Assert.AreNotEqual(RemuxRefusal.None, Check(new byte[4096], "clip.mov")); + + // A truncated MOV: its samples are past the end of the file. + var mov = TestVideos.Mov(es); + Assert.AreEqual(RemuxRefusal.Unreadable, Check(mov[..(mov.Length - 100)], "clip.mov")); + } + + [TestMethod] + public void RemuxingTwiceGivesTheSameBytes() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + var mov = TestVideos.Mov(es, new MovOptions(Audio: true, Language: "eng", Created: Created)); + string Once() + { + using var source = new MemoryStream(mov); + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None)); + return Convert.ToHexStringLower(SHA256.HashData(Remux(plan!, source))); + } + + Assert.AreEqual(Once(), Once()); + } + + private static MediaContainer Read(Stream stream) + { + stream.Position = 0; + return ContainerReader.Read(stream, ContainerReader.AnyDate, samples: true)!; + } + + private static byte[] Remux(RemuxPlan plan, Stream source) + { + using var output = new MemoryStream(); + Mp4Remuxer.Write(plan, source, output, CancellationToken.None); + return output.ToArray(); + } + + private static void AssertSameSamples(MediaTrack before, Stream source, MediaTrack after, Stream output, string what) + { + Assert.HasCount(before.Samples.Count, after.Samples, what); + Assert.AreEqual(before.Timescale, after.Timescale, what); + var a = new byte[1]; + var b = new byte[1]; + for (var i = 0; i < before.Samples.Count; i++) + { + var (x, y) = (before.Samples[i], after.Samples[i]); + Assert.AreEqual((x.Size, x.DecodeTime, x.PresentationTime, x.Key), (y.Size, y.DecodeTime, y.PresentationTime, y.Key), $"{what} {i}"); + CollectionAssert.AreEqual(ContainerReader.ReadSample(source, x, ref a).ToArray(), ContainerReader.ReadSample(output, y, ref b).ToArray(), $"{what} {i}"); + } + } +} diff --git a/tests/Febe.Tests/Media/Containers/TestVideos.cs b/tests/Febe.Tests/Media/Containers/TestVideos.cs index a150de8..1ee6bc5 100644 --- a/tests/Febe.Tests/Media/Containers/TestVideos.cs +++ b/tests/Febe.Tests/Media/Containers/TestVideos.cs @@ -308,6 +308,66 @@ internal static class TestVideos return output.ToArray(); } + /// + /// A QuickTime file (major brand qt , as phones write MOV) of the stream and, with , + /// an AAC track (or MP3) of fixed frames; with the options of a camera: track languages, rotation, both dates, the + /// AAC priming hidden by an edit, a delayed start (an empty edit) and a second audio track that the MP4 drops. + /// + public static byte[] Mov(ElementaryStream es, MovOptions? options = null) + { + var o = options ?? new MovOptions(); + var samples = new List(); + var data = new List(); + for (var i = 0; i < es.Count; i++) + { + var bytes = es.LengthPrefixed(i); + data.Add(bytes); + samples.Add(new Mp4OutputSample(bytes.Length, (long)i * FrameTicks, (long)es.Rank[i] * FrameTicks, es.Key[i])); + } + + var tracks = new List + { + new() + { + IsVideo = true, + Timescale = Timescale, + Samples = samples, + WriteSample = (i, s) => s.Write(data[i]), + Width = es.Width, + Height = es.Height, + Rotation = o.Rotation, + AvcConfiguration = es.Hevc ? null : es.AvcC, + HevcConfiguration = es.Hevc ? es.AvcC : null, + Language = o.Language, + EmptyEditDuration = o.VideoEmptyEdit, + }, + }; + for (var track = 0; track < (o.Audio ? 1 : 0) + o.ExtraAudioTracks; track++) + { + var frames = (int)Math.Ceiling(es.Count / 30.0 * 44100 / 1024) + (o.AudioPriming > 0 ? 1 : 0); + var payload = new byte[] { 0x21, 0x10, 0x04, 0x60, 0x8C, 0x1C, (byte)track }; + tracks.Add(new Mp4OutputTrack + { + IsVideo = false, + Timescale = 44100, + Samples = [.. Enumerable.Range(0, frames).Select(i => new Mp4OutputSample(payload.Length, i * 1024L, i * 1024L, true))], + WriteSample = (_, s) => s.Write(payload), + AacConfiguration = o.Mp3 ? null : [0x12, 0x10], // AAC LC, 44.1 kHz, stereo + IsMp3 = o.Mp3, + SampleRate = 44100, + Channels = 2, + Language = o.Language, + EditMediaTime = o.AudioPriming > 0 ? o.AudioPriming : null, + }); + } + + using var output = new MemoryStream(); + Mp4Writer.Prepare(tracks, new Mp4MovieInfo(o.Created, o.Modified)).WriteTo(output); + var file = output.ToArray(); + "qt "u8.CopyTo(file.AsSpan(8)); // the major brand of ftyp + return file; + } + /// /// A fragmented MP4 (empty sample tables in moov, then moof+mdat pairs of frames). /// With the sample durations come from trex, each fragment has two runs that @@ -400,7 +460,7 @@ internal static class TestVideos /// A Matroska file with one video track of SimpleBlocks, in a single cluster; block times are in ticks of /// nanoseconds (milliseconds by default). /// - public static byte[] Matroska(ElementaryStream es, DateTimeOffset? created = null, bool webm = false, uint timecodeScale = 1_000_000) + public static byte[] Matroska(ElementaryStream es, DateTimeOffset? created = null, bool webm = false, uint timecodeScale = 1_000_000, string? codecId = null) { var shift = 0; for (var i = 0; i < es.Count; i++) @@ -422,7 +482,7 @@ internal static class TestVideos var video = Element(0xE0, Element(0xB0, U16((ushort)es.Width)), Element(0xBA, U16((ushort)es.Height))); var track = Element(0xAE, Element(0xD7, [1]), Element(0x73C5, [7]), Element(0x83, [1]), - Element(0x86, es.Hevc ? "V_MPEGH/ISO/HEVC"u8.ToArray() : "V_MPEG4/ISO/AVC"u8.ToArray()), Element(0x63A2, es.AvcC), video); + Element(0x86, codecId is not null ? Encoding.ASCII.GetBytes(codecId) : es.Hevc ? "V_MPEGH/ISO/HEVC"u8.ToArray() : "V_MPEG4/ISO/AVC"u8.ToArray()), Element(0x63A2, es.AvcC), video); var blocks = new List { Element(0xE7, [0]) }; for (var i = 0; i < es.Count; i++) { @@ -558,3 +618,19 @@ internal static class TestVideos return b; } } + +/// What puts in a QuickTime file. +/// One audio track (AAC unless ). +/// Further audio tracks (an MP4 of Febe keeps one). +/// Samples of AAC priming hidden by the audio edit (media time of the edit); 0: no edit. +/// Ticks (of 30000 a second) before the video starts: an empty edit. +internal sealed record MovOptions( + bool Audio = false, + bool Mp3 = false, + int ExtraAudioTracks = 0, + string? Language = null, + int Rotation = 0, + DateTimeOffset? Created = null, + DateTimeOffset? Modified = null, + long AudioPriming = 0, + long VideoEmptyEdit = 0); diff --git a/tests/Febe.Tests/Media/Containers/VideoFramesTests.cs b/tests/Febe.Tests/Media/Containers/VideoFramesTests.cs index 6f77033..10d95c4 100644 --- a/tests/Febe.Tests/Media/Containers/VideoFramesTests.cs +++ b/tests/Febe.Tests/Media/Containers/VideoFramesTests.cs @@ -140,6 +140,103 @@ public sealed class VideoFramesTests Assert.AreEqual(RemuxRefusal.AlreadyMp4, Mp4Remuxer.Check(mp4, "video.mp4", out _, CancellationToken.None)); } + [TestMethod] + public void HevcFramesWork() + { + var es = ElementaryStream.LoadHevc("INITQP_A_Sony_1"); + using var stream = new MemoryStream(TestVideos.Mp4(es)); + using var reader = VideoFrameReader.Open(stream, out var info); + Assert.IsTrue(info.Available); + + var target = reader.Locate([TimeSpan.FromMilliseconds(1010)]).Single(); + Assert.AreEqual(TimeSpan.FromSeconds(1), target.Actual); + using var frame = reader.Decode([target], CancellationToken.None).Single(); + + var shown = new List(); + var decoder = new Febe.Core.Codecs.H265.H265Decoder(); + decoder.FrameOutput += shown.Add; + decoder.DecodeAnnexB(File.ReadAllBytes(Codecs.H265.H265ConformanceStream.Load(es.Name).BitstreamPath)); + var expected = VideoFrameDecoder.ToImage(shown[30], 0, 0); + var pixels = frame.Image.ToArray(); + for (var i = 0; i < expected.Width * expected.Height; i++) + { + Assert.AreEqual((expected.Rgb[i * 3], expected.Rgb[(i * 3) + 1], expected.Rgb[(i * 3) + 2]), (pixels[i * 4], pixels[(i * 4) + 1], pixels[(i * 4) + 2]), $"pixel {i}"); + } + } + + [TestMethod] + public void TheInstantFollowsTheEditList() + { + // The video starts half a second into the presentation (an empty edit): the browser shows nothing of it before. + var es = ElementaryStream.Load("BA1_Sony_D"); + using var stream = new MemoryStream(TestVideos.Mov(es, new MovOptions(VideoEmptyEdit: TestVideos.Timescale / 2))); + using var reader = VideoFrameReader.Open(stream, out var info); + Assert.IsTrue(info.Available); + + var targets = reader.Locate([TimeSpan.FromMilliseconds(200), TimeSpan.FromMilliseconds(510), TimeSpan.FromMilliseconds(1010)]); + + Assert.AreEqual((Array.IndexOf(es.Rank, 0), TimeSpan.FromMilliseconds(500)), (targets[0].Sample, targets[0].Actual), "before the start: the first frame"); + Assert.AreEqual(TimeSpan.FromMilliseconds(500), targets[1].Actual); + Assert.AreEqual((Array.IndexOf(es.Rank, 15), TimeSpan.FromSeconds(1)), (targets[2].Sample, targets[2].Actual), "frame 15 is shown at 0.5 + 0.5 s"); + } + + [TestMethod] + public void EveryKSecondsAndNInAllFindTheFramesShown() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + using var stream = new MemoryStream(TestVideos.Mp4(es)); + using var reader = VideoFrameReader.Open(stream, out var info); + + var every = reader.Locate(ExportFrames.Every(info.Duration, TimeSpan.FromMilliseconds(250))); + Assert.AreEqual(TimeSpan.Zero, every[0].Actual); + foreach (var t in every) + { + Assert.IsLessThanOrEqualTo(t.Requested, t.Actual, "the frame shown at an instant started at or before it"); + Assert.IsLessThan(TimeSpan.FromMilliseconds(34), t.Requested - t.Actual, "and less than a frame before"); + } + + var spread = reader.Locate(ExportFrames.Spread(info.Duration, 4)); + Assert.HasCount(4, spread.Select(t => t.Sample).Distinct().ToList(), "four different frames"); + var frames = reader.Decode(spread, CancellationToken.None).ToList(); + try + { + CollectionAssert.AreEquivalent(new[] { 0, 1, 2, 3 }, frames.Select(f => f.Index).ToArray(), "one picture per target"); + } + finally + { + frames.ForEach(f => f.Dispose()); + } + } + + [TestMethod] + public void AnUnsupportedCodecSaysNotAvailable() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + using var stream = new MemoryStream(TestVideos.Matroska(es, webm: true, codecId: "V_VP9")); + 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 ADamagedStreamGivesNoPicture() + { + // The container is fine, the pictures are noise: no frame comes out, nothing throws. + var es = ElementaryStream.Load("BA1_Sony_D"); + var mp4 = TestVideos.Mp4(es); + var mdat = mp4.AsSpan().IndexOf("mdat"u8) + 4; + new Random(5).NextBytes(mp4.AsSpan(mdat + 64)); + using var stream = new MemoryStream(mp4); + using var reader = VideoFrameReader.Open(stream, out var info); + Assert.IsTrue(info.Available, "the tables are readable"); + + var frames = reader.Decode(reader.Locate([TimeSpan.FromMilliseconds(900)]), CancellationToken.None).ToList(); + frames.ForEach(f => f.Dispose()); + Assert.IsEmpty(frames); + } + /// The frame shown at position , decoded straight from the stream. private static H264Frame ShownFrame(ElementaryStream es, int rank) {