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

+172
View File
@@ -0,0 +1,172 @@
using Febe.Core.Codecs.Images;
using static Febe.Tests.Imaging.TestImages;
namespace Febe.Tests.Imaging;
/// <summary>The in-house BMP decoder on files built by hand: variants the reference set lacks, and damage.</summary>
[TestClass]
public sealed class BmpDecoderTests
{
private const uint BiRgb = 0;
private const uint BiRle8 = 1;
private const uint BiRle4 = 2;
private const uint BiBitfields = 3;
private const uint BiJpeg = 4;
private const uint BiPng = 5;
private const uint BiAlphaBitfields = 6;
// BGRx palette entries: black, red, green, blue.
private static readonly byte[] Palette4 = [0, 0, 0, 0, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 0];
[TestMethod]
public void TwoBitsPerPixelBottomUp()
{
// 3×2, stride 4 bytes; the first row in the file is the bottom one. Top row 0 1 2, bottom row 3 2 1.
byte[] pixels = [0b11_10_01_00, 0, 0, 0, 0b00_01_10_00, 0, 0, 0];
using var image = BmpDecoder.Decode(Bmp(40, 3, 2, 2, BiRgb, Palette4, pixels));
Assert.AreEqual((0, 0, 0, 255), image.GetPixel(0, 0));
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(1, 0));
Assert.AreEqual((0, 255, 0, 255), image.GetPixel(2, 0));
Assert.AreEqual((0, 0, 255, 255), image.GetPixel(0, 1));
Assert.AreEqual((0, 255, 0, 255), image.GetPixel(1, 1));
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(2, 1));
}
[TestMethod]
public void ACoreHeaderHasThreeBytePaletteEntries()
{
byte[] palette = [10, 20, 30, 40, 50, 60];
byte[] pixels = [0b0100_0000, 0, 0, 0];
using var image = BmpDecoder.Decode(Bmp(12, 3, 1, 1, BiRgb, palette, pixels));
Assert.AreEqual((30, 20, 10, 255), image.GetPixel(0, 0));
Assert.AreEqual((60, 50, 40, 255), image.GetPixel(1, 0));
Assert.AreEqual((30, 20, 10, 255), image.GetPixel(2, 0));
}
[TestMethod]
public void SixteenBitsWithFourMasksAfterAnInformationHeader()
{
// ARGB 4444: a = 8 → 136, r = 15 → 255, g = 0, b = 15 → 255.
byte[] masks = [0x00, 0x0F, 0, 0, 0xF0, 0x00, 0, 0, 0x0F, 0x00, 0, 0, 0x00, 0xF0, 0, 0];
byte[] pixels = [0x0F, 0x8F, 0x00, 0x00];
using var image = BmpDecoder.Decode(Bmp(40, 1, 1, 16, BiAlphaBitfields, masks, pixels), out var info);
Assert.IsTrue(info.HasAlpha);
Assert.AreEqual((255, 0, 255, 136), image.GetPixel(0, 0));
}
[TestMethod]
public void ThirtyTwoBitsWithMasksInAnyOrder()
{
// V4 header with masks for R G B A in memory order: bytes are R, G, B, A.
byte[] pixels = [1, 2, 3, 4, 250, 251, 252, 253];
var bmp = Bmp(108, 2, -1, 32, BiBitfields, [], pixels, masks: [0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000]);
using var image = BmpDecoder.Decode(bmp);
Assert.AreEqual((1, 2, 3, 4), image.GetPixel(0, 0));
Assert.AreEqual((250, 251, 252, 253), image.GetPixel(1, 0));
// BI_RGB ignores the alpha byte, even with a V4 header.
using var opaque = BmpDecoder.Decode(Bmp(108, 2, -1, 32, BiRgb, [], pixels));
Assert.AreEqual((3, 2, 1, 255), opaque.GetPixel(0, 0));
}
[TestMethod]
public void RleDeltasAndLineEndsLeaveTheSkippedPixelsTransparent()
{
byte[] palette = [0, 0, 255, 0, 255, 0, 0, 0]; // BGRx: red, blue
byte[] data = [2, 1, 0, 0, 0, 2, 1, 1, 1, 0, 0, 1];
using var image = BmpDecoder.Decode(Bmp(40, 4, 3, 8, BiRle8, palette, data, colorsUsed: 2));
Assert.AreEqual((0, 0, 255, 255), image.GetPixel(0, 2), "riga in basso, indice 1");
Assert.AreEqual((0, 0, 255, 255), image.GetPixel(1, 2));
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(2, 2));
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(0, 1), "riga saltata dallo spostamento");
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(1, 0), "dopo lo spostamento (1, 1), indice 0");
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(0, 0));
}
[TestMethod]
public void AnRle4AbsoluteRunOfOddLengthIsPaddedToAWord()
{
var palette = Enumerable.Range(0, 16).SelectMany(i => new byte[] { 0, 0, (byte)(i * 16), 0 }).ToArray();
byte[] data = [0, 5, 0x12, 0x34, 0x50, 0, 2, 0x67, 0, 1];
using var image = BmpDecoder.Decode(Bmp(40, 7, 1, 4, BiRle4, palette, data));
byte[] expected = [1, 2, 3, 4, 5, 6, 7];
for (var x = 0; x < expected.Length; x++)
{
Assert.AreEqual((byte)(expected[x] * 16), image.GetPixel(x, 0).R, $"pixel {x}");
}
}
[TestMethod]
public void AnIndexBeyondAShortPaletteIsOpaqueBlack()
{
byte[] palette = [1, 2, 3, 0, 4, 5, 6, 0];
byte[] pixels = [1, 5, 0, 0];
using var image = BmpDecoder.Decode(Bmp(40, 2, 1, 8, BiRgb, palette, pixels, colorsUsed: 2));
Assert.AreEqual((6, 5, 4, 255), image.GetPixel(0, 0));
Assert.AreEqual((0, 0, 0, 255), image.GetPixel(1, 0));
}
[TestMethod]
public void AnEmbeddedPngIsDecodedByThePngDecoder()
{
using var source = TestImages.Random(5, 3, 8);
var png = PngEncoder.Encode(source);
var bmp = Bmp(40, 5, 3, 0, BiPng, [], png);
using var image = BmpDecoder.Decode(bmp);
ImageAssert.AreEqual(source, image, "PNG nel BMP");
Assert.AreEqual(ImageFormat.Bmp, BmpDecoder.Identify(bmp).Format);
}
[TestMethod]
public void DamagedOrUnsupportedFilesThrow()
{
byte[] row = [0, 0, 0, 0];
var cases = new Dictionary<string, (byte[] Bytes, bool Unsupported)>
{
["vuoto"] = ([], false),
["non BMP"] = ("BA\0\0"u8.ToArray(), false),
["solo l'intestazione del file"] = (Bmp(40, 1, 1, 24, BiRgb, [], row)[..16], false),
["intestazione di 20 byte"] = (PatchHeaderSize(Bmp(40, 1, 1, 24, BiRgb, [], row), 20), true),
["larghezza zero"] = (Bmp(40, 0, 1, 24, BiRgb, [], row), false),
["larghezza negativa"] = (Bmp(40, -3, 1, 24, BiRgb, [], row), false),
["7 bit per pixel"] = (Bmp(40, 1, 1, 7, BiRgb, [], row), false),
["64 bit per pixel"] = (Bmp(40, 1, 1, 64, BiRgb, [], new byte[8]), true),
["JPEG dentro"] = (Bmp(40, 1, 1, 0, BiJpeg, [], [0xFF, 0xD8, 0xFF]), true),
["compressione 9"] = (Bmp(40, 1, 1, 24, 9, [], row), true),
["RLE8 a 4 bit"] = (Bmp(40, 1, 1, 4, BiRle8, Palette4, [0, 1]), false),
["RLE dall'alto"] = (Bmp(40, 1, -1, 8, BiRle8, Palette4, [0, 1]), false),
["RLE tagliato"] = (Bmp(40, 4, 2, 8, BiRle8, Palette4, [2, 1, 0]), false),
["tratto assoluto tagliato"] = (Bmp(40, 4, 1, 8, BiRle8, Palette4, [0, 4, 1, 2]), false),
["pixel tagliati"] = (Bmp(40, 4, 4, 24, BiRgb, [], new byte[40]), false),
["maschere non contigue"] = (Bmp(108, 1, 1, 32, BiBitfields, [], row, masks: [0x00FF00FF, 0x0000FF00, 0, 0]), false),
["maschere oltre i 16 bit"] = (Bmp(108, 1, 1, 16, BiBitfields, [], row, masks: [0x00FF0000, 0x0000FF00, 0xFF, 0]), false),
["maschere mancanti"] = (Bmp(40, 1, 1, 32, BiBitfields, [], [])[..54], false),
};
foreach (var (name, (bytes, unsupported)) in cases)
{
if (unsupported)
{
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => BmpDecoder.Decode(bytes), name);
}
else
{
Assert.Throws<ImageDecodeException>(() => BmpDecoder.Decode(bytes), name);
}
}
}
[TestMethod]
public void AnImageBeyondTheLimitsIsRefusedButStillIdentified()
{
var bmp = Bmp(40, 100_000, 1, 24, BiRgb, [], new byte[4]);
Assert.ThrowsExactly<ImageLimitException>(() => BmpDecoder.Decode(bmp));
Assert.AreEqual(100_000, BmpDecoder.Identify(bmp).Width);
}
private static byte[] PatchHeaderSize(byte[] bmp, uint size)
{
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(bmp.AsSpan(14), size);
return bmp;
}
}
+192
View File
@@ -0,0 +1,192 @@
using Febe.Core.Codecs.Images;
using static Febe.Tests.Imaging.TestImages;
namespace Febe.Tests.Imaging;
/// <summary>The in-house GIF decoder on files built from GIF89a: palettes, transparency, clipping, damage.</summary>
[TestClass]
public sealed class GifDecoderTests
{
// Four colours: black, red, green, blue.
private static readonly byte[] Palette4 = [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255];
[TestMethod]
public void AFrameOnTheWholeCanvasTakesItsColoursFromTheGlobalPalette()
{
byte[] indices = [0, 1, 2, 3, 3, 2, 1, 0];
var gif = Gif(4, 2, Palette4, GifFrame(0, 0, 4, 2, indices, 2));
using var image = GifDecoder.Decode(gif, out var info);
Assert.AreEqual((ImageFormat.Gif, 4, 2, 1), (info.Format, info.Width, info.Height, info.FrameCount));
Assert.AreEqual((0, 0, 0, 255), image.GetPixel(0, 0));
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(1, 0));
Assert.AreEqual((0, 0, 255, 255), image.GetPixel(3, 0));
Assert.AreEqual((0, 255, 0, 255), image.GetPixel(1, 1));
}
[TestMethod]
public void TheTransparentIndexAndTheAreaOutsideTheFrameAreTransparent()
{
byte[] indices = [1, 2, 2, 1];
var gif = Gif(4, 3, Palette4, GifControl(2), GifFrame(1, 1, 2, 2, indices, 2));
using var image = GifDecoder.Decode(gif);
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(0, 0), "fuori dal fotogramma");
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(1, 1));
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(2, 1), "indice trasparente");
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(2, 2));
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(3, 2));
}
[TestMethod]
public void TheTransparencyOfALaterControlBlockDoesNotChangeTheFirstFrame()
{
byte[] indices = [1, 2];
var gif = Gif(2, 1, Palette4, GifFrame(0, 0, 2, 1, indices, 2), GifControl(1), GifFrame(0, 0, 2, 1, indices, 2));
using var image = GifDecoder.Decode(gif, out var info);
Assert.AreEqual(2, info.FrameCount);
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(0, 0));
}
[TestMethod]
public void ALocalPaletteWinsOverTheGlobalOne()
{
byte[] local = [9, 9, 9, 7, 7, 7];
var gif = Gif(2, 1, Palette4, GifFrame(0, 0, 2, 1, [0, 1], 2, local));
using var image = GifDecoder.Decode(gif);
Assert.AreEqual((9, 9, 9, 255), image.GetPixel(0, 0));
Assert.AreEqual((7, 7, 7, 255), image.GetPixel(1, 0));
}
[TestMethod]
public void AFrameLargerThanTheCanvasIsClippedAndAnEmptyCanvasTakesTheFrameSize()
{
var indices = Enumerable.Range(0, 12).Select(i => (byte)(i % 4)).ToArray();
using (var clipped = GifDecoder.Decode(Gif(3, 2, Palette4, GifFrame(1, 0, 4, 3, indices, 2))))
{
Assert.AreEqual((3, 2), (clipped.Width, clipped.Height));
Assert.AreEqual((0, 0, 0, 0), clipped.GetPixel(0, 0));
Assert.AreEqual((0, 0, 0, 255), clipped.GetPixel(1, 0));
Assert.AreEqual((255, 0, 0, 255), clipped.GetPixel(2, 0));
Assert.AreEqual((0, 0, 0, 255), clipped.GetPixel(1, 1), "riga 1 del fotogramma, colonna 0: indice 4 % 4");
}
using var sized = GifDecoder.Decode(Gif(0, 0, Palette4, GifFrame(2, 1, 4, 3, indices, 2)));
Assert.AreEqual((6, 4), (sized.Width, sized.Height));
Assert.AreEqual((0, 0, 255, 255), sized.GetPixel(5, 1));
}
[TestMethod]
public void InterlacedRowsGoWhereTheFourPassesPutThem()
{
for (var height = 1; height <= 40; height++)
{
var rows = Enumerable.Range(0, height).Select(r => GifDecoder.InterlacedRow(r, height)).ToList();
CollectionAssert.AreEquivalent(Enumerable.Range(0, height).ToList(), rows, $"altezza {height}");
}
CollectionAssert.AreEqual(new[] { 0, 8, 4, 2, 6, 1, 3, 5, 7, 9 }, Enumerable.Range(0, 10).Select(r => GifDecoder.InterlacedRow(r, 10)).ToArray());
// Row r of the file holds the colour of its own image row: decoding puts each one back in place.
const int height10 = 10;
var indices = new byte[2 * height10];
for (var r = 0; r < height10; r++)
{
indices[2 * r] = indices[(2 * r) + 1] = (byte)GifDecoder.InterlacedRow(r, height10);
}
var palette = Enumerable.Range(0, 16).SelectMany(i => new[] { (byte)(i * 10), (byte)0, (byte)0 }).ToArray();
using var image = GifDecoder.Decode(Gif(2, height10, palette, GifFrame(0, 0, 2, height10, indices, 4, interlaced: true)));
for (var y = 0; y < height10; y++)
{
Assert.AreEqual((byte)(y * 10), image.GetPixel(1, y).R, $"riga {y}");
}
}
[TestMethod]
public void LiteralCodesAtEveryInitialSizeDecode()
{
for (var minCodeSize = 2; minCodeSize <= 8; minCodeSize++)
{
var colours = 1 << minCodeSize;
var random = new Random(minCodeSize);
var indices = new byte[37 * 23];
for (var i = 0; i < indices.Length; i++)
{
indices[i] = (byte)random.Next(colours);
}
var output = new byte[indices.Length];
var data = GifLiteralLzw(indices, minCodeSize);
Assert.AreEqual(indices.Length, GifDecoder.DecodeLzw(data, 0, minCodeSize, output), $"codici da {minCodeSize + 1} bit");
CollectionAssert.AreEqual(indices, output, $"codici da {minCodeSize + 1} bit");
}
}
[TestMethod]
public void DataThatStopsEarlyLeavesTheRestTransparent()
{
var indices = Enumerable.Repeat((byte)1, 16).ToArray();
var full = Gif(4, 4, Palette4, GifFrame(0, 0, 4, 4, indices, 2));
// Cut inside the LZW data, before the end code: the first pixels are there, the others are not.
var cut = full[..(full.Length - 6)];
using var image = GifDecoder.Decode(cut);
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(0, 0));
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(3, 3));
// Every shorter file either fails cleanly or gives an image of the canvas size.
for (var length = 0; length < full.Length; length++)
{
try
{
using var partial = GifDecoder.Decode(full[..length]);
Assert.AreEqual((4, 4), (partial.Width, partial.Height), $"tagliato a {length}");
}
catch (ImageDecodeException)
{
}
}
}
[TestMethod]
public void CommentsBeforeTheFirstFrameAreMetadataAndOtherExtensionsAreSkipped()
{
byte[] comment = [0x21, 0xFE, 5, (byte)'C', (byte)'i', (byte)'a', (byte)'o', (byte)' ', 3, (byte)'G', (byte)'I', (byte)'F', 0];
byte[] netscape = [0x21, 0xFF, 11, .. "NETSCAPE2.0"u8, 3, 1, 0, 0, 0];
var gif = Gif(1, 1, Palette4, comment, netscape, GifFrame(0, 0, 1, 1, [3], 2));
var info = GifDecoder.Identify(gif);
Assert.AreEqual("Ciao GIF", info.Metadata.Texts.Single().Text);
using var image = GifDecoder.Decode(gif);
Assert.AreEqual((0, 0, 255, 255), image.GetPixel(0, 0));
}
[TestMethod]
public void DamagedFilesThrowAnImageDecodeException()
{
var frame = GifFrame(0, 0, 1, 1, [1], 2);
var badCodeSize = frame.ToArray();
badCodeSize[10] = 12;
var cases = new Dictionary<string, byte[]>
{
["vuoto"] = [],
["non GIF"] = "GIF90a"u8.ToArray(),
["senza schermo logico"] = "GIF89a\x01\0"u8.ToArray(),
["senza fotogrammi"] = Gif(1, 1, Palette4),
["senza tavolozza"] = Gif(1, 1, null, frame),
["codici LZW da 13 bit"] = Gif(1, 1, Palette4, badCodeSize),
["tavolozza globale tagliata"] = Gif(1, 1, Palette4)[..20],
};
foreach (var (name, bytes) in cases)
{
Assert.Throws<ImageDecodeException>(() => GifDecoder.Decode(bytes), name);
}
}
[TestMethod]
public void ACanvasBeyondTheLimitsIsRefusedButStillIdentified()
{
var gif = Gif(60000, 60000, Palette4, GifFrame(0, 0, 1, 1, [1], 2));
Assert.ThrowsExactly<ImageLimitException>(() => GifDecoder.Decode(gif));
Assert.AreEqual((60000, 60000), (GifDecoder.Identify(gif).Width, GifDecoder.Identify(gif).Height));
}
}
+43
View File
@@ -0,0 +1,43 @@
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>Comparisons of decoded images that say where they differ.</summary>
internal static class ImageAssert
{
/// <summary>Same size and the same bytes in every pixel.</summary>
public static void AreEqual(RgbaImage expected, RgbaImage actual, string what)
{
Assert.AreEqual((expected.Width, expected.Height), (actual.Width, actual.Height), $"{what}: misura diversa.");
AreEqual(expected.Width, expected.Pixels, actual.Pixels, what);
}
/// <summary>The same RGBA bytes, for images of the given width.</summary>
public static void AreEqual(int width, ReadOnlySpan<byte> expected, ReadOnlySpan<byte> actual, string what)
{
Assert.AreEqual(expected.Length, actual.Length, $"{what}: lunghezza diversa.");
var first = -1;
var different = 0;
for (var i = 0; i < expected.Length; i += 4)
{
if (!expected.Slice(i, 4).SequenceEqual(actual.Slice(i, 4)))
{
different++;
if (first < 0)
{
first = i;
}
}
}
if (different > 0)
{
var pixel = first / 4;
Assert.Fail(
$"{what}: {different} pixel diversi; il primo in ({pixel % width}, {pixel / width}): atteso "
+ $"{Format(expected.Slice(first, 4))}, letto {Format(actual.Slice(first, 4))}.");
}
}
private static string Format(ReadOnlySpan<byte> rgba) => $"({rgba[0]}, {rgba[1]}, {rgba[2]}, {rgba[3]})";
}
+127
View File
@@ -0,0 +1,127 @@
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// Damaged files from the reference set, changed at random with fixed seeds: a decoder either reads them or throws
/// <see cref="ImageDecodeException"/>, never anything else (no index out of range, no overflow, no huge allocation).
/// </summary>
[TestClass]
public sealed class ImageFuzzTests
{
private const int MutationsPerFile = 120;
private static readonly ImageLimits Small = new() { MaxPixels = 1_000_000, MaxWorkingBytes = 16 * 1024 * 1024, MaxMetadataBytes = 64 * 1024 };
public static IEnumerable<object[]> Formats =>
[
[ReferenceFormat.Png],
[ReferenceFormat.Gif],
[ReferenceFormat.Bmp],
];
[TestMethod]
[DynamicData(nameof(Formats))]
public void ChangedBytesNeverBreakTheDecoder(ReferenceFormat format)
{
var seed = 1000 + (int)format;
foreach (var reference in ReferenceImages.Of(format))
{
var original = reference.ReadInput();
var random = new Random(seed++);
for (var i = 0; i < MutationsPerFile; i++)
{
var mutated = Mutate(original, random);
if (format == ReferenceFormat.Png && random.Next(3) > 0)
{
// Most changes to a PNG only meet a wrong CRC: fixing it lets them reach the pixels.
TestImages.FixPngCrcs(mutated);
}
TryDecode(mutated, $"{reference.Name}, modifica {i}");
}
}
}
[TestMethod]
public void ChangedBytesNeverBreakTheFacade()
{
var random = new Random(77);
foreach (var reference in ReferenceImages.All)
{
var mutated = Mutate(reference.ReadInput(), random);
try
{
using var image = ImageDecoder.Decode(mutated, Small);
ImageDecoder.Identify(mutated, Small);
}
catch (ImageDecodeException)
{
}
}
}
private static void TryDecode(byte[] bytes, string what)
{
try
{
using var image = ImageDecoder.Decode(bytes, Small);
Assert.IsGreaterThan(0, image.Width, what);
}
catch (ImageDecodeException)
{
}
catch (Exception ex)
{
Assert.Fail($"{what}: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
}
try
{
ImageDecoder.Identify(bytes, Small);
}
catch (ImageDecodeException)
{
}
catch (Exception ex)
{
Assert.Fail($"{what} (Identify): {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
}
}
private static byte[] Mutate(byte[] original, Random random)
{
var bytes = original.ToArray();
switch (random.Next(4))
{
case 0:
// A few random bytes anywhere after the signature.
for (var k = random.Next(1, 9); k > 0; k--)
{
bytes[random.Next(Math.Min(8, bytes.Length - 1), bytes.Length)] = (byte)random.Next(256);
}
return bytes;
case 1:
// A byte of the headers set to an extreme.
bytes[random.Next(Math.Min(8, bytes.Length - 1), Math.Min(bytes.Length, 80))] = random.Next(2) == 0 ? (byte)0 : (byte)0xFF;
return bytes;
case 2:
// Cut short.
return bytes[..random.Next(1, bytes.Length)];
default:
// A run of bytes flipped.
var start = random.Next(8, bytes.Length);
var length = Math.Min(bytes.Length - start, random.Next(1, 64));
for (var k = 0; k < length; k++)
{
bytes[start + k] ^= 0x5A;
}
return bytes;
}
}
}
@@ -0,0 +1,95 @@
using System.Text;
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>The common pieces of the in-house image codecs: format recognition, the RGBA image, the limits.</summary>
[TestClass]
public sealed class ImagingBaseTests
{
[TestMethod]
public void FormatsAreRecognisedFromTheirFirstBytes()
{
var bmp = new byte[18];
"BM"u8.CopyTo(bmp);
bmp[14] = 40;
var cases = new (byte[] Bytes, ImageFormat Format)[]
{
([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0], ImageFormat.Png),
([0xFF, 0xD8, 0xFF, 0xE0], ImageFormat.Jpeg),
("GIF89a"u8.ToArray(), ImageFormat.Gif),
("GIF87a"u8.ToArray(), ImageFormat.Gif),
(bmp, ImageFormat.Bmp),
("RIFF\0\0\0\0WEBPVP8 "u8.ToArray(), ImageFormat.WebP),
("II*\0"u8.ToArray(), ImageFormat.Tiff),
("MM\0*"u8.ToArray(), ImageFormat.Tiff),
("\0\0\0\u0018ftypheic"u8.ToArray(), ImageFormat.Heif),
("\0\0\0\u0018ftypmif1"u8.ToArray(), ImageFormat.Heif),
("\0\0\0\u0018ftypavif"u8.ToArray(), ImageFormat.Avif),
("\0\0\0\u0018ftypisom"u8.ToArray(), ImageFormat.Unknown),
("RIFF\0\0\0\0AVI "u8.ToArray(), ImageFormat.Unknown),
("GIF89"u8.ToArray(), ImageFormat.Unknown),
("BM"u8.ToArray(), ImageFormat.Unknown),
([0x89, 0x50, 0x4E, 0x47], ImageFormat.Unknown),
([], ImageFormat.Unknown),
(Encoding.ASCII.GetBytes("<html>"), ImageFormat.Unknown),
};
foreach (var (bytes, format) in cases)
{
Assert.AreEqual(format, ImageFormatSniffer.Detect(bytes), Convert.ToHexString(bytes));
}
// A BMP whose information header has a size no version has is not taken for one.
bmp[14] = 41;
Assert.AreEqual(ImageFormat.Unknown, ImageFormatSniffer.Detect(bmp));
}
[TestMethod]
public void AnImageHasRowsOfFourBytesPerPixel()
{
using var image = new RgbaImage(3, 2);
Assert.AreEqual((12, 24), (image.Stride, image.Length));
Assert.IsTrue(image.Pixels.ToArray().All(b => b == 0));
Assert.IsFalse(image.IsOpaque());
image.GetRow(1)[4..8].Fill(200);
Assert.AreEqual((200, 200, 200, 200), image.GetPixel(1, 1));
Assert.AreEqual(200, image.ToArray()[16]);
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => image.GetRow(2).Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => image.GetPixel(3, 0));
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => new RgbaImage(0, 1));
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => new RgbaImage(50_000, 50_000));
Assert.ThrowsExactly<ArgumentException>(() => new RgbaImage(2, 2, new byte[15]));
}
[TestMethod]
public void ARentedImageStartsClearAndGoesBackToThePool()
{
for (var round = 0; round < 3; round++)
{
var image = RgbaImage.Rent(33, 17);
Assert.IsTrue(image.IsPooled);
Assert.IsTrue(image.Pixels.ToArray().All(b => b == 0), $"giro {round}: un array del pool arriva sporco");
image.Pixels.Fill(0xAB);
image.Dispose();
Assert.ThrowsExactly<ObjectDisposedException>(() => image.GetRow(0).Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
// Disposing an image that owns its array changes nothing.
var owned = new RgbaImage(1, 1);
owned.Dispose();
Assert.AreEqual(4, owned.Pixels.Length);
}
[TestMethod]
public void TheFacadeSaysWhichFormatsItCannotReadYet()
{
var jpeg = ReferenceImages.Of(ReferenceFormat.Jpeg).First().ReadInput();
var error = Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Decode(jpeg));
Assert.Contains("JPEG", error.Message);
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Identify(Encoding.ASCII.GetBytes("testo qualsiasi")));
Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.Png) && ImageDecoder.CanDecode(ImageFormat.Gif) && ImageDecoder.CanDecode(ImageFormat.Bmp));
Assert.IsFalse(ImageDecoder.CanDecode(ImageFormat.Jpeg) || ImageDecoder.CanDecode(ImageFormat.WebP) || ImageDecoder.CanDecode(ImageFormat.Unknown));
}
}
+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();
}
}
@@ -0,0 +1,148 @@
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;
}
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;
}
}
@@ -6,8 +6,8 @@ namespace Febe.Tests.Imaging;
/// <summary>
/// Integrity of the reference set in Imaging/Riferimenti: every listed file is there and nothing else, each input starts
/// with the magic of its format and has the listed size, each expected image is a well-formed straight RGBA8 PNG of the
/// listed size. The pixels are not read here: Febe's own PNG decoder (step 2 of track C1) will read them, without
/// SkiaSharp.
/// listed size. The pixels are not read here: <see cref="ReferenceDecodeTests"/> reads them with Febe's own PNG decoder
/// (step 2 of track C1), without SkiaSharp.
/// </summary>
[TestClass]
public sealed class ReferenceSetTests
@@ -24,8 +24,8 @@ il nostro codice, non si aggiunge qui.
confrontati, uguali, con il disegno con matrice di SkiaSharp (quello che faceva `ImageDecoding`).
- **L'immagine attesa** non è scritta dal codificatore di SkiaSharp ma da uno scritto a mano nel programma: PNG RGBA a
8 bit (tipo di colore 6), senza interlacciamento, ogni riga con il filtro 0, un solo `IDAT` (zlib della BCL), nessun
altro blocco oltre a `IHDR`, `IDAT`, `IEND`. Così il lettore PNG di casa (tappa C1, passo 2) la legge senza SkiaSharp;
fino ad allora la prova d'integrità ne controlla solo la struttura.
altro blocco oltre a `IHDR`, `IDAT`, `IEND`. Così il lettore PNG di casa (tappa C1, passo 2) la legge senza SkiaSharp,
e un lettore minimo nelle prove, che conosce solo questa forma, controlla che legga giusto.
## I casi
@@ -89,5 +89,9 @@ lettore ricava prima della trasformata inversa, poi i pixel di un'immagine sempl
- `Imaging/ReferenceSetTests.cs`: integrità dell'insieme. Ogni file elencato c'è e non c'è altro; ogni ingresso
comincia con la firma del suo formato e ha la misura elencata (ruotata per l'orientamento EXIF 5–8); ogni immagine
attesa è un PNG RGBA a 8 bit ben formato (CRC di ogni blocco) della misura elencata; l'insieme resta piccolo.
- `Imaging/ReferenceDecodeTests.cs` (dalla tappa C1, passo 2): ogni immagine attesa si legge uguale con il lettore PNG
di casa e con un lettore minimo indipendente; i lettori PNG, GIF e BMP di casa danno, per ogni caso del loro formato,
esattamente i pixel dell'immagine attesa; la facciata `ImageDecoder` sceglie il lettore dai primi byte e per JPEG e
WebP dice che non li legge ancora.
- `Febe.Tests.csproj` copia la cartella nell'uscita delle prove; `.gitattributes` segna le estensioni delle immagini
come binarie e tiene `elenco.txt` con le righe Unix.
+301
View File
@@ -0,0 +1,301 @@
using System.Buffers.Binary;
using System.IO.Compression;
using System.Text;
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// Small images and files built by the tests: random RGBA images from a fixed seed, and PNG, GIF and BMP files written
/// byte by byte from the specifications, to reach the cases the reference set does not have (damaged files above all).
/// </summary>
internal static class TestImages
{
/// <summary>An image of random pixels; <paramref name="opaque"/> forces alpha 255.</summary>
public static RgbaImage Random(int width, int height, int seed, bool opaque = false)
{
var random = new Random(seed);
var pixels = new byte[width * height * 4];
random.NextBytes(pixels);
if (opaque)
{
for (var i = 3; i < pixels.Length; i += 4)
{
pixels[i] = 255;
}
}
return new RgbaImage(width, height, pixels);
}
/// <summary>A smooth image (gradients and a little noise), the kind adaptive filtering is for.</summary>
public static RgbaImage Gradient(int width, int height, int seed)
{
var random = new Random(seed);
var image = new RgbaImage(width, height);
for (var y = 0; y < height; y++)
{
var row = image.GetRow(y);
for (var x = 0; x < width; x++)
{
row[x * 4] = (byte)(x * 255 / Math.Max(1, width - 1));
row[(x * 4) + 1] = (byte)(y * 255 / Math.Max(1, height - 1));
row[(x * 4) + 2] = (byte)((x + y + random.Next(3)) & 0xFF);
row[(x * 4) + 3] = (byte)(255 - (x & 0x3F));
}
}
return image;
}
/// <summary>The chunks of a PNG: type and payload, in order (the CRC is checked).</summary>
public static List<(string Type, byte[] Payload)> PngChunks(byte[] png)
{
var chunks = new List<(string, byte[])>();
var pos = 8;
while (pos < png.Length)
{
var length = (int)BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos));
var type = Encoding.ASCII.GetString(png, pos + 4, 4);
Assert.AreEqual(Crc32.Compute(png.AsSpan(pos + 4, length + 4)), BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos + 8 + length)), $"CRC di {type}");
chunks.Add((type, png.AsSpan(pos + 8, length).ToArray()));
pos += length + 12;
}
return chunks;
}
/// <summary>Writes a PNG from its chunks (signature and CRCs added).</summary>
public static byte[] Png(params (string Type, byte[] Payload)[] chunks)
{
using var output = new MemoryStream();
output.Write([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
foreach (var (type, payload) in chunks)
{
output.Write(Chunk(type, payload));
}
return output.ToArray();
}
/// <summary>One chunk: length, type, payload, CRC.</summary>
public static byte[] Chunk(string type, byte[] payload)
{
var chunk = new byte[payload.Length + 12];
BinaryPrimitives.WriteUInt32BigEndian(chunk, (uint)payload.Length);
Encoding.ASCII.GetBytes(type, chunk.AsSpan(4));
payload.CopyTo(chunk, 8);
BinaryPrimitives.WriteUInt32BigEndian(chunk.AsSpan(8 + payload.Length), Crc32.Compute(chunk.AsSpan(4, payload.Length + 4)));
return chunk;
}
/// <summary>An IHDR payload.</summary>
public static byte[] Ihdr(int width, int height, int depth, int colorType, int interlace = 0)
{
var payload = new byte[13];
BinaryPrimitives.WriteUInt32BigEndian(payload, (uint)width);
BinaryPrimitives.WriteUInt32BigEndian(payload.AsSpan(4), (uint)height);
payload[8] = (byte)depth;
payload[9] = (byte)colorType;
payload[12] = (byte)interlace;
return payload;
}
/// <summary>The zlib stream of <paramref name="data"/>.</summary>
public static byte[] Zlib(byte[] data)
{
using var output = new MemoryStream();
using (var zlib = new ZLibStream(output, CompressionLevel.Optimal, leaveOpen: true))
{
zlib.Write(data);
}
return output.ToArray();
}
/// <summary>Latin-1 bytes of a keyword or text.</summary>
public static byte[] Latin1(string text) => Encoding.Latin1.GetBytes(text);
/// <summary>Concatenation of byte arrays.</summary>
public static byte[] Join(params byte[][] parts) => parts.SelectMany(p => p).ToArray();
/// <summary>Recomputes the CRC of every chunk of a PNG whose bytes were changed (stops at the first broken length).</summary>
public static void FixPngCrcs(byte[] png)
{
var pos = 8;
while (pos + 12 <= png.Length)
{
var length = BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos));
if (length > png.Length - pos - 12)
{
return;
}
BinaryPrimitives.WriteUInt32BigEndian(png.AsSpan(pos + 8 + (int)length), Crc32.Compute(png.AsSpan(pos + 4, (int)length + 4)));
pos += (int)length + 12;
}
}
/// <summary>
/// GIF LZW data sub-blocks for <paramref name="indices"/> that use only literal codes: a clear code every few
/// literals keeps the code size at <paramref name="minCodeSize"/> + 1. Ends with the end code and the terminator.
/// </summary>
public static byte[] GifLiteralLzw(ReadOnlySpan<byte> indices, int minCodeSize)
{
var clear = 1 << minCodeSize;
var codeSize = minCodeSize + 1;
var perGroup = Math.Max(1, clear - 2);
var bits = new List<byte>();
ulong accumulator = 0;
var count = 0;
void Emit(int code)
{
accumulator |= (ulong)code << count;
count += codeSize;
while (count >= 8)
{
bits.Add((byte)accumulator);
accumulator >>= 8;
count -= 8;
}
}
for (var i = 0; i < indices.Length; i++)
{
if (i % perGroup == 0)
{
Emit(clear);
}
Emit(indices[i]);
}
Emit(clear + 1);
if (count > 0)
{
bits.Add((byte)accumulator);
}
var output = new List<byte>();
for (var i = 0; i < bits.Count; i += 255)
{
var n = Math.Min(255, bits.Count - i);
output.Add((byte)n);
output.AddRange(bits.GetRange(i, n));
}
output.Add(0);
return output.ToArray();
}
/// <summary>A GIF89a file: header, logical screen, optional global palette, then the given blocks and the trailer.</summary>
public static byte[] Gif(int width, int height, byte[]? globalPalette, params byte[][] blocks)
{
var output = new List<byte>();
output.AddRange("GIF89a"u8.ToArray());
output.AddRange(BitConverter.GetBytes((ushort)width));
output.AddRange(BitConverter.GetBytes((ushort)height));
output.Add(globalPalette is null ? (byte)0 : (byte)(0x80 | PaletteSizeBits(globalPalette)));
output.Add(0);
output.Add(0);
if (globalPalette is not null)
{
output.AddRange(globalPalette);
}
foreach (var block in blocks)
{
output.AddRange(block);
}
output.Add(0x3B);
return output.ToArray();
}
/// <summary>A graphic control extension with a transparent index (or none with -1).</summary>
public static byte[] GifControl(int transparent) =>
[0x21, 0xF9, 4, transparent >= 0 ? (byte)1 : (byte)0, 0, 0, transparent >= 0 ? (byte)transparent : (byte)0, 0];
/// <summary>An image block: descriptor, optional local palette, LZW data of <paramref name="indices"/>.</summary>
public static byte[] GifFrame(int left, int top, int width, int height, ReadOnlySpan<byte> indices, int minCodeSize, byte[]? localPalette = null, bool interlaced = false)
{
var output = new List<byte> { 0x2C };
output.AddRange(BitConverter.GetBytes((ushort)left));
output.AddRange(BitConverter.GetBytes((ushort)top));
output.AddRange(BitConverter.GetBytes((ushort)width));
output.AddRange(BitConverter.GetBytes((ushort)height));
var packed = interlaced ? 0x40 : 0;
if (localPalette is not null)
{
packed |= 0x80 | PaletteSizeBits(localPalette);
}
output.Add((byte)packed);
if (localPalette is not null)
{
output.AddRange(localPalette);
}
output.Add((byte)minCodeSize);
output.AddRange(GifLiteralLzw(indices, minCodeSize));
return output.ToArray();
}
private static int PaletteSizeBits(byte[] palette)
{
var entries = palette.Length / 3;
var bits = 0;
while ((2 << bits) < entries)
{
bits++;
}
Assert.AreEqual(2 << bits, entries, "la tavolozza di un GIF ha 2, 4, 8... voci");
return bits;
}
/// <summary>
/// A BMP with an information header of <paramref name="headerSize"/> bytes (40, 108, 124...; 12 for a core header),
/// then <paramref name="afterHeader"/> (masks, palette) and the pixel data.
/// </summary>
public static byte[] Bmp(int headerSize, int width, int height, int bitsPerPixel, uint compression, byte[] afterHeader, byte[] pixels, uint colorsUsed = 0, uint[]? masks = null)
{
var info = new byte[headerSize];
BinaryPrimitives.WriteUInt32LittleEndian(info, (uint)headerSize);
if (headerSize == 12)
{
BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(4), (ushort)width);
BinaryPrimitives.WriteInt16LittleEndian(info.AsSpan(6), (short)height);
BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(8), 1);
BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(10), (ushort)bitsPerPixel);
}
else
{
BinaryPrimitives.WriteInt32LittleEndian(info.AsSpan(4), width);
BinaryPrimitives.WriteInt32LittleEndian(info.AsSpan(8), height);
BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(12), 1);
BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(14), (ushort)bitsPerPixel);
BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(16), compression);
BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(20), (uint)pixels.Length);
BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(32), colorsUsed);
if (masks is not null)
{
for (var i = 0; i < masks.Length; i++)
{
BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(40 + (i * 4)), masks[i]);
}
}
}
var offset = 14 + headerSize + afterHeader.Length;
var file = new byte[offset + pixels.Length];
file[0] = (byte)'B';
file[1] = (byte)'M';
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(2), (uint)file.Length);
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(10), (uint)offset);
info.CopyTo(file, 14);
afterHeader.CopyTo(file, 14 + headerSize);
pixels.CopyTo(file, offset);
return file;
}
}