diff --git a/docs/decisioni.md b/docs/decisioni.md
index 2bc90cb..bef0d74 100644
--- a/docs/decisioni.md
+++ b/docs/decisioni.md
@@ -421,3 +421,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-17 | `chiave.bin` si crea intero o non si crea: file `.part` nella stessa cartella, scritto fino al disco, poi rinominato senza sostituire (`OwnerOnlyFiles.CreateNew`) | Prima il file nasceva vuoto e poi si scriveva: con il disco pieno restava un `chiave.bin` corto, scambiato per la chiave di un altro processo, e da lì ogni avvio con «richieste» si fermava finché Alberto non lo cancellava a mano |
| 2026-11-17 | Con la raccolta «pagine» il registro scrive una riga «Raccolta «pagine»: tutte le ricette con il browser» all'avvio | §6.0 dice che il registro nomina la strada presa; prima la scriveva solo con «richieste» |
| 2026-11-18 | Insieme fisso di immagini di riferimento per i codec di casa in `tests/Febe.Tests/Imaging/Riferimenti` (57 casi, circa 2,2 MB, descritti in `LEGGIMI.md`): per ogni caso un file d'ingresso (PNG, GIF e BMP costruiti a mano dalle specifiche; PNG, JPEG base e WebP codificati da SkiaSharp; JPEG con un `APP1` EXIF di orientamento inserito a mano) e `.atteso.png`, la lettura di SkiaSharp 4.153.1 in RGBA a 8 bit non premoltiplicata, raddrizzata. Generato una volta sola, con il permesso di Alberto, da un programma usa e getta fuori dal repository; contenuto solo sintetico. Le immagini attese sono PNG RGBA a 8 bit senza interlacciamento, filtro 0, un solo `IDAT`, scritti a mano e non dal codificatore di SkiaSharp, così le legge il lettore PNG di casa (passo 2 di C1); fino ad allora `ReferenceSetTests` controlla solo la struttura (firme, misure, CRC dei blocchi, nessun file in più o in meno). JPEG progressivo, intervalli di ripristino e CMYK/Adobe non hanno riferimento: li proveranno codificatori di prova nostri dalla T.81 (allegati F e G) con controlli sui coefficienti. Estensioni delle immagini `binary` in `.gitattributes`, `elenco.txt` con `eol=lf` | SkiaSharp esce da Febe (C1): serve un termine di confronto prima di toglierlo, e dopo non si potrà più generarlo. Un riferimento che solo SkiaSharp sapesse leggere sarebbe inutile proprio quando serve |
+| 2026-11-18 | Base dei codec d'immagine di casa in `src/Febe.Core/Codecs/Images` (spazio dei nomi `Febe.Core.Codecs.Images`, accanto a `Codecs/Containers` del ramo `funzione/decoder-h264`): `RgbaImage` (RGBA a 8 bit non premoltiplicata, array suo o preso dal pool e reso con `Dispose`), `ImageLimits` (predefiniti 65535 pixel per lato, 100 milioni di pixel come `ImageDecoding.MaxDecodedPixels`, 512 MiB di memoria di lavoro, 16 MiB di metadati decompressi), `ImageDecodeException` con `ImageLimitException` e `ImageFormatNotSupportedException`, `ImageFormatSniffer`, la facciata `ImageDecoder`; lettore e scrittore PNG, lettori GIF e BMP dalle specifiche, CRC-32 e LZW scritti in casa, zlib di `System.IO.Compression`. Scelte di lettura: i campioni a 16 bit tengono il byte alto e le maschere BMP sotto gli 8 bit si scalano con arrotondamento (così i 37 riferimenti PNG, GIF e BMP coincidono byte per byte); nessuna gestione del colore (profilo ICC, gamma); un blocco PNG ausiliario con il CRC sbagliato si salta, uno critico ferma la lettura; un PNG senza `IEND` dopo dati completi si accetta, uno tagliato prima no; un GIF tagliato o con dati LZW rotti dà ciò che si è letto, il resto trasparente; del GIF solo il primo fotogramma, sulla tela trasparente senza il colore di sfondo, più il numero dei fotogrammi; nel BMP l'alfa viene solo da una maschera alfa di `BI_BITFIELDS`/`BI_ALPHABITFIELDS`, i pixel saltati da RLE restano trasparenti, `BI_PNG` passa al lettore PNG, `BI_JPEG` e 64 bit non si leggono. `Identify` legge misura, fotogrammi e metadati senza applicare i limiti di misura; `Decode` li applica prima di allocare. Lo scrittore PNG scrive RGB o RGBA a 8 bit (RGB in automatico se tutto è opaco), per ogni riga il filtro con la minima somma dei valori assoluti (specifica PNG §12.8), `IDAT` da 64 KiB e, a richiesta, `eXIf`, `iCCP` e l'XMP in un `iTXt` | C1: SkiaSharp esce da Febe e niente componenti esterni (decisione di Alberto del 18 novembre 2026). Lettori tolleranti dove lo sono i browser (GIF, metadati), severi dove un'immagine letta a metà passerebbe per buona (PNG, BMP); limiti controllati prima di ogni allocazione, perché pochi byte di un file possono chiedere gigabyte |
diff --git a/src/Febe.Core/Codecs/Images/BmpDecoder.cs b/src/Febe.Core/Codecs/Images/BmpDecoder.cs
new file mode 100644
index 0000000..d1be22b
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/BmpDecoder.cs
@@ -0,0 +1,497 @@
+using System.Buffers.Binary;
+using System.Numerics;
+
+namespace Febe.Core.Codecs.Images;
+
+///
+/// Reads Windows BMP files: core (OS/2 1.x), information and V2–V5 headers; 1, 2, 4, 8, 16, 24 and 32 bits per pixel;
+/// BI_RGB, BI_BITFIELDS, BI_ALPHABITFIELDS, BI_RLE8, BI_RLE4 and an embedded PNG (BI_PNG); rows from the bottom or
+/// from the top. Alpha comes only from an alpha mask of a BITFIELDS image (V3 headers and later); everything else is
+/// opaque. Pixels an RLE image skips stay (0, 0, 0, 0). Colour profiles and gamma are not applied.
+///
+public static class BmpDecoder
+{
+ private const int FileHeaderSize = 14;
+ 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;
+
+ /// Whether the bytes start like a BMP file.
+ public static bool IsBmp(ReadOnlySpan data) =>
+ data.Length >= 18 && data[0] == (byte)'B' && data[1] == (byte)'M' && ImageFormatSniffer.IsBmpHeaderSize(BinaryPrimitives.ReadUInt32LittleEndian(data[14..]));
+
+ /// Size of a BMP, without decoding the pixels.
+ public static ImageInfo Identify(ReadOnlyMemory data, ImageLimits? limits = null)
+ {
+ var header = ReadHeader(data.Span);
+ if (header.Compression == BiPng)
+ {
+ var png = PngDecoder.Identify(data[header.PixelOffset..], limits);
+ return png with { Format = ImageFormat.Bmp };
+ }
+
+ return new ImageInfo(ImageFormat.Bmp, header.Width, header.Height, 1, header.AlphaMask != 0, ImageMetadata.Empty);
+ }
+
+ /// Decodes a BMP to straight RGBA8, top row first.
+ /// The file is damaged, truncated or not a BMP.
+ /// A BMP variant Febe does not read (JPEG inside, OS/2 Huffman, 64 bits).
+ /// The image is larger than allow.
+ public static RgbaImage Decode(ReadOnlyMemory data, ImageLimits? limits = null, bool pooled = false)
+ {
+ limits ??= ImageLimits.Default;
+ var span = data.Span;
+ var header = ReadHeader(span);
+ if (header.Compression == BiPng)
+ {
+ return PngDecoder.Decode(data[header.PixelOffset..], limits, pooled);
+ }
+
+ var image = RgbaImage.Create(header.Width, header.Height, limits, pooled);
+ try
+ {
+ switch (header.Compression)
+ {
+ case BiRle8:
+ case BiRle4:
+ DecodeRle(span, header, image);
+ break;
+
+ default:
+ DecodeRows(span, header, image);
+ break;
+ }
+
+ return image;
+ }
+ catch
+ {
+ image.Dispose();
+ throw;
+ }
+ }
+
+ /// Decodes a BMP and returns what returns as well.
+ public static RgbaImage Decode(ReadOnlyMemory data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
+ {
+ var image = Decode(data, limits, pooled);
+ try
+ {
+ info = Identify(data, limits);
+ return image;
+ }
+ catch
+ {
+ image.Dispose();
+ throw;
+ }
+ }
+
+ private sealed class BmpHeader
+ {
+ public int Width;
+ public int Height;
+ public bool TopDown;
+ public int BitsPerPixel;
+ public uint Compression;
+ public int PixelOffset;
+ public uint RedMask;
+ public uint GreenMask;
+ public uint BlueMask;
+ public uint AlphaMask;
+
+ /// RGBA of each palette index (256 entries; those the file does not give are opaque black).
+ public uint[]? Palette;
+
+ public int Stride => (int)((((long)Width * BitsPerPixel) + 31) / 32 * 4);
+ }
+
+ private static BmpHeader ReadHeader(ReadOnlySpan data)
+ {
+ if (data.Length < 2 || data[0] != (byte)'B' || data[1] != (byte)'M')
+ {
+ throw new ImageDecodeException("Non è un file BMP.");
+ }
+
+ if (data.Length < FileHeaderSize + 4)
+ {
+ throw new ImageDecodeException("BMP troncato: manca l'intestazione.");
+ }
+
+ var infoSize = BinaryPrimitives.ReadUInt32LittleEndian(data[FileHeaderSize..]);
+ if (!ImageFormatSniffer.IsBmpHeaderSize(infoSize))
+ {
+ throw new ImageFormatNotSupportedException($"BMP con un'intestazione di {infoSize} byte, che Febe non conosce.");
+ }
+
+ if (data.Length < FileHeaderSize + infoSize)
+ {
+ throw new ImageDecodeException("BMP troncato: l'intestazione finisce dopo il file.");
+ }
+
+ var info = data.Slice(FileHeaderSize, (int)infoSize);
+ var header = new BmpHeader();
+ long width;
+ long height;
+ int planes;
+ var paletteEntrySize = 4;
+ uint colorsUsed = 0;
+ if (infoSize == 12)
+ {
+ width = BinaryPrimitives.ReadUInt16LittleEndian(info[4..]);
+ height = BinaryPrimitives.ReadInt16LittleEndian(info[6..]);
+ planes = BinaryPrimitives.ReadUInt16LittleEndian(info[8..]);
+ header.BitsPerPixel = BinaryPrimitives.ReadUInt16LittleEndian(info[10..]);
+ header.Compression = BiRgb;
+ paletteEntrySize = 3;
+ }
+ else
+ {
+ width = BinaryPrimitives.ReadInt32LittleEndian(info[4..]);
+ height = BinaryPrimitives.ReadInt32LittleEndian(info[8..]);
+ planes = BinaryPrimitives.ReadUInt16LittleEndian(info[12..]);
+ header.BitsPerPixel = BinaryPrimitives.ReadUInt16LittleEndian(info[14..]);
+ if (infoSize >= 20)
+ {
+ header.Compression = BinaryPrimitives.ReadUInt32LittleEndian(info[16..]);
+ }
+
+ if (infoSize >= 36)
+ {
+ colorsUsed = BinaryPrimitives.ReadUInt32LittleEndian(info[32..]);
+ }
+
+ if (infoSize is 16 or 64 && header.Compression is 3 or 4)
+ {
+ throw new ImageFormatNotSupportedException("BMP di OS/2 con compressione Huffman o RLE24, che Febe non legge.");
+ }
+ }
+
+ if (planes != 1 && planes != 0)
+ {
+ throw new ImageDecodeException($"BMP danneggiato: {planes} piani di colore.");
+ }
+
+ header.TopDown = height < 0;
+ height = Math.Abs(height);
+ if (width <= 0 || height == 0 || height > int.MaxValue)
+ {
+ throw new ImageDecodeException($"BMP danneggiato: misura non valida ({width}×{height}).");
+ }
+
+ header.Width = (int)width;
+ header.Height = (int)height;
+
+ switch (header.Compression)
+ {
+ case BiJpeg:
+ throw new ImageFormatNotSupportedException("BMP con un JPEG dentro, che Febe non legge.");
+ case BiRgb or BiBitfields or BiAlphaBitfields or BiRle8 or BiRle4 or BiPng:
+ break;
+ default:
+ throw new ImageFormatNotSupportedException($"BMP con la compressione {header.Compression}, che Febe non conosce.");
+ }
+
+ var bpp = header.BitsPerPixel;
+ var valid = header.Compression switch
+ {
+ BiRgb => bpp is 1 or 2 or 4 or 8 or 16 or 24 or 32,
+ BiBitfields or BiAlphaBitfields => bpp is 16 or 32,
+ BiRle8 => bpp == 8,
+ BiRle4 => bpp == 4,
+ _ => true,
+ };
+ if (!valid)
+ {
+ throw bpp == 64
+ ? new ImageFormatNotSupportedException("BMP a 64 bit per pixel, che Febe non legge.")
+ : new ImageDecodeException($"BMP danneggiato: {bpp} bit per pixel con la compressione {header.Compression}.");
+ }
+
+ if ((header.Compression is BiRle8 or BiRle4) && header.TopDown)
+ {
+ throw new ImageDecodeException("BMP danneggiato: un'immagine RLE non può essere dall'alto.");
+ }
+
+ var afterHeader = FileHeaderSize + (int)infoSize;
+ if (header.Compression is BiBitfields or BiAlphaBitfields)
+ {
+ if (infoSize >= 52)
+ {
+ header.RedMask = BinaryPrimitives.ReadUInt32LittleEndian(info[40..]);
+ header.GreenMask = BinaryPrimitives.ReadUInt32LittleEndian(info[44..]);
+ header.BlueMask = BinaryPrimitives.ReadUInt32LittleEndian(info[48..]);
+ header.AlphaMask = infoSize >= 56 ? BinaryPrimitives.ReadUInt32LittleEndian(info[52..]) : 0;
+ }
+ else
+ {
+ // An information header is followed by the three (or four) masks.
+ var maskCount = header.Compression == BiAlphaBitfields ? 4 : 3;
+ if (data.Length < afterHeader + (maskCount * 4))
+ {
+ throw new ImageDecodeException("BMP troncato: mancano le maschere dei colori.");
+ }
+
+ header.RedMask = BinaryPrimitives.ReadUInt32LittleEndian(data[afterHeader..]);
+ header.GreenMask = BinaryPrimitives.ReadUInt32LittleEndian(data[(afterHeader + 4)..]);
+ header.BlueMask = BinaryPrimitives.ReadUInt32LittleEndian(data[(afterHeader + 8)..]);
+ header.AlphaMask = maskCount == 4 ? BinaryPrimitives.ReadUInt32LittleEndian(data[(afterHeader + 12)..]) : 0;
+ afterHeader += maskCount * 4;
+ }
+
+ if (!IsContiguous(header.RedMask) || !IsContiguous(header.GreenMask) || !IsContiguous(header.BlueMask) || !IsContiguous(header.AlphaMask)
+ || (header.BitsPerPixel == 16 && ((header.RedMask | header.GreenMask | header.BlueMask | header.AlphaMask) >> 16) != 0))
+ {
+ throw new ImageDecodeException("BMP danneggiato: maschere dei colori non valide.");
+ }
+ }
+ else if (bpp == 16)
+ {
+ (header.RedMask, header.GreenMask, header.BlueMask) = (0x7C00, 0x03E0, 0x001F);
+ }
+ else if (bpp == 32)
+ {
+ (header.RedMask, header.GreenMask, header.BlueMask) = (0x00FF0000, 0x0000FF00, 0x000000FF);
+ }
+
+ var offset = BinaryPrimitives.ReadUInt32LittleEndian(data[10..]);
+ if (bpp <= 8 && header.Compression != BiPng)
+ {
+ var max = 1 << bpp;
+ var count = colorsUsed == 0 || colorsUsed > max ? max : (int)colorsUsed;
+ if (offset >= afterHeader)
+ {
+ // The pixels may start before the palette would end: the palette is what fits in between.
+ count = (int)Math.Min(count, (offset - afterHeader) / paletteEntrySize);
+ }
+
+ count = Math.Min(count, Math.Max(0, (data.Length - afterHeader) / paletteEntrySize));
+ var palette = new uint[256];
+ Array.Fill(palette, 0xFF000000u);
+ for (var i = 0; i < count; i++)
+ {
+ var p = afterHeader + (i * paletteEntrySize);
+ palette[i] = Rgba(data[p + 2], data[p + 1], data[p], 255);
+ }
+
+ header.Palette = palette;
+ if (offset < afterHeader)
+ {
+ offset = (uint)(afterHeader + (count * paletteEntrySize));
+ }
+ }
+ else if (offset < afterHeader)
+ {
+ offset = (uint)afterHeader;
+ }
+
+ if (offset >= data.Length)
+ {
+ throw new ImageDecodeException("BMP troncato: i pixel cominciano dopo la fine del file.");
+ }
+
+ header.PixelOffset = (int)offset;
+ return header;
+ }
+
+ private static bool IsContiguous(uint mask) => mask == 0 || (((mask >> BitOperations.TrailingZeroCount(mask)) + 1) & (mask >> BitOperations.TrailingZeroCount(mask))) == 0;
+
+ private static uint Rgba(byte r, byte g, byte b, byte a) => r | ((uint)g << 8) | ((uint)b << 16) | ((uint)a << 24);
+
+ private static void DecodeRows(ReadOnlySpan data, BmpHeader header, RgbaImage image)
+ {
+ var stride = header.Stride;
+ var width = header.Width;
+ var height = header.Height;
+ var needed = (long)stride * (height - 1) + ((((long)width * header.BitsPerPixel) + 7) / 8);
+ if (header.PixelOffset + needed > data.Length)
+ {
+ throw new ImageDecodeException("BMP troncato: i pixel finiscono dopo il file.");
+ }
+
+ var bpp = header.BitsPerPixel;
+ Span red = stackalloc byte[256];
+ Span green = stackalloc byte[256];
+ Span blue = stackalloc byte[256];
+ Span alpha = stackalloc byte[256];
+ var rs = MaskShift(header.RedMask, red);
+ var gs = MaskShift(header.GreenMask, green);
+ var bs = MaskShift(header.BlueMask, blue);
+ var hasAlpha = header.AlphaMask != 0;
+ var @as = hasAlpha ? MaskShift(header.AlphaMask, alpha) : default;
+ var palette = header.Palette;
+
+ for (var y = 0; y < height; y++)
+ {
+ var source = data.Slice(header.PixelOffset + (y * stride));
+ var destination = image.GetRow(header.TopDown ? y : height - 1 - y);
+ switch (bpp)
+ {
+ case 1 or 2 or 4 or 8:
+ {
+ var mask = (1 << bpp) - 1;
+ var perByte = 8 / bpp;
+ for (var x = 0; x < width; x++)
+ {
+ var shift = 8 - bpp - ((x % perByte) * bpp);
+ var index = (source[x / perByte] >> shift) & mask;
+ BinaryPrimitives.WriteUInt32LittleEndian(destination[(x * 4)..], palette![index]);
+ }
+
+ break;
+ }
+
+ case 24:
+ for (int x = 0, s = 0, d = 0; x < width; x++, s += 3, d += 4)
+ {
+ destination[d] = source[s + 2];
+ destination[d + 1] = source[s + 1];
+ destination[d + 2] = source[s];
+ destination[d + 3] = 255;
+ }
+
+ break;
+
+ case 32 when header.RedMask == 0x00FF0000 && header.GreenMask == 0x0000FF00 && header.BlueMask == 0x000000FF && (!hasAlpha || header.AlphaMask == 0xFF000000):
+ for (int x = 0, s = 0; x < width; x++, s += 4)
+ {
+ destination[s] = source[s + 2];
+ destination[s + 1] = source[s + 1];
+ destination[s + 2] = source[s];
+ destination[s + 3] = hasAlpha ? source[s + 3] : (byte)255;
+ }
+
+ break;
+
+ default:
+ for (int x = 0, d = 0; x < width; x++, d += 4)
+ {
+ var pixel = bpp == 16
+ ? BinaryPrimitives.ReadUInt16LittleEndian(source[(x * 2)..])
+ : BinaryPrimitives.ReadUInt32LittleEndian(source[(x * 4)..]);
+ destination[d] = Channel(pixel, header.RedMask, rs, red);
+ destination[d + 1] = Channel(pixel, header.GreenMask, gs, green);
+ destination[d + 2] = Channel(pixel, header.BlueMask, bs, blue);
+ destination[d + 3] = hasAlpha ? Channel(pixel, header.AlphaMask, @as, alpha) : (byte)255;
+ }
+
+ break;
+ }
+ }
+ }
+
+ ///
+ /// The shift of a mask and, for masks of up to 8 bits, the 8-bit value of each of their values (scaled with
+ /// rounding: 31 → 255, 1 of 5 bits → 8) in . Wider masks keep their top 8 bits.
+ ///
+ private static (int Shift, int Bits) MaskShift(uint mask, Span table)
+ {
+ if (mask == 0)
+ {
+ return (0, 0);
+ }
+
+ var shift = BitOperations.TrailingZeroCount(mask);
+ var bits = BitOperations.PopCount(mask);
+ if (bits <= 8)
+ {
+ var max = (1 << bits) - 1;
+ for (var v = 0; v <= max; v++)
+ {
+ table[v] = (byte)(((v * 255) + (max / 2)) / max);
+ }
+ }
+
+ return (shift, bits);
+ }
+
+ private static byte Channel(uint pixel, uint mask, (int Shift, int Bits) layout, ReadOnlySpan table)
+ {
+ if (layout.Bits == 0)
+ {
+ return 0;
+ }
+
+ var value = (pixel & mask) >> layout.Shift;
+ return layout.Bits <= 8 ? table[(int)value] : (byte)(value >> (layout.Bits - 8));
+ }
+
+ private static void DecodeRle(ReadOnlySpan data, BmpHeader header, RgbaImage image)
+ {
+ var palette = header.Palette!;
+ var four = header.Compression == BiRle4;
+ var width = header.Width;
+ var height = header.Height;
+ var pixels = image.Pixels;
+ var pos = header.PixelOffset;
+ int x = 0, y = 0;
+ while (y < height)
+ {
+ if (pos + 2 > data.Length)
+ {
+ throw new ImageDecodeException("BMP troncato: i dati RLE finiscono prima della fine dell'immagine.");
+ }
+
+ int count = data[pos], value = data[pos + 1];
+ pos += 2;
+ if (count > 0)
+ {
+ // An encoded run: «count» pixels of one index (RLE8) or of two alternating indices (RLE4).
+ var rowStart = (height - 1 - y) * width;
+ for (var k = 0; k < count && x < width; k++, x++)
+ {
+ var index = four ? ((k & 1) == 0 ? value >> 4 : value & 0x0F) : value;
+ BinaryPrimitives.WriteUInt32LittleEndian(pixels[((rowStart + x) * 4)..], palette[index]);
+ }
+
+ continue;
+ }
+
+ switch (value)
+ {
+ case 0:
+ x = 0;
+ y++;
+ break;
+
+ case 1:
+ return;
+
+ case 2:
+ if (pos + 2 > data.Length)
+ {
+ throw new ImageDecodeException("BMP troncato: uno spostamento RLE finisce dopo il file.");
+ }
+
+ x += data[pos];
+ y += data[pos + 1];
+ pos += 2;
+ break;
+
+ default:
+ {
+ // An absolute run: «value» indices one after the other, padded to an even number of bytes.
+ var bytes = four ? (value + 1) / 2 : value;
+ if (pos + bytes > data.Length)
+ {
+ throw new ImageDecodeException("BMP troncato: un tratto RLE assoluto finisce dopo il file.");
+ }
+
+ var rowStart = (height - 1 - y) * width;
+ for (var k = 0; k < value && x < width; k++, x++)
+ {
+ var index = four ? ((k & 1) == 0 ? data[pos + (k / 2)] >> 4 : data[pos + (k / 2)] & 0x0F) : data[pos + k];
+ BinaryPrimitives.WriteUInt32LittleEndian(pixels[((rowStart + x) * 4)..], palette[index]);
+ }
+
+ pos += bytes + (bytes & 1);
+ break;
+ }
+ }
+ }
+ }
+}
diff --git a/src/Febe.Core/Codecs/Images/Crc32.cs b/src/Febe.Core/Codecs/Images/Crc32.cs
new file mode 100644
index 0000000..a64fc01
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/Crc32.cs
@@ -0,0 +1,72 @@
+using System.Buffers.Binary;
+
+namespace Febe.Core.Codecs.Images;
+
+///
+/// The CRC-32 of PNG chunks (ISO 3309 / ITU-T V.42, polynomial 0xEDB88320 reflected, PNG specification annex D),
+/// computed eight bytes at a time with tables built at start-up.
+///
+internal static class Crc32
+{
+ private const uint Polynomial = 0xEDB88320u;
+
+ // Table[k][b]: the CRC of byte b followed by k zero bytes; Table[0] is the classic byte table.
+ private static readonly uint[] Table = BuildTable();
+
+ /// The CRC of .
+ public static uint Compute(ReadOnlySpan data) => Append(0, data);
+
+ /// The CRC of the bytes already summed into followed by .
+ public static uint Append(uint crc, ReadOnlySpan data)
+ {
+ var table = Table;
+ var c = ~crc;
+ while (data.Length >= 8)
+ {
+ var low = BinaryPrimitives.ReadUInt32LittleEndian(data) ^ c;
+ var high = BinaryPrimitives.ReadUInt32LittleEndian(data[4..]);
+ c = table[(7 * 256) + (low & 0xFF)]
+ ^ table[(6 * 256) + ((low >> 8) & 0xFF)]
+ ^ table[(5 * 256) + ((low >> 16) & 0xFF)]
+ ^ table[(4 * 256) + (low >> 24)]
+ ^ table[(3 * 256) + (high & 0xFF)]
+ ^ table[(2 * 256) + ((high >> 8) & 0xFF)]
+ ^ table[256 + ((high >> 16) & 0xFF)]
+ ^ table[high >> 24];
+ data = data[8..];
+ }
+
+ foreach (var b in data)
+ {
+ c = table[(c ^ b) & 0xFF] ^ (c >> 8);
+ }
+
+ return ~c;
+ }
+
+ private static uint[] BuildTable()
+ {
+ var table = new uint[8 * 256];
+ for (uint n = 0; n < 256; n++)
+ {
+ var c = n;
+ for (var k = 0; k < 8; k++)
+ {
+ c = (c & 1) != 0 ? Polynomial ^ (c >> 1) : c >> 1;
+ }
+
+ table[n] = c;
+ }
+
+ for (var n = 0; n < 256; n++)
+ {
+ for (var k = 1; k < 8; k++)
+ {
+ var previous = table[((k - 1) * 256) + n];
+ table[(k * 256) + n] = table[previous & 0xFF] ^ (previous >> 8);
+ }
+ }
+
+ return table;
+ }
+}
diff --git a/src/Febe.Core/Codecs/Images/GifDecoder.cs b/src/Febe.Core/Codecs/Images/GifDecoder.cs
new file mode 100644
index 0000000..709b848
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/GifDecoder.cs
@@ -0,0 +1,531 @@
+using System.Buffers;
+using System.Buffers.Binary;
+using System.Text;
+
+namespace Febe.Core.Codecs.Images;
+
+///
+/// Reads GIF files (GIF87a and GIF89a): the first frame only, on a canvas of the logical screen size, with global or
+/// local palette, the transparent index of its graphic control extension and interlacing. Outside the first frame,
+/// and where the frame's index is transparent, the canvas is (0, 0, 0, 0); the background colour is not painted, as
+/// browsers do. Disposal methods only matter from the second frame, which is not decoded; the frames are counted.
+/// A file that ends before its trailer, or LZW data that stops early, gives what was decoded so far.
+///
+public static class GifDecoder
+{
+ private const int MaxCodeBits = 12;
+ private const int MaxCodes = 1 << MaxCodeBits;
+
+ /// Whether the bytes start with a GIF signature.
+ public static bool IsGif(ReadOnlySpan data) =>
+ data.Length >= 6 && data[..3].SequenceEqual("GIF"u8) && (data[3..6].SequenceEqual("89a"u8) || data[3..6].SequenceEqual("87a"u8));
+
+ /// Canvas size, frame count and comments of a GIF, without decoding the pixels.
+ public static ImageInfo Identify(ReadOnlyMemory data, ImageLimits? limits = null)
+ {
+ limits ??= ImageLimits.Default;
+ var file = Walk(data.Span, limits, countFrames: true);
+ return file.ToInfo();
+ }
+
+ /// Decodes the first frame of a GIF to straight RGBA8.
+ /// The file is damaged, has no frame or is not a GIF.
+ /// The image is larger than allow.
+ public static RgbaImage Decode(ReadOnlyMemory data, ImageLimits? limits = null, bool pooled = false)
+ {
+ limits ??= ImageLimits.Default;
+ var span = data.Span;
+ var file = Walk(span, limits, countFrames: false);
+ return DecodeFirstFrame(span, file, limits, pooled);
+ }
+
+ /// Decodes the first frame of a GIF and returns what returns as well.
+ public static RgbaImage Decode(ReadOnlyMemory data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
+ {
+ limits ??= ImageLimits.Default;
+ var span = data.Span;
+ var file = Walk(span, limits, countFrames: true);
+ var image = DecodeFirstFrame(span, file, limits, pooled);
+ info = file.ToInfo();
+ return image;
+ }
+
+ private sealed class GifFile
+ {
+ public int CanvasWidth;
+ public int CanvasHeight;
+ public int GlobalPaletteStart = -1;
+ public int GlobalPaletteCount;
+
+ public int FrameCount;
+ public int FrameLeft;
+ public int FrameTop;
+ public int FrameWidth;
+ public int FrameHeight;
+ public bool FrameInterlaced;
+ public int FramePaletteStart = -1;
+ public int FramePaletteCount;
+ public int FrameTransparent = -1;
+ public int FrameCodeSize;
+ public int FrameDataStart;
+
+ public List? Comments;
+
+ public ImageInfo ToInfo() => new(
+ ImageFormat.Gif,
+ CanvasWidth,
+ CanvasHeight,
+ Math.Max(1, FrameCount),
+ true,
+ Comments is null ? ImageMetadata.Empty : new ImageMetadata { Texts = Comments });
+ }
+
+ private static GifFile Walk(ReadOnlySpan data, ImageLimits limits, bool countFrames)
+ {
+ if (!IsGif(data))
+ {
+ throw new ImageDecodeException("Non è un file GIF.");
+ }
+
+ if (data.Length < 13)
+ {
+ throw new ImageDecodeException("GIF troncato: manca il descrittore dello schermo logico.");
+ }
+
+ var file = new GifFile
+ {
+ CanvasWidth = BinaryPrimitives.ReadUInt16LittleEndian(data[6..]),
+ CanvasHeight = BinaryPrimitives.ReadUInt16LittleEndian(data[8..]),
+ };
+ var packed = data[10];
+ var pos = 13;
+ if ((packed & 0x80) != 0)
+ {
+ file.GlobalPaletteCount = 2 << (packed & 7);
+ file.GlobalPaletteStart = pos;
+ pos += file.GlobalPaletteCount * 3;
+ if (pos > data.Length)
+ {
+ throw new ImageDecodeException("GIF troncato: la tavolozza globale finisce dopo il file.");
+ }
+ }
+
+ var transparent = -1;
+ var metadataBudget = limits.MaxMetadataBytes;
+ while (pos < data.Length)
+ {
+ var block = data[pos++];
+ if (block == 0x3B)
+ {
+ break;
+ }
+
+ if (block == 0x21)
+ {
+ if (pos >= data.Length)
+ {
+ break;
+ }
+
+ var label = data[pos++];
+ if (label == 0xF9 && pos + 5 <= data.Length && data[pos] >= 4)
+ {
+ // Graphic control extension: the transparent index applies to the next image only.
+ transparent = (data[pos + 1] & 1) != 0 ? data[pos + 4] : -1;
+ }
+ else if (label == 0xFE && file.FrameCount == 0)
+ {
+ ReadComment(data, pos, file, ref metadataBudget);
+ }
+
+ pos = SkipSubBlocks(data, pos);
+ continue;
+ }
+
+ if (block != 0x2C)
+ {
+ // Not a block GIF knows: what follows cannot be read; browsers stop here too.
+ break;
+ }
+
+ if (pos + 9 > data.Length)
+ {
+ break;
+ }
+
+ file.FrameCount++;
+ var framePacked = data[pos + 8];
+ if (file.FrameCount == 1)
+ {
+ file.FrameLeft = BinaryPrimitives.ReadUInt16LittleEndian(data[pos..]);
+ file.FrameTop = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 2)..]);
+ file.FrameWidth = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 4)..]);
+ file.FrameHeight = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 6)..]);
+ file.FrameInterlaced = (framePacked & 0x40) != 0;
+ file.FrameTransparent = transparent;
+ }
+
+ pos += 9;
+ if ((framePacked & 0x80) != 0)
+ {
+ var count = 2 << (framePacked & 7);
+ if (file.FrameCount == 1)
+ {
+ file.FramePaletteStart = pos;
+ file.FramePaletteCount = count;
+ }
+
+ pos += count * 3;
+ if (pos > data.Length)
+ {
+ if (file.FrameCount == 1)
+ {
+ throw new ImageDecodeException("GIF troncato: la tavolozza locale finisce dopo il file.");
+ }
+
+ file.FrameCount--;
+ break;
+ }
+ }
+
+ if (pos >= data.Length)
+ {
+ if (file.FrameCount == 1)
+ {
+ throw new ImageDecodeException("GIF troncato: mancano i dati del primo fotogramma.");
+ }
+
+ file.FrameCount--;
+ break;
+ }
+
+ if (file.FrameCount == 1)
+ {
+ file.FrameCodeSize = data[pos];
+ file.FrameDataStart = pos + 1;
+ if (!countFrames)
+ {
+ break;
+ }
+ }
+
+ pos = SkipSubBlocks(data, pos + 1);
+ transparent = -1;
+ }
+
+ if (file.FrameCount == 0)
+ {
+ throw new ImageDecodeException("GIF senza fotogrammi.");
+ }
+
+ if (file.CanvasWidth == 0 || file.CanvasHeight == 0)
+ {
+ // Some encoders leave the logical screen empty: the first frame then gives the size.
+ file.CanvasWidth = file.FrameLeft + file.FrameWidth;
+ file.CanvasHeight = file.FrameTop + file.FrameHeight;
+ }
+
+ return file;
+ }
+
+ private static int SkipSubBlocks(ReadOnlySpan data, int pos)
+ {
+ while (pos < data.Length)
+ {
+ var size = data[pos++];
+ if (size == 0)
+ {
+ return pos;
+ }
+
+ pos += size;
+ }
+
+ return data.Length;
+ }
+
+ private static void ReadComment(ReadOnlySpan data, int pos, GifFile file, ref int budget)
+ {
+ var builder = new StringBuilder();
+ while (pos < data.Length)
+ {
+ var size = data[pos++];
+ if (size == 0)
+ {
+ break;
+ }
+
+ var n = Math.Min(size, data.Length - pos);
+ if (n > budget)
+ {
+ return;
+ }
+
+ budget -= n;
+ builder.Append(Encoding.Latin1.GetString(data.Slice(pos, n)));
+ pos += n;
+ }
+
+ (file.Comments ??= []).Add(new ImageText(string.Empty, builder.ToString()));
+ }
+
+ private static RgbaImage DecodeFirstFrame(ReadOnlySpan data, GifFile file, ImageLimits limits, bool pooled)
+ {
+ var (paletteStart, paletteCount) = file.FramePaletteStart >= 0
+ ? (file.FramePaletteStart, file.FramePaletteCount)
+ : (file.GlobalPaletteStart, file.GlobalPaletteCount);
+ if (paletteStart < 0)
+ {
+ throw new ImageDecodeException("GIF danneggiato: il primo fotogramma non ha tavolozza.");
+ }
+
+ if (file.FrameCodeSize is < 1 or > MaxCodeBits - 1)
+ {
+ throw new ImageDecodeException($"GIF danneggiato: dimensione iniziale dei codici LZW non valida ({file.FrameCodeSize}).");
+ }
+
+ var image = RgbaImage.Create(file.CanvasWidth, file.CanvasHeight, limits, pooled);
+ var frameWidth = file.FrameWidth;
+ var frameHeight = file.FrameHeight;
+ if (frameWidth == 0 || frameHeight == 0)
+ {
+ return image;
+ }
+
+ var frameBytes = (long)frameWidth * frameHeight;
+ limits.CheckWorkingBytes(frameBytes);
+ var indices = ArrayPool.Shared.Rent((int)frameBytes);
+ try
+ {
+ var decoded = DecodeLzw(data, file.FrameDataStart, file.FrameCodeSize, indices.AsSpan(0, (int)frameBytes));
+
+ // RGBA of each palette index; indices beyond the palette are opaque black, the transparent one is skipped.
+ Span colours = stackalloc uint[256];
+ Span rgba = stackalloc byte[4];
+ for (var i = 0; i < 256; i++)
+ {
+ if (i < paletteCount)
+ {
+ var p = paletteStart + (i * 3);
+ rgba[0] = data[p];
+ rgba[1] = data[p + 1];
+ rgba[2] = data[p + 2];
+ }
+ else
+ {
+ rgba[0] = rgba[1] = rgba[2] = 0;
+ }
+
+ rgba[3] = 255;
+ colours[i] = BinaryPrimitives.ReadUInt32LittleEndian(rgba);
+ }
+
+ var transparent = file.FrameTransparent;
+ var pixels = image.Pixels;
+ var canvasWidth = file.CanvasWidth;
+ var canvasHeight = file.CanvasHeight;
+ var visibleWidth = Math.Min(frameWidth, canvasWidth - file.FrameLeft);
+ for (var r = 0; r < frameHeight; r++)
+ {
+ var rowStart = r * frameWidth;
+ if (rowStart >= decoded)
+ {
+ break;
+ }
+
+ var y = file.FrameTop + (file.FrameInterlaced ? InterlacedRow(r, frameHeight) : r);
+ if (y >= canvasHeight || visibleWidth <= 0)
+ {
+ continue;
+ }
+
+ var count = Math.Min(visibleWidth, decoded - rowStart);
+ var destination = pixels.Slice(((y * canvasWidth) + file.FrameLeft) * RgbaImage.BytesPerPixel, count * RgbaImage.BytesPerPixel);
+ var source = indices.AsSpan(rowStart, count);
+ for (var x = 0; x < count; x++)
+ {
+ var index = source[x];
+ if (index != transparent)
+ {
+ BinaryPrimitives.WriteUInt32LittleEndian(destination[(x * 4)..], colours[index]);
+ }
+ }
+ }
+
+ return image;
+ }
+ catch
+ {
+ image.Dispose();
+ throw;
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(indices);
+ }
+ }
+
+ /// The row of the image that the -th decoded row of an interlaced frame fills.
+ internal static int InterlacedRow(int r, int height)
+ {
+ var pass1 = (height + 7) / 8;
+ if (r < pass1)
+ {
+ return r * 8;
+ }
+
+ r -= pass1;
+ var pass2 = (height + 3) / 8;
+ if (r < pass2)
+ {
+ return 4 + (r * 8);
+ }
+
+ r -= pass2;
+ var pass3 = (height + 1) / 4;
+ if (r < pass3)
+ {
+ return 2 + (r * 4);
+ }
+
+ r -= pass3;
+ return 1 + (r * 2);
+ }
+
+ ///
+ /// Decodes the LZW data sub-blocks that start at into (GIF89a
+ /// appendix F: variable-length codes from + 1 bits up to 12, least significant bit
+ /// first) and returns how many indices were written. A damaged stream stops the decoding there.
+ ///
+ internal static int DecodeLzw(ReadOnlySpan data, int pos, int minCodeSize, Span output)
+ {
+ var prefix = ArrayPool.Shared.Rent(MaxCodes);
+ var lengths = ArrayPool.Shared.Rent(MaxCodes);
+ var suffix = ArrayPool.Shared.Rent(MaxCodes);
+ var first = ArrayPool.Shared.Rent(MaxCodes);
+ try
+ {
+ var clear = 1 << minCodeSize;
+ var end = clear + 1;
+ for (var i = 0; i < clear; i++)
+ {
+ prefix[i] = 0;
+ lengths[i] = 1;
+ suffix[i] = (byte)i;
+ first[i] = (byte)i;
+ }
+
+ var codeSize = minCodeSize + 1;
+ var next = clear + 2;
+ var old = -1;
+ var written = 0;
+ uint bits = 0;
+ var bitCount = 0;
+ var blockLeft = 0;
+ while (written < output.Length)
+ {
+ while (bitCount < codeSize)
+ {
+ if (blockLeft == 0)
+ {
+ if (pos >= data.Length || data[pos] == 0)
+ {
+ return written;
+ }
+
+ blockLeft = data[pos++];
+ }
+
+ if (pos >= data.Length)
+ {
+ return written;
+ }
+
+ bits |= (uint)data[pos++] << bitCount;
+ bitCount += 8;
+ blockLeft--;
+ }
+
+ var code = (int)(bits & ((1u << codeSize) - 1));
+ bits >>= codeSize;
+ bitCount -= codeSize;
+
+ if (code == clear)
+ {
+ codeSize = minCodeSize + 1;
+ next = clear + 2;
+ old = -1;
+ continue;
+ }
+
+ if (code == end)
+ {
+ return written;
+ }
+
+ if (old < 0)
+ {
+ if (code > clear)
+ {
+ return written;
+ }
+
+ output[written++] = (byte)code;
+ old = code;
+ if (next >= 1 << codeSize && codeSize < MaxCodeBits)
+ {
+ codeSize++;
+ }
+
+ continue;
+ }
+
+ if (code > next || (code == next && next >= MaxCodes))
+ {
+ return written;
+ }
+
+ if (next < MaxCodes)
+ {
+ // The new entry is the previous string followed by the first byte of the current one; when the code
+ // is the entry being made (KwKwK), that first byte is the previous string's own.
+ var firstByte = code == next ? first[old] : first[code];
+ prefix[next] = (ushort)old;
+ suffix[next] = firstByte;
+ first[next] = first[old];
+ lengths[next] = (ushort)(lengths[old] + 1);
+ next++;
+ }
+
+ var length = lengths[code];
+ var stop = written + length;
+ var c = code;
+ for (var o = stop - 1; o >= written; o--)
+ {
+ if (o < output.Length)
+ {
+ output[o] = suffix[c];
+ }
+
+ c = prefix[c];
+ }
+
+ written = Math.Min(stop, output.Length);
+ old = code;
+ if (next >= 1 << codeSize && codeSize < MaxCodeBits)
+ {
+ codeSize++;
+ }
+ }
+
+ return written;
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(prefix);
+ ArrayPool.Shared.Return(lengths);
+ ArrayPool.Shared.Return(suffix);
+ ArrayPool.Shared.Return(first);
+ }
+ }
+}
diff --git a/src/Febe.Core/Codecs/Images/ImageDecodeException.cs b/src/Febe.Core/Codecs/Images/ImageDecodeException.cs
new file mode 100644
index 0000000..5552866
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/ImageDecodeException.cs
@@ -0,0 +1,58 @@
+namespace Febe.Core.Codecs.Images;
+
+///
+/// The bytes are not an image Febe can read: damaged, truncated, or outside what the format allows. The message
+/// (Italian) says what was wrong, never what the image contains.
+///
+public class ImageDecodeException : Exception
+{
+ public ImageDecodeException()
+ {
+ }
+
+ public ImageDecodeException(string message)
+ : base(message)
+ {
+ }
+
+ public ImageDecodeException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+}
+
+/// The image is well formed but larger than allows: it is not decoded.
+public sealed class ImageLimitException : ImageDecodeException
+{
+ public ImageLimitException()
+ {
+ }
+
+ public ImageLimitException(string message)
+ : base(message)
+ {
+ }
+
+ public ImageLimitException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+}
+
+/// The format was recognised but Febe has no decoder for it (yet), or not for this variant of it.
+public sealed class ImageFormatNotSupportedException : ImageDecodeException
+{
+ public ImageFormatNotSupportedException()
+ {
+ }
+
+ public ImageFormatNotSupportedException(string message)
+ : base(message)
+ {
+ }
+
+ public ImageFormatNotSupportedException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+}
diff --git a/src/Febe.Core/Codecs/Images/ImageDecoder.cs b/src/Febe.Core/Codecs/Images/ImageDecoder.cs
new file mode 100644
index 0000000..b61486b
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/ImageDecoder.cs
@@ -0,0 +1,41 @@
+namespace Febe.Core.Codecs.Images;
+
+///
+/// Decodes an image of any format Febe reads, chosen from its first bytes. The pixels come out as stored in the file:
+/// the EXIF orientation is not applied here.
+///
+public static class ImageDecoder
+{
+ /// Whether Febe has a decoder for .
+ public static bool CanDecode(ImageFormat format) => format is ImageFormat.Png or ImageFormat.Gif or ImageFormat.Bmp;
+
+ /// Size, frames and metadata of an image, without decoding the pixels.
+ /// The format is not known or has no decoder yet.
+ /// The file is damaged.
+ public static ImageInfo Identify(ReadOnlyMemory data, ImageLimits? limits = null) =>
+ ImageFormatSniffer.Detect(data.Span) switch
+ {
+ ImageFormat.Png => PngDecoder.Identify(data, limits),
+ ImageFormat.Gif => GifDecoder.Identify(data, limits),
+ ImageFormat.Bmp => BmpDecoder.Identify(data, limits),
+ var other => throw NotSupported(other),
+ };
+
+ /// Decodes an image to straight RGBA8 (the first frame of an animation).
+ /// The format is not known or has no decoder yet.
+ /// The file is damaged.
+ /// The image is larger than allow.
+ public static RgbaImage Decode(ReadOnlyMemory data, ImageLimits? limits = null, bool pooled = false) =>
+ ImageFormatSniffer.Detect(data.Span) switch
+ {
+ ImageFormat.Png => PngDecoder.Decode(data, limits, pooled),
+ ImageFormat.Gif => GifDecoder.Decode(data, limits, pooled),
+ ImageFormat.Bmp => BmpDecoder.Decode(data, limits, pooled),
+ var other => throw NotSupported(other),
+ };
+
+ private static ImageFormatNotSupportedException NotSupported(ImageFormat format) =>
+ format == ImageFormat.Unknown
+ ? new ImageFormatNotSupportedException("Formato d'immagine non riconosciuto.")
+ : new ImageFormatNotSupportedException($"Febe non legge ancora le immagini {format.ToString().ToUpperInvariant()}.");
+}
diff --git a/src/Febe.Core/Codecs/Images/ImageFormat.cs b/src/Febe.Core/Codecs/Images/ImageFormat.cs
new file mode 100644
index 0000000..1a8f2d2
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/ImageFormat.cs
@@ -0,0 +1,85 @@
+using System.Buffers.Binary;
+
+namespace Febe.Core.Codecs.Images;
+
+/// Image formats Febe recognises from their first bytes (not all of them can be decoded).
+public enum ImageFormat
+{
+ Unknown,
+ Png,
+ Jpeg,
+ Gif,
+ Bmp,
+ WebP,
+ Tiff,
+
+ /// HEIF with HEVC pictures (HEIC), or a generic HEIF.
+ Heif,
+
+ /// HEIF with AV1 pictures.
+ Avif,
+}
+
+/// Recognises an image format from the first bytes of a file.
+public static class ImageFormatSniffer
+{
+ /// Bytes needs to tell every format apart; fewer are fine for most formats.
+ public const int HeaderLength = 32;
+
+ /// The format the bytes start with, or .
+ public static ImageFormat Detect(ReadOnlySpan header)
+ {
+ if (header.Length >= 8 && header[..8].SequenceEqual(PngSignature))
+ {
+ return ImageFormat.Png;
+ }
+
+ if (header.Length >= 3 && header[0] == 0xFF && header[1] == 0xD8 && header[2] == 0xFF)
+ {
+ return ImageFormat.Jpeg;
+ }
+
+ if (header.Length >= 6 && header[..3].SequenceEqual("GIF"u8) && (header[3..6].SequenceEqual("89a"u8) || header[3..6].SequenceEqual("87a"u8)))
+ {
+ return ImageFormat.Gif;
+ }
+
+ if (header.Length >= 18 && header[0] == (byte)'B' && header[1] == (byte)'M' && IsBmpHeaderSize(BinaryPrimitives.ReadUInt32LittleEndian(header[14..])))
+ {
+ return ImageFormat.Bmp;
+ }
+
+ if (header.Length >= 12 && header[..4].SequenceEqual("RIFF"u8) && header[8..12].SequenceEqual("WEBP"u8))
+ {
+ return ImageFormat.WebP;
+ }
+
+ if (header.Length >= 4 && (header[..4].SequenceEqual("II*\0"u8) || header[..4].SequenceEqual("MM\0*"u8)))
+ {
+ return ImageFormat.Tiff;
+ }
+
+ if (header.Length >= 12 && header[4..8].SequenceEqual("ftyp"u8))
+ {
+ var brand = header[8..12];
+ if (brand.SequenceEqual("avif"u8) || brand.SequenceEqual("avis"u8))
+ {
+ return ImageFormat.Avif;
+ }
+
+ if (brand.SequenceEqual("heic"u8) || brand.SequenceEqual("heix"u8) || brand.SequenceEqual("heim"u8) || brand.SequenceEqual("heis"u8)
+ || brand.SequenceEqual("hevc"u8) || brand.SequenceEqual("hevx"u8) || brand.SequenceEqual("mif1"u8) || brand.SequenceEqual("msf1"u8))
+ {
+ return ImageFormat.Heif;
+ }
+ }
+
+ return ImageFormat.Unknown;
+ }
+
+ /// The eight bytes every PNG file starts with.
+ internal static ReadOnlySpan PngSignature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
+
+ /// The sizes of the BMP information headers that exist (core, info, V2, V3, OS/2 2.x, V4, V5).
+ internal static bool IsBmpHeaderSize(uint size) => size is 12 or 16 or 40 or 52 or 56 or 64 or 108 or 124;
+}
diff --git a/src/Febe.Core/Codecs/Images/ImageLimits.cs b/src/Febe.Core/Codecs/Images/ImageLimits.cs
new file mode 100644
index 0000000..2702a01
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/ImageLimits.cs
@@ -0,0 +1,59 @@
+namespace Febe.Core.Codecs.Images;
+
+///
+/// How large an image the decoders accept. A file states its size in a few bytes, so without limits a tiny file could
+/// ask for gigabytes; the decoders check these before allocating anything.
+///
+public sealed record ImageLimits
+{
+ /// The limits used when a caller passes none.
+ public static ImageLimits Default { get; } = new();
+
+ /// Largest width, in pixels.
+ public int MaxWidth { get; init; } = 65535;
+
+ /// Largest height, in pixels.
+ public int MaxHeight { get; init; } = 65535;
+
+ /// Largest width × height. 100 megapixels are 400 MB of RGBA.
+ public long MaxPixels { get; init; } = 100_000_000;
+
+ ///
+ /// Largest working memory a decoder may take besides the decoded image (for example the indices of a GIF frame).
+ ///
+ public long MaxWorkingBytes { get; init; } = 512L * 1024 * 1024;
+
+ ///
+ /// Largest size of the metadata of one image once decompressed (texts, colour profile, EXIF), all chunks together:
+ /// a compressed text chunk can otherwise expand a thousandfold.
+ ///
+ public int MaxMetadataBytes { get; init; } = 16 * 1024 * 1024;
+
+ /// Throws when an image of that size is not allowed.
+ internal void CheckSize(long width, long height)
+ {
+ if (width <= 0 || height <= 0)
+ {
+ throw new ImageDecodeException($"Misura dell'immagine non valida ({width}×{height}).");
+ }
+
+ if (width > MaxWidth || height > MaxHeight || width * height > MaxPixels)
+ {
+ throw new ImageLimitException($"Immagine troppo grande ({width}×{height}): il limite è {MaxWidth}×{MaxHeight} e {MaxPixels} pixel.");
+ }
+
+ if (width * height * RgbaImage.BytesPerPixel > Array.MaxLength)
+ {
+ throw new ImageLimitException($"Immagine troppo grande ({width}×{height}) per la memoria di un processo.");
+ }
+ }
+
+ /// Throws when a decoder would need more working memory than allowed.
+ internal void CheckWorkingBytes(long bytes)
+ {
+ if (bytes > MaxWorkingBytes || bytes > Array.MaxLength)
+ {
+ throw new ImageLimitException($"La lettura dell'immagine chiederebbe troppa memoria ({bytes} byte, il limite è {MaxWorkingBytes}).");
+ }
+ }
+}
diff --git a/src/Febe.Core/Codecs/Images/ImageMetadata.cs b/src/Febe.Core/Codecs/Images/ImageMetadata.cs
new file mode 100644
index 0000000..2236cdb
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/ImageMetadata.cs
@@ -0,0 +1,39 @@
+namespace Febe.Core.Codecs.Images;
+
+/// A text an image carries (PNG tEXt, zTXt, iTXt; GIF comment).
+/// The keyword («Title», «Comment», «XML:com.adobe.xmp»...); empty for a GIF comment.
+/// The text.
+/// The language tag of an iTXt chunk, empty otherwise.
+/// The translated keyword of an iTXt chunk, empty otherwise.
+public sealed record ImageText(string Keyword, string Text, string Language = "", string TranslatedKeyword = "");
+
+/// Metadata read from an image file, without interpreting it.
+public sealed class ImageMetadata
+{
+ /// No metadata.
+ public static ImageMetadata Empty { get; } = new();
+
+ /// The EXIF block as a TIFF structure (starts with «II*\0» or «MM\0*»), or null.
+ public byte[]? Exif { get; init; }
+
+ /// The ICC colour profile, decompressed, or null.
+ public byte[]? IccProfile { get; init; }
+
+ /// The name of the ICC profile as the file gives it, or null.
+ public string? IccProfileName { get; init; }
+
+ /// The XMP packet (from the iTXt chunk «XML:com.adobe.xmp» of a PNG), or null.
+ public string? Xmp { get; init; }
+
+ /// The texts, in file order (the XMP packet is in , not here).
+ public IReadOnlyList Texts { get; init; } = [];
+}
+
+/// What a file says about its image, read without decoding the pixels.
+/// The format.
+/// Width in pixels, as stored (no EXIF orientation applied).
+/// Height in pixels, as stored.
+/// Frames of an animation (GIF images, APNG frames); 1 for a still image.
+/// Whether the format of the pixels can carry transparency (not whether any pixel is transparent).
+/// The metadata.
+public sealed record ImageInfo(ImageFormat Format, int Width, int Height, int FrameCount, bool HasAlpha, ImageMetadata Metadata);
diff --git a/src/Febe.Core/Codecs/Images/PngDecoder.cs b/src/Febe.Core/Codecs/Images/PngDecoder.cs
new file mode 100644
index 0000000..a288bda
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/PngDecoder.cs
@@ -0,0 +1,917 @@
+using System.Buffers;
+using System.Buffers.Binary;
+using System.IO.Compression;
+using System.Numerics;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace Febe.Core.Codecs.Images;
+
+///
+/// Reads PNG files (W3C PNG specification, third edition): every colour type and bit depth, palettes with tRNS,
+/// colour keys, Adam7 interlacing, the five row filters. The pixels come out as straight RGBA8; 16-bit samples keep
+/// their high byte. Gamma, chromaticities and colour profiles are not applied (the profile is returned in the
+/// metadata). The CRC of every chunk is checked: a damaged critical chunk stops the decoding, a damaged ancillary chunk
+/// is skipped.
+///
+public static class PngDecoder
+{
+ private const int MaxChunkLength = int.MaxValue;
+ private const string XmpKeyword = "XML:com.adobe.xmp";
+
+ // Adam7: first column, first row, column step, row step of the seven passes.
+ private static ReadOnlySpan Adam7 =>
+ [
+ 0, 0, 8, 8,
+ 4, 0, 8, 8,
+ 0, 4, 4, 8,
+ 2, 0, 4, 4,
+ 0, 2, 2, 4,
+ 1, 0, 2, 2,
+ 0, 1, 1, 2,
+ ];
+
+ /// Whether the bytes start with the PNG signature.
+ public static bool IsPng(ReadOnlySpan data) => data.Length >= 8 && data[..8].SequenceEqual(ImageFormatSniffer.PngSignature);
+
+ /// Size, frames and metadata of a PNG, without decoding the pixels.
+ public static ImageInfo Identify(ReadOnlyMemory data, ImageLimits? limits = null)
+ {
+ var file = Parse(data, limits ?? ImageLimits.Default, readMetadata: true);
+ return file.ToInfo();
+ }
+
+ /// Decodes a PNG to straight RGBA8.
+ /// The file is damaged, truncated or not a PNG.
+ /// The image is larger than allow.
+ public static RgbaImage Decode(ReadOnlyMemory data, ImageLimits? limits = null, bool pooled = false)
+ {
+ limits ??= ImageLimits.Default;
+ var file = Parse(data, limits, readMetadata: false);
+ return DecodePixels(data, file, limits, pooled);
+ }
+
+ /// Decodes a PNG to straight RGBA8 and returns what returns as well.
+ public static RgbaImage Decode(ReadOnlyMemory data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
+ {
+ limits ??= ImageLimits.Default;
+ var file = Parse(data, limits, readMetadata: true);
+ var image = DecodePixels(data, file, limits, pooled);
+ info = file.ToInfo();
+ return image;
+ }
+
+ private sealed class PngFile
+ {
+ public int Width;
+ public int Height;
+ public int BitDepth;
+ public int ColorType;
+ public bool Interlaced;
+
+ /// 256 RGBA entries; entries the file does not give are opaque black.
+ public byte[]? Palette;
+ public int PaletteCount;
+
+ public bool HasColorKey;
+ public ushort KeyRed;
+ public ushort KeyGreen;
+ public ushort KeyBlue;
+ public bool HasPaletteAlpha;
+
+ public readonly List<(int Start, int Length)> Idat = [];
+ public int FrameCount = 1;
+
+ public byte[]? Exif;
+ public byte[]? Icc;
+ public string? IccName;
+ public string? Xmp;
+ public List? Texts;
+
+ public int Channels => ColorType switch { 2 => 3, 4 => 2, 6 => 4, _ => 1 };
+
+ public int BitsPerPixel => Channels * BitDepth;
+
+ public ImageInfo ToInfo() => new(
+ ImageFormat.Png,
+ Width,
+ Height,
+ FrameCount,
+ ColorType is 4 or 6 || HasColorKey || HasPaletteAlpha,
+ Exif is null && Icc is null && Xmp is null && Texts is null
+ ? ImageMetadata.Empty
+ : new ImageMetadata { Exif = Exif, IccProfile = Icc, IccProfileName = IccName, Xmp = Xmp, Texts = Texts ?? [] });
+ }
+
+ private static PngFile Parse(ReadOnlyMemory memory, ImageLimits limits, bool readMetadata)
+ {
+ var data = memory.Span;
+ if (!IsPng(data))
+ {
+ throw new ImageDecodeException("Non è un file PNG.");
+ }
+
+ var file = new PngFile();
+ var seenHeader = false;
+ var seenPalette = false;
+ var seenTransparency = false;
+ var idatState = 0; // 0 none yet, 1 inside the IDAT run, 2 after it
+ var metadataBudget = limits.MaxMetadataBytes;
+ var pos = 8;
+ while (pos < data.Length)
+ {
+ if (data.Length - pos < 12)
+ {
+ throw new ImageDecodeException("PNG troncato: un blocco finisce prima della fine del file.");
+ }
+
+ var length = BinaryPrimitives.ReadUInt32BigEndian(data[pos..]);
+ if (length > MaxChunkLength || length > data.Length - pos - 12)
+ {
+ throw new ImageDecodeException("PNG troncato: un blocco dichiara più byte di quelli che il file contiene.");
+ }
+
+ var type = data.Slice(pos + 4, 4);
+ var payloadStart = pos + 8;
+ var payload = data.Slice(payloadStart, (int)length);
+ var storedCrc = BinaryPrimitives.ReadUInt32BigEndian(data[(payloadStart + (int)length)..]);
+ pos = payloadStart + (int)length + 4;
+ if (!IsChunkType(type))
+ {
+ throw new ImageDecodeException("PNG danneggiato: tipo di blocco non valido.");
+ }
+
+ var name = Encoding.ASCII.GetString(type);
+ var critical = (type[0] & 0x20) == 0;
+ if (Crc32.Compute(data.Slice(payloadStart - 4, (int)length + 4)) != storedCrc)
+ {
+ if (critical)
+ {
+ throw new ImageDecodeException($"PNG danneggiato: il CRC del blocco {name} non corrisponde.");
+ }
+
+ continue;
+ }
+
+ if (!seenHeader && name != "IHDR")
+ {
+ throw new ImageDecodeException("PNG danneggiato: il primo blocco non è IHDR.");
+ }
+
+ if (idatState == 1 && name != "IDAT")
+ {
+ idatState = 2;
+ }
+
+ switch (name)
+ {
+ case "IHDR":
+ if (seenHeader)
+ {
+ throw new ImageDecodeException("PNG danneggiato: IHDR ripetuto.");
+ }
+
+ ReadHeader(file, payload);
+ seenHeader = true;
+ break;
+
+ case "PLTE":
+ if (seenPalette || idatState != 0)
+ {
+ throw new ImageDecodeException("PNG danneggiato: PLTE ripetuto o dopo i dati dell'immagine.");
+ }
+
+ seenPalette = true;
+ ReadPalette(file, payload);
+ break;
+
+ case "tRNS":
+ if (!seenTransparency && idatState == 0)
+ {
+ seenTransparency = true;
+ ReadTransparency(file, payload);
+ }
+
+ break;
+
+ case "IDAT":
+ if (idatState == 2)
+ {
+ throw new ImageDecodeException("PNG danneggiato: i blocchi IDAT non sono uno dopo l'altro.");
+ }
+
+ if (file.ColorType == 3 && file.Palette is null)
+ {
+ throw new ImageDecodeException("PNG danneggiato: immagine a tavolozza senza PLTE.");
+ }
+
+ idatState = 1;
+ if (length > 0)
+ {
+ file.Idat.Add((payloadStart, (int)length));
+ }
+
+ break;
+
+ case "IEND":
+ pos = data.Length;
+ break;
+
+ case "acTL":
+ if (payload.Length >= 8 && idatState == 0)
+ {
+ var frames = BinaryPrimitives.ReadUInt32BigEndian(payload);
+ file.FrameCount = frames is > 0 and <= int.MaxValue ? (int)frames : 1;
+ }
+
+ break;
+
+ case "tEXt" or "zTXt" or "iTXt" or "iCCP" or "eXIf":
+ if (readMetadata)
+ {
+ ReadMetadata(file, name, payload, ref metadataBudget);
+ }
+
+ break;
+
+ default:
+ if (critical)
+ {
+ throw new ImageFormatNotSupportedException($"PNG con un blocco critico che Febe non conosce ({name}).");
+ }
+
+ break;
+ }
+ }
+
+ if (!seenHeader)
+ {
+ throw new ImageDecodeException("PNG troncato: manca IHDR.");
+ }
+
+ if (idatState == 0)
+ {
+ throw new ImageDecodeException("PNG senza dati dell'immagine (IDAT).");
+ }
+
+ return file;
+ }
+
+ private static bool IsChunkType(ReadOnlySpan type)
+ {
+ foreach (var c in type)
+ {
+ if (!char.IsAsciiLetter((char)c))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static void ReadHeader(PngFile file, ReadOnlySpan payload)
+ {
+ if (payload.Length != 13)
+ {
+ throw new ImageDecodeException("PNG danneggiato: IHDR della lunghezza sbagliata.");
+ }
+
+ var width = BinaryPrimitives.ReadUInt32BigEndian(payload);
+ var height = BinaryPrimitives.ReadUInt32BigEndian(payload[4..]);
+ if (width == 0 || height == 0 || width > int.MaxValue || height > int.MaxValue)
+ {
+ throw new ImageDecodeException($"PNG danneggiato: misura non valida ({width}×{height}).");
+ }
+
+ int depth = payload[8];
+ int colorType = payload[9];
+ var valid = colorType switch
+ {
+ 0 => depth is 1 or 2 or 4 or 8 or 16,
+ 3 => depth is 1 or 2 or 4 or 8,
+ 2 or 4 or 6 => depth is 8 or 16,
+ _ => false,
+ };
+ if (!valid)
+ {
+ throw new ImageDecodeException($"PNG danneggiato: profondità {depth} non ammessa per il tipo di colore {colorType}.");
+ }
+
+ if (payload[10] != 0 || payload[11] != 0 || payload[12] > 1)
+ {
+ throw new ImageDecodeException("PNG danneggiato: metodo di compressione, di filtro o d'interlacciamento sconosciuto.");
+ }
+
+ file.Width = (int)width;
+ file.Height = (int)height;
+ file.BitDepth = depth;
+ file.ColorType = colorType;
+ file.Interlaced = payload[12] == 1;
+ }
+
+ private static void ReadPalette(PngFile file, ReadOnlySpan payload)
+ {
+ if (payload.Length == 0 || payload.Length % 3 != 0 || payload.Length > 256 * 3)
+ {
+ throw new ImageDecodeException("PNG danneggiato: PLTE della lunghezza sbagliata.");
+ }
+
+ if (file.ColorType is 0 or 4)
+ {
+ throw new ImageDecodeException("PNG danneggiato: PLTE in un'immagine in scala di grigi.");
+ }
+
+ if (file.ColorType != 3)
+ {
+ // A suggested palette for an RGB image: nothing to do with the pixels.
+ return;
+ }
+
+ var palette = new byte[256 * 4];
+ for (var i = 0; i < 256; i++)
+ {
+ palette[(i * 4) + 3] = 255;
+ }
+
+ var count = payload.Length / 3;
+ for (var i = 0; i < count; i++)
+ {
+ palette[i * 4] = payload[i * 3];
+ palette[(i * 4) + 1] = payload[(i * 3) + 1];
+ palette[(i * 4) + 2] = payload[(i * 3) + 2];
+ }
+
+ file.Palette = palette;
+ file.PaletteCount = count;
+ }
+
+ private static void ReadTransparency(PngFile file, ReadOnlySpan payload)
+ {
+ switch (file.ColorType)
+ {
+ case 0 when payload.Length >= 2:
+ file.HasColorKey = true;
+ file.KeyRed = file.KeyGreen = file.KeyBlue = BinaryPrimitives.ReadUInt16BigEndian(payload);
+ break;
+
+ case 2 when payload.Length >= 6:
+ file.HasColorKey = true;
+ file.KeyRed = BinaryPrimitives.ReadUInt16BigEndian(payload);
+ file.KeyGreen = BinaryPrimitives.ReadUInt16BigEndian(payload[2..]);
+ file.KeyBlue = BinaryPrimitives.ReadUInt16BigEndian(payload[4..]);
+ break;
+
+ case 3:
+ if (file.Palette is not { } palette)
+ {
+ throw new ImageDecodeException("PNG danneggiato: tRNS prima di PLTE.");
+ }
+
+ // Entries beyond the palette are ignored, as libpng does.
+ var count = Math.Min(payload.Length, file.PaletteCount);
+ for (var i = 0; i < count; i++)
+ {
+ palette[(i * 4) + 3] = payload[i];
+ }
+
+ file.HasPaletteAlpha = count > 0;
+ break;
+
+ default:
+ // tRNS is not allowed with an alpha channel; a short one is ignored.
+ break;
+ }
+ }
+
+ private static void ReadMetadata(PngFile file, string name, ReadOnlySpan payload, ref int budget)
+ {
+ // Damaged or oversized metadata is skipped: it must never stop an image from being shown.
+ switch (name)
+ {
+ case "eXIf":
+ if (file.Exif is null && payload.Length >= 4 && (payload[..4].SequenceEqual("II*\0"u8) || payload[..4].SequenceEqual("MM\0*"u8)) && Spend(ref budget, payload.Length))
+ {
+ file.Exif = payload.ToArray();
+ }
+
+ break;
+
+ case "iCCP":
+ {
+ var zero = payload.IndexOf((byte)0);
+ if (file.Icc is not null || zero is < 1 or > 79 || payload.Length < zero + 2 || payload[zero + 1] != 0)
+ {
+ break;
+ }
+
+ if (Inflate(payload[(zero + 2)..], budget) is { } profile && Spend(ref budget, profile.Length))
+ {
+ file.Icc = profile;
+ file.IccName = Encoding.Latin1.GetString(payload[..zero]);
+ }
+
+ break;
+ }
+
+ case "tEXt":
+ {
+ var zero = payload.IndexOf((byte)0);
+ if (zero is < 1 or > 79 || !Spend(ref budget, payload.Length))
+ {
+ break;
+ }
+
+ AddText(file, new ImageText(Encoding.Latin1.GetString(payload[..zero]), Encoding.Latin1.GetString(payload[(zero + 1)..])));
+ break;
+ }
+
+ case "zTXt":
+ {
+ var zero = payload.IndexOf((byte)0);
+ if (zero is < 1 or > 79 || payload.Length < zero + 2 || payload[zero + 1] != 0)
+ {
+ break;
+ }
+
+ if (Inflate(payload[(zero + 2)..], budget) is { } text && Spend(ref budget, text.Length))
+ {
+ AddText(file, new ImageText(Encoding.Latin1.GetString(payload[..zero]), Encoding.Latin1.GetString(text)));
+ }
+
+ break;
+ }
+
+ case "iTXt":
+ ReadInternationalText(file, payload, ref budget);
+ break;
+ }
+ }
+
+ private static void ReadInternationalText(PngFile file, ReadOnlySpan payload, ref int budget)
+ {
+ var zero = payload.IndexOf((byte)0);
+ if (zero is < 1 or > 79 || payload.Length < zero + 3)
+ {
+ return;
+ }
+
+ var keyword = Encoding.Latin1.GetString(payload[..zero]);
+ var compressed = payload[zero + 1];
+ var method = payload[zero + 2];
+ var rest = payload[(zero + 3)..];
+ var languageEnd = rest.IndexOf((byte)0);
+ if (languageEnd < 0)
+ {
+ return;
+ }
+
+ var language = Encoding.ASCII.GetString(rest[..languageEnd]);
+ rest = rest[(languageEnd + 1)..];
+ var translatedEnd = rest.IndexOf((byte)0);
+ if (translatedEnd < 0)
+ {
+ return;
+ }
+
+ string translated;
+ try
+ {
+ translated = StrictUtf8.GetString(rest[..translatedEnd]);
+ }
+ catch (DecoderFallbackException)
+ {
+ return;
+ }
+
+ rest = rest[(translatedEnd + 1)..];
+ byte[]? raw;
+ if (compressed == 0)
+ {
+ raw = Spend(ref budget, rest.Length) ? rest.ToArray() : null;
+ }
+ else if (compressed == 1 && method == 0)
+ {
+ raw = Inflate(rest, budget);
+ if (raw is not null && !Spend(ref budget, raw.Length))
+ {
+ raw = null;
+ }
+ }
+ else
+ {
+ return;
+ }
+
+ if (raw is null)
+ {
+ return;
+ }
+
+ string text;
+ try
+ {
+ text = StrictUtf8.GetString(raw);
+ }
+ catch (DecoderFallbackException)
+ {
+ return;
+ }
+
+ if (keyword == XmpKeyword)
+ {
+ file.Xmp ??= text;
+ return;
+ }
+
+ AddText(file, new ImageText(keyword, text, language, translated));
+ }
+
+ private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
+
+ private static void AddText(PngFile file, ImageText text) => (file.Texts ??= []).Add(text);
+
+ private static bool Spend(ref int budget, int bytes)
+ {
+ if (bytes > budget)
+ {
+ return false;
+ }
+
+ budget -= bytes;
+ return true;
+ }
+
+ /// Inflates a zlib stream of metadata; null when it is damaged or longer than .
+ internal static byte[]? Inflate(ReadOnlySpan compressed, int maxBytes)
+ {
+ try
+ {
+ using var input = new MemoryStream(compressed.ToArray(), writable: false);
+ using var zlib = new ZLibStream(input, CompressionMode.Decompress);
+ using var output = new MemoryStream();
+ var buffer = new byte[16 * 1024];
+ int read;
+ while ((read = zlib.Read(buffer)) > 0)
+ {
+ if (output.Length + read > maxBytes)
+ {
+ return null;
+ }
+
+ output.Write(buffer, 0, read);
+ }
+
+ return output.ToArray();
+ }
+ catch (InvalidDataException)
+ {
+ return null;
+ }
+ }
+
+ private static long RowBytes(PngFile file, int width) => (((long)width * file.BitsPerPixel) + 7) / 8;
+
+ private static RgbaImage DecodePixels(ReadOnlyMemory data, PngFile file, ImageLimits limits, bool pooled)
+ {
+ limits.CheckSize(file.Width, file.Height);
+ var maxRow = RowBytes(file, file.Width);
+ limits.CheckWorkingBytes(2 * (maxRow + 1));
+ var image = RgbaImage.Create(file.Width, file.Height, limits, pooled);
+ var current = ArrayPool.Shared.Rent((int)maxRow + 1);
+ var previous = ArrayPool.Shared.Rent((int)maxRow + 1);
+ try
+ {
+ using var zlib = new ZLibStream(new SegmentStream(data, file.Idat), CompressionMode.Decompress);
+ var bpp = Math.Max(1, file.BitsPerPixel / 8);
+ var pixels = image.Pixels;
+ var stride = image.Stride;
+ if (!file.Interlaced)
+ {
+ DecodePass(zlib, file, file.Width, file.Height, bpp, current, previous, pixels, 0, stride, RgbaImage.BytesPerPixel);
+ }
+ else
+ {
+ var adam7 = Adam7;
+ for (var pass = 0; pass < 7; pass++)
+ {
+ int x0 = adam7[pass * 4], y0 = adam7[(pass * 4) + 1], dx = adam7[(pass * 4) + 2], dy = adam7[(pass * 4) + 3];
+ var passWidth = file.Width > x0 ? (file.Width - x0 + dx - 1) / dx : 0;
+ var passHeight = file.Height > y0 ? (file.Height - y0 + dy - 1) / dy : 0;
+ if (passWidth == 0 || passHeight == 0)
+ {
+ continue;
+ }
+
+ DecodePass(zlib, file, passWidth, passHeight, bpp, current, previous, pixels, (y0 * stride) + (x0 * RgbaImage.BytesPerPixel), dy * stride, dx * RgbaImage.BytesPerPixel);
+ }
+ }
+
+ return image;
+ }
+ catch (InvalidDataException ex)
+ {
+ image.Dispose();
+ throw new ImageDecodeException("PNG danneggiato: i dati compressi dell'immagine non sono validi.", ex);
+ }
+ catch (EndOfStreamException ex)
+ {
+ image.Dispose();
+ throw new ImageDecodeException("PNG troncato: i dati dell'immagine finiscono prima dell'ultima riga.", ex);
+ }
+ catch
+ {
+ image.Dispose();
+ throw;
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(current);
+ ArrayPool.Shared.Return(previous);
+ }
+ }
+
+ private static void DecodePass(
+ ZLibStream zlib,
+ PngFile file,
+ int width,
+ int height,
+ int bpp,
+ byte[] current,
+ byte[] previous,
+ Span pixels,
+ int firstOffset,
+ int rowStep,
+ int pixelStep)
+ {
+ var rowBytes = (int)RowBytes(file, width);
+ var prev = previous.AsSpan(0, rowBytes + 1);
+ var cur = current.AsSpan(0, rowBytes + 1);
+ prev.Clear();
+ var offset = firstOffset;
+ for (var y = 0; y < height; y++)
+ {
+ zlib.ReadExactly(cur);
+ var filter = cur[0];
+ var row = cur[1..];
+ Unfilter(filter, row, prev[1..], bpp);
+ ConvertRow(file, row, width, pixels[offset..], pixelStep);
+ offset += rowStep;
+
+ var swap = cur;
+ cur = prev;
+ prev = swap;
+ }
+ }
+
+ /// Undoes the row filter (PNG specification §7.3, §9.2): is changed in place.
+ internal static void Unfilter(byte filter, Span row, ReadOnlySpan previous, int bpp)
+ {
+ var n = row.Length;
+ switch (filter)
+ {
+ case 0:
+ return;
+
+ case 1:
+ for (var i = bpp; i < n; i++)
+ {
+ row[i] += row[i - bpp];
+ }
+
+ return;
+
+ case 2:
+ {
+ var i = 0;
+ if (Vector.IsHardwareAccelerated)
+ {
+ var width = Vector.Count;
+ for (; i + width <= n; i += width)
+ {
+ (new Vector(row[i..]) + new Vector(previous[i..])).CopyTo(row[i..]);
+ }
+ }
+
+ for (; i < n; i++)
+ {
+ row[i] += previous[i];
+ }
+
+ return;
+ }
+
+ case 3:
+ for (var i = 0; i < bpp && i < n; i++)
+ {
+ row[i] += (byte)(previous[i] >> 1);
+ }
+
+ for (var i = bpp; i < n; i++)
+ {
+ row[i] += (byte)((row[i - bpp] + previous[i]) >> 1);
+ }
+
+ return;
+
+ case 4:
+ for (var i = 0; i < bpp && i < n; i++)
+ {
+ row[i] += previous[i];
+ }
+
+ for (var i = bpp; i < n; i++)
+ {
+ row[i] += Paeth(row[i - bpp], previous[i], previous[i - bpp]);
+ }
+
+ return;
+
+ default:
+ throw new ImageDecodeException($"PNG danneggiato: filtro di riga sconosciuto ({filter}).");
+ }
+ }
+
+ /// The Paeth predictor (PNG specification §9.4).
+ internal static byte Paeth(byte a, byte b, byte c)
+ {
+ var pa = Math.Abs(b - c);
+ var pb = Math.Abs(a - c);
+ var pc = Math.Abs(a + b - c - c);
+ if (pa <= pb && pa <= pc)
+ {
+ return a;
+ }
+
+ return pb <= pc ? b : c;
+ }
+
+ /// Converts pixels of an unfiltered row to RGBA8, one pixel every bytes.
+ private static void ConvertRow(PngFile file, ReadOnlySpan row, int count, Span dest, int step)
+ {
+ var depth = file.BitDepth;
+ switch (file.ColorType)
+ {
+ case 3:
+ ConvertIndexed(row, count, dest, step, depth, file.Palette!);
+ return;
+
+ case 0 when depth < 8:
+ ConvertLowGrey(row, count, dest, step, depth, file.HasColorKey ? file.KeyGreen : -1);
+ return;
+
+ case 0 when depth == 8:
+ {
+ var key = file.HasColorKey ? file.KeyGreen : -1;
+ for (int i = 0, d = 0; i < count; i++, d += step)
+ {
+ var g = row[i];
+ dest[d] = g;
+ dest[d + 1] = g;
+ dest[d + 2] = g;
+ dest[d + 3] = g == key ? (byte)0 : (byte)255;
+ }
+
+ return;
+ }
+
+ case 0:
+ {
+ var key = file.HasColorKey ? file.KeyGreen : -1;
+ for (int i = 0, d = 0; i < count; i++, d += step)
+ {
+ var v = BinaryPrimitives.ReadUInt16BigEndian(row[(i * 2)..]);
+ var g = (byte)(v >> 8);
+ dest[d] = g;
+ dest[d + 1] = g;
+ dest[d + 2] = g;
+ dest[d + 3] = v == key ? (byte)0 : (byte)255;
+ }
+
+ return;
+ }
+
+ case 2 when depth == 8:
+ {
+ var hasKey = file.HasColorKey;
+ int kr = file.KeyRed, kg = file.KeyGreen, kb = file.KeyBlue;
+ for (int i = 0, s = 0, d = 0; i < count; i++, s += 3, d += step)
+ {
+ byte r = row[s], g = row[s + 1], b = row[s + 2];
+ dest[d] = r;
+ dest[d + 1] = g;
+ dest[d + 2] = b;
+ dest[d + 3] = hasKey && r == kr && g == kg && b == kb ? (byte)0 : (byte)255;
+ }
+
+ return;
+ }
+
+ case 2:
+ {
+ var hasKey = file.HasColorKey;
+ int kr = file.KeyRed, kg = file.KeyGreen, kb = file.KeyBlue;
+ for (int i = 0, s = 0, d = 0; i < count; i++, s += 6, d += step)
+ {
+ var r = BinaryPrimitives.ReadUInt16BigEndian(row[s..]);
+ var g = BinaryPrimitives.ReadUInt16BigEndian(row[(s + 2)..]);
+ var b = BinaryPrimitives.ReadUInt16BigEndian(row[(s + 4)..]);
+ dest[d] = (byte)(r >> 8);
+ dest[d + 1] = (byte)(g >> 8);
+ dest[d + 2] = (byte)(b >> 8);
+ dest[d + 3] = hasKey && r == kr && g == kg && b == kb ? (byte)0 : (byte)255;
+ }
+
+ return;
+ }
+
+ case 4 when depth == 8:
+ for (int i = 0, s = 0, d = 0; i < count; i++, s += 2, d += step)
+ {
+ var g = row[s];
+ dest[d] = g;
+ dest[d + 1] = g;
+ dest[d + 2] = g;
+ dest[d + 3] = row[s + 1];
+ }
+
+ return;
+
+ case 4:
+ for (int i = 0, s = 0, d = 0; i < count; i++, s += 4, d += step)
+ {
+ var g = row[s];
+ dest[d] = g;
+ dest[d + 1] = g;
+ dest[d + 2] = g;
+ dest[d + 3] = row[s + 2];
+ }
+
+ return;
+
+ case 6 when depth == 8:
+ if (step == RgbaImage.BytesPerPixel)
+ {
+ row[..(count * 4)].CopyTo(dest);
+ return;
+ }
+
+ for (int i = 0, s = 0, d = 0; i < count; i++, s += 4, d += step)
+ {
+ MemoryMarshal.Write(dest[d..], MemoryMarshal.Read(row[s..]));
+ }
+
+ return;
+
+ default:
+ for (int i = 0, s = 0, d = 0; i < count; i++, s += 8, d += step)
+ {
+ dest[d] = row[s];
+ dest[d + 1] = row[s + 2];
+ dest[d + 2] = row[s + 4];
+ dest[d + 3] = row[s + 6];
+ }
+
+ return;
+ }
+ }
+
+ private static void ConvertIndexed(ReadOnlySpan row, int count, Span dest, int step, int depth, byte[] palette)
+ {
+ if (depth == 8)
+ {
+ for (int i = 0, d = 0; i < count; i++, d += step)
+ {
+ MemoryMarshal.Write(dest[d..], MemoryMarshal.Read(palette.AsSpan(row[i] * 4)));
+ }
+
+ return;
+ }
+
+ var mask = (1 << depth) - 1;
+ var perByte = 8 / depth;
+ for (int i = 0, d = 0; i < count; i++, d += step)
+ {
+ var shift = 8 - depth - ((i % perByte) * depth);
+ var index = (row[i / perByte] >> shift) & mask;
+ MemoryMarshal.Write(dest[d..], MemoryMarshal.Read(palette.AsSpan(index * 4)));
+ }
+ }
+
+ private static void ConvertLowGrey(ReadOnlySpan row, int count, Span dest, int step, int depth, int key)
+ {
+ var mask = (1 << depth) - 1;
+ var scale = 255 / mask;
+ var perByte = 8 / depth;
+ for (int i = 0, d = 0; i < count; i++, d += step)
+ {
+ var shift = 8 - depth - ((i % perByte) * depth);
+ var v = (row[i / perByte] >> shift) & mask;
+ var g = (byte)(v * scale);
+ dest[d] = g;
+ dest[d + 1] = g;
+ dest[d + 2] = g;
+ dest[d + 3] = v == key ? (byte)0 : (byte)255;
+ }
+ }
+}
diff --git a/src/Febe.Core/Codecs/Images/PngEncoder.cs b/src/Febe.Core/Codecs/Images/PngEncoder.cs
new file mode 100644
index 0000000..431056d
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/PngEncoder.cs
@@ -0,0 +1,402 @@
+using System.Buffers;
+using System.Buffers.Binary;
+using System.IO.Compression;
+using System.Text;
+
+namespace Febe.Core.Codecs.Images;
+
+/// What writes for the pixels.
+public enum PngColorMode
+{
+ /// RGB when every pixel is opaque, RGBA otherwise.
+ Auto,
+
+ /// 8-bit RGB (colour type 2): alpha is dropped.
+ Rgb,
+
+ /// 8-bit RGBA (colour type 6).
+ Rgba,
+}
+
+/// How picks the filter of each row.
+public enum PngFilterStrategy
+{
+ ///
+ /// For each row the filter whose output has the smallest sum of absolute values, read as signed bytes (the
+ /// heuristic the PNG specification suggests in §12.8).
+ ///
+ Adaptive,
+ None,
+ Sub,
+ Up,
+ Average,
+ Paeth,
+}
+
+/// Options of .
+public sealed record PngEncoderOptions
+{
+ /// The options used when a caller passes none.
+ public static PngEncoderOptions Default { get; } = new();
+
+ public PngColorMode ColorMode { get; init; } = PngColorMode.Auto;
+
+ public PngFilterStrategy Filter { get; init; } = PngFilterStrategy.Adaptive;
+
+ public CompressionLevel CompressionLevel { get; init; } = CompressionLevel.Optimal;
+
+ ///
+ /// EXIF to write in an eXIf chunk: a TIFF structure («II*\0» or «MM\0*»), optionally preceded by the «Exif\0\0»
+ /// of a JPEG APP1 segment, which is removed.
+ ///
+ public byte[]? Exif { get; init; }
+
+ /// ICC profile to write, compressed, in an iCCP chunk.
+ public byte[]? IccProfile { get; init; }
+
+ /// Name of the profile in the iCCP chunk: 1 to 79 Latin-1 characters.
+ public string IccProfileName { get; init; } = "ICC Profile";
+
+ /// XMP packet to write in an uncompressed iTXt chunk with the keyword «XML:com.adobe.xmp».
+ public string? Xmp { get; init; }
+}
+
+///
+/// Writes 8-bit RGB or RGBA PNG files (W3C PNG specification): one zlib stream (System.IO.Compression) split into IDAT
+/// chunks of 64 KiB, the filter of each row chosen by , optional eXIf, iCCP and XMP.
+///
+public static class PngEncoder
+{
+ private const int IdatChunkSize = 64 * 1024;
+
+ /// The PNG file of .
+ public static byte[] Encode(RgbaImage image, PngEncoderOptions? options = null)
+ {
+ using var output = new MemoryStream();
+ Encode(image, output, options);
+ return output.ToArray();
+ }
+
+ /// Writes the PNG file of to .
+ public static void Encode(RgbaImage image, Stream output, PngEncoderOptions? options = null)
+ {
+ ArgumentNullException.ThrowIfNull(image);
+ ArgumentNullException.ThrowIfNull(output);
+ options ??= PngEncoderOptions.Default;
+ var exif = options.Exif is { } givenExif ? ExifPayload(givenExif) : null;
+ var iccName = options.IccProfile is null ? null : IccName(options.IccProfileName);
+
+ var alpha = options.ColorMode switch
+ {
+ PngColorMode.Rgb => false,
+ PngColorMode.Rgba => true,
+ _ => !image.IsOpaque(),
+ };
+
+ output.Write(ImageFormatSniffer.PngSignature);
+
+ Span header = stackalloc byte[13];
+ BinaryPrimitives.WriteUInt32BigEndian(header, (uint)image.Width);
+ BinaryPrimitives.WriteUInt32BigEndian(header[4..], (uint)image.Height);
+ header[8] = 8;
+ header[9] = alpha ? (byte)6 : (byte)2;
+ header[10] = 0;
+ header[11] = 0;
+ header[12] = 0;
+ WriteChunk(output, "IHDR"u8, header);
+
+ if (options.IccProfile is { } profile)
+ {
+ using var payload = new MemoryStream();
+ payload.Write(iccName);
+ payload.WriteByte(0);
+ payload.WriteByte(0);
+ using (var zlib = new ZLibStream(payload, options.CompressionLevel, leaveOpen: true))
+ {
+ zlib.Write(profile);
+ }
+
+ WriteChunk(output, "iCCP"u8, payload.GetBuffer().AsSpan(0, (int)payload.Length));
+ }
+
+ if (exif is not null)
+ {
+ WriteChunk(output, "eXIf"u8, exif);
+ }
+
+ if (options.Xmp is { } xmp)
+ {
+ using var payload = new MemoryStream();
+ payload.Write("XML:com.adobe.xmp"u8);
+ payload.Write([0, 0, 0, 0, 0]); // end of keyword, not compressed, method, empty language, empty translation
+ payload.Write(Encoding.UTF8.GetBytes(xmp));
+ WriteChunk(output, "iTXt"u8, payload.GetBuffer().AsSpan(0, (int)payload.Length));
+ }
+
+ using (var idat = new IdatStream(output))
+ {
+ using (var zlib = new ZLibStream(idat, options.CompressionLevel, leaveOpen: true))
+ {
+ WriteRows(image, zlib, alpha, options.Filter);
+ }
+
+ idat.Complete();
+ }
+
+ WriteChunk(output, "IEND"u8, []);
+ }
+
+ private static void WriteRows(RgbaImage image, Stream zlib, bool alpha, PngFilterStrategy strategy)
+ {
+ var bpp = alpha ? 4 : 3;
+ var rowBytes = image.Width * bpp;
+ var pool = ArrayPool.Shared;
+ var raw = pool.Rent(rowBytes);
+ var previous = pool.Rent(rowBytes);
+ var candidates = pool.Rent((rowBytes + 1) * 5);
+ try
+ {
+ var prev = previous.AsSpan(0, rowBytes);
+ prev.Clear();
+ for (var y = 0; y < image.Height; y++)
+ {
+ var source = image.GetRow(y);
+ var row = raw.AsSpan(0, rowBytes);
+ if (alpha)
+ {
+ source.CopyTo(row);
+ }
+ else
+ {
+ for (int s = 0, d = 0; d < rowBytes; s += 4, d += 3)
+ {
+ row[d] = source[s];
+ row[d + 1] = source[s + 1];
+ row[d + 2] = source[s + 2];
+ }
+ }
+
+ ReadOnlySpan chosen;
+ if (strategy == PngFilterStrategy.Adaptive)
+ {
+ var best = -1L;
+ chosen = default;
+ for (var filter = 0; filter < 5; filter++)
+ {
+ var output = candidates.AsSpan(filter * (rowBytes + 1), rowBytes + 1);
+ var sum = Filter((byte)filter, row, prev, bpp, output);
+ if (best < 0 || sum < best)
+ {
+ best = sum;
+ chosen = output;
+ }
+ }
+ }
+ else
+ {
+ var output = candidates.AsSpan(0, rowBytes + 1);
+ Filter((byte)(strategy - PngFilterStrategy.None), row, prev, bpp, output);
+ chosen = output;
+ }
+
+ zlib.Write(chosen);
+ row.CopyTo(prev);
+ }
+ }
+ finally
+ {
+ pool.Return(raw);
+ pool.Return(previous);
+ pool.Return(candidates);
+ }
+ }
+
+ ///
+ /// Writes the filter byte and the filtered row to and returns the sum of the absolute
+ /// values of the filtered bytes, read as signed.
+ ///
+ internal static long Filter(byte filter, ReadOnlySpan row, ReadOnlySpan previous, int bpp, Span output)
+ {
+ output[0] = filter;
+ var o = output[1..];
+ var n = row.Length;
+ long sum = 0;
+ switch (filter)
+ {
+ case 0:
+ row.CopyTo(o);
+ for (var i = 0; i < n; i++)
+ {
+ sum += Math.Abs((int)(sbyte)row[i]);
+ }
+
+ break;
+
+ case 1:
+ for (var i = 0; i < n; i++)
+ {
+ var v = (byte)(row[i] - (i >= bpp ? row[i - bpp] : 0));
+ o[i] = v;
+ sum += Math.Abs((int)(sbyte)v);
+ }
+
+ break;
+
+ case 2:
+ for (var i = 0; i < n; i++)
+ {
+ var v = (byte)(row[i] - previous[i]);
+ o[i] = v;
+ sum += Math.Abs((int)(sbyte)v);
+ }
+
+ break;
+
+ case 3:
+ for (var i = 0; i < n; i++)
+ {
+ var left = i >= bpp ? row[i - bpp] : 0;
+ var v = (byte)(row[i] - ((left + previous[i]) >> 1));
+ o[i] = v;
+ sum += Math.Abs((int)(sbyte)v);
+ }
+
+ break;
+
+ default:
+ for (var i = 0; i < n; i++)
+ {
+ var left = i >= bpp ? row[i - bpp] : (byte)0;
+ var upLeft = i >= bpp ? previous[i - bpp] : (byte)0;
+ var v = (byte)(row[i] - PngDecoder.Paeth(left, previous[i], upLeft));
+ o[i] = v;
+ sum += Math.Abs((int)(sbyte)v);
+ }
+
+ break;
+ }
+
+ return sum;
+ }
+
+ private static byte[] ExifPayload(byte[] exif)
+ {
+ ReadOnlySpan span = exif;
+ if (span.StartsWith("Exif\0\0"u8))
+ {
+ span = span[6..];
+ }
+
+ if (span.Length < 8 || !(span.StartsWith("II*\0"u8) || span.StartsWith("MM\0*"u8)))
+ {
+ throw new ArgumentException("EXIF must be a TIFF structure starting with «II*\\0» or «MM\\0*».", nameof(exif));
+ }
+
+ return span.ToArray();
+ }
+
+ private static byte[] IccName(string name)
+ {
+ if (name.Length is < 1 or > 79 || name[0] == ' ' || name[^1] == ' ')
+ {
+ throw new ArgumentException("The profile name must have 1 to 79 characters, without leading or trailing spaces.", nameof(name));
+ }
+
+ foreach (var c in name)
+ {
+ if (c is < ' ' or (> '~' and < '¡') or > 'ÿ')
+ {
+ throw new ArgumentException("The profile name must be printable Latin-1.", nameof(name));
+ }
+ }
+
+ return Encoding.Latin1.GetBytes(name);
+ }
+
+ private static void WriteChunk(Stream output, ReadOnlySpan type, ReadOnlySpan payload)
+ {
+ Span word = stackalloc byte[4];
+ BinaryPrimitives.WriteUInt32BigEndian(word, (uint)payload.Length);
+ output.Write(word);
+ output.Write(type);
+ output.Write(payload);
+ BinaryPrimitives.WriteUInt32BigEndian(word, Crc32.Append(Crc32.Compute(type), payload));
+ output.Write(word);
+ }
+
+ /// Collects the zlib stream and writes it out as IDAT chunks of bytes.
+ private sealed class IdatStream(Stream output) : Stream
+ {
+ private readonly byte[] _buffer = ArrayPool.Shared.Rent(IdatChunkSize);
+ private int _count;
+ private bool _returned;
+
+ public override bool CanRead => false;
+
+ public override bool CanSeek => false;
+
+ public override bool CanWrite => true;
+
+ public override long Length => throw new NotSupportedException();
+
+ public override long Position
+ {
+ get => throw new NotSupportedException();
+ set => throw new NotSupportedException();
+ }
+
+ public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
+
+ public override void Write(ReadOnlySpan buffer)
+ {
+ while (buffer.Length > 0)
+ {
+ var n = Math.Min(IdatChunkSize - _count, buffer.Length);
+ buffer[..n].CopyTo(_buffer.AsSpan(_count));
+ _count += n;
+ buffer = buffer[n..];
+ if (_count == IdatChunkSize)
+ {
+ Emit();
+ }
+ }
+ }
+
+ /// Writes the last, shorter chunk.
+ public void Complete()
+ {
+ if (_count > 0)
+ {
+ Emit();
+ }
+ }
+
+ public override void Flush()
+ {
+ // Chunks are written when full or at Complete: a flush of the zlib stream must not cut a chunk.
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ protected override void Dispose(bool disposing)
+ {
+ if (!_returned)
+ {
+ _returned = true;
+ ArrayPool.Shared.Return(_buffer);
+ }
+
+ base.Dispose(disposing);
+ }
+
+ private void Emit()
+ {
+ WriteChunk(output, "IDAT"u8, _buffer.AsSpan(0, _count));
+ _count = 0;
+ }
+ }
+}
diff --git a/src/Febe.Core/Codecs/Images/RgbaImage.cs b/src/Febe.Core/Codecs/Images/RgbaImage.cs
new file mode 100644
index 0000000..3dc2903
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/RgbaImage.cs
@@ -0,0 +1,145 @@
+using System.Buffers;
+
+namespace Febe.Core.Codecs.Images;
+
+///
+/// A decoded image: × pixels, top row first, each pixel four bytes R, G, B, A
+/// (8 bits each, alpha not premultiplied: the colour under an alpha of 0 is kept as the file had it).
+///
+///
+/// The pixels live either in an array of exactly the right size () or in an array
+/// rented from (), which gives back; a pooled
+/// image must not be used after that. Disposing an image that owns its array does nothing, so callers can always
+/// dispose.
+///
+public sealed class RgbaImage : IDisposable
+{
+ /// Bytes of one pixel.
+ public const int BytesPerPixel = 4;
+
+ private byte[]? _buffer;
+ private readonly bool _pooled;
+
+ /// A new image, every pixel (0, 0, 0, 0).
+ public RgbaImage(int width, int height)
+ : this(width, height, new byte[CheckedLength(width, height)], pooled: false)
+ {
+ }
+
+ /// An image over , which must hold exactly width × height × 4 bytes; not copied.
+ public RgbaImage(int width, int height, byte[] pixels)
+ : this(width, height, pixels ?? throw new ArgumentNullException(nameof(pixels)), pooled: false)
+ {
+ if (pixels.Length != CheckedLength(width, height))
+ {
+ throw new ArgumentException($"Expected {CheckedLength(width, height)} bytes, got {pixels.Length}.", nameof(pixels));
+ }
+ }
+
+ private RgbaImage(int width, int height, byte[] buffer, bool pooled)
+ {
+ Width = width;
+ Height = height;
+ Length = width * height * BytesPerPixel;
+ _buffer = buffer;
+ _pooled = pooled;
+ }
+
+ ///
+ /// A new image whose pixels come from the shared array pool, every pixel (0, 0, 0, 0). Give it back with
+ /// .
+ ///
+ public static RgbaImage Rent(int width, int height)
+ {
+ var length = CheckedLength(width, height);
+ var buffer = ArrayPool.Shared.Rent(length);
+ buffer.AsSpan(0, length).Clear();
+ return new RgbaImage(width, height, buffer, pooled: true);
+ }
+
+ /// A new image for a decoder: size checked against , pooled or not.
+ internal static RgbaImage Create(int width, int height, ImageLimits limits, bool pooled)
+ {
+ limits.CheckSize(width, height);
+ return pooled ? Rent(width, height) : new RgbaImage(width, height);
+ }
+
+ /// Width in pixels.
+ public int Width { get; }
+
+ /// Height in pixels.
+ public int Height { get; }
+
+ /// Bytes of one row ( × 4).
+ public int Stride => Width * BytesPerPixel;
+
+ /// Bytes of the whole image.
+ public int Length { get; }
+
+ /// Whether the pixels come from the array pool.
+ public bool IsPooled => _pooled;
+
+ /// All the pixels, row after row.
+ public Span Pixels => Buffer.AsSpan(0, Length);
+
+ /// The pixels of row (0 is the top row).
+ public Span GetRow(int y)
+ {
+ ArgumentOutOfRangeException.ThrowIfNegative(y);
+ ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(y, Height);
+ return Buffer.AsSpan(y * Stride, Stride);
+ }
+
+ /// The pixel at (, ) as R, G, B, A.
+ public (byte R, byte G, byte B, byte A) GetPixel(int x, int y)
+ {
+ ArgumentOutOfRangeException.ThrowIfNegative(x);
+ ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(x, Width);
+ var row = GetRow(y);
+ var i = x * BytesPerPixel;
+ return (row[i], row[i + 1], row[i + 2], row[i + 3]);
+ }
+
+ /// Whether every pixel has alpha 255.
+ public bool IsOpaque()
+ {
+ var pixels = Pixels;
+ for (var i = 3; i < pixels.Length; i += BytesPerPixel)
+ {
+ if (pixels[i] != 255)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /// A copy of the pixels in an array of exactly bytes.
+ public byte[] ToArray() => Pixels.ToArray();
+
+ /// Gives a pooled array back to the pool; the image cannot be used afterwards.
+ public void Dispose()
+ {
+ if (_pooled && _buffer is { } buffer)
+ {
+ _buffer = null;
+ ArrayPool.Shared.Return(buffer);
+ }
+ }
+
+ private byte[] Buffer => _buffer ?? throw new ObjectDisposedException(nameof(RgbaImage));
+
+ private static int CheckedLength(int width, int height)
+ {
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
+ var length = (long)width * height * BytesPerPixel;
+ if (length > Array.MaxLength)
+ {
+ throw new ArgumentOutOfRangeException(nameof(width), $"An image of {width}×{height} does not fit in one array.");
+ }
+
+ return (int)length;
+ }
+}
diff --git a/src/Febe.Core/Codecs/Images/SegmentStream.cs b/src/Febe.Core/Codecs/Images/SegmentStream.cs
new file mode 100644
index 0000000..fd8e3fe
--- /dev/null
+++ b/src/Febe.Core/Codecs/Images/SegmentStream.cs
@@ -0,0 +1,66 @@
+namespace Febe.Core.Codecs.Images;
+
+///
+/// A read-only stream over pieces of one buffer read one after the other, without copying them: the IDAT chunks of a
+/// PNG, which together are a single zlib stream.
+///
+internal sealed class SegmentStream(ReadOnlyMemory data, IReadOnlyList<(int Start, int Length)> segments) : Stream
+{
+ private int _segment;
+ private int _offset;
+
+ public override bool CanRead => true;
+
+ public override bool CanSeek => false;
+
+ public override bool CanWrite => false;
+
+ public override long Length => throw new NotSupportedException();
+
+ public override long Position
+ {
+ get => throw new NotSupportedException();
+ set => throw new NotSupportedException();
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));
+
+ public override int Read(Span buffer)
+ {
+ var written = 0;
+ while (written < buffer.Length && _segment < segments.Count)
+ {
+ var (start, length) = segments[_segment];
+ var available = length - _offset;
+ if (available == 0)
+ {
+ _segment++;
+ _offset = 0;
+ continue;
+ }
+
+ var n = Math.Min(available, buffer.Length - written);
+ data.Span.Slice(start + _offset, n).CopyTo(buffer[written..]);
+ _offset += n;
+ written += n;
+ }
+
+ return written;
+ }
+
+ public override int ReadByte()
+ {
+ Span one = stackalloc byte[1];
+ return Read(one) == 1 ? one[0] : -1;
+ }
+
+ public override void Flush()
+ {
+ }
+
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+}
diff --git a/tests/Febe.Tests/Imaging/BmpDecoderTests.cs b/tests/Febe.Tests/Imaging/BmpDecoderTests.cs
new file mode 100644
index 0000000..7829d36
--- /dev/null
+++ b/tests/Febe.Tests/Imaging/BmpDecoderTests.cs
@@ -0,0 +1,172 @@
+using Febe.Core.Codecs.Images;
+using static Febe.Tests.Imaging.TestImages;
+
+namespace Febe.Tests.Imaging;
+
+/// The in-house BMP decoder on files built by hand: variants the reference set lacks, and damage.
+[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
+ {
+ ["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(() => BmpDecoder.Decode(bytes), name);
+ }
+ else
+ {
+ Assert.Throws(() => BmpDecoder.Decode(bytes), name);
+ }
+ }
+ }
+
+ [TestMethod]
+ public void AnImageBeyondTheLimitsIsRefusedButStillIdentified()
+ {
+ var bmp = Bmp(40, 100_000, 1, 24, BiRgb, [], new byte[4]);
+ Assert.ThrowsExactly(() => 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;
+ }
+}
diff --git a/tests/Febe.Tests/Imaging/GifDecoderTests.cs b/tests/Febe.Tests/Imaging/GifDecoderTests.cs
new file mode 100644
index 0000000..43e61d3
--- /dev/null
+++ b/tests/Febe.Tests/Imaging/GifDecoderTests.cs
@@ -0,0 +1,192 @@
+using Febe.Core.Codecs.Images;
+using static Febe.Tests.Imaging.TestImages;
+
+namespace Febe.Tests.Imaging;
+
+/// The in-house GIF decoder on files built from GIF89a: palettes, transparency, clipping, damage.
+[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
+ {
+ ["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(() => GifDecoder.Decode(bytes), name);
+ }
+ }
+
+ [TestMethod]
+ public void ACanvasBeyondTheLimitsIsRefusedButStillIdentified()
+ {
+ var gif = Gif(60000, 60000, Palette4, GifFrame(0, 0, 1, 1, [1], 2));
+ Assert.ThrowsExactly(() => GifDecoder.Decode(gif));
+ Assert.AreEqual((60000, 60000), (GifDecoder.Identify(gif).Width, GifDecoder.Identify(gif).Height));
+ }
+}
diff --git a/tests/Febe.Tests/Imaging/ImageAssert.cs b/tests/Febe.Tests/Imaging/ImageAssert.cs
new file mode 100644
index 0000000..c2cbf4b
--- /dev/null
+++ b/tests/Febe.Tests/Imaging/ImageAssert.cs
@@ -0,0 +1,43 @@
+using Febe.Core.Codecs.Images;
+
+namespace Febe.Tests.Imaging;
+
+/// Comparisons of decoded images that say where they differ.
+internal static class ImageAssert
+{
+ /// Same size and the same bytes in every pixel.
+ 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);
+ }
+
+ /// The same RGBA bytes, for images of the given width.
+ public static void AreEqual(int width, ReadOnlySpan expected, ReadOnlySpan 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 rgba) => $"({rgba[0]}, {rgba[1]}, {rgba[2]}, {rgba[3]})";
+}
diff --git a/tests/Febe.Tests/Imaging/ImageFuzzTests.cs b/tests/Febe.Tests/Imaging/ImageFuzzTests.cs
new file mode 100644
index 0000000..e36ba13
--- /dev/null
+++ b/tests/Febe.Tests/Imaging/ImageFuzzTests.cs
@@ -0,0 +1,127 @@
+using Febe.Core.Codecs.Images;
+
+namespace Febe.Tests.Imaging;
+
+///
+/// Damaged files from the reference set, changed at random with fixed seeds: a decoder either reads them or throws
+/// , never anything else (no index out of range, no overflow, no huge allocation).
+///
+[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