Files
Febe/tests/Febe.Tests/Imaging/ReferenceDecodeTests.cs
Alby96andClaude Opus 5.5 b4383a6110 Lettore e scrittore WebP di casa (C1, passo 4)
Il lettore WebP, scritto dalla RFC 9649 e dalla RFC 6386, prende il posto di
SkiaSharp per i WebP: VP8 con perdita, VP8L senza perdita, ALPH grezzo e
compresso con ogni filtro, VP8X con ICCP, EXIF e XMP, e di un'animazione il
primo fotogramma fuso sulla tela, con il numero dei fotogrammi. La facciata
ImageDecoder ora legge i WebP.

Contro i riferimenti di SkiaSharp i quattro WebP senza perdita coincidono byte
per byte; i quattro con perdita stanno fra 68,7 e 74,4 dB per canale, scarto
massimo 1, alfa esatta. File danneggiati, tagliati o fuori dai limiti si
rifiutano; i limiti si controllano prima di allocare.

Lo scrittore fa WebP senza perdita (tavolozza, sottrazione del verde,
predittore, trasformata del colore, LZ77, cache dei colori, Huffman) e il
formato esteso solo quando ci sono metadati: i 57 riferimenti tornano esatti e
pesano l'88% del PNG di casa. Niente componenti esterni.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:01:47 +01:00

156 lines
6.2 KiB
C#

using System.Buffers.Binary;
using System.IO.Compression;
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// The in-house PNG, GIF and BMP decoders against the reference set (Imaging/Riferimenti/LEGGIMI.md): every pixel
/// must be the one SkiaSharp read, exactly. The expected images are read with our own PNG decoder, which is first
/// checked on them against a reader of a dozen lines that only knows their trivial layout.
/// </summary>
[TestClass]
public sealed class ReferenceDecodeTests
{
public static IEnumerable<object[]> PngCases => ReferenceImages.NamesOf(ReferenceFormat.Png);
public static IEnumerable<object[]> GifCases => ReferenceImages.NamesOf(ReferenceFormat.Gif);
public static IEnumerable<object[]> BmpCases => ReferenceImages.NamesOf(ReferenceFormat.Bmp);
[TestMethod]
public void EveryExpectedImageReadsTheSameWithTheDecoderAndWithTheTrivialReader()
{
foreach (var reference in ReferenceImages.All)
{
var png = reference.ReadExpectedPng();
using var image = PngDecoder.Decode(png);
Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height), reference.Name);
ImageAssert.AreEqual(reference.Width, TrivialRead(png, reference.Width, reference.Height), image.Pixels, reference.Name + ".atteso.png");
}
}
[TestMethod]
[DynamicData(nameof(PngCases))]
public void ThePngDecoderReadsTheReferenceExactly(string name) => CheckExact(name, data => PngDecoder.Decode(data));
[TestMethod]
[DynamicData(nameof(GifCases))]
public void TheGifDecoderReadsTheReferenceExactly(string name) => CheckExact(name, data => GifDecoder.Decode(data));
[TestMethod]
[DynamicData(nameof(BmpCases))]
public void TheBmpDecoderReadsTheReferenceExactly(string name) => CheckExact(name, data => BmpDecoder.Decode(data));
[TestMethod]
public void TheFacadeChoosesTheDecoderFromTheFirstBytes()
{
foreach (var reference in ReferenceImages.All)
{
var input = reference.ReadInput();
var format = ImageFormatSniffer.Detect(input);
var expected = reference.Format switch
{
ReferenceFormat.Png => ImageFormat.Png,
ReferenceFormat.Jpeg => ImageFormat.Jpeg,
ReferenceFormat.WebP => ImageFormat.WebP,
ReferenceFormat.Gif => ImageFormat.Gif,
_ => ImageFormat.Bmp,
};
Assert.AreEqual(expected, format, reference.Name);
if (!ImageDecoder.CanDecode(format))
{
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Decode(input), reference.Name);
continue;
}
if (reference.Format == ReferenceFormat.Jpeg || (reference.Format == ReferenceFormat.WebP && !reference.Name.Contains("senza-perdita", StringComparison.Ordinal)))
{
// Lossy: JpegReferenceTests and WebPReferenceTests compare it with thresholds (JPEG with the EXIF
// orientation applied).
continue;
}
using var image = ImageDecoder.Decode(input);
using var expectedImage = PngDecoder.Decode(reference.ReadExpectedPng());
ImageAssert.AreEqual(expectedImage, image, reference.Name);
var info = ImageDecoder.Identify(input);
Assert.AreEqual((format, reference.Width, reference.Height), (info.Format, info.Width, info.Height), reference.Name);
}
}
[TestMethod]
public void TheAnimatedGifHasMoreThanOneFrameAndTheOthersOne()
{
foreach (var reference in ReferenceImages.Of(ReferenceFormat.Gif))
{
var info = GifDecoder.Identify(reference.ReadInput());
if (reference.Name == "gif-animata")
{
Assert.IsGreaterThan(1, info.FrameCount, reference.Name);
}
else
{
Assert.AreEqual(1, info.FrameCount, reference.Name);
}
using var image = GifDecoder.Decode(reference.ReadInput(), out var again);
Assert.AreEqual(info.FrameCount, again.FrameCount, reference.Name);
}
}
[TestMethod]
public void HandBuiltPngsCarryTheirTextChunk()
{
// LEGGIMI.md: every hand-built PNG has a tEXt to skip; the metadata reader finds it.
foreach (var reference in ReferenceImages.Of(ReferenceFormat.Png).Where(c => !c.Name.StartsWith("png-skia", StringComparison.Ordinal)))
{
var info = PngDecoder.Identify(reference.ReadInput());
Assert.IsNotEmpty(info.Metadata.Texts, reference.Name);
Assert.AreEqual(1, info.FrameCount, reference.Name);
}
}
private static void CheckExact(string name, Func<byte[], RgbaImage> decode)
{
var reference = ReferenceImages.Get(name);
using var expected = PngDecoder.Decode(reference.ReadExpectedPng());
using var actual = decode(reference.ReadInput());
ImageAssert.AreEqual(expected, actual, name);
}
/// <summary>
/// Reads an expected image knowing only how they were written: IHDR, IDAT chunks, one zlib stream of rows that
/// all use filter 0, RGBA8. Independent of <see cref="PngDecoder"/>.
/// </summary>
private static byte[] TrivialRead(byte[] png, int width, int height)
{
using var idat = new MemoryStream();
var pos = 8;
while (pos < png.Length)
{
var length = (int)BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos));
if (png.AsSpan(pos + 4, 4).SequenceEqual("IDAT"u8))
{
idat.Write(png, pos + 8, length);
}
pos += length + 12;
}
idat.Position = 0;
using var zlib = new ZLibStream(idat, CompressionMode.Decompress);
var pixels = new byte[width * height * 4];
var row = new byte[1 + (width * 4)];
for (var y = 0; y < height; y++)
{
zlib.ReadExactly(row);
Assert.AreEqual(0, row[0], "le immagini attese usano solo il filtro 0");
row.AsSpan(1).CopyTo(pixels.AsSpan(y * width * 4));
}
return pixels;
}
}