using System.Buffers; using System.Buffers.Binary; using System.Text; namespace Febe.Core.Codecs.Images; /// /// Reads GIF files (GIF87a and GIF89a): the first frame only, on a canvas of the logical screen size, with global or /// local palette, the transparent index of its graphic control extension and interlacing. Outside the first frame, /// and where the frame's index is transparent, the canvas is (0, 0, 0, 0); the background colour is not painted, as /// browsers do. Disposal methods only matter from the second frame, which is not decoded; the frames are counted. /// A file that ends before its trailer, or LZW data that stops early, gives what was decoded so far. /// public static class GifDecoder { private const int MaxCodeBits = 12; private const int MaxCodes = 1 << MaxCodeBits; /// Whether the bytes start with a GIF signature. public static bool IsGif(ReadOnlySpan data) => data.Length >= 6 && data[..3].SequenceEqual("GIF"u8) && (data[3..6].SequenceEqual("89a"u8) || data[3..6].SequenceEqual("87a"u8)); /// Canvas size, frame count and comments of a GIF, without decoding the pixels. public static ImageInfo Identify(ReadOnlyMemory data, ImageLimits? limits = null) { limits ??= ImageLimits.Default; var file = Walk(data.Span, limits, countFrames: true); return file.ToInfo(); } /// Decodes the first frame of a GIF to straight RGBA8. /// The file is damaged, has no frame or is not a GIF. /// The image is larger than allow. public static RgbaImage Decode(ReadOnlyMemory data, ImageLimits? limits = null, bool pooled = false) { limits ??= ImageLimits.Default; var span = data.Span; var file = Walk(span, limits, countFrames: false); return DecodeFirstFrame(span, file, limits, pooled); } /// Decodes the first frame of a GIF and returns what returns as well. public static RgbaImage Decode(ReadOnlyMemory data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false) { limits ??= ImageLimits.Default; var span = data.Span; var file = Walk(span, limits, countFrames: true); var image = DecodeFirstFrame(span, file, limits, pooled); info = file.ToInfo(); return image; } private sealed class GifFile { public int CanvasWidth; public int CanvasHeight; public int GlobalPaletteStart = -1; public int GlobalPaletteCount; public int FrameCount; public int FrameLeft; public int FrameTop; public int FrameWidth; public int FrameHeight; public bool FrameInterlaced; public int FramePaletteStart = -1; public int FramePaletteCount; public int FrameTransparent = -1; public int FrameCodeSize; public int FrameDataStart; public List? Comments; public ImageInfo ToInfo() => new( ImageFormat.Gif, CanvasWidth, CanvasHeight, Math.Max(1, FrameCount), true, Comments is null ? ImageMetadata.Empty : new ImageMetadata { Texts = Comments }); } private static GifFile Walk(ReadOnlySpan data, ImageLimits limits, bool countFrames) { if (!IsGif(data)) { throw new ImageDecodeException("Non รจ un file GIF."); } if (data.Length < 13) { throw new ImageDecodeException("GIF troncato: manca il descrittore dello schermo logico."); } var file = new GifFile { CanvasWidth = BinaryPrimitives.ReadUInt16LittleEndian(data[6..]), CanvasHeight = BinaryPrimitives.ReadUInt16LittleEndian(data[8..]), }; var packed = data[10]; var pos = 13; if ((packed & 0x80) != 0) { file.GlobalPaletteCount = 2 << (packed & 7); file.GlobalPaletteStart = pos; pos += file.GlobalPaletteCount * 3; if (pos > data.Length) { throw new ImageDecodeException("GIF troncato: la tavolozza globale finisce dopo il file."); } } var transparent = -1; var metadataBudget = limits.MaxMetadataBytes; while (pos < data.Length) { var block = data[pos++]; if (block == 0x3B) { break; } if (block == 0x21) { if (pos >= data.Length) { break; } var label = data[pos++]; if (label == 0xF9 && pos + 5 <= data.Length && data[pos] >= 4) { // Graphic control extension: the transparent index applies to the next image only. transparent = (data[pos + 1] & 1) != 0 ? data[pos + 4] : -1; } else if (label == 0xFE && file.FrameCount == 0) { ReadComment(data, pos, file, ref metadataBudget); } pos = SkipSubBlocks(data, pos); continue; } if (block != 0x2C) { // Not a block GIF knows: what follows cannot be read; browsers stop here too. break; } if (pos + 9 > data.Length) { break; } file.FrameCount++; var framePacked = data[pos + 8]; if (file.FrameCount == 1) { file.FrameLeft = BinaryPrimitives.ReadUInt16LittleEndian(data[pos..]); file.FrameTop = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 2)..]); file.FrameWidth = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 4)..]); file.FrameHeight = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 6)..]); file.FrameInterlaced = (framePacked & 0x40) != 0; file.FrameTransparent = transparent; } pos += 9; if ((framePacked & 0x80) != 0) { var count = 2 << (framePacked & 7); if (file.FrameCount == 1) { file.FramePaletteStart = pos; file.FramePaletteCount = count; } pos += count * 3; if (pos > data.Length) { if (file.FrameCount == 1) { throw new ImageDecodeException("GIF troncato: la tavolozza locale finisce dopo il file."); } file.FrameCount--; break; } } if (pos >= data.Length) { if (file.FrameCount == 1) { throw new ImageDecodeException("GIF troncato: mancano i dati del primo fotogramma."); } file.FrameCount--; break; } if (file.FrameCount == 1) { file.FrameCodeSize = data[pos]; file.FrameDataStart = pos + 1; if (!countFrames) { break; } } pos = SkipSubBlocks(data, pos + 1); transparent = -1; } if (file.FrameCount == 0) { throw new ImageDecodeException("GIF senza fotogrammi."); } if (file.CanvasWidth == 0 || file.CanvasHeight == 0) { // Some encoders leave the logical screen empty: the first frame then gives the size. file.CanvasWidth = file.FrameLeft + file.FrameWidth; file.CanvasHeight = file.FrameTop + file.FrameHeight; } return file; } private static int SkipSubBlocks(ReadOnlySpan data, int pos) { while (pos < data.Length) { var size = data[pos++]; if (size == 0) { return pos; } pos += size; } return data.Length; } private static void ReadComment(ReadOnlySpan data, int pos, GifFile file, ref int budget) { var builder = new StringBuilder(); while (pos < data.Length) { var size = data[pos++]; if (size == 0) { break; } var n = Math.Min(size, data.Length - pos); if (n > budget) { return; } budget -= n; builder.Append(Encoding.Latin1.GetString(data.Slice(pos, n))); pos += n; } (file.Comments ??= []).Add(new ImageText(string.Empty, builder.ToString())); } private static RgbaImage DecodeFirstFrame(ReadOnlySpan data, GifFile file, ImageLimits limits, bool pooled) { var (paletteStart, paletteCount) = file.FramePaletteStart >= 0 ? (file.FramePaletteStart, file.FramePaletteCount) : (file.GlobalPaletteStart, file.GlobalPaletteCount); if (paletteStart < 0) { throw new ImageDecodeException("GIF danneggiato: il primo fotogramma non ha tavolozza."); } if (file.FrameCodeSize is < 1 or > MaxCodeBits - 1) { throw new ImageDecodeException($"GIF danneggiato: dimensione iniziale dei codici LZW non valida ({file.FrameCodeSize})."); } var image = RgbaImage.Create(file.CanvasWidth, file.CanvasHeight, limits, pooled); var frameWidth = file.FrameWidth; var frameHeight = file.FrameHeight; if (frameWidth == 0 || frameHeight == 0) { return image; } var frameBytes = (long)frameWidth * frameHeight; limits.CheckWorkingBytes(frameBytes); var indices = ImageBuffers.Rent((int)frameBytes); try { var decoded = DecodeLzw(data, file.FrameDataStart, file.FrameCodeSize, indices.AsSpan(0, (int)frameBytes)); // RGBA of each palette index; indices beyond the palette are opaque black, the transparent one is skipped. Span colours = stackalloc uint[256]; Span rgba = stackalloc byte[4]; for (var i = 0; i < 256; i++) { if (i < paletteCount) { var p = paletteStart + (i * 3); rgba[0] = data[p]; rgba[1] = data[p + 1]; rgba[2] = data[p + 2]; } else { rgba[0] = rgba[1] = rgba[2] = 0; } rgba[3] = 255; colours[i] = BinaryPrimitives.ReadUInt32LittleEndian(rgba); } var transparent = file.FrameTransparent; var pixels = image.Pixels; var canvasWidth = file.CanvasWidth; var canvasHeight = file.CanvasHeight; var visibleWidth = Math.Min(frameWidth, canvasWidth - file.FrameLeft); for (var r = 0; r < frameHeight; r++) { var rowStart = r * frameWidth; if (rowStart >= decoded) { break; } var y = file.FrameTop + (file.FrameInterlaced ? InterlacedRow(r, frameHeight) : r); if (y >= canvasHeight || visibleWidth <= 0) { continue; } var count = Math.Min(visibleWidth, decoded - rowStart); var destination = pixels.Slice(((y * canvasWidth) + file.FrameLeft) * RgbaImage.BytesPerPixel, count * RgbaImage.BytesPerPixel); var source = indices.AsSpan(rowStart, count); for (var x = 0; x < count; x++) { var index = source[x]; if (index != transparent) { BinaryPrimitives.WriteUInt32LittleEndian(destination[(x * 4)..], colours[index]); } } } return image; } catch { image.Dispose(); throw; } finally { ImageBuffers.Return(indices); } } /// The row of the image that the -th decoded row of an interlaced frame fills. internal static int InterlacedRow(int r, int height) { var pass1 = (height + 7) / 8; if (r < pass1) { return r * 8; } r -= pass1; var pass2 = (height + 3) / 8; if (r < pass2) { return 4 + (r * 8); } r -= pass2; var pass3 = (height + 1) / 4; if (r < pass3) { return 2 + (r * 4); } r -= pass3; return 1 + (r * 2); } /// /// Decodes the LZW data sub-blocks that start at into (GIF89a /// appendix F: variable-length codes from + 1 bits up to 12, least significant bit /// first) and returns how many indices were written. A damaged stream stops the decoding there. /// internal static int DecodeLzw(ReadOnlySpan data, int pos, int minCodeSize, Span output) { var prefix = ArrayPool.Shared.Rent(MaxCodes); var lengths = ArrayPool.Shared.Rent(MaxCodes); var suffix = ArrayPool.Shared.Rent(MaxCodes); var first = ArrayPool.Shared.Rent(MaxCodes); try { var clear = 1 << minCodeSize; var end = clear + 1; for (var i = 0; i < clear; i++) { prefix[i] = 0; lengths[i] = 1; suffix[i] = (byte)i; first[i] = (byte)i; } var codeSize = minCodeSize + 1; var next = clear + 2; var old = -1; var written = 0; uint bits = 0; var bitCount = 0; var blockLeft = 0; while (written < output.Length) { while (bitCount < codeSize) { if (blockLeft == 0) { if (pos >= data.Length || data[pos] == 0) { return written; } blockLeft = data[pos++]; } if (pos >= data.Length) { return written; } bits |= (uint)data[pos++] << bitCount; bitCount += 8; blockLeft--; } var code = (int)(bits & ((1u << codeSize) - 1)); bits >>= codeSize; bitCount -= codeSize; if (code == clear) { codeSize = minCodeSize + 1; next = clear + 2; old = -1; continue; } if (code == end) { return written; } if (old < 0) { if (code > clear) { return written; } output[written++] = (byte)code; old = code; if (next >= 1 << codeSize && codeSize < MaxCodeBits) { codeSize++; } continue; } if (code > next || (code == next && next >= MaxCodes)) { return written; } if (next < MaxCodes) { // The new entry is the previous string followed by the first byte of the current one; when the code // is the entry being made (KwKwK), that first byte is the previous string's own. var firstByte = code == next ? first[old] : first[code]; prefix[next] = (ushort)old; suffix[next] = firstByte; first[next] = first[old]; lengths[next] = (ushort)(lengths[old] + 1); next++; } var length = lengths[code]; var stop = written + length; var c = code; for (var o = stop - 1; o >= written; o--) { if (o < output.Length) { output[o] = suffix[c]; } c = prefix[c]; } written = Math.Min(stop, output.Length); old = code; if (next >= 1 << codeSize && codeSize < MaxCodeBits) { codeSize++; } } return written; } finally { ArrayPool.Shared.Return(prefix); ArrayPool.Shared.Return(lengths); ArrayPool.Shared.Return(suffix); ArrayPool.Shared.Return(first); } } }