Lettori PNG, GIF e BMP e scrittore PNG di casa (C1, passo 2)

Prima parte dei codec d'immagine scritti in casa per togliere SkiaSharp (decisione di Alberto del 18 novembre 2026: niente componenti esterni). In Febe.Core/Codecs/Images: la base comune (RgbaImage RGBA a 8 bit non premoltiplicata, anche dal pool; ImageLimits controllati prima di ogni allocazione; ImageDecodeException e sottotipi per limiti e formati non letti; riconoscimento del formato dai primi byte; facciata ImageDecoder), il lettore PNG (tutti i tipi di colore e le profondità, tavolozza e tRNS, Adam7, i cinque filtri, CRC di ogni blocco, metadati eXIf, iCCP, tEXt, zTXt, iTXt e XMP, numero dei fotogrammi APNG), lo scrittore PNG (RGB/RGBA a 8 bit, filtro adattivo per riga, eXIf, iCCP, XMP), il lettore GIF (LZW, primo fotogramma, trasparenza, interlacciamento, tavolozze, numero dei fotogrammi) e il lettore BMP (1-32 bit, BI_RGB, BITFIELDS, RLE8, RLE4, PNG dentro, dal basso e dall'alto). CRC-32 e LZW sono nostri, zlib è quello della BCL.

Le prove leggono i 37 riferimenti PNG, GIF e BMP e li trovano uguali byte per byte alle immagini attese, lette a loro volta con il nostro lettore PNG verificato contro un lettore minimo indipendente; poi andate e ritorno dello scrittore, metadati, file danneggiati e tagliati, limiti, e modifiche casuali a seme fisso che devono dare un'immagine o un'ImageDecodeException e nient'altro. Una riga in decisioni.md dice le scelte di lettura.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 13:26:58 +01:00
1 parent 3e4608c62d
commit 8bf76f18ff
23 files changed
+4382 -4

No files matched your search

+383
View File
@@ -0,0 +1,383 @@
using System.Buffers.Binary;
using System.IO.Compression;
using System.Text;
using Febe.Core.Codecs.Images;
using static Febe.Tests.Imaging.TestImages;
namespace Febe.Tests.Imaging;
/// <summary>The in-house PNG decoder and encoder, beyond the reference set: round trips, metadata, damaged files.</summary>
[TestClass]
public sealed class PngCodecTests
{
// An 8-bit RGBA row of 2 pixels, filter 0: red opaque, green half transparent.
private static readonly byte[] TwoPixels = [0, 255, 0, 0, 255, 0, 255, 0, 128];
[TestMethod]
public void TheCrcIsTheOneOfThePngSpecification()
{
Assert.AreEqual(0xCBF43926u, Crc32.Compute("123456789"u8));
Assert.AreEqual(0xAE426082u, Crc32.Compute("IEND"u8));
// Eight bytes at a time and one at a time agree on every length and every split.
var data = new byte[300];
new Random(7).NextBytes(data);
for (var length = 0; length <= data.Length; length += 7)
{
var whole = Crc32.Compute(data.AsSpan(0, length));
Assert.AreEqual(BitwiseCrc(data.AsSpan(0, length)), whole, $"lunghezza {length}");
var split = length / 3;
Assert.AreEqual(whole, Crc32.Append(Crc32.Compute(data.AsSpan(0, split)), data.AsSpan(split, length - split)), $"divisa a {split}");
}
}
[TestMethod]
[DataRow(PngFilterStrategy.Adaptive)]
[DataRow(PngFilterStrategy.None)]
[DataRow(PngFilterStrategy.Sub)]
[DataRow(PngFilterStrategy.Up)]
[DataRow(PngFilterStrategy.Average)]
[DataRow(PngFilterStrategy.Paeth)]
public void EveryFilterStrategyRoundTrips(PngFilterStrategy filter)
{
var seed = 11;
foreach (var (width, height) in new[] { (1, 1), (2, 3), (17, 5), (300, 7), (5, 300) })
{
using var image = TestImages.Random(width, height, seed++);
var png = PngEncoder.Encode(image, new PngEncoderOptions { Filter = filter });
using var back = PngDecoder.Decode(png);
ImageAssert.AreEqual(image, back, $"{filter} {width}×{height}");
using var smooth = Gradient(width, height, seed++);
using var smoothBack = PngDecoder.Decode(PngEncoder.Encode(smooth, new PngEncoderOptions { Filter = filter }));
ImageAssert.AreEqual(smooth, smoothBack, $"{filter} {width}×{height} sfumato");
}
}
[TestMethod]
public void AdaptiveFilteringUsesTheFiveFiltersAndCompressesBetterThanNone()
{
using var image = Gradient(200, 120, 3);
var adaptive = PngEncoder.Encode(image);
var none = PngEncoder.Encode(image, new PngEncoderOptions { Filter = PngFilterStrategy.None });
Assert.IsLessThan(none.Length, adaptive.Length);
var raw = Inflate(Join(PngChunks(adaptive).Where(c => c.Type == "IDAT").Select(c => c.Payload).ToArray()));
var rowBytes = (200 * 4) + 1;
var used = Enumerable.Range(0, 120).Select(y => raw[y * rowBytes]).ToHashSet();
Assert.IsTrue(used.All(f => f <= 4), "filtro fuori dalla specifica");
Assert.IsGreaterThan(1, used.Count, "il filtro adattivo sceglie per ogni riga");
}
[TestMethod]
public void AutoWritesRgbForAnOpaqueImageAndRgbaOtherwise()
{
using var opaque = TestImages.Random(9, 4, 1, opaque: true);
var png = PngEncoder.Encode(opaque);
Assert.AreEqual(2, PngChunks(png)[0].Payload[9], "tipo di colore");
using (var back = PngDecoder.Decode(png))
{
ImageAssert.AreEqual(opaque, back, "RGB");
}
using var translucent = TestImages.Random(9, 4, 2);
Assert.AreEqual(6, PngChunks(PngEncoder.Encode(translucent))[0].Payload[9], "tipo di colore");
// Rgb drops alpha, Rgba keeps it even for an opaque image.
using var dropped = PngDecoder.Decode(PngEncoder.Encode(translucent, new PngEncoderOptions { ColorMode = PngColorMode.Rgb }));
for (var i = 0; i < dropped.Length; i += 4)
{
Assert.IsTrue(dropped.Pixels.Slice(i, 3).SequenceEqual(translucent.Pixels.Slice(i, 3)) && dropped.Pixels[i + 3] == 255, $"pixel {i / 4}");
}
Assert.AreEqual(6, PngChunks(PngEncoder.Encode(opaque, new PngEncoderOptions { ColorMode = PngColorMode.Rgba }))[0].Payload[9]);
}
[TestMethod]
public void ALargeImageIsSplitIntoSeveralIdatChunks()
{
using var image = TestImages.Random(300, 300, 5);
var png = PngEncoder.Encode(image, new PngEncoderOptions { CompressionLevel = CompressionLevel.NoCompression });
var chunks = PngChunks(png);
Assert.IsGreaterThan(5, chunks.Count(c => c.Type == "IDAT"));
Assert.IsTrue(chunks.Where(c => c.Type == "IDAT").SkipLast(1).All(c => c.Payload.Length == 64 * 1024));
CollectionAssert.AreEqual(new[] { "IHDR", "IDAT", "IEND" }, chunks.Select(c => c.Type).Distinct().ToArray());
using var back = PngDecoder.Decode(png);
ImageAssert.AreEqual(image, back, "300×300");
}
[TestMethod]
public void EveryReferenceImageRoundTripsThroughTheEncoder()
{
foreach (var reference in ReferenceImages.All)
{
using var expected = PngDecoder.Decode(reference.ReadExpectedPng());
using var back = PngDecoder.Decode(PngEncoder.Encode(expected));
ImageAssert.AreEqual(expected, back, reference.Name);
}
}
[TestMethod]
public void ExifIccAndXmpAreWrittenBeforeTheDataAndReadBack()
{
var exif = Join("MM\0*"u8.ToArray(), [0, 0, 0, 8, 0, 0]);
var icc = new byte[3000];
new Random(9).NextBytes(icc);
const string xmp = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><dc:title>Città è più</dc:title></x:xmpmeta>";
using var image = TestImages.Random(4, 4, 3);
var png = PngEncoder.Encode(image, new PngEncoderOptions
{
Exif = Join("Exif\0\0"u8.ToArray(), exif),
IccProfile = icc,
IccProfileName = "Profilo di prova",
Xmp = xmp,
});
var types = PngChunks(png).Select(c => c.Type).ToList();
CollectionAssert.AreEqual(new[] { "IHDR", "iCCP", "eXIf", "iTXt", "IDAT", "IEND" }, types);
var info = PngDecoder.Identify(png);
CollectionAssert.AreEqual(exif, info.Metadata.Exif, "l'«Exif\\0\\0» di JPEG è tolto");
CollectionAssert.AreEqual(icc, info.Metadata.IccProfile);
Assert.AreEqual("Profilo di prova", info.Metadata.IccProfileName);
Assert.AreEqual(xmp, info.Metadata.Xmp);
Assert.IsEmpty(info.Metadata.Texts, "l'XMP non è fra i testi");
using var decoded = PngDecoder.Decode(png, out var again);
Assert.AreEqual(xmp, again.Metadata.Xmp);
ImageAssert.AreEqual(image, decoded, "con i metadati");
}
[TestMethod]
public void TheEncoderRefusesMetadataItCannotWrite()
{
using var image = new RgbaImage(1, 1);
Assert.ThrowsExactly<ArgumentException>(() => PngEncoder.Encode(image, new PngEncoderOptions { Exif = [1, 2, 3, 4, 5, 6, 7, 8] }));
Assert.ThrowsExactly<ArgumentException>(() => PngEncoder.Encode(image, new PngEncoderOptions { IccProfile = [1], IccProfileName = "" }));
Assert.ThrowsExactly<ArgumentException>(() => PngEncoder.Encode(image, new PngEncoderOptions { IccProfile = [1], IccProfileName = new string('a', 80) }));
Assert.ThrowsExactly<ArgumentException>(() => PngEncoder.Encode(image, new PngEncoderOptions { IccProfile = [1], IccProfileName = "Città€" }));
}
[TestMethod]
public void TextsAreReadFromTextZtxtAndItxt()
{
var png = Png(
("IHDR", Ihdr(2, 1, 8, 6)),
("tEXt", Join(Latin1("Title"), [0], Latin1("Città"))),
("zTXt", Join(Latin1("Comment"), [0, 0], Zlib(Latin1(new string('z', 5000))))),
("iTXt", Join(Latin1("Description"), [0, 1, 0], Encoding.ASCII.GetBytes("it"), [0], Encoding.UTF8.GetBytes("Descrizione"), [0], Zlib(Encoding.UTF8.GetBytes("Un po' di più €")))),
("iTXt", Join(Latin1("Author"), [0, 0, 0, 0, 0], Encoding.UTF8.GetBytes("Alberto"))),
("IDAT", Zlib(TwoPixels)),
("IEND", []));
var texts = PngDecoder.Identify(png).Metadata.Texts;
Assert.HasCount(4, texts);
Assert.AreEqual(new ImageText("Title", "Città"), texts[0]);
Assert.AreEqual(new ImageText("Comment", new string('z', 5000)), texts[1]);
Assert.AreEqual(new ImageText("Description", "Un po' di più €", "it", "Descrizione"), texts[2]);
Assert.AreEqual(new ImageText("Author", "Alberto"), texts[3]);
}
[TestMethod]
public void MetadataBeyondTheBudgetIsDroppedAndTheImageStillDecodes()
{
var bomb = Zlib(new byte[2_000_000]);
var png = Png(
("IHDR", Ihdr(2, 1, 8, 6)),
("zTXt", Join(Latin1("Comment"), [0, 0], bomb)),
("iCCP", Join(Latin1("p"), [0, 0], bomb)),
("tEXt", Join(Latin1("Title"), [0], Latin1("breve"))),
("IDAT", Zlib(TwoPixels)),
("IEND", []));
var limits = new ImageLimits { MaxMetadataBytes = 1000 };
using var image = PngDecoder.Decode(png, out var info, limits);
Assert.AreEqual(new ImageText("Title", "breve"), info.Metadata.Texts.Single());
Assert.IsNull(info.Metadata.IccProfile);
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(0, 0));
Assert.AreEqual((0, 255, 0, 128), image.GetPixel(1, 0));
}
[TestMethod]
public void AnAnimatedPngCountsItsFramesAndDecodesTheDefaultImage()
{
var actl = new byte[8];
BinaryPrimitives.WriteUInt32BigEndian(actl, 3);
var png = Png(("IHDR", Ihdr(2, 1, 8, 6)), ("acTL", actl), ("IDAT", Zlib(TwoPixels)), ("fcTL", new byte[26]), ("IEND", []));
using var image = PngDecoder.Decode(png, out var info);
Assert.AreEqual(3, info.FrameCount);
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(0, 0));
}
[TestMethod]
public void APaletteIndexBeyondThePaletteIsOpaqueBlack()
{
var png = Png(
("IHDR", Ihdr(3, 1, 8, 3)),
("PLTE", [10, 20, 30, 40, 50, 60]),
("tRNS", [7, 8, 9, 9, 9]),
("IDAT", Zlib([0, 0, 1, 2])),
("IEND", []));
using var image = PngDecoder.Decode(png, out var info);
Assert.IsTrue(info.HasAlpha);
Assert.AreEqual((10, 20, 30, 7), image.GetPixel(0, 0));
Assert.AreEqual((40, 50, 60, 8), image.GetPixel(1, 0));
Assert.AreEqual((0, 0, 0, 255), image.GetPixel(2, 0));
}
[TestMethod]
public void ADamagedAncillaryChunkIsSkippedAndADamagedCriticalOneStopsTheDecoding()
{
var text = Chunk("tEXt", Join(Latin1("Title"), [0], Latin1("x")));
text[^1] ^= 1;
var png = Join(Png(("IHDR", Ihdr(2, 1, 8, 6))), text, Chunk("IDAT", Zlib(TwoPixels)), Chunk("IEND", []));
using (var image = PngDecoder.Decode(png, out var info))
{
Assert.IsEmpty(info.Metadata.Texts);
Assert.AreEqual((0, 255, 0, 128), image.GetPixel(1, 0));
}
var idat = Chunk("IDAT", Zlib(TwoPixels));
idat[10] ^= 0x40;
var broken = Join(Png(("IHDR", Ihdr(2, 1, 8, 6))), idat, Chunk("IEND", []));
var error = Assert.ThrowsExactly<ImageDecodeException>(() => PngDecoder.Decode(broken));
Assert.Contains("CRC", error.Message);
}
[TestMethod]
public void DamagedFilesThrowAnImageDecodeException()
{
var header = ("IHDR", Ihdr(2, 1, 8, 6));
var end = ("IEND", Array.Empty<byte>());
var cases = new Dictionary<string, byte[]>
{
["vuoto"] = [],
["solo la firma"] = Png(),
["non PNG"] = Encoding.ASCII.GetBytes("non sono un'immagine, solo testo"),
["senza IHDR"] = Png(("IDAT", Zlib(TwoPixels)), end),
["senza IDAT"] = Png(header, end),
["IHDR corto"] = Png(("IHDR", new byte[12]), ("IDAT", Zlib(TwoPixels)), end),
["larghezza zero"] = Png(("IHDR", Ihdr(0, 1, 8, 6)), ("IDAT", Zlib(TwoPixels)), end),
["RGB a 4 bit"] = Png(("IHDR", Ihdr(2, 1, 4, 2)), ("IDAT", Zlib(TwoPixels)), end),
["tipo di colore 5"] = Png(("IHDR", Ihdr(2, 1, 8, 5)), ("IDAT", Zlib(TwoPixels)), end),
["interlacciamento 2"] = Png(("IHDR", Ihdr(2, 1, 8, 6, interlace: 2)), ("IDAT", Zlib(TwoPixels)), end),
["tavolozza senza PLTE"] = Png(("IHDR", Ihdr(2, 1, 8, 3)), ("IDAT", Zlib([0, 0, 0])), end),
["PLTE in scala di grigi"] = Png(("IHDR", Ihdr(2, 1, 8, 0)), ("PLTE", [1, 2, 3]), ("IDAT", Zlib([0, 0, 0])), end),
["PLTE di 4 byte"] = Png(("IHDR", Ihdr(2, 1, 8, 3)), ("PLTE", [1, 2, 3, 4]), ("IDAT", Zlib([0, 0, 0])), end),
["IDAT separati"] = Png(header, ("IDAT", Zlib(TwoPixels)[..4]), ("tEXt", Join(Latin1("a"), [0])), ("IDAT", Zlib(TwoPixels)[4..]), end),
["zlib non valido"] = Png(header, ("IDAT", [0x78, 0x9C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), end),
["dati corti"] = Png(header, ("IDAT", Zlib(TwoPixels[..5])), end),
["filtro 5"] = Png(header, ("IDAT", Zlib(Join([5], TwoPixels[1..]))), end),
["IHDR doppio"] = Png(header, header, ("IDAT", Zlib(TwoPixels)), end),
["tipo di blocco con una cifra"] = Png(header, ("ab1d", []), ("IDAT", Zlib(TwoPixels)), end),
};
foreach (var (name, bytes) in cases)
{
var error = Assert.Throws<ImageDecodeException>(() => PngDecoder.Decode(bytes), name);
Assert.IsFalse(string.IsNullOrWhiteSpace(error.Message), name);
}
}
[TestMethod]
public void AnUnknownCriticalChunkIsNotSupportedAndAnUnknownAncillaryOneIsSkipped()
{
var crushed = Png(("IHDR", Ihdr(2, 1, 8, 6)), ("CgBI", [0, 0, 0, 0]), ("IDAT", Zlib(TwoPixels)), ("IEND", []));
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => PngDecoder.Decode(crushed));
var extra = Png(("IHDR", Ihdr(2, 1, 8, 6)), ("vpAg", [1, 2, 3]), ("IDAT", Zlib(TwoPixels)), ("prVt", []), ("IEND", []));
using var image = PngDecoder.Decode(Join(extra, Encoding.ASCII.GetBytes("dopo IEND")));
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(0, 0));
}
[TestMethod]
public void EveryTruncationEitherFailsOrGivesTheWholeImage()
{
var reference = ReferenceImages.Get("png-tav-4-adam7");
var full = reference.ReadInput();
using var expected = PngDecoder.Decode(full);
var whole = 0;
for (var length = 0; length < full.Length; length++)
{
var cut = full[..length];
try
{
using var image = PngDecoder.Decode(cut);
ImageAssert.AreEqual(expected, image, $"tagliato a {length}");
whole++;
}
catch (ImageDecodeException)
{
}
}
// Only cuts at a chunk boundary after the last IDAT keep everything (a missing IEND is accepted).
var lastIdatEnd = 8;
var boundaries = new List<int>();
for (var pos = 8; pos < full.Length;)
{
var length = (int)BinaryPrimitives.ReadUInt32BigEndian(full.AsSpan(pos));
var type = Encoding.ASCII.GetString(full, pos + 4, 4);
pos += length + 12;
boundaries.Add(pos);
if (type == "IDAT")
{
lastIdatEnd = pos;
}
}
Assert.AreEqual(boundaries.Count(b => b >= lastIdatEnd && b < full.Length), whole);
Assert.IsGreaterThanOrEqualTo(1, whole);
}
[TestMethod]
public void ImagesBeyondTheLimitsAreRefusedBeforeDecoding()
{
var huge = Png(("IHDR", Ihdr(70_000, 1, 8, 6)), ("IDAT", Zlib([0])), ("IEND", []));
Assert.ThrowsExactly<ImageLimitException>(() => PngDecoder.Decode(huge));
Assert.AreEqual(70_000, PngDecoder.Identify(huge).Width, "la misura si legge anche oltre i limiti");
using var image = TestImages.Random(50, 50, 4);
var png = PngEncoder.Encode(image);
Assert.ThrowsExactly<ImageLimitException>(() => PngDecoder.Decode(png, new ImageLimits { MaxPixels = 2499 }));
Assert.ThrowsExactly<ImageLimitException>(() => PngDecoder.Decode(png, new ImageLimits { MaxWidth = 49 }));
using var allowed = PngDecoder.Decode(png, new ImageLimits { MaxPixels = 2500 });
ImageAssert.AreEqual(image, allowed, "al limite");
}
[TestMethod]
public void APooledDecodeGivesTheSamePixels()
{
var reference = ReferenceImages.Get("png-rgba-16");
using var plain = PngDecoder.Decode(reference.ReadInput());
var pooled = PngDecoder.Decode(reference.ReadInput(), pooled: true);
Assert.IsTrue(pooled.IsPooled);
ImageAssert.AreEqual(plain, pooled, reference.Name);
pooled.Dispose();
pooled.Dispose();
Assert.ThrowsExactly<ObjectDisposedException>(() => pooled.Pixels.Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
private static uint BitwiseCrc(ReadOnlySpan<byte> data)
{
var crc = 0xFFFFFFFFu;
foreach (var b in data)
{
crc ^= b;
for (var k = 0; k < 8; k++)
{
crc = (crc & 1) != 0 ? 0xEDB88320u ^ (crc >> 1) : crc >> 1;
}
}
return ~crc;
}
private static byte[] Inflate(byte[] zlib)
{
using var input = new MemoryStream(zlib);
using var stream = new ZLibStream(input, CompressionMode.Decompress);
using var output = new MemoryStream();
stream.CopyTo(output);
return output.ToArray();
}
}