Lettori PNG, GIF e BMP e scrittore PNG di casa (C1, passo 2)
Prima parte dei codec d'immagine scritti in casa per togliere SkiaSharp (decisione di Alberto del 18 novembre 2026: niente componenti esterni). In Febe.Core/Codecs/Images: la base comune (RgbaImage RGBA a 8 bit non premoltiplicata, anche dal pool; ImageLimits controllati prima di ogni allocazione; ImageDecodeException e sottotipi per limiti e formati non letti; riconoscimento del formato dai primi byte; facciata ImageDecoder), il lettore PNG (tutti i tipi di colore e le profondità, tavolozza e tRNS, Adam7, i cinque filtri, CRC di ogni blocco, metadati eXIf, iCCP, tEXt, zTXt, iTXt e XMP, numero dei fotogrammi APNG), lo scrittore PNG (RGB/RGBA a 8 bit, filtro adattivo per riga, eXIf, iCCP, XMP), il lettore GIF (LZW, primo fotogramma, trasparenza, interlacciamento, tavolozze, numero dei fotogrammi) e il lettore BMP (1-32 bit, BI_RGB, BITFIELDS, RLE8, RLE4, PNG dentro, dal basso e dall'alto). CRC-32 e LZW sono nostri, zlib è quello della BCL. Le prove leggono i 37 riferimenti PNG, GIF e BMP e li trovano uguali byte per byte alle immagini attese, lette a loro volta con il nostro lettore PNG verificato contro un lettore minimo indipendente; poi andate e ritorno dello scrittore, metadati, file danneggiati e tagliati, limiti, e modifiche casuali a seme fisso che devono dare un'immagine o un'ImageDecodeException e nient'altro. Una riga in decisioni.md dice le scelte di lettura. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3e4608c62d
commit
8bf76f18ff
23 files changed
+4382
-4
No files matched your search
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
Reference in new issue
Block a user