C1: codec delle immagini scritti in casa, SkiaSharp esce (#58) #62

Merged
Alby96 merged 11 commits from funzione/codec-immagini into main 2026-11-26 13:17:41 +01:00
23 changed files with 4382 additions and 4 deletions
Showing only changes of commit 8bf76f18ff - Show all commits

No files matched your search

+1
View File
@@ -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 |
+497
View File
@@ -0,0 +1,497 @@
using System.Buffers.Binary;
using System.Numerics;
namespace Febe.Core.Codecs.Images;
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>Whether the bytes start like a BMP file.</summary>
public static bool IsBmp(ReadOnlySpan<byte> data) =>
data.Length >= 18 && data[0] == (byte)'B' && data[1] == (byte)'M' && ImageFormatSniffer.IsBmpHeaderSize(BinaryPrimitives.ReadUInt32LittleEndian(data[14..]));
/// <summary>Size of a BMP, without decoding the pixels.</summary>
public static ImageInfo Identify(ReadOnlyMemory<byte> 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);
}
/// <summary>Decodes a BMP to straight RGBA8, top row first.</summary>
/// <exception cref="ImageDecodeException">The file is damaged, truncated or not a BMP.</exception>
/// <exception cref="ImageFormatNotSupportedException">A BMP variant Febe does not read (JPEG inside, OS/2 Huffman, 64 bits).</exception>
/// <exception cref="ImageLimitException">The image is larger than <paramref name="limits"/> allow.</exception>
public static RgbaImage Decode(ReadOnlyMemory<byte> 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;
}
}
/// <summary>Decodes a BMP and returns what <see cref="Identify"/> returns as well.</summary>
public static RgbaImage Decode(ReadOnlyMemory<byte> 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;
/// <summary>RGBA of each palette index (256 entries; those the file does not give are opaque black).</summary>
public uint[]? Palette;
public int Stride => (int)((((long)Width * BitsPerPixel) + 31) / 32 * 4);
}
private static BmpHeader ReadHeader(ReadOnlySpan<byte> 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<byte> 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<byte> red = stackalloc byte[256];
Span<byte> green = stackalloc byte[256];
Span<byte> blue = stackalloc byte[256];
Span<byte> 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;
}
}
}
/// <summary>
/// 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 <paramref name="table"/>. Wider masks keep their top 8 bits.
/// </summary>
private static (int Shift, int Bits) MaskShift(uint mask, Span<byte> 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<byte> 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<byte> 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;
}
}
}
}
}
+72
View File
@@ -0,0 +1,72 @@
using System.Buffers.Binary;
namespace Febe.Core.Codecs.Images;
/// <summary>
/// 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.
/// </summary>
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();
/// <summary>The CRC of <paramref name="data"/>.</summary>
public static uint Compute(ReadOnlySpan<byte> data) => Append(0, data);
/// <summary>The CRC of the bytes already summed into <paramref name="crc"/> followed by <paramref name="data"/>.</summary>
public static uint Append(uint crc, ReadOnlySpan<byte> 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;
}
}
+531
View File
@@ -0,0 +1,531 @@
using System.Buffers;
using System.Buffers.Binary;
using System.Text;
namespace Febe.Core.Codecs.Images;
/// <summary>
/// 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.
/// </summary>
public static class GifDecoder
{
private const int MaxCodeBits = 12;
private const int MaxCodes = 1 << MaxCodeBits;
/// <summary>Whether the bytes start with a GIF signature.</summary>
public static bool IsGif(ReadOnlySpan<byte> data) =>
data.Length >= 6 && data[..3].SequenceEqual("GIF"u8) && (data[3..6].SequenceEqual("89a"u8) || data[3..6].SequenceEqual("87a"u8));
/// <summary>Canvas size, frame count and comments of a GIF, without decoding the pixels.</summary>
public static ImageInfo Identify(ReadOnlyMemory<byte> data, ImageLimits? limits = null)
{
limits ??= ImageLimits.Default;
var file = Walk(data.Span, limits, countFrames: true);
return file.ToInfo();
}
/// <summary>Decodes the first frame of a GIF to straight RGBA8.</summary>
/// <exception cref="ImageDecodeException">The file is damaged, has no frame or is not a GIF.</exception>
/// <exception cref="ImageLimitException">The image is larger than <paramref name="limits"/> allow.</exception>
public static RgbaImage Decode(ReadOnlyMemory<byte> 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);
}
/// <summary>Decodes the first frame of a GIF and returns what <see cref="Identify"/> returns as well.</summary>
public static RgbaImage Decode(ReadOnlyMemory<byte> 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<ImageText>? 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<byte> 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<byte> 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<byte> 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<byte> 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<byte>.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<uint> colours = stackalloc uint[256];
Span<byte> 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<byte>.Shared.Return(indices);
}
}
/// <summary>The row of the image that the <paramref name="r"/>-th decoded row of an interlaced frame fills.</summary>
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);
}
/// <summary>
/// Decodes the LZW data sub-blocks that start at <paramref name="pos"/> into <paramref name="output"/> (GIF89a
/// appendix F: variable-length codes from <paramref name="minCodeSize"/> + 1 bits up to 12, least significant bit
/// first) and returns how many indices were written. A damaged stream stops the decoding there.
/// </summary>
internal static int DecodeLzw(ReadOnlySpan<byte> data, int pos, int minCodeSize, Span<byte> output)
{
var prefix = ArrayPool<ushort>.Shared.Rent(MaxCodes);
var lengths = ArrayPool<ushort>.Shared.Rent(MaxCodes);
var suffix = ArrayPool<byte>.Shared.Rent(MaxCodes);
var first = ArrayPool<byte>.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<ushort>.Shared.Return(prefix);
ArrayPool<ushort>.Shared.Return(lengths);
ArrayPool<byte>.Shared.Return(suffix);
ArrayPool<byte>.Shared.Return(first);
}
}
}
@@ -0,0 +1,58 @@
namespace Febe.Core.Codecs.Images;
/// <summary>
/// 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.
/// </summary>
public class ImageDecodeException : Exception
{
public ImageDecodeException()
{
}
public ImageDecodeException(string message)
: base(message)
{
}
public ImageDecodeException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>The image is well formed but larger than <see cref="ImageLimits"/> allows: it is not decoded.</summary>
public sealed class ImageLimitException : ImageDecodeException
{
public ImageLimitException()
{
}
public ImageLimitException(string message)
: base(message)
{
}
public ImageLimitException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>The format was recognised but Febe has no decoder for it (yet), or not for this variant of it.</summary>
public sealed class ImageFormatNotSupportedException : ImageDecodeException
{
public ImageFormatNotSupportedException()
{
}
public ImageFormatNotSupportedException(string message)
: base(message)
{
}
public ImageFormatNotSupportedException(string message, Exception innerException)
: base(message, innerException)
{
}
}
@@ -0,0 +1,41 @@
namespace Febe.Core.Codecs.Images;
/// <summary>
/// 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.
/// </summary>
public static class ImageDecoder
{
/// <summary>Whether Febe has a decoder for <paramref name="format"/>.</summary>
public static bool CanDecode(ImageFormat format) => format is ImageFormat.Png or ImageFormat.Gif or ImageFormat.Bmp;
/// <summary>Size, frames and metadata of an image, without decoding the pixels.</summary>
/// <exception cref="ImageFormatNotSupportedException">The format is not known or has no decoder yet.</exception>
/// <exception cref="ImageDecodeException">The file is damaged.</exception>
public static ImageInfo Identify(ReadOnlyMemory<byte> 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),
};
/// <summary>Decodes an image to straight RGBA8 (the first frame of an animation).</summary>
/// <exception cref="ImageFormatNotSupportedException">The format is not known or has no decoder yet.</exception>
/// <exception cref="ImageDecodeException">The file is damaged.</exception>
/// <exception cref="ImageLimitException">The image is larger than <paramref name="limits"/> allow.</exception>
public static RgbaImage Decode(ReadOnlyMemory<byte> 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()}.");
}
@@ -0,0 +1,85 @@
using System.Buffers.Binary;
namespace Febe.Core.Codecs.Images;
/// <summary>Image formats Febe recognises from their first bytes (not all of them can be decoded).</summary>
public enum ImageFormat
{
Unknown,
Png,
Jpeg,
Gif,
Bmp,
WebP,
Tiff,
/// <summary>HEIF with HEVC pictures (HEIC), or a generic HEIF.</summary>
Heif,
/// <summary>HEIF with AV1 pictures.</summary>
Avif,
}
/// <summary>Recognises an image format from the first bytes of a file.</summary>
public static class ImageFormatSniffer
{
/// <summary>Bytes <see cref="Detect"/> needs to tell every format apart; fewer are fine for most formats.</summary>
public const int HeaderLength = 32;
/// <summary>The format the bytes start with, or <see cref="ImageFormat.Unknown"/>.</summary>
public static ImageFormat Detect(ReadOnlySpan<byte> 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;
}
/// <summary>The eight bytes every PNG file starts with.</summary>
internal static ReadOnlySpan<byte> PngSignature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
/// <summary>The sizes of the BMP information headers that exist (core, info, V2, V3, OS/2 2.x, V4, V5).</summary>
internal static bool IsBmpHeaderSize(uint size) => size is 12 or 16 or 40 or 52 or 56 or 64 or 108 or 124;
}
@@ -0,0 +1,59 @@
namespace Febe.Core.Codecs.Images;
/// <summary>
/// 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.
/// </summary>
public sealed record ImageLimits
{
/// <summary>The limits used when a caller passes none.</summary>
public static ImageLimits Default { get; } = new();
/// <summary>Largest width, in pixels.</summary>
public int MaxWidth { get; init; } = 65535;
/// <summary>Largest height, in pixels.</summary>
public int MaxHeight { get; init; } = 65535;
/// <summary>Largest width × height. 100 megapixels are 400 MB of RGBA.</summary>
public long MaxPixels { get; init; } = 100_000_000;
/// <summary>
/// Largest working memory a decoder may take besides the decoded image (for example the indices of a GIF frame).
/// </summary>
public long MaxWorkingBytes { get; init; } = 512L * 1024 * 1024;
/// <summary>
/// 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.
/// </summary>
public int MaxMetadataBytes { get; init; } = 16 * 1024 * 1024;
/// <summary>Throws <see cref="ImageLimitException"/> when an image of that size is not allowed.</summary>
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.");
}
}
/// <summary>Throws <see cref="ImageLimitException"/> when a decoder would need more working memory than allowed.</summary>
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}).");
}
}
}
@@ -0,0 +1,39 @@
namespace Febe.Core.Codecs.Images;
/// <summary>A text an image carries (PNG tEXt, zTXt, iTXt; GIF comment).</summary>
/// <param name="Keyword">The keyword («Title», «Comment», «XML:com.adobe.xmp»...); empty for a GIF comment.</param>
/// <param name="Text">The text.</param>
/// <param name="Language">The language tag of an iTXt chunk, empty otherwise.</param>
/// <param name="TranslatedKeyword">The translated keyword of an iTXt chunk, empty otherwise.</param>
public sealed record ImageText(string Keyword, string Text, string Language = "", string TranslatedKeyword = "");
/// <summary>Metadata read from an image file, without interpreting it.</summary>
public sealed class ImageMetadata
{
/// <summary>No metadata.</summary>
public static ImageMetadata Empty { get; } = new();
/// <summary>The EXIF block as a TIFF structure (starts with «II*\0» or «MM\0*»), or null.</summary>
public byte[]? Exif { get; init; }
/// <summary>The ICC colour profile, decompressed, or null.</summary>
public byte[]? IccProfile { get; init; }
/// <summary>The name of the ICC profile as the file gives it, or null.</summary>
public string? IccProfileName { get; init; }
/// <summary>The XMP packet (from the iTXt chunk «XML:com.adobe.xmp» of a PNG), or null.</summary>
public string? Xmp { get; init; }
/// <summary>The texts, in file order (the XMP packet is in <see cref="Xmp"/>, not here).</summary>
public IReadOnlyList<ImageText> Texts { get; init; } = [];
}
/// <summary>What a file says about its image, read without decoding the pixels.</summary>
/// <param name="Format">The format.</param>
/// <param name="Width">Width in pixels, as stored (no EXIF orientation applied).</param>
/// <param name="Height">Height in pixels, as stored.</param>
/// <param name="FrameCount">Frames of an animation (GIF images, APNG frames); 1 for a still image.</param>
/// <param name="HasAlpha">Whether the format of the pixels can carry transparency (not whether any pixel is transparent).</param>
/// <param name="Metadata">The metadata.</param>
public sealed record ImageInfo(ImageFormat Format, int Width, int Height, int FrameCount, bool HasAlpha, ImageMetadata Metadata);
+917
View File
@@ -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;
/// <summary>
/// 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.
/// </summary>
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<byte> 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,
];
/// <summary>Whether the bytes start with the PNG signature.</summary>
public static bool IsPng(ReadOnlySpan<byte> data) => data.Length >= 8 && data[..8].SequenceEqual(ImageFormatSniffer.PngSignature);
/// <summary>Size, frames and metadata of a PNG, without decoding the pixels.</summary>
public static ImageInfo Identify(ReadOnlyMemory<byte> data, ImageLimits? limits = null)
{
var file = Parse(data, limits ?? ImageLimits.Default, readMetadata: true);
return file.ToInfo();
}
/// <summary>Decodes a PNG to straight RGBA8.</summary>
/// <exception cref="ImageDecodeException">The file is damaged, truncated or not a PNG.</exception>
/// <exception cref="ImageLimitException">The image is larger than <paramref name="limits"/> allow.</exception>
public static RgbaImage Decode(ReadOnlyMemory<byte> data, ImageLimits? limits = null, bool pooled = false)
{
limits ??= ImageLimits.Default;
var file = Parse(data, limits, readMetadata: false);
return DecodePixels(data, file, limits, pooled);
}
/// <summary>Decodes a PNG to straight RGBA8 and returns what <see cref="Identify"/> returns as well.</summary>
public static RgbaImage Decode(ReadOnlyMemory<byte> 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;
/// <summary>256 RGBA entries; entries the file does not give are opaque black.</summary>
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<ImageText>? 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<byte> 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<byte> type)
{
foreach (var c in type)
{
if (!char.IsAsciiLetter((char)c))
{
return false;
}
}
return true;
}
private static void ReadHeader(PngFile file, ReadOnlySpan<byte> 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<byte> 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<byte> 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<byte> 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<byte> 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;
}
/// <summary>Inflates a zlib stream of metadata; null when it is damaged or longer than <paramref name="maxBytes"/>.</summary>
internal static byte[]? Inflate(ReadOnlySpan<byte> 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<byte> 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<byte>.Shared.Rent((int)maxRow + 1);
var previous = ArrayPool<byte>.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<byte>.Shared.Return(current);
ArrayPool<byte>.Shared.Return(previous);
}
}
private static void DecodePass(
ZLibStream zlib,
PngFile file,
int width,
int height,
int bpp,
byte[] current,
byte[] previous,
Span<byte> 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;
}
}
/// <summary>Undoes the row filter (PNG specification §7.3, §9.2): <paramref name="row"/> is changed in place.</summary>
internal static void Unfilter(byte filter, Span<byte> row, ReadOnlySpan<byte> 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<byte>.Count;
for (; i + width <= n; i += width)
{
(new Vector<byte>(row[i..]) + new Vector<byte>(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}).");
}
}
/// <summary>The Paeth predictor (PNG specification §9.4).</summary>
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;
}
/// <summary>Converts <paramref name="count"/> pixels of an unfiltered row to RGBA8, one pixel every <paramref name="step"/> bytes.</summary>
private static void ConvertRow(PngFile file, ReadOnlySpan<byte> row, int count, Span<byte> 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<uint>(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<byte> row, int count, Span<byte> 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<uint>(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<uint>(palette.AsSpan(index * 4)));
}
}
private static void ConvertLowGrey(ReadOnlySpan<byte> row, int count, Span<byte> 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;
}
}
}
+402
View File
@@ -0,0 +1,402 @@
using System.Buffers;
using System.Buffers.Binary;
using System.IO.Compression;
using System.Text;
namespace Febe.Core.Codecs.Images;
/// <summary>What <see cref="PngEncoder"/> writes for the pixels.</summary>
public enum PngColorMode
{
/// <summary>RGB when every pixel is opaque, RGBA otherwise.</summary>
Auto,
/// <summary>8-bit RGB (colour type 2): alpha is dropped.</summary>
Rgb,
/// <summary>8-bit RGBA (colour type 6).</summary>
Rgba,
}
/// <summary>How <see cref="PngEncoder"/> picks the filter of each row.</summary>
public enum PngFilterStrategy
{
/// <summary>
/// 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).
/// </summary>
Adaptive,
None,
Sub,
Up,
Average,
Paeth,
}
/// <summary>Options of <see cref="PngEncoder"/>.</summary>
public sealed record PngEncoderOptions
{
/// <summary>The options used when a caller passes none.</summary>
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;
/// <summary>
/// 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.
/// </summary>
public byte[]? Exif { get; init; }
/// <summary>ICC profile to write, compressed, in an iCCP chunk.</summary>
public byte[]? IccProfile { get; init; }
/// <summary>Name of the profile in the iCCP chunk: 1 to 79 Latin-1 characters.</summary>
public string IccProfileName { get; init; } = "ICC Profile";
/// <summary>XMP packet to write in an uncompressed iTXt chunk with the keyword «XML:com.adobe.xmp».</summary>
public string? Xmp { get; init; }
}
/// <summary>
/// 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 <see cref="PngFilterStrategy"/>, optional eXIf, iCCP and XMP.
/// </summary>
public static class PngEncoder
{
private const int IdatChunkSize = 64 * 1024;
/// <summary>The PNG file of <paramref name="image"/>.</summary>
public static byte[] Encode(RgbaImage image, PngEncoderOptions? options = null)
{
using var output = new MemoryStream();
Encode(image, output, options);
return output.ToArray();
}
/// <summary>Writes the PNG file of <paramref name="image"/> to <paramref name="output"/>.</summary>
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<byte> 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<byte>.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<byte> 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);
}
}
/// <summary>
/// Writes the filter byte and the filtered row to <paramref name="output"/> and returns the sum of the absolute
/// values of the filtered bytes, read as signed.
/// </summary>
internal static long Filter(byte filter, ReadOnlySpan<byte> row, ReadOnlySpan<byte> previous, int bpp, Span<byte> 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<byte> 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<byte> type, ReadOnlySpan<byte> payload)
{
Span<byte> 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);
}
/// <summary>Collects the zlib stream and writes it out as IDAT chunks of <see cref="IdatChunkSize"/> bytes.</summary>
private sealed class IdatStream(Stream output) : Stream
{
private readonly byte[] _buffer = ArrayPool<byte>.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<byte> 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();
}
}
}
/// <summary>Writes the last, shorter chunk.</summary>
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<byte>.Shared.Return(_buffer);
}
base.Dispose(disposing);
}
private void Emit()
{
WriteChunk(output, "IDAT"u8, _buffer.AsSpan(0, _count));
_count = 0;
}
}
}
+145
View File
@@ -0,0 +1,145 @@
using System.Buffers;
namespace Febe.Core.Codecs.Images;
/// <summary>
/// A decoded image: <see cref="Width"/> × <see cref="Height"/> 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).
/// </summary>
/// <remarks>
/// The pixels live either in an array of exactly the right size (<see cref="RgbaImage(int, int)"/>) or in an array
/// rented from <see cref="ArrayPool{T}.Shared"/> (<see cref="Rent"/>), which <see cref="Dispose"/> 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.
/// </remarks>
public sealed class RgbaImage : IDisposable
{
/// <summary>Bytes of one pixel.</summary>
public const int BytesPerPixel = 4;
private byte[]? _buffer;
private readonly bool _pooled;
/// <summary>A new image, every pixel (0, 0, 0, 0).</summary>
public RgbaImage(int width, int height)
: this(width, height, new byte[CheckedLength(width, height)], pooled: false)
{
}
/// <summary>An image over <paramref name="pixels"/>, which must hold exactly width × height × 4 bytes; not copied.</summary>
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;
}
/// <summary>
/// A new image whose pixels come from the shared array pool, every pixel (0, 0, 0, 0). Give it back with
/// <see cref="Dispose"/>.
/// </summary>
public static RgbaImage Rent(int width, int height)
{
var length = CheckedLength(width, height);
var buffer = ArrayPool<byte>.Shared.Rent(length);
buffer.AsSpan(0, length).Clear();
return new RgbaImage(width, height, buffer, pooled: true);
}
/// <summary>A new image for a decoder: size checked against <paramref name="limits"/>, pooled or not.</summary>
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);
}
/// <summary>Width in pixels.</summary>
public int Width { get; }
/// <summary>Height in pixels.</summary>
public int Height { get; }
/// <summary>Bytes of one row (<see cref="Width"/> × 4).</summary>
public int Stride => Width * BytesPerPixel;
/// <summary>Bytes of the whole image.</summary>
public int Length { get; }
/// <summary>Whether the pixels come from the array pool.</summary>
public bool IsPooled => _pooled;
/// <summary>All the pixels, row after row.</summary>
public Span<byte> Pixels => Buffer.AsSpan(0, Length);
/// <summary>The pixels of row <paramref name="y"/> (0 is the top row).</summary>
public Span<byte> GetRow(int y)
{
ArgumentOutOfRangeException.ThrowIfNegative(y);
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(y, Height);
return Buffer.AsSpan(y * Stride, Stride);
}
/// <summary>The pixel at (<paramref name="x"/>, <paramref name="y"/>) as R, G, B, A.</summary>
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]);
}
/// <summary>Whether every pixel has alpha 255.</summary>
public bool IsOpaque()
{
var pixels = Pixels;
for (var i = 3; i < pixels.Length; i += BytesPerPixel)
{
if (pixels[i] != 255)
{
return false;
}
}
return true;
}
/// <summary>A copy of the pixels in an array of exactly <see cref="Length"/> bytes.</summary>
public byte[] ToArray() => Pixels.ToArray();
/// <summary>Gives a pooled array back to the pool; the image cannot be used afterwards.</summary>
public void Dispose()
{
if (_pooled && _buffer is { } buffer)
{
_buffer = null;
ArrayPool<byte>.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;
}
}
@@ -0,0 +1,66 @@
namespace Febe.Core.Codecs.Images;
/// <summary>
/// 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.
/// </summary>
internal sealed class SegmentStream(ReadOnlyMemory<byte> 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<byte> 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<byte> 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();
}
+172
View File
@@ -0,0 +1,172 @@
using Febe.Core.Codecs.Images;
using static Febe.Tests.Imaging.TestImages;
namespace Febe.Tests.Imaging;
/// <summary>The in-house BMP decoder on files built by hand: variants the reference set lacks, and damage.</summary>
[TestClass]
public sealed class BmpDecoderTests
{
private const uint BiRgb = 0;
private const uint BiRle8 = 1;
private const uint BiRle4 = 2;
private const uint BiBitfields = 3;
private const uint BiJpeg = 4;
private const uint BiPng = 5;
private const uint BiAlphaBitfields = 6;
// BGRx palette entries: black, red, green, blue.
private static readonly byte[] Palette4 = [0, 0, 0, 0, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 0];
[TestMethod]
public void TwoBitsPerPixelBottomUp()
{
// 3×2, stride 4 bytes; the first row in the file is the bottom one. Top row 0 1 2, bottom row 3 2 1.
byte[] pixels = [0b11_10_01_00, 0, 0, 0, 0b00_01_10_00, 0, 0, 0];
using var image = BmpDecoder.Decode(Bmp(40, 3, 2, 2, BiRgb, Palette4, pixels));
Assert.AreEqual((0, 0, 0, 255), image.GetPixel(0, 0));
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(1, 0));
Assert.AreEqual((0, 255, 0, 255), image.GetPixel(2, 0));
Assert.AreEqual((0, 0, 255, 255), image.GetPixel(0, 1));
Assert.AreEqual((0, 255, 0, 255), image.GetPixel(1, 1));
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(2, 1));
}
[TestMethod]
public void ACoreHeaderHasThreeBytePaletteEntries()
{
byte[] palette = [10, 20, 30, 40, 50, 60];
byte[] pixels = [0b0100_0000, 0, 0, 0];
using var image = BmpDecoder.Decode(Bmp(12, 3, 1, 1, BiRgb, palette, pixels));
Assert.AreEqual((30, 20, 10, 255), image.GetPixel(0, 0));
Assert.AreEqual((60, 50, 40, 255), image.GetPixel(1, 0));
Assert.AreEqual((30, 20, 10, 255), image.GetPixel(2, 0));
}
[TestMethod]
public void SixteenBitsWithFourMasksAfterAnInformationHeader()
{
// ARGB 4444: a = 8 → 136, r = 15 → 255, g = 0, b = 15 → 255.
byte[] masks = [0x00, 0x0F, 0, 0, 0xF0, 0x00, 0, 0, 0x0F, 0x00, 0, 0, 0x00, 0xF0, 0, 0];
byte[] pixels = [0x0F, 0x8F, 0x00, 0x00];
using var image = BmpDecoder.Decode(Bmp(40, 1, 1, 16, BiAlphaBitfields, masks, pixels), out var info);
Assert.IsTrue(info.HasAlpha);
Assert.AreEqual((255, 0, 255, 136), image.GetPixel(0, 0));
}
[TestMethod]
public void ThirtyTwoBitsWithMasksInAnyOrder()
{
// V4 header with masks for R G B A in memory order: bytes are R, G, B, A.
byte[] pixels = [1, 2, 3, 4, 250, 251, 252, 253];
var bmp = Bmp(108, 2, -1, 32, BiBitfields, [], pixels, masks: [0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000]);
using var image = BmpDecoder.Decode(bmp);
Assert.AreEqual((1, 2, 3, 4), image.GetPixel(0, 0));
Assert.AreEqual((250, 251, 252, 253), image.GetPixel(1, 0));
// BI_RGB ignores the alpha byte, even with a V4 header.
using var opaque = BmpDecoder.Decode(Bmp(108, 2, -1, 32, BiRgb, [], pixels));
Assert.AreEqual((3, 2, 1, 255), opaque.GetPixel(0, 0));
}
[TestMethod]
public void RleDeltasAndLineEndsLeaveTheSkippedPixelsTransparent()
{
byte[] palette = [0, 0, 255, 0, 255, 0, 0, 0]; // BGRx: red, blue
byte[] data = [2, 1, 0, 0, 0, 2, 1, 1, 1, 0, 0, 1];
using var image = BmpDecoder.Decode(Bmp(40, 4, 3, 8, BiRle8, palette, data, colorsUsed: 2));
Assert.AreEqual((0, 0, 255, 255), image.GetPixel(0, 2), "riga in basso, indice 1");
Assert.AreEqual((0, 0, 255, 255), image.GetPixel(1, 2));
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(2, 2));
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(0, 1), "riga saltata dallo spostamento");
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(1, 0), "dopo lo spostamento (1, 1), indice 0");
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(0, 0));
}
[TestMethod]
public void AnRle4AbsoluteRunOfOddLengthIsPaddedToAWord()
{
var palette = Enumerable.Range(0, 16).SelectMany(i => new byte[] { 0, 0, (byte)(i * 16), 0 }).ToArray();
byte[] data = [0, 5, 0x12, 0x34, 0x50, 0, 2, 0x67, 0, 1];
using var image = BmpDecoder.Decode(Bmp(40, 7, 1, 4, BiRle4, palette, data));
byte[] expected = [1, 2, 3, 4, 5, 6, 7];
for (var x = 0; x < expected.Length; x++)
{
Assert.AreEqual((byte)(expected[x] * 16), image.GetPixel(x, 0).R, $"pixel {x}");
}
}
[TestMethod]
public void AnIndexBeyondAShortPaletteIsOpaqueBlack()
{
byte[] palette = [1, 2, 3, 0, 4, 5, 6, 0];
byte[] pixels = [1, 5, 0, 0];
using var image = BmpDecoder.Decode(Bmp(40, 2, 1, 8, BiRgb, palette, pixels, colorsUsed: 2));
Assert.AreEqual((6, 5, 4, 255), image.GetPixel(0, 0));
Assert.AreEqual((0, 0, 0, 255), image.GetPixel(1, 0));
}
[TestMethod]
public void AnEmbeddedPngIsDecodedByThePngDecoder()
{
using var source = TestImages.Random(5, 3, 8);
var png = PngEncoder.Encode(source);
var bmp = Bmp(40, 5, 3, 0, BiPng, [], png);
using var image = BmpDecoder.Decode(bmp);
ImageAssert.AreEqual(source, image, "PNG nel BMP");
Assert.AreEqual(ImageFormat.Bmp, BmpDecoder.Identify(bmp).Format);
}
[TestMethod]
public void DamagedOrUnsupportedFilesThrow()
{
byte[] row = [0, 0, 0, 0];
var cases = new Dictionary<string, (byte[] Bytes, bool Unsupported)>
{
["vuoto"] = ([], false),
["non BMP"] = ("BA\0\0"u8.ToArray(), false),
["solo l'intestazione del file"] = (Bmp(40, 1, 1, 24, BiRgb, [], row)[..16], false),
["intestazione di 20 byte"] = (PatchHeaderSize(Bmp(40, 1, 1, 24, BiRgb, [], row), 20), true),
["larghezza zero"] = (Bmp(40, 0, 1, 24, BiRgb, [], row), false),
["larghezza negativa"] = (Bmp(40, -3, 1, 24, BiRgb, [], row), false),
["7 bit per pixel"] = (Bmp(40, 1, 1, 7, BiRgb, [], row), false),
["64 bit per pixel"] = (Bmp(40, 1, 1, 64, BiRgb, [], new byte[8]), true),
["JPEG dentro"] = (Bmp(40, 1, 1, 0, BiJpeg, [], [0xFF, 0xD8, 0xFF]), true),
["compressione 9"] = (Bmp(40, 1, 1, 24, 9, [], row), true),
["RLE8 a 4 bit"] = (Bmp(40, 1, 1, 4, BiRle8, Palette4, [0, 1]), false),
["RLE dall'alto"] = (Bmp(40, 1, -1, 8, BiRle8, Palette4, [0, 1]), false),
["RLE tagliato"] = (Bmp(40, 4, 2, 8, BiRle8, Palette4, [2, 1, 0]), false),
["tratto assoluto tagliato"] = (Bmp(40, 4, 1, 8, BiRle8, Palette4, [0, 4, 1, 2]), false),
["pixel tagliati"] = (Bmp(40, 4, 4, 24, BiRgb, [], new byte[40]), false),
["maschere non contigue"] = (Bmp(108, 1, 1, 32, BiBitfields, [], row, masks: [0x00FF00FF, 0x0000FF00, 0, 0]), false),
["maschere oltre i 16 bit"] = (Bmp(108, 1, 1, 16, BiBitfields, [], row, masks: [0x00FF0000, 0x0000FF00, 0xFF, 0]), false),
["maschere mancanti"] = (Bmp(40, 1, 1, 32, BiBitfields, [], [])[..54], false),
};
foreach (var (name, (bytes, unsupported)) in cases)
{
if (unsupported)
{
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => BmpDecoder.Decode(bytes), name);
}
else
{
Assert.Throws<ImageDecodeException>(() => BmpDecoder.Decode(bytes), name);
}
}
}
[TestMethod]
public void AnImageBeyondTheLimitsIsRefusedButStillIdentified()
{
var bmp = Bmp(40, 100_000, 1, 24, BiRgb, [], new byte[4]);
Assert.ThrowsExactly<ImageLimitException>(() => BmpDecoder.Decode(bmp));
Assert.AreEqual(100_000, BmpDecoder.Identify(bmp).Width);
}
private static byte[] PatchHeaderSize(byte[] bmp, uint size)
{
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(bmp.AsSpan(14), size);
return bmp;
}
}
+192
View File
@@ -0,0 +1,192 @@
using Febe.Core.Codecs.Images;
using static Febe.Tests.Imaging.TestImages;
namespace Febe.Tests.Imaging;
/// <summary>The in-house GIF decoder on files built from GIF89a: palettes, transparency, clipping, damage.</summary>
[TestClass]
public sealed class GifDecoderTests
{
// Four colours: black, red, green, blue.
private static readonly byte[] Palette4 = [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255];
[TestMethod]
public void AFrameOnTheWholeCanvasTakesItsColoursFromTheGlobalPalette()
{
byte[] indices = [0, 1, 2, 3, 3, 2, 1, 0];
var gif = Gif(4, 2, Palette4, GifFrame(0, 0, 4, 2, indices, 2));
using var image = GifDecoder.Decode(gif, out var info);
Assert.AreEqual((ImageFormat.Gif, 4, 2, 1), (info.Format, info.Width, info.Height, info.FrameCount));
Assert.AreEqual((0, 0, 0, 255), image.GetPixel(0, 0));
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(1, 0));
Assert.AreEqual((0, 0, 255, 255), image.GetPixel(3, 0));
Assert.AreEqual((0, 255, 0, 255), image.GetPixel(1, 1));
}
[TestMethod]
public void TheTransparentIndexAndTheAreaOutsideTheFrameAreTransparent()
{
byte[] indices = [1, 2, 2, 1];
var gif = Gif(4, 3, Palette4, GifControl(2), GifFrame(1, 1, 2, 2, indices, 2));
using var image = GifDecoder.Decode(gif);
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(0, 0), "fuori dal fotogramma");
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(1, 1));
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(2, 1), "indice trasparente");
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(2, 2));
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(3, 2));
}
[TestMethod]
public void TheTransparencyOfALaterControlBlockDoesNotChangeTheFirstFrame()
{
byte[] indices = [1, 2];
var gif = Gif(2, 1, Palette4, GifFrame(0, 0, 2, 1, indices, 2), GifControl(1), GifFrame(0, 0, 2, 1, indices, 2));
using var image = GifDecoder.Decode(gif, out var info);
Assert.AreEqual(2, info.FrameCount);
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(0, 0));
}
[TestMethod]
public void ALocalPaletteWinsOverTheGlobalOne()
{
byte[] local = [9, 9, 9, 7, 7, 7];
var gif = Gif(2, 1, Palette4, GifFrame(0, 0, 2, 1, [0, 1], 2, local));
using var image = GifDecoder.Decode(gif);
Assert.AreEqual((9, 9, 9, 255), image.GetPixel(0, 0));
Assert.AreEqual((7, 7, 7, 255), image.GetPixel(1, 0));
}
[TestMethod]
public void AFrameLargerThanTheCanvasIsClippedAndAnEmptyCanvasTakesTheFrameSize()
{
var indices = Enumerable.Range(0, 12).Select(i => (byte)(i % 4)).ToArray();
using (var clipped = GifDecoder.Decode(Gif(3, 2, Palette4, GifFrame(1, 0, 4, 3, indices, 2))))
{
Assert.AreEqual((3, 2), (clipped.Width, clipped.Height));
Assert.AreEqual((0, 0, 0, 0), clipped.GetPixel(0, 0));
Assert.AreEqual((0, 0, 0, 255), clipped.GetPixel(1, 0));
Assert.AreEqual((255, 0, 0, 255), clipped.GetPixel(2, 0));
Assert.AreEqual((0, 0, 0, 255), clipped.GetPixel(1, 1), "riga 1 del fotogramma, colonna 0: indice 4 % 4");
}
using var sized = GifDecoder.Decode(Gif(0, 0, Palette4, GifFrame(2, 1, 4, 3, indices, 2)));
Assert.AreEqual((6, 4), (sized.Width, sized.Height));
Assert.AreEqual((0, 0, 255, 255), sized.GetPixel(5, 1));
}
[TestMethod]
public void InterlacedRowsGoWhereTheFourPassesPutThem()
{
for (var height = 1; height <= 40; height++)
{
var rows = Enumerable.Range(0, height).Select(r => GifDecoder.InterlacedRow(r, height)).ToList();
CollectionAssert.AreEquivalent(Enumerable.Range(0, height).ToList(), rows, $"altezza {height}");
}
CollectionAssert.AreEqual(new[] { 0, 8, 4, 2, 6, 1, 3, 5, 7, 9 }, Enumerable.Range(0, 10).Select(r => GifDecoder.InterlacedRow(r, 10)).ToArray());
// Row r of the file holds the colour of its own image row: decoding puts each one back in place.
const int height10 = 10;
var indices = new byte[2 * height10];
for (var r = 0; r < height10; r++)
{
indices[2 * r] = indices[(2 * r) + 1] = (byte)GifDecoder.InterlacedRow(r, height10);
}
var palette = Enumerable.Range(0, 16).SelectMany(i => new[] { (byte)(i * 10), (byte)0, (byte)0 }).ToArray();
using var image = GifDecoder.Decode(Gif(2, height10, palette, GifFrame(0, 0, 2, height10, indices, 4, interlaced: true)));
for (var y = 0; y < height10; y++)
{
Assert.AreEqual((byte)(y * 10), image.GetPixel(1, y).R, $"riga {y}");
}
}
[TestMethod]
public void LiteralCodesAtEveryInitialSizeDecode()
{
for (var minCodeSize = 2; minCodeSize <= 8; minCodeSize++)
{
var colours = 1 << minCodeSize;
var random = new Random(minCodeSize);
var indices = new byte[37 * 23];
for (var i = 0; i < indices.Length; i++)
{
indices[i] = (byte)random.Next(colours);
}
var output = new byte[indices.Length];
var data = GifLiteralLzw(indices, minCodeSize);
Assert.AreEqual(indices.Length, GifDecoder.DecodeLzw(data, 0, minCodeSize, output), $"codici da {minCodeSize + 1} bit");
CollectionAssert.AreEqual(indices, output, $"codici da {minCodeSize + 1} bit");
}
}
[TestMethod]
public void DataThatStopsEarlyLeavesTheRestTransparent()
{
var indices = Enumerable.Repeat((byte)1, 16).ToArray();
var full = Gif(4, 4, Palette4, GifFrame(0, 0, 4, 4, indices, 2));
// Cut inside the LZW data, before the end code: the first pixels are there, the others are not.
var cut = full[..(full.Length - 6)];
using var image = GifDecoder.Decode(cut);
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(0, 0));
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(3, 3));
// Every shorter file either fails cleanly or gives an image of the canvas size.
for (var length = 0; length < full.Length; length++)
{
try
{
using var partial = GifDecoder.Decode(full[..length]);
Assert.AreEqual((4, 4), (partial.Width, partial.Height), $"tagliato a {length}");
}
catch (ImageDecodeException)
{
}
}
}
[TestMethod]
public void CommentsBeforeTheFirstFrameAreMetadataAndOtherExtensionsAreSkipped()
{
byte[] comment = [0x21, 0xFE, 5, (byte)'C', (byte)'i', (byte)'a', (byte)'o', (byte)' ', 3, (byte)'G', (byte)'I', (byte)'F', 0];
byte[] netscape = [0x21, 0xFF, 11, .. "NETSCAPE2.0"u8, 3, 1, 0, 0, 0];
var gif = Gif(1, 1, Palette4, comment, netscape, GifFrame(0, 0, 1, 1, [3], 2));
var info = GifDecoder.Identify(gif);
Assert.AreEqual("Ciao GIF", info.Metadata.Texts.Single().Text);
using var image = GifDecoder.Decode(gif);
Assert.AreEqual((0, 0, 255, 255), image.GetPixel(0, 0));
}
[TestMethod]
public void DamagedFilesThrowAnImageDecodeException()
{
var frame = GifFrame(0, 0, 1, 1, [1], 2);
var badCodeSize = frame.ToArray();
badCodeSize[10] = 12;
var cases = new Dictionary<string, byte[]>
{
["vuoto"] = [],
["non GIF"] = "GIF90a"u8.ToArray(),
["senza schermo logico"] = "GIF89a\x01\0"u8.ToArray(),
["senza fotogrammi"] = Gif(1, 1, Palette4),
["senza tavolozza"] = Gif(1, 1, null, frame),
["codici LZW da 13 bit"] = Gif(1, 1, Palette4, badCodeSize),
["tavolozza globale tagliata"] = Gif(1, 1, Palette4)[..20],
};
foreach (var (name, bytes) in cases)
{
Assert.Throws<ImageDecodeException>(() => GifDecoder.Decode(bytes), name);
}
}
[TestMethod]
public void ACanvasBeyondTheLimitsIsRefusedButStillIdentified()
{
var gif = Gif(60000, 60000, Palette4, GifFrame(0, 0, 1, 1, [1], 2));
Assert.ThrowsExactly<ImageLimitException>(() => GifDecoder.Decode(gif));
Assert.AreEqual((60000, 60000), (GifDecoder.Identify(gif).Width, GifDecoder.Identify(gif).Height));
}
}
+43
View File
@@ -0,0 +1,43 @@
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>Comparisons of decoded images that say where they differ.</summary>
internal static class ImageAssert
{
/// <summary>Same size and the same bytes in every pixel.</summary>
public static void AreEqual(RgbaImage expected, RgbaImage actual, string what)
{
Assert.AreEqual((expected.Width, expected.Height), (actual.Width, actual.Height), $"{what}: misura diversa.");
AreEqual(expected.Width, expected.Pixels, actual.Pixels, what);
}
/// <summary>The same RGBA bytes, for images of the given width.</summary>
public static void AreEqual(int width, ReadOnlySpan<byte> expected, ReadOnlySpan<byte> actual, string what)
{
Assert.AreEqual(expected.Length, actual.Length, $"{what}: lunghezza diversa.");
var first = -1;
var different = 0;
for (var i = 0; i < expected.Length; i += 4)
{
if (!expected.Slice(i, 4).SequenceEqual(actual.Slice(i, 4)))
{
different++;
if (first < 0)
{
first = i;
}
}
}
if (different > 0)
{
var pixel = first / 4;
Assert.Fail(
$"{what}: {different} pixel diversi; il primo in ({pixel % width}, {pixel / width}): atteso "
+ $"{Format(expected.Slice(first, 4))}, letto {Format(actual.Slice(first, 4))}.");
}
}
private static string Format(ReadOnlySpan<byte> rgba) => $"({rgba[0]}, {rgba[1]}, {rgba[2]}, {rgba[3]})";
}
+127
View File
@@ -0,0 +1,127 @@
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// Damaged files from the reference set, changed at random with fixed seeds: a decoder either reads them or throws
/// <see cref="ImageDecodeException"/>, never anything else (no index out of range, no overflow, no huge allocation).
/// </summary>
[TestClass]
public sealed class ImageFuzzTests
{
private const int MutationsPerFile = 120;
private static readonly ImageLimits Small = new() { MaxPixels = 1_000_000, MaxWorkingBytes = 16 * 1024 * 1024, MaxMetadataBytes = 64 * 1024 };
public static IEnumerable<object[]> Formats =>
[
[ReferenceFormat.Png],
[ReferenceFormat.Gif],
[ReferenceFormat.Bmp],
];
[TestMethod]
[DynamicData(nameof(Formats))]
public void ChangedBytesNeverBreakTheDecoder(ReferenceFormat format)
{
var seed = 1000 + (int)format;
foreach (var reference in ReferenceImages.Of(format))
{
var original = reference.ReadInput();
var random = new Random(seed++);
for (var i = 0; i < MutationsPerFile; i++)
{
var mutated = Mutate(original, random);
if (format == ReferenceFormat.Png && random.Next(3) > 0)
{
// Most changes to a PNG only meet a wrong CRC: fixing it lets them reach the pixels.
TestImages.FixPngCrcs(mutated);
}
TryDecode(mutated, $"{reference.Name}, modifica {i}");
}
}
}
[TestMethod]
public void ChangedBytesNeverBreakTheFacade()
{
var random = new Random(77);
foreach (var reference in ReferenceImages.All)
{
var mutated = Mutate(reference.ReadInput(), random);
try
{
using var image = ImageDecoder.Decode(mutated, Small);
ImageDecoder.Identify(mutated, Small);
}
catch (ImageDecodeException)
{
}
}
}
private static void TryDecode(byte[] bytes, string what)
{
try
{
using var image = ImageDecoder.Decode(bytes, Small);
Assert.IsGreaterThan(0, image.Width, what);
}
catch (ImageDecodeException)
{
}
catch (Exception ex)
{
Assert.Fail($"{what}: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
}
try
{
ImageDecoder.Identify(bytes, Small);
}
catch (ImageDecodeException)
{
}
catch (Exception ex)
{
Assert.Fail($"{what} (Identify): {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
}
}
private static byte[] Mutate(byte[] original, Random random)
{
var bytes = original.ToArray();
switch (random.Next(4))
{
case 0:
// A few random bytes anywhere after the signature.
for (var k = random.Next(1, 9); k > 0; k--)
{
bytes[random.Next(Math.Min(8, bytes.Length - 1), bytes.Length)] = (byte)random.Next(256);
}
return bytes;
case 1:
// A byte of the headers set to an extreme.
bytes[random.Next(Math.Min(8, bytes.Length - 1), Math.Min(bytes.Length, 80))] = random.Next(2) == 0 ? (byte)0 : (byte)0xFF;
return bytes;
case 2:
// Cut short.
return bytes[..random.Next(1, bytes.Length)];
default:
// A run of bytes flipped.
var start = random.Next(8, bytes.Length);
var length = Math.Min(bytes.Length - start, random.Next(1, 64));
for (var k = 0; k < length; k++)
{
bytes[start + k] ^= 0x5A;
}
return bytes;
}
}
}
@@ -0,0 +1,95 @@
using System.Text;
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>The common pieces of the in-house image codecs: format recognition, the RGBA image, the limits.</summary>
[TestClass]
public sealed class ImagingBaseTests
{
[TestMethod]
public void FormatsAreRecognisedFromTheirFirstBytes()
{
var bmp = new byte[18];
"BM"u8.CopyTo(bmp);
bmp[14] = 40;
var cases = new (byte[] Bytes, ImageFormat Format)[]
{
([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0], ImageFormat.Png),
([0xFF, 0xD8, 0xFF, 0xE0], ImageFormat.Jpeg),
("GIF89a"u8.ToArray(), ImageFormat.Gif),
("GIF87a"u8.ToArray(), ImageFormat.Gif),
(bmp, ImageFormat.Bmp),
("RIFF\0\0\0\0WEBPVP8 "u8.ToArray(), ImageFormat.WebP),
("II*\0"u8.ToArray(), ImageFormat.Tiff),
("MM\0*"u8.ToArray(), ImageFormat.Tiff),
("\0\0\0\u0018ftypheic"u8.ToArray(), ImageFormat.Heif),
("\0\0\0\u0018ftypmif1"u8.ToArray(), ImageFormat.Heif),
("\0\0\0\u0018ftypavif"u8.ToArray(), ImageFormat.Avif),
("\0\0\0\u0018ftypisom"u8.ToArray(), ImageFormat.Unknown),
("RIFF\0\0\0\0AVI "u8.ToArray(), ImageFormat.Unknown),
("GIF89"u8.ToArray(), ImageFormat.Unknown),
("BM"u8.ToArray(), ImageFormat.Unknown),
([0x89, 0x50, 0x4E, 0x47], ImageFormat.Unknown),
([], ImageFormat.Unknown),
(Encoding.ASCII.GetBytes("<html>"), ImageFormat.Unknown),
};
foreach (var (bytes, format) in cases)
{
Assert.AreEqual(format, ImageFormatSniffer.Detect(bytes), Convert.ToHexString(bytes));
}
// A BMP whose information header has a size no version has is not taken for one.
bmp[14] = 41;
Assert.AreEqual(ImageFormat.Unknown, ImageFormatSniffer.Detect(bmp));
}
[TestMethod]
public void AnImageHasRowsOfFourBytesPerPixel()
{
using var image = new RgbaImage(3, 2);
Assert.AreEqual((12, 24), (image.Stride, image.Length));
Assert.IsTrue(image.Pixels.ToArray().All(b => b == 0));
Assert.IsFalse(image.IsOpaque());
image.GetRow(1)[4..8].Fill(200);
Assert.AreEqual((200, 200, 200, 200), image.GetPixel(1, 1));
Assert.AreEqual(200, image.ToArray()[16]);
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => image.GetRow(2).Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => image.GetPixel(3, 0));
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => new RgbaImage(0, 1));
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => new RgbaImage(50_000, 50_000));
Assert.ThrowsExactly<ArgumentException>(() => new RgbaImage(2, 2, new byte[15]));
}
[TestMethod]
public void ARentedImageStartsClearAndGoesBackToThePool()
{
for (var round = 0; round < 3; round++)
{
var image = RgbaImage.Rent(33, 17);
Assert.IsTrue(image.IsPooled);
Assert.IsTrue(image.Pixels.ToArray().All(b => b == 0), $"giro {round}: un array del pool arriva sporco");
image.Pixels.Fill(0xAB);
image.Dispose();
Assert.ThrowsExactly<ObjectDisposedException>(() => image.GetRow(0).Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
// Disposing an image that owns its array changes nothing.
var owned = new RgbaImage(1, 1);
owned.Dispose();
Assert.AreEqual(4, owned.Pixels.Length);
}
[TestMethod]
public void TheFacadeSaysWhichFormatsItCannotReadYet()
{
var jpeg = ReferenceImages.Of(ReferenceFormat.Jpeg).First().ReadInput();
var error = Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Decode(jpeg));
Assert.Contains("JPEG", error.Message);
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Identify(Encoding.ASCII.GetBytes("testo qualsiasi")));
Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.Png) && ImageDecoder.CanDecode(ImageFormat.Gif) && ImageDecoder.CanDecode(ImageFormat.Bmp));
Assert.IsFalse(ImageDecoder.CanDecode(ImageFormat.Jpeg) || ImageDecoder.CanDecode(ImageFormat.WebP) || ImageDecoder.CanDecode(ImageFormat.Unknown));
}
}
+383
View File
@@ -0,0 +1,383 @@
using System.Buffers.Binary;
using System.IO.Compression;
using System.Text;
using Febe.Core.Codecs.Images;
using static Febe.Tests.Imaging.TestImages;
namespace Febe.Tests.Imaging;
/// <summary>The in-house PNG decoder and encoder, beyond the reference set: round trips, metadata, damaged files.</summary>
[TestClass]
public sealed class PngCodecTests
{
// An 8-bit RGBA row of 2 pixels, filter 0: red opaque, green half transparent.
private static readonly byte[] TwoPixels = [0, 255, 0, 0, 255, 0, 255, 0, 128];
[TestMethod]
public void TheCrcIsTheOneOfThePngSpecification()
{
Assert.AreEqual(0xCBF43926u, Crc32.Compute("123456789"u8));
Assert.AreEqual(0xAE426082u, Crc32.Compute("IEND"u8));
// Eight bytes at a time and one at a time agree on every length and every split.
var data = new byte[300];
new Random(7).NextBytes(data);
for (var length = 0; length <= data.Length; length += 7)
{
var whole = Crc32.Compute(data.AsSpan(0, length));
Assert.AreEqual(BitwiseCrc(data.AsSpan(0, length)), whole, $"lunghezza {length}");
var split = length / 3;
Assert.AreEqual(whole, Crc32.Append(Crc32.Compute(data.AsSpan(0, split)), data.AsSpan(split, length - split)), $"divisa a {split}");
}
}
[TestMethod]
[DataRow(PngFilterStrategy.Adaptive)]
[DataRow(PngFilterStrategy.None)]
[DataRow(PngFilterStrategy.Sub)]
[DataRow(PngFilterStrategy.Up)]
[DataRow(PngFilterStrategy.Average)]
[DataRow(PngFilterStrategy.Paeth)]
public void EveryFilterStrategyRoundTrips(PngFilterStrategy filter)
{
var seed = 11;
foreach (var (width, height) in new[] { (1, 1), (2, 3), (17, 5), (300, 7), (5, 300) })
{
using var image = TestImages.Random(width, height, seed++);
var png = PngEncoder.Encode(image, new PngEncoderOptions { Filter = filter });
using var back = PngDecoder.Decode(png);
ImageAssert.AreEqual(image, back, $"{filter} {width}×{height}");
using var smooth = Gradient(width, height, seed++);
using var smoothBack = PngDecoder.Decode(PngEncoder.Encode(smooth, new PngEncoderOptions { Filter = filter }));
ImageAssert.AreEqual(smooth, smoothBack, $"{filter} {width}×{height} sfumato");
}
}
[TestMethod]
public void AdaptiveFilteringUsesTheFiveFiltersAndCompressesBetterThanNone()
{
using var image = Gradient(200, 120, 3);
var adaptive = PngEncoder.Encode(image);
var none = PngEncoder.Encode(image, new PngEncoderOptions { Filter = PngFilterStrategy.None });
Assert.IsLessThan(none.Length, adaptive.Length);
var raw = Inflate(Join(PngChunks(adaptive).Where(c => c.Type == "IDAT").Select(c => c.Payload).ToArray()));
var rowBytes = (200 * 4) + 1;
var used = Enumerable.Range(0, 120).Select(y => raw[y * rowBytes]).ToHashSet();
Assert.IsTrue(used.All(f => f <= 4), "filtro fuori dalla specifica");
Assert.IsGreaterThan(1, used.Count, "il filtro adattivo sceglie per ogni riga");
}
[TestMethod]
public void AutoWritesRgbForAnOpaqueImageAndRgbaOtherwise()
{
using var opaque = TestImages.Random(9, 4, 1, opaque: true);
var png = PngEncoder.Encode(opaque);
Assert.AreEqual(2, PngChunks(png)[0].Payload[9], "tipo di colore");
using (var back = PngDecoder.Decode(png))
{
ImageAssert.AreEqual(opaque, back, "RGB");
}
using var translucent = TestImages.Random(9, 4, 2);
Assert.AreEqual(6, PngChunks(PngEncoder.Encode(translucent))[0].Payload[9], "tipo di colore");
// Rgb drops alpha, Rgba keeps it even for an opaque image.
using var dropped = PngDecoder.Decode(PngEncoder.Encode(translucent, new PngEncoderOptions { ColorMode = PngColorMode.Rgb }));
for (var i = 0; i < dropped.Length; i += 4)
{
Assert.IsTrue(dropped.Pixels.Slice(i, 3).SequenceEqual(translucent.Pixels.Slice(i, 3)) && dropped.Pixels[i + 3] == 255, $"pixel {i / 4}");
}
Assert.AreEqual(6, PngChunks(PngEncoder.Encode(opaque, new PngEncoderOptions { ColorMode = PngColorMode.Rgba }))[0].Payload[9]);
}
[TestMethod]
public void ALargeImageIsSplitIntoSeveralIdatChunks()
{
using var image = TestImages.Random(300, 300, 5);
var png = PngEncoder.Encode(image, new PngEncoderOptions { CompressionLevel = CompressionLevel.NoCompression });
var chunks = PngChunks(png);
Assert.IsGreaterThan(5, chunks.Count(c => c.Type == "IDAT"));
Assert.IsTrue(chunks.Where(c => c.Type == "IDAT").SkipLast(1).All(c => c.Payload.Length == 64 * 1024));
CollectionAssert.AreEqual(new[] { "IHDR", "IDAT", "IEND" }, chunks.Select(c => c.Type).Distinct().ToArray());
using var back = PngDecoder.Decode(png);
ImageAssert.AreEqual(image, back, "300×300");
}
[TestMethod]
public void EveryReferenceImageRoundTripsThroughTheEncoder()
{
foreach (var reference in ReferenceImages.All)
{
using var expected = PngDecoder.Decode(reference.ReadExpectedPng());
using var back = PngDecoder.Decode(PngEncoder.Encode(expected));
ImageAssert.AreEqual(expected, back, reference.Name);
}
}
[TestMethod]
public void ExifIccAndXmpAreWrittenBeforeTheDataAndReadBack()
{
var exif = Join("MM\0*"u8.ToArray(), [0, 0, 0, 8, 0, 0]);
var icc = new byte[3000];
new Random(9).NextBytes(icc);
const string xmp = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><dc:title>Città è più</dc:title></x:xmpmeta>";
using var image = TestImages.Random(4, 4, 3);
var png = PngEncoder.Encode(image, new PngEncoderOptions
{
Exif = Join("Exif\0\0"u8.ToArray(), exif),
IccProfile = icc,
IccProfileName = "Profilo di prova",
Xmp = xmp,
});
var types = PngChunks(png).Select(c => c.Type).ToList();
CollectionAssert.AreEqual(new[] { "IHDR", "iCCP", "eXIf", "iTXt", "IDAT", "IEND" }, types);
var info = PngDecoder.Identify(png);
CollectionAssert.AreEqual(exif, info.Metadata.Exif, "l'«Exif\\0\\0» di JPEG è tolto");
CollectionAssert.AreEqual(icc, info.Metadata.IccProfile);
Assert.AreEqual("Profilo di prova", info.Metadata.IccProfileName);
Assert.AreEqual(xmp, info.Metadata.Xmp);
Assert.IsEmpty(info.Metadata.Texts, "l'XMP non è fra i testi");
using var decoded = PngDecoder.Decode(png, out var again);
Assert.AreEqual(xmp, again.Metadata.Xmp);
ImageAssert.AreEqual(image, decoded, "con i metadati");
}
[TestMethod]
public void TheEncoderRefusesMetadataItCannotWrite()
{
using var image = new RgbaImage(1, 1);
Assert.ThrowsExactly<ArgumentException>(() => PngEncoder.Encode(image, new PngEncoderOptions { Exif = [1, 2, 3, 4, 5, 6, 7, 8] }));
Assert.ThrowsExactly<ArgumentException>(() => PngEncoder.Encode(image, new PngEncoderOptions { IccProfile = [1], IccProfileName = "" }));
Assert.ThrowsExactly<ArgumentException>(() => PngEncoder.Encode(image, new PngEncoderOptions { IccProfile = [1], IccProfileName = new string('a', 80) }));
Assert.ThrowsExactly<ArgumentException>(() => PngEncoder.Encode(image, new PngEncoderOptions { IccProfile = [1], IccProfileName = "Città€" }));
}
[TestMethod]
public void TextsAreReadFromTextZtxtAndItxt()
{
var png = Png(
("IHDR", Ihdr(2, 1, 8, 6)),
("tEXt", Join(Latin1("Title"), [0], Latin1("Città"))),
("zTXt", Join(Latin1("Comment"), [0, 0], Zlib(Latin1(new string('z', 5000))))),
("iTXt", Join(Latin1("Description"), [0, 1, 0], Encoding.ASCII.GetBytes("it"), [0], Encoding.UTF8.GetBytes("Descrizione"), [0], Zlib(Encoding.UTF8.GetBytes("Un po' di più €")))),
("iTXt", Join(Latin1("Author"), [0, 0, 0, 0, 0], Encoding.UTF8.GetBytes("Alberto"))),
("IDAT", Zlib(TwoPixels)),
("IEND", []));
var texts = PngDecoder.Identify(png).Metadata.Texts;
Assert.HasCount(4, texts);
Assert.AreEqual(new ImageText("Title", "Città"), texts[0]);
Assert.AreEqual(new ImageText("Comment", new string('z', 5000)), texts[1]);
Assert.AreEqual(new ImageText("Description", "Un po' di più €", "it", "Descrizione"), texts[2]);
Assert.AreEqual(new ImageText("Author", "Alberto"), texts[3]);
}
[TestMethod]
public void MetadataBeyondTheBudgetIsDroppedAndTheImageStillDecodes()
{
var bomb = Zlib(new byte[2_000_000]);
var png = Png(
("IHDR", Ihdr(2, 1, 8, 6)),
("zTXt", Join(Latin1("Comment"), [0, 0], bomb)),
("iCCP", Join(Latin1("p"), [0, 0], bomb)),
("tEXt", Join(Latin1("Title"), [0], Latin1("breve"))),
("IDAT", Zlib(TwoPixels)),
("IEND", []));
var limits = new ImageLimits { MaxMetadataBytes = 1000 };
using var image = PngDecoder.Decode(png, out var info, limits);
Assert.AreEqual(new ImageText("Title", "breve"), info.Metadata.Texts.Single());
Assert.IsNull(info.Metadata.IccProfile);
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(0, 0));
Assert.AreEqual((0, 255, 0, 128), image.GetPixel(1, 0));
}
[TestMethod]
public void AnAnimatedPngCountsItsFramesAndDecodesTheDefaultImage()
{
var actl = new byte[8];
BinaryPrimitives.WriteUInt32BigEndian(actl, 3);
var png = Png(("IHDR", Ihdr(2, 1, 8, 6)), ("acTL", actl), ("IDAT", Zlib(TwoPixels)), ("fcTL", new byte[26]), ("IEND", []));
using var image = PngDecoder.Decode(png, out var info);
Assert.AreEqual(3, info.FrameCount);
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(0, 0));
}
[TestMethod]
public void APaletteIndexBeyondThePaletteIsOpaqueBlack()
{
var png = Png(
("IHDR", Ihdr(3, 1, 8, 3)),
("PLTE", [10, 20, 30, 40, 50, 60]),
("tRNS", [7, 8, 9, 9, 9]),
("IDAT", Zlib([0, 0, 1, 2])),
("IEND", []));
using var image = PngDecoder.Decode(png, out var info);
Assert.IsTrue(info.HasAlpha);
Assert.AreEqual((10, 20, 30, 7), image.GetPixel(0, 0));
Assert.AreEqual((40, 50, 60, 8), image.GetPixel(1, 0));
Assert.AreEqual((0, 0, 0, 255), image.GetPixel(2, 0));
}
[TestMethod]
public void ADamagedAncillaryChunkIsSkippedAndADamagedCriticalOneStopsTheDecoding()
{
var text = Chunk("tEXt", Join(Latin1("Title"), [0], Latin1("x")));
text[^1] ^= 1;
var png = Join(Png(("IHDR", Ihdr(2, 1, 8, 6))), text, Chunk("IDAT", Zlib(TwoPixels)), Chunk("IEND", []));
using (var image = PngDecoder.Decode(png, out var info))
{
Assert.IsEmpty(info.Metadata.Texts);
Assert.AreEqual((0, 255, 0, 128), image.GetPixel(1, 0));
}
var idat = Chunk("IDAT", Zlib(TwoPixels));
idat[10] ^= 0x40;
var broken = Join(Png(("IHDR", Ihdr(2, 1, 8, 6))), idat, Chunk("IEND", []));
var error = Assert.ThrowsExactly<ImageDecodeException>(() => PngDecoder.Decode(broken));
Assert.Contains("CRC", error.Message);
}
[TestMethod]
public void DamagedFilesThrowAnImageDecodeException()
{
var header = ("IHDR", Ihdr(2, 1, 8, 6));
var end = ("IEND", Array.Empty<byte>());
var cases = new Dictionary<string, byte[]>
{
["vuoto"] = [],
["solo la firma"] = Png(),
["non PNG"] = Encoding.ASCII.GetBytes("non sono un'immagine, solo testo"),
["senza IHDR"] = Png(("IDAT", Zlib(TwoPixels)), end),
["senza IDAT"] = Png(header, end),
["IHDR corto"] = Png(("IHDR", new byte[12]), ("IDAT", Zlib(TwoPixels)), end),
["larghezza zero"] = Png(("IHDR", Ihdr(0, 1, 8, 6)), ("IDAT", Zlib(TwoPixels)), end),
["RGB a 4 bit"] = Png(("IHDR", Ihdr(2, 1, 4, 2)), ("IDAT", Zlib(TwoPixels)), end),
["tipo di colore 5"] = Png(("IHDR", Ihdr(2, 1, 8, 5)), ("IDAT", Zlib(TwoPixels)), end),
["interlacciamento 2"] = Png(("IHDR", Ihdr(2, 1, 8, 6, interlace: 2)), ("IDAT", Zlib(TwoPixels)), end),
["tavolozza senza PLTE"] = Png(("IHDR", Ihdr(2, 1, 8, 3)), ("IDAT", Zlib([0, 0, 0])), end),
["PLTE in scala di grigi"] = Png(("IHDR", Ihdr(2, 1, 8, 0)), ("PLTE", [1, 2, 3]), ("IDAT", Zlib([0, 0, 0])), end),
["PLTE di 4 byte"] = Png(("IHDR", Ihdr(2, 1, 8, 3)), ("PLTE", [1, 2, 3, 4]), ("IDAT", Zlib([0, 0, 0])), end),
["IDAT separati"] = Png(header, ("IDAT", Zlib(TwoPixels)[..4]), ("tEXt", Join(Latin1("a"), [0])), ("IDAT", Zlib(TwoPixels)[4..]), end),
["zlib non valido"] = Png(header, ("IDAT", [0x78, 0x9C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), end),
["dati corti"] = Png(header, ("IDAT", Zlib(TwoPixels[..5])), end),
["filtro 5"] = Png(header, ("IDAT", Zlib(Join([5], TwoPixels[1..]))), end),
["IHDR doppio"] = Png(header, header, ("IDAT", Zlib(TwoPixels)), end),
["tipo di blocco con una cifra"] = Png(header, ("ab1d", []), ("IDAT", Zlib(TwoPixels)), end),
};
foreach (var (name, bytes) in cases)
{
var error = Assert.Throws<ImageDecodeException>(() => PngDecoder.Decode(bytes), name);
Assert.IsFalse(string.IsNullOrWhiteSpace(error.Message), name);
}
}
[TestMethod]
public void AnUnknownCriticalChunkIsNotSupportedAndAnUnknownAncillaryOneIsSkipped()
{
var crushed = Png(("IHDR", Ihdr(2, 1, 8, 6)), ("CgBI", [0, 0, 0, 0]), ("IDAT", Zlib(TwoPixels)), ("IEND", []));
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => PngDecoder.Decode(crushed));
var extra = Png(("IHDR", Ihdr(2, 1, 8, 6)), ("vpAg", [1, 2, 3]), ("IDAT", Zlib(TwoPixels)), ("prVt", []), ("IEND", []));
using var image = PngDecoder.Decode(Join(extra, Encoding.ASCII.GetBytes("dopo IEND")));
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(0, 0));
}
[TestMethod]
public void EveryTruncationEitherFailsOrGivesTheWholeImage()
{
var reference = ReferenceImages.Get("png-tav-4-adam7");
var full = reference.ReadInput();
using var expected = PngDecoder.Decode(full);
var whole = 0;
for (var length = 0; length < full.Length; length++)
{
var cut = full[..length];
try
{
using var image = PngDecoder.Decode(cut);
ImageAssert.AreEqual(expected, image, $"tagliato a {length}");
whole++;
}
catch (ImageDecodeException)
{
}
}
// Only cuts at a chunk boundary after the last IDAT keep everything (a missing IEND is accepted).
var lastIdatEnd = 8;
var boundaries = new List<int>();
for (var pos = 8; pos < full.Length;)
{
var length = (int)BinaryPrimitives.ReadUInt32BigEndian(full.AsSpan(pos));
var type = Encoding.ASCII.GetString(full, pos + 4, 4);
pos += length + 12;
boundaries.Add(pos);
if (type == "IDAT")
{
lastIdatEnd = pos;
}
}
Assert.AreEqual(boundaries.Count(b => b >= lastIdatEnd && b < full.Length), whole);
Assert.IsGreaterThanOrEqualTo(1, whole);
}
[TestMethod]
public void ImagesBeyondTheLimitsAreRefusedBeforeDecoding()
{
var huge = Png(("IHDR", Ihdr(70_000, 1, 8, 6)), ("IDAT", Zlib([0])), ("IEND", []));
Assert.ThrowsExactly<ImageLimitException>(() => PngDecoder.Decode(huge));
Assert.AreEqual(70_000, PngDecoder.Identify(huge).Width, "la misura si legge anche oltre i limiti");
using var image = TestImages.Random(50, 50, 4);
var png = PngEncoder.Encode(image);
Assert.ThrowsExactly<ImageLimitException>(() => PngDecoder.Decode(png, new ImageLimits { MaxPixels = 2499 }));
Assert.ThrowsExactly<ImageLimitException>(() => PngDecoder.Decode(png, new ImageLimits { MaxWidth = 49 }));
using var allowed = PngDecoder.Decode(png, new ImageLimits { MaxPixels = 2500 });
ImageAssert.AreEqual(image, allowed, "al limite");
}
[TestMethod]
public void APooledDecodeGivesTheSamePixels()
{
var reference = ReferenceImages.Get("png-rgba-16");
using var plain = PngDecoder.Decode(reference.ReadInput());
var pooled = PngDecoder.Decode(reference.ReadInput(), pooled: true);
Assert.IsTrue(pooled.IsPooled);
ImageAssert.AreEqual(plain, pooled, reference.Name);
pooled.Dispose();
pooled.Dispose();
Assert.ThrowsExactly<ObjectDisposedException>(() => pooled.Pixels.Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
private static uint BitwiseCrc(ReadOnlySpan<byte> data)
{
var crc = 0xFFFFFFFFu;
foreach (var b in data)
{
crc ^= b;
for (var k = 0; k < 8; k++)
{
crc = (crc & 1) != 0 ? 0xEDB88320u ^ (crc >> 1) : crc >> 1;
}
}
return ~crc;
}
private static byte[] Inflate(byte[] zlib)
{
using var input = new MemoryStream(zlib);
using var stream = new ZLibStream(input, CompressionMode.Decompress);
using var output = new MemoryStream();
stream.CopyTo(output);
return output.ToArray();
}
}
@@ -0,0 +1,148 @@
using System.Buffers.Binary;
using System.IO.Compression;
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// The in-house PNG, GIF and BMP decoders against the reference set (Imaging/Riferimenti/LEGGIMI.md): every pixel
/// must be the one SkiaSharp read, exactly. The expected images are read with our own PNG decoder, which is first
/// checked on them against a reader of a dozen lines that only knows their trivial layout.
/// </summary>
[TestClass]
public sealed class ReferenceDecodeTests
{
public static IEnumerable<object[]> PngCases => ReferenceImages.NamesOf(ReferenceFormat.Png);
public static IEnumerable<object[]> GifCases => ReferenceImages.NamesOf(ReferenceFormat.Gif);
public static IEnumerable<object[]> BmpCases => ReferenceImages.NamesOf(ReferenceFormat.Bmp);
[TestMethod]
public void EveryExpectedImageReadsTheSameWithTheDecoderAndWithTheTrivialReader()
{
foreach (var reference in ReferenceImages.All)
{
var png = reference.ReadExpectedPng();
using var image = PngDecoder.Decode(png);
Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height), reference.Name);
ImageAssert.AreEqual(reference.Width, TrivialRead(png, reference.Width, reference.Height), image.Pixels, reference.Name + ".atteso.png");
}
}
[TestMethod]
[DynamicData(nameof(PngCases))]
public void ThePngDecoderReadsTheReferenceExactly(string name) => CheckExact(name, data => PngDecoder.Decode(data));
[TestMethod]
[DynamicData(nameof(GifCases))]
public void TheGifDecoderReadsTheReferenceExactly(string name) => CheckExact(name, data => GifDecoder.Decode(data));
[TestMethod]
[DynamicData(nameof(BmpCases))]
public void TheBmpDecoderReadsTheReferenceExactly(string name) => CheckExact(name, data => BmpDecoder.Decode(data));
[TestMethod]
public void TheFacadeChoosesTheDecoderFromTheFirstBytes()
{
foreach (var reference in ReferenceImages.All)
{
var input = reference.ReadInput();
var format = ImageFormatSniffer.Detect(input);
var expected = reference.Format switch
{
ReferenceFormat.Png => ImageFormat.Png,
ReferenceFormat.Jpeg => ImageFormat.Jpeg,
ReferenceFormat.WebP => ImageFormat.WebP,
ReferenceFormat.Gif => ImageFormat.Gif,
_ => ImageFormat.Bmp,
};
Assert.AreEqual(expected, format, reference.Name);
if (!ImageDecoder.CanDecode(format))
{
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Decode(input), reference.Name);
continue;
}
using var image = ImageDecoder.Decode(input);
using var expectedImage = PngDecoder.Decode(reference.ReadExpectedPng());
ImageAssert.AreEqual(expectedImage, image, reference.Name);
var info = ImageDecoder.Identify(input);
Assert.AreEqual((format, reference.Width, reference.Height), (info.Format, info.Width, info.Height), reference.Name);
}
}
[TestMethod]
public void TheAnimatedGifHasMoreThanOneFrameAndTheOthersOne()
{
foreach (var reference in ReferenceImages.Of(ReferenceFormat.Gif))
{
var info = GifDecoder.Identify(reference.ReadInput());
if (reference.Name == "gif-animata")
{
Assert.IsGreaterThan(1, info.FrameCount, reference.Name);
}
else
{
Assert.AreEqual(1, info.FrameCount, reference.Name);
}
using var image = GifDecoder.Decode(reference.ReadInput(), out var again);
Assert.AreEqual(info.FrameCount, again.FrameCount, reference.Name);
}
}
[TestMethod]
public void HandBuiltPngsCarryTheirTextChunk()
{
// LEGGIMI.md: every hand-built PNG has a tEXt to skip; the metadata reader finds it.
foreach (var reference in ReferenceImages.Of(ReferenceFormat.Png).Where(c => !c.Name.StartsWith("png-skia", StringComparison.Ordinal)))
{
var info = PngDecoder.Identify(reference.ReadInput());
Assert.IsNotEmpty(info.Metadata.Texts, reference.Name);
Assert.AreEqual(1, info.FrameCount, reference.Name);
}
}
private static void CheckExact(string name, Func<byte[], RgbaImage> decode)
{
var reference = ReferenceImages.Get(name);
using var expected = PngDecoder.Decode(reference.ReadExpectedPng());
using var actual = decode(reference.ReadInput());
ImageAssert.AreEqual(expected, actual, name);
}
/// <summary>
/// Reads an expected image knowing only how they were written: IHDR, IDAT chunks, one zlib stream of rows that
/// all use filter 0, RGBA8. Independent of <see cref="PngDecoder"/>.
/// </summary>
private static byte[] TrivialRead(byte[] png, int width, int height)
{
using var idat = new MemoryStream();
var pos = 8;
while (pos < png.Length)
{
var length = (int)BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos));
if (png.AsSpan(pos + 4, 4).SequenceEqual("IDAT"u8))
{
idat.Write(png, pos + 8, length);
}
pos += length + 12;
}
idat.Position = 0;
using var zlib = new ZLibStream(idat, CompressionMode.Decompress);
var pixels = new byte[width * height * 4];
var row = new byte[1 + (width * 4)];
for (var y = 0; y < height; y++)
{
zlib.ReadExactly(row);
Assert.AreEqual(0, row[0], "le immagini attese usano solo il filtro 0");
row.AsSpan(1).CopyTo(pixels.AsSpan(y * width * 4));
}
return pixels;
}
}
@@ -6,8 +6,8 @@ namespace Febe.Tests.Imaging;
/// <summary>
/// Integrity of the reference set in Imaging/Riferimenti: every listed file is there and nothing else, each input starts
/// with the magic of its format and has the listed size, each expected image is a well-formed straight RGBA8 PNG of the
/// listed size. The pixels are not read here: Febe's own PNG decoder (step 2 of track C1) will read them, without
/// SkiaSharp.
/// listed size. The pixels are not read here: <see cref="ReferenceDecodeTests"/> reads them with Febe's own PNG decoder
/// (step 2 of track C1), without SkiaSharp.
/// </summary>
[TestClass]
public sealed class ReferenceSetTests
@@ -24,8 +24,8 @@ il nostro codice, non si aggiunge qui.
confrontati, uguali, con il disegno con matrice di SkiaSharp (quello che faceva `ImageDecoding`).
- **L'immagine attesa** non è scritta dal codificatore di SkiaSharp ma da uno scritto a mano nel programma: PNG RGBA a
8 bit (tipo di colore 6), senza interlacciamento, ogni riga con il filtro 0, un solo `IDAT` (zlib della BCL), nessun
altro blocco oltre a `IHDR`, `IDAT`, `IEND`. Così il lettore PNG di casa (tappa C1, passo 2) la legge senza SkiaSharp;
fino ad allora la prova d'integrità ne controlla solo la struttura.
altro blocco oltre a `IHDR`, `IDAT`, `IEND`. Così il lettore PNG di casa (tappa C1, passo 2) la legge senza SkiaSharp,
e un lettore minimo nelle prove, che conosce solo questa forma, controlla che legga giusto.
## I casi
@@ -89,5 +89,9 @@ lettore ricava prima della trasformata inversa, poi i pixel di un'immagine sempl
- `Imaging/ReferenceSetTests.cs`: integrità dell'insieme. Ogni file elencato c'è e non c'è altro; ogni ingresso
comincia con la firma del suo formato e ha la misura elencata (ruotata per l'orientamento EXIF 5–8); ogni immagine
attesa è un PNG RGBA a 8 bit ben formato (CRC di ogni blocco) della misura elencata; l'insieme resta piccolo.
- `Imaging/ReferenceDecodeTests.cs` (dalla tappa C1, passo 2): ogni immagine attesa si legge uguale con il lettore PNG
di casa e con un lettore minimo indipendente; i lettori PNG, GIF e BMP di casa danno, per ogni caso del loro formato,
esattamente i pixel dell'immagine attesa; la facciata `ImageDecoder` sceglie il lettore dai primi byte e per JPEG e
WebP dice che non li legge ancora.
- `Febe.Tests.csproj` copia la cartella nell'uscita delle prove; `.gitattributes` segna le estensioni delle immagini
come binarie e tiene `elenco.txt` con le righe Unix.
+301
View File
@@ -0,0 +1,301 @@
using System.Buffers.Binary;
using System.IO.Compression;
using System.Text;
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// Small images and files built by the tests: random RGBA images from a fixed seed, and PNG, GIF and BMP files written
/// byte by byte from the specifications, to reach the cases the reference set does not have (damaged files above all).
/// </summary>
internal static class TestImages
{
/// <summary>An image of random pixels; <paramref name="opaque"/> forces alpha 255.</summary>
public static RgbaImage Random(int width, int height, int seed, bool opaque = false)
{
var random = new Random(seed);
var pixels = new byte[width * height * 4];
random.NextBytes(pixels);
if (opaque)
{
for (var i = 3; i < pixels.Length; i += 4)
{
pixels[i] = 255;
}
}
return new RgbaImage(width, height, pixels);
}
/// <summary>A smooth image (gradients and a little noise), the kind adaptive filtering is for.</summary>
public static RgbaImage Gradient(int width, int height, int seed)
{
var random = new Random(seed);
var image = new RgbaImage(width, height);
for (var y = 0; y < height; y++)
{
var row = image.GetRow(y);
for (var x = 0; x < width; x++)
{
row[x * 4] = (byte)(x * 255 / Math.Max(1, width - 1));
row[(x * 4) + 1] = (byte)(y * 255 / Math.Max(1, height - 1));
row[(x * 4) + 2] = (byte)((x + y + random.Next(3)) & 0xFF);
row[(x * 4) + 3] = (byte)(255 - (x & 0x3F));
}
}
return image;
}
/// <summary>The chunks of a PNG: type and payload, in order (the CRC is checked).</summary>
public static List<(string Type, byte[] Payload)> PngChunks(byte[] png)
{
var chunks = new List<(string, byte[])>();
var pos = 8;
while (pos < png.Length)
{
var length = (int)BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos));
var type = Encoding.ASCII.GetString(png, pos + 4, 4);
Assert.AreEqual(Crc32.Compute(png.AsSpan(pos + 4, length + 4)), BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos + 8 + length)), $"CRC di {type}");
chunks.Add((type, png.AsSpan(pos + 8, length).ToArray()));
pos += length + 12;
}
return chunks;
}
/// <summary>Writes a PNG from its chunks (signature and CRCs added).</summary>
public static byte[] Png(params (string Type, byte[] Payload)[] chunks)
{
using var output = new MemoryStream();
output.Write([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
foreach (var (type, payload) in chunks)
{
output.Write(Chunk(type, payload));
}
return output.ToArray();
}
/// <summary>One chunk: length, type, payload, CRC.</summary>
public static byte[] Chunk(string type, byte[] payload)
{
var chunk = new byte[payload.Length + 12];
BinaryPrimitives.WriteUInt32BigEndian(chunk, (uint)payload.Length);
Encoding.ASCII.GetBytes(type, chunk.AsSpan(4));
payload.CopyTo(chunk, 8);
BinaryPrimitives.WriteUInt32BigEndian(chunk.AsSpan(8 + payload.Length), Crc32.Compute(chunk.AsSpan(4, payload.Length + 4)));
return chunk;
}
/// <summary>An IHDR payload.</summary>
public static byte[] Ihdr(int width, int height, int depth, int colorType, int interlace = 0)
{
var payload = new byte[13];
BinaryPrimitives.WriteUInt32BigEndian(payload, (uint)width);
BinaryPrimitives.WriteUInt32BigEndian(payload.AsSpan(4), (uint)height);
payload[8] = (byte)depth;
payload[9] = (byte)colorType;
payload[12] = (byte)interlace;
return payload;
}
/// <summary>The zlib stream of <paramref name="data"/>.</summary>
public static byte[] Zlib(byte[] data)
{
using var output = new MemoryStream();
using (var zlib = new ZLibStream(output, CompressionLevel.Optimal, leaveOpen: true))
{
zlib.Write(data);
}
return output.ToArray();
}
/// <summary>Latin-1 bytes of a keyword or text.</summary>
public static byte[] Latin1(string text) => Encoding.Latin1.GetBytes(text);
/// <summary>Concatenation of byte arrays.</summary>
public static byte[] Join(params byte[][] parts) => parts.SelectMany(p => p).ToArray();
/// <summary>Recomputes the CRC of every chunk of a PNG whose bytes were changed (stops at the first broken length).</summary>
public static void FixPngCrcs(byte[] png)
{
var pos = 8;
while (pos + 12 <= png.Length)
{
var length = BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos));
if (length > png.Length - pos - 12)
{
return;
}
BinaryPrimitives.WriteUInt32BigEndian(png.AsSpan(pos + 8 + (int)length), Crc32.Compute(png.AsSpan(pos + 4, (int)length + 4)));
pos += (int)length + 12;
}
}
/// <summary>
/// GIF LZW data sub-blocks for <paramref name="indices"/> that use only literal codes: a clear code every few
/// literals keeps the code size at <paramref name="minCodeSize"/> + 1. Ends with the end code and the terminator.
/// </summary>
public static byte[] GifLiteralLzw(ReadOnlySpan<byte> indices, int minCodeSize)
{
var clear = 1 << minCodeSize;
var codeSize = minCodeSize + 1;
var perGroup = Math.Max(1, clear - 2);
var bits = new List<byte>();
ulong accumulator = 0;
var count = 0;
void Emit(int code)
{
accumulator |= (ulong)code << count;
count += codeSize;
while (count >= 8)
{
bits.Add((byte)accumulator);
accumulator >>= 8;
count -= 8;
}
}
for (var i = 0; i < indices.Length; i++)
{
if (i % perGroup == 0)
{
Emit(clear);
}
Emit(indices[i]);
}
Emit(clear + 1);
if (count > 0)
{
bits.Add((byte)accumulator);
}
var output = new List<byte>();
for (var i = 0; i < bits.Count; i += 255)
{
var n = Math.Min(255, bits.Count - i);
output.Add((byte)n);
output.AddRange(bits.GetRange(i, n));
}
output.Add(0);
return output.ToArray();
}
/// <summary>A GIF89a file: header, logical screen, optional global palette, then the given blocks and the trailer.</summary>
public static byte[] Gif(int width, int height, byte[]? globalPalette, params byte[][] blocks)
{
var output = new List<byte>();
output.AddRange("GIF89a"u8.ToArray());
output.AddRange(BitConverter.GetBytes((ushort)width));
output.AddRange(BitConverter.GetBytes((ushort)height));
output.Add(globalPalette is null ? (byte)0 : (byte)(0x80 | PaletteSizeBits(globalPalette)));
output.Add(0);
output.Add(0);
if (globalPalette is not null)
{
output.AddRange(globalPalette);
}
foreach (var block in blocks)
{
output.AddRange(block);
}
output.Add(0x3B);
return output.ToArray();
}
/// <summary>A graphic control extension with a transparent index (or none with -1).</summary>
public static byte[] GifControl(int transparent) =>
[0x21, 0xF9, 4, transparent >= 0 ? (byte)1 : (byte)0, 0, 0, transparent >= 0 ? (byte)transparent : (byte)0, 0];
/// <summary>An image block: descriptor, optional local palette, LZW data of <paramref name="indices"/>.</summary>
public static byte[] GifFrame(int left, int top, int width, int height, ReadOnlySpan<byte> indices, int minCodeSize, byte[]? localPalette = null, bool interlaced = false)
{
var output = new List<byte> { 0x2C };
output.AddRange(BitConverter.GetBytes((ushort)left));
output.AddRange(BitConverter.GetBytes((ushort)top));
output.AddRange(BitConverter.GetBytes((ushort)width));
output.AddRange(BitConverter.GetBytes((ushort)height));
var packed = interlaced ? 0x40 : 0;
if (localPalette is not null)
{
packed |= 0x80 | PaletteSizeBits(localPalette);
}
output.Add((byte)packed);
if (localPalette is not null)
{
output.AddRange(localPalette);
}
output.Add((byte)minCodeSize);
output.AddRange(GifLiteralLzw(indices, minCodeSize));
return output.ToArray();
}
private static int PaletteSizeBits(byte[] palette)
{
var entries = palette.Length / 3;
var bits = 0;
while ((2 << bits) < entries)
{
bits++;
}
Assert.AreEqual(2 << bits, entries, "la tavolozza di un GIF ha 2, 4, 8... voci");
return bits;
}
/// <summary>
/// A BMP with an information header of <paramref name="headerSize"/> bytes (40, 108, 124...; 12 for a core header),
/// then <paramref name="afterHeader"/> (masks, palette) and the pixel data.
/// </summary>
public static byte[] Bmp(int headerSize, int width, int height, int bitsPerPixel, uint compression, byte[] afterHeader, byte[] pixels, uint colorsUsed = 0, uint[]? masks = null)
{
var info = new byte[headerSize];
BinaryPrimitives.WriteUInt32LittleEndian(info, (uint)headerSize);
if (headerSize == 12)
{
BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(4), (ushort)width);
BinaryPrimitives.WriteInt16LittleEndian(info.AsSpan(6), (short)height);
BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(8), 1);
BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(10), (ushort)bitsPerPixel);
}
else
{
BinaryPrimitives.WriteInt32LittleEndian(info.AsSpan(4), width);
BinaryPrimitives.WriteInt32LittleEndian(info.AsSpan(8), height);
BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(12), 1);
BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(14), (ushort)bitsPerPixel);
BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(16), compression);
BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(20), (uint)pixels.Length);
BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(32), colorsUsed);
if (masks is not null)
{
for (var i = 0; i < masks.Length; i++)
{
BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(40 + (i * 4)), masks[i]);
}
}
}
var offset = 14 + headerSize + afterHeader.Length;
var file = new byte[offset + pixels.Length];
file[0] = (byte)'B';
file[1] = (byte)'M';
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(2), (uint)file.Length);
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(10), (uint)offset);
info.CopyTo(file, 14);
afterHeader.CopyTo(file, 14 + headerSize);
pixels.CopyTo(file, offset);
return file;
}
}