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; /// /// 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. /// 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 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, ]; /// Whether the bytes start with the PNG signature. public static bool IsPng(ReadOnlySpan data) => data.Length >= 8 && data[..8].SequenceEqual(ImageFormatSniffer.PngSignature); /// Size, frames and metadata of a PNG, without decoding the pixels. public static ImageInfo Identify(ReadOnlyMemory data, ImageLimits? limits = null) { var file = Parse(data, limits ?? ImageLimits.Default, readMetadata: true); return file.ToInfo(); } /// Decodes a PNG to straight RGBA8. /// The file is damaged, truncated or not a PNG. /// The image is larger than allow. public static RgbaImage Decode(ReadOnlyMemory data, ImageLimits? limits = null, bool pooled = false) { limits ??= ImageLimits.Default; var file = Parse(data, limits, readMetadata: false); RequireEnd(file); return DecodePixels(data, file, limits, pooled); } /// Decodes a PNG to straight RGBA8 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 file = Parse(data, limits, readMetadata: true); RequireEnd(file); var image = DecodePixels(data, file, limits, pooled); info = file.ToInfo(); return image; } /// /// Spec §3, §8.4: a PNG that ends before its end marker is incomplete, even when its image data is complete, and is /// not decoded; still reads its size. /// private static void RequireEnd(PngFile file) { if (!file.SeenEnd) { throw new ImageDecodeException("PNG troncato: manca il blocco di fine (IEND)."); } } private sealed class PngFile { public bool SeenEnd; public int Width; public int Height; public int BitDepth; public int ColorType; public bool Interlaced; /// 256 RGBA entries; entries the file does not give are opaque black. 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? Texts; public List? ColorChunks; public List? Unread; public bool Animated; 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 && ColorChunks is null && Unread is null ? ImageMetadata.Empty : new ImageMetadata { Exif = Exif, Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif), IccProfile = Icc, IccProfileName = IccName, Xmp = Xmp, Texts = Texts ?? [], ColorChunks = ColorChunks ?? [], Unread = Unread ?? [], }) { BitsPerSample = ColorType == 3 ? 8 : BitDepth, IsAnimated = Animated, }; } private static PngFile Parse(ReadOnlyMemory 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 seenEnd = false; 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": seenEnd = true; pos = data.Length; break; case "acTL": file.Animated |= idatState == 0; if (payload.Length >= 8 && idatState == 0) { var frames = BinaryPrimitives.ReadUInt32BigEndian(payload); file.FrameCount = frames is > 0 and <= int.MaxValue ? (int)frames : 1; } break; case "gAMA" or "cHRM" or "sRGB": if (readMetadata && !(file.ColorChunks ??= []).Contains(name)) { file.ColorChunks.Add(name); } break; case "tEXt" or "zTXt" or "iTXt" or "iCCP" or "eXIf": if (readMetadata) { ReadMetadata(file, name, payload, ref metadataBudget); } break; case "fcTL" or "fdAT": break; default: if (critical) { throw new ImageFormatNotSupportedException($"PNG con un blocco critico che Febe non conosce ({name})."); } if (readMetadata && !(file.Unread ??= []).Contains(name)) { file.Unread.Add(name); } break; } } if (!seenHeader) { throw new ImageDecodeException("PNG troncato: manca IHDR."); } if (idatState == 0) { throw new ImageDecodeException("PNG senza dati dell'immagine (IDAT)."); } file.SeenEnd = seenEnd; return file; } private static bool IsChunkType(ReadOnlySpan type) { foreach (var c in type) { if (!char.IsAsciiLetter((char)c)) { return false; } } return true; } private static void ReadHeader(PngFile file, ReadOnlySpan 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 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 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 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 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; } /// Inflates a zlib stream of metadata; null when it is damaged or longer than . internal static byte[]? Inflate(ReadOnlySpan 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 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.Shared.Rent((int)maxRow + 1); var previous = ArrayPool.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.Shared.Return(current); ArrayPool.Shared.Return(previous); } } private static void DecodePass( ZLibStream zlib, PngFile file, int width, int height, int bpp, byte[] current, byte[] previous, Span 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; } } /// Undoes the row filter (PNG specification §7.3, §9.2): is changed in place. internal static void Unfilter(byte filter, Span row, ReadOnlySpan 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.Count; for (; i + width <= n; i += width) { (new Vector(row[i..]) + new Vector(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})."); } } /// The Paeth predictor (PNG specification §9.4). 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; } /// Converts pixels of an unfiltered row to RGBA8, one pixel every bytes. private static void ConvertRow(PngFile file, ReadOnlySpan row, int count, Span 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(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 row, int count, Span 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(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(palette.AsSpan(index * 4))); } } private static void ConvertLowGrey(ReadOnlySpan row, int count, Span 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; } } }