Correggo i difetti confermati dalla revisione di funzione/codec-immagini e aggiungo le prove che li avrebbero trovati. - JPEG: una tabella di Huffman con troppi codici corti dava ArgumentOutOfRangeException invece di ImageDecodeException, e un file rovinato faceva fallire importazione e ricostruzione; ora il controllo si fa prima di scrivere le voci. La prova che diceva di coprirlo cadeva invece su «tabella troncata»: ora tiene il totale giusto e controlla il messaggio. - JPEG: il troncamento delle scansioni di Huffman si vede a ogni riga di MCU, non dopo l'ultimo MCU (un file tagliato dopo le intestazioni costava 6,7 s). - JPEG: IDCT ridotta a 1/2 e 1/4 calcolata dai coefficienti; miniatura di una foto 4000x3000 da 126 a 59 ms in Release. Il predittore senza perdita non cerca più l'indice della componente a ogni campione. - WebP: con livello del filtro del fotogramma 0 il filtro è spento, come nei decodificatori di riferimento; VP8L costruisce solo i gruppi nominati dai meta codici (prima fino a 335 MB di tabelle da 160 KB di file). - BMP OS/2: altezza senza segno e sempre dal basso. - Array di lavoro dei codec oltre 16 MiB fuori dal pool condiviso, che li avrebbe tenuti dopo l'uso. - Conversione: profilo ICC copiato solo se RGB, profondità oltre 8 bit e blocchi gAMA/cHRM/sRGB dichiarati in NotCarried, Lossy vero quando si perde precisione. - Impronta e misure di una foto da una sola lettura e decodifica; ReadSize legge solo l'inizio di JPEG, GIF e BMP. - docs: decisioni (righe aggiunte, con la correzione dei 2,0 MB del set di riferimento) e windows.md (Febe.exe rimisurato: 85,6 MB, a capo sistemato). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
532 lines
17 KiB
C#
532 lines
17 KiB
C#
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 = ImageBuffers.Rent<byte>((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
|
|
{
|
|
ImageBuffers.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);
|
|
}
|
|
}
|
|
}
|