Files
Febe/tests/Febe.Tests/Imaging/ImageConversionCheckTests.cs
T
Alby96andClaude Opus 5.5 958cb71cd6 E3: correzioni della revisione di formati e fotogrammi
Le 16 osservazioni confermate della revisione, ognuna con la sua prova:

- JPEG: il controllo stima la memoria di lavoro del decodificatore
  (progressivo), così un file che non si decodifica esce «troppo
  grande» e non «illeggibile».
- Un EXIF che non si tiene lascia un EXIF minimo con l'orientamento,
  perché la foto convertita non esca girata.
- Fotogrammi: istanti in millisecondi interi; la copia trova l'indice
  del nome dall'istante, non dall'ordine delle righe.
- Video di durata sconosciuta misurati prima di registrare: contano
  nei limiti di 500 per richiesta e 5000 per video.
- Rimuxaggio: la durata del segmento di elst passa nell'MP4, la fine
  tagliata resta nascosta (anche nei fotogrammi).
- H.264: il punto di recupero vale come IDR solo con exact_match_flag.
- MP3 in MP4: objectTypeIndication 0x69 fino a 24 kHz, 0x6B oltre.
- Conversione della libreria: il lavoro toglie le righe di un formato
  spento o cambiato; spegnere toglie anche i «Non riuscito»; «Riprova»
  solo i formati di adesso; pausa per spazio prima di rileggere
  l'originale.
- «Anche i N» conta e mette in coda solo il tipo che si cambia; le
  impostazioni dell'esportazione si salvano una per volta.
- Eliminazione e «Tieni il più grande» scelgono i convertiti nella
  stessa transazione: nessun convertito orfano.
- Un file arrivato tardi in un elemento vecchio mette in coda solo sé
  (file nuovo = salvato da quando il formato è scelto).
- Zip dei fotogrammi a pezzi di 64 KB: un browser lento che legge non
  si interrompe, uno fermo sì.

Decisioni in docs/decisioni.md (28/11), §4.10 della specifica precisato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 13:30:33 +01:00

218 lines
13 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
/// <summary>
/// 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.
/// </summary>
[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);
}
/// <summary>A JPEG of only its header (SOI, SOF, SOS, EOI): enough for the check, which never decodes.</summary>
private static byte[] JpegHeader(int frameMarker, int width, int height, byte lumaSampling)
{
return
[
0xFF, 0xD8,
0xFF, (byte)frameMarker, 0, 17, 8, (byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width, 3,
1, lumaSampling, 0, 2, 0x11, 1, 3, 0x11, 1,
0xFF, 0xDA, 0, 12, 3, 1, 0x00, 2, 0x11, 3, 0x11, 0, 0, 0,
0xFF, 0xD9,
];
}
[TestMethod]
public async Task AProgressiveJpegTheDecoderWouldRefuseIsTooLargeNotUnreadable()
{
// 8000 × 8000 = 64 MP, within the 100 MP of PNG and JPG. Baseline it needs 3 bytes a pixel besides the picture;
// progressive 4:4:4 keeps its coefficients too, 9 bytes a pixel: 576 MB, over the decoder's 512 MiB.
var baseline = JpegHeader(0xC0, 8000, 8000, 0x11);
var progressive = JpegHeader(0xC2, 8000, 8000, 0x11);
var progressive420 = JpegHeader(0xC2, 8000, 8000, 0x22);
Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(baseline, ImageFormat.Png).Action);
Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(progressive420, ImageFormat.Png).Action, "4:2:0: 4,5 byte a pixel");
Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyOriginal, ImageFormat.Jpeg, ImageConversionLosses.AsIsTooLarge),
ImageConverter.Check(progressive, ImageFormat.Png));
Assert.AreEqual(576_000_000L, ImageDecoder.Identify(progressive).DecodeWorkingBytes);
// The copy and the library conversion say «troppo grande», never «Febe non riesce a leggere l'immagine».
var sha = Convert.ToHexStringLower(SHA256.HashData(progressive));
using var prepared = await MediaConverter.PrepareAsync(() => new MemoryStream(progressive), "post/grande.jpg", MediaKind.Photo,
ExportFormat.Png, sha, new ConversionThrottle(), CancellationToken.None);
Assert.AreEqual(ExportVariant.Whole, prepared.Variant);
CollectionAssert.AreEqual(new[] { ImageConversionLosses.AsIsTooLarge }, prepared.Notes.ToArray());
}
[TestMethod]
public void WhatTheCheckLetsThroughTheDecoderConverts()
{
// A real progressive 4:4:4 JPEG of 64 × 64 under a working budget between the 3 bytes a pixel of a baseline
// decode and the 9 of a progressive one: the check sends it as it is, so the conversion never throws.
using var picture = Gradient(64, 64, seed: 3);
var baseline = ImageConverter.Encode(picture, ImageFormat.Jpeg, null, new ImageConversionOptions { JpegSubsampling = JpegSubsampling.Ratio444 });
var progressive = JpegTestEncoder.Write(JpegDecoder.DecodeCoefficients(baseline), new JpegTestOptions { Progressive = true });
var options = new ImageConversionOptions { Limits = new ImageLimits { MaxWorkingBytes = 64 * 64 * 6 } };
Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(baseline, ImageFormat.Png, options).Action);
Assert.AreEqual(ImageFormat.Png, ImageFormatSniffer.Detect(ImageConverter.Convert(baseline, ImageFormat.Png, options).Data));
Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(progressive, ImageFormat.Png, options).NoteCode);
Assert.ThrowsExactly<ImageLimitException>(() => ImageConverter.Convert(progressive, ImageFormat.Png, options));
Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(progressive, ImageFormat.Png).Action, "con i limiti di sempre");
Assert.AreEqual(ImageFormat.Png, ImageFormatSniffer.Detect(ImageConverter.Convert(progressive, ImageFormat.Png).Data));
}
}