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,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user