diff --git a/src/Titano.Core/Codecs/Png/PngDecoder.cs b/src/Titano.Core/Codecs/Png/PngDecoder.cs
new file mode 100644
index 00000000..72d74a2e
--- /dev/null
+++ b/src/Titano.Core/Codecs/Png/PngDecoder.cs
@@ -0,0 +1,359 @@
+using System.Buffers.Binary;
+using System.IO.Compression;
+using Titano.Core.Hashing;
+using Titano.Core.Imaging;
+
+namespace Titano.Core.Codecs.Png;
+
+/// IHDR facts of a PNG stream.
+public sealed record PngInfo(int Width, int Height, int BitDepth, PngColorType ColorType, bool Interlaced);
+
+/// Decoded PNG pixels: interleaved, top-down, palette and tRNS expanded.
+public sealed class PngImage
+{
+ internal PngImage(PngInfo info, int channels, byte[]? pixels8, ushort[]? pixels16, IReadOnlyList warnings)
+ {
+ Info = info;
+ Channels = channels;
+ Pixels8 = pixels8;
+ Pixels16 = pixels16;
+ Warnings = warnings;
+ }
+
+ public PngInfo Info { get; }
+ public int Width => Info.Width;
+ public int Height => Info.Height;
+
+ /// 1 = gray, 2 = gray+alpha, 3 = RGB, 4 = RGBA (palette → RGB/RGBA; tRNS adds alpha).
+ public int Channels { get; }
+
+ /// 8 (; 1/2/4-bit gray is scaled to 0..255) or 16 ().
+ public int BitDepth => Pixels16 is null ? 8 : 16;
+
+ public byte[]? Pixels8 { get; }
+ public ushort[]? Pixels16 { get; }
+
+ /// Recoverable problems (CRC mismatches, truncated or corrupt image data, unknown critical chunks).
+ public IReadOnlyList Warnings { get; }
+}
+
+///
+/// PNG decoder: every colour type and bit depth (1/2/4/8/16), PLTE + tRNS, Adam7, all five filters, zlib through
+/// . CRC mismatches are tolerated with a warning; damaged image data yields the rows decoded so
+/// far plus a warning. Ancillary colour chunks (gAMA, iCCP, cHRM) are ignored: samples are taken as sRGB.
+///
+public static class PngDecoder
+{
+ private static ReadOnlySpan Signature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
+
+ private static readonly (int X, int Y, int Dx, int Dy)[] 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)];
+
+ public static PngInfo ReadInfo(ReadOnlySpan data)
+ {
+ if (data.Length < 33 || !data.StartsWith(Signature) || !data.Slice(12, 4).SequenceEqual("IHDR"u8))
+ throw new InvalidDataException("PNG: missing signature or IHDR");
+ return ParseHeader(data.Slice(16, 13));
+ }
+
+ /// Upper bound on width × height, checked before allocation.
+ public static PngImage Decode(ReadOnlySpan data, long maxPixels = 1L << 28)
+ {
+ var info = ReadInfo(data);
+ if ((long)info.Width * info.Height > maxPixels) throw new InvalidDataException($"PNG: {info.Width}x{info.Height} exceeds the pixel limit");
+ var warnings = new List();
+ byte[]? palette = null;
+ byte[]? trns = null;
+ using var idat = new MemoryStream();
+ var pos = 8;
+ var ended = false;
+ while (pos + 8 <= data.Length)
+ {
+ var length = BinaryPrimitives.ReadUInt32BigEndian(data[pos..]);
+ var type = data.Slice(pos + 4, 4);
+ if (length > int.MaxValue || pos + 12 + (long)length > data.Length)
+ {
+ warnings.Add("PNG: truncated chunk");
+ break;
+ }
+ var body = data.Slice(pos + 8, (int)length);
+ var crc = BinaryPrimitives.ReadUInt32BigEndian(data[(pos + 8 + (int)length)..]);
+ if (Crc32.Compute(data.Slice(pos + 4, 4 + (int)length)) != crc) warnings.Add($"PNG: CRC mismatch in {Name(type)}");
+ pos += 12 + (int)length;
+ if (type.SequenceEqual("IDAT"u8))
+ {
+ idat.Write(body);
+ }
+ else if (type.SequenceEqual("PLTE"u8))
+ {
+ if (body.Length % 3 != 0 || body.Length > 768 || body.Length == 0) throw new InvalidDataException("PNG: bad PLTE");
+ palette = body.ToArray();
+ }
+ else if (type.SequenceEqual("tRNS"u8))
+ {
+ trns = body.ToArray();
+ }
+ else if (type.SequenceEqual("IEND"u8))
+ {
+ ended = true;
+ break;
+ }
+ else if (!type.SequenceEqual("IHDR"u8) && (type[0] & 0x20) == 0)
+ {
+ warnings.Add($"PNG: unknown critical chunk {Name(type)} ignored");
+ }
+ }
+ if (!ended) warnings.Add("PNG: missing IEND");
+ if (idat.Length == 0) throw new InvalidDataException("PNG: no image data");
+ if (info.ColorType == PngColorType.Palette && palette is null) throw new InvalidDataException("PNG: palette image without PLTE");
+
+ var layout = Layout.For(info, palette, trns);
+ idat.Position = 0;
+ using var z = new ZLibStream(idat, CompressionMode.Decompress);
+ return layout.Sixteen ? Decode16(info, layout, z, warnings) : Decode8(info, layout, z, warnings);
+ }
+
+ /// Decodes into a linear-light buffer (samples are sRGB-encoded; alpha stays linear).
+ /// Return gray as three identical channels.
+ /// Keep alpha as a fourth channel (gray is then expanded).
+ public static ImageBuffer DecodeToLinear(ReadOnlySpan data, bool expandGray = false, bool keepAlpha = false)
+ {
+ var image = Decode(data);
+ var gray = image.Channels <= 2;
+ var hasAlpha = image.Channels is 2 or 4;
+ var output = keepAlpha && hasAlpha ? 4 : gray && !expandGray ? 1 : 3;
+ return image.Pixels8 is { } p8
+ ? PixelConvert.FromInterleaved8(p8, image.Width, image.Height, image.Channels, outputChannels: output)
+ : PixelConvert.FromInterleaved16(image.Pixels16, image.Width, image.Height, image.Channels, outputChannels: output);
+ }
+
+ private static string Name(ReadOnlySpan type) => string.Create(4, type.ToArray(), (s, t) =>
+ {
+ for (var i = 0; i < 4; i++) s[i] = t[i] is >= 32 and < 127 ? (char)t[i] : '?';
+ });
+
+ private static PngInfo ParseHeader(ReadOnlySpan h)
+ {
+ var width = BinaryPrimitives.ReadUInt32BigEndian(h);
+ var height = BinaryPrimitives.ReadUInt32BigEndian(h[4..]);
+ int depth = h[8], type = h[9];
+ if (width is 0 or > int.MaxValue || height is 0 or > int.MaxValue) throw new InvalidDataException("PNG: bad dimensions");
+ var valid = type 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 InvalidDataException($"PNG: invalid colour type {type} / bit depth {depth}");
+ if (h[10] != 0 || h[11] != 0 || h[12] > 1) throw new InvalidDataException("PNG: unsupported compression, filter or interlace method");
+ return new PngInfo((int)width, (int)height, depth, (PngColorType)type, h[12] == 1);
+ }
+
+ /// Sample geometry of the stored scanlines and of the expanded output.
+ private sealed class Layout
+ {
+ public int SourceChannels, BitsPerPixel, BytesPerPixel, OutChannels;
+ public bool Sixteen;
+ public byte[]? Palette;
+ public byte[]? PaletteAlpha;
+
+ /// tRNS colour key in source sample units (gray: 1 value, RGB: 3), or null.
+ public int[]? Key;
+
+ public static Layout For(PngInfo info, byte[]? palette, byte[]? trns)
+ {
+ var l = new Layout
+ {
+ SourceChannels = info.ColorType switch
+ {
+ PngColorType.Gray or PngColorType.Palette => 1,
+ PngColorType.GrayAlpha => 2,
+ PngColorType.Rgb => 3,
+ _ => 4,
+ },
+ Sixteen = info.BitDepth == 16,
+ };
+ l.BitsPerPixel = l.SourceChannels * info.BitDepth;
+ l.BytesPerPixel = Math.Max(1, l.BitsPerPixel / 8);
+ l.OutChannels = l.SourceChannels;
+ switch (info.ColorType)
+ {
+ case PngColorType.Palette:
+ l.Palette = palette;
+ l.OutChannels = 3;
+ if (trns is { Length: > 0 })
+ {
+ l.PaletteAlpha = new byte[256];
+ Array.Fill(l.PaletteAlpha, (byte)255);
+ trns.AsSpan(0, Math.Min(trns.Length, 256)).CopyTo(l.PaletteAlpha);
+ l.OutChannels = 4;
+ }
+ break;
+ case PngColorType.Gray when trns is { Length: >= 2 }:
+ l.Key = [trns[0] << 8 | trns[1]];
+ l.OutChannels = 2;
+ break;
+ case PngColorType.Rgb when trns is { Length: >= 6 }:
+ l.Key = [trns[0] << 8 | trns[1], trns[2] << 8 | trns[3], trns[4] << 8 | trns[5]];
+ l.OutChannels = 4;
+ break;
+ }
+ return l;
+ }
+ }
+
+ private static PngImage Decode8(PngInfo info, Layout l, Stream z, List warnings)
+ {
+ var pixels = new byte[checked((long)info.Width * info.Height * l.OutChannels)];
+ var row = new byte[info.Width * l.OutChannels];
+ Inflate(info, l, z, warnings, (raw, y, x0, dx, count) =>
+ {
+ Expand8(raw, info.BitDepth, count, l, row);
+ for (int i = 0, x = x0; i < count; i++, x += dx)
+ {
+ row.AsSpan(i * l.OutChannels, l.OutChannels).CopyTo(pixels.AsSpan((int)(((long)y * info.Width + x) * l.OutChannels)));
+ }
+ });
+ return new PngImage(info, l.OutChannels, pixels, null, warnings);
+ }
+
+ private static PngImage Decode16(PngInfo info, Layout l, Stream z, List warnings)
+ {
+ var pixels = new ushort[checked((long)info.Width * info.Height * l.OutChannels)];
+ Inflate(info, l, z, warnings, (raw, y, x0, dx, count) =>
+ {
+ for (int i = 0, x = x0; i < count; i++, x += dx)
+ {
+ var dst = pixels.AsSpan((int)(((long)y * info.Width + x) * l.OutChannels), l.OutChannels);
+ var transparent = l.Key is not null;
+ for (var c = 0; c < l.SourceChannels; c++)
+ {
+ dst[c] = BinaryPrimitives.ReadUInt16BigEndian(raw[((i * l.SourceChannels + c) * 2)..]);
+ if (l.Key is not null && dst[c] != l.Key[c]) transparent = false;
+ }
+ if (l.Key is not null) dst[l.SourceChannels] = transparent ? (ushort)0 : ushort.MaxValue;
+ }
+ });
+ return new PngImage(info, l.OutChannels, null, pixels, warnings);
+ }
+
+ private delegate void RowHandler(ReadOnlySpan raw, int y, int x0, int dx, int count);
+
+ /// Streams every (pass,) row out of zlib, unfilters it and hands the raw samples to .
+ private static void Inflate(PngInfo info, Layout l, Stream z, List warnings, RowHandler handle)
+ {
+ var passes = info.Interlaced ? Adam7 : [(0, 0, 1, 1)];
+ var maxRow = (int)(((long)info.Width * l.BitsPerPixel + 7) / 8);
+ var line = new byte[maxRow + 1];
+ var prior = new byte[maxRow];
+ try
+ {
+ foreach (var (px, py, dx, dy) in passes)
+ {
+ if (px >= info.Width || py >= info.Height) continue;
+ var count = (info.Width - px + dx - 1) / dx;
+ var rowBytes = (int)(((long)count * l.BitsPerPixel + 7) / 8);
+ Array.Clear(prior);
+ for (var y = py; y < info.Height; y += dy)
+ {
+ var buffer = line.AsSpan(0, rowBytes + 1);
+ if (z.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) < buffer.Length)
+ {
+ warnings.Add("PNG: image data truncated");
+ return;
+ }
+ if (buffer[0] > 4)
+ {
+ warnings.Add($"PNG: invalid filter type {buffer[0]}");
+ return;
+ }
+ var row = buffer[1..];
+ Unfilter(buffer[0], row, prior.AsSpan(0, rowBytes), l.BytesPerPixel);
+ handle(row, y, px, dx, count);
+ row.CopyTo(prior);
+ }
+ }
+ }
+ catch (InvalidDataException ex)
+ {
+ warnings.Add("PNG: corrupt image data: " + ex.Message);
+ }
+ }
+
+ private static void Unfilter(int filter, Span row, ReadOnlySpan prior, int bpp)
+ {
+ switch (filter)
+ {
+ case 1:
+ for (var i = bpp; i < row.Length; i++) row[i] += row[i - bpp];
+ break;
+ case 2:
+ for (var i = 0; i < row.Length; i++) row[i] += prior[i];
+ break;
+ case 3:
+ for (var i = 0; i < bpp && i < row.Length; i++) row[i] += (byte)(prior[i] >> 1);
+ for (var i = bpp; i < row.Length; i++) row[i] += (byte)((row[i - bpp] + prior[i]) >> 1);
+ break;
+ case 4:
+ for (var i = 0; i < bpp && i < row.Length; i++) row[i] += prior[i];
+ for (var i = bpp; i < row.Length; i++) row[i] += (byte)PngEncoder.Paeth(row[i - bpp], prior[i], prior[i - bpp]);
+ break;
+ }
+ }
+
+ /// Expands one row of ≤ 8-bit samples (sub-byte gray, palette, tRNS key) to 8-bit output channels.
+ private static void Expand8(ReadOnlySpan raw, int depth, int count, Layout l, Span dst)
+ {
+ var oc = l.OutChannels;
+ if (depth == 8 && l.Palette is null && l.Key is null)
+ {
+ raw[..(count * oc)].CopyTo(dst);
+ return;
+ }
+ if (depth == 8 && l.Key is not null)
+ {
+ var sc = l.SourceChannels;
+ for (var i = 0; i < count; i++)
+ {
+ var opaque = false;
+ for (var c = 0; c < sc; c++)
+ {
+ var v = raw[i * sc + c];
+ dst[i * oc + c] = v;
+ if (v != l.Key[c]) opaque = true;
+ }
+ dst[i * oc + sc] = opaque ? (byte)255 : (byte)0;
+ }
+ return;
+ }
+ // Sub-byte or palette: one sample per pixel, MSB first.
+ var mask = (1 << depth) - 1;
+ var scale = l.Palette is null ? 255 / mask : 1;
+ for (var i = 0; i < count; i++)
+ {
+ var bit = i * depth;
+ var v = (raw[bit >> 3] >> (8 - depth - (bit & 7))) & mask;
+ if (l.Palette is { } pal)
+ {
+ var o = dst.Slice(i * oc, oc);
+ if (3 * v + 2 < pal.Length)
+ {
+ o[0] = pal[3 * v];
+ o[1] = pal[3 * v + 1];
+ o[2] = pal[3 * v + 2];
+ }
+ else
+ {
+ o[..3].Clear(); // out-of-range index: black, as libpng
+ }
+ if (oc == 4) o[3] = l.PaletteAlpha![v];
+ }
+ else
+ {
+ dst[i * oc] = (byte)(v * scale);
+ if (l.Key is not null) dst[i * oc + 1] = v == l.Key[0] ? (byte)0 : (byte)255;
+ }
+ }
+ }
+}
diff --git a/src/Titano.Core/Codecs/Png/PngEncoder.cs b/src/Titano.Core/Codecs/Png/PngEncoder.cs
index 6c9273fc..3fc68112 100644
--- a/src/Titano.Core/Codecs/Png/PngEncoder.cs
+++ b/src/Titano.Core/Codecs/Png/PngEncoder.cs
@@ -1,14 +1,16 @@
using System.Buffers.Binary;
using System.IO.Compression;
using Titano.Core.Hashing;
+using Titano.Core.Imaging;
namespace Titano.Core.Codecs.Png;
-/// PNG colour types written by .
+/// PNG colour types ( is decoded but never written by ).
public enum PngColorType : byte
{
Gray = 0,
Rgb = 2,
+ Palette = 3,
GrayAlpha = 4,
Rgba = 6,
}
@@ -29,6 +31,7 @@ public static class PngEncoder
public static void Encode(Stream output, ReadOnlySpan pixels, int width, int height, PngColorType colorType, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize, IEnumerable<(string Type, byte[] Data)>? extraChunks = null)
{
if (bitDepth is not (8 or 16)) throw new ArgumentOutOfRangeException(nameof(bitDepth));
+ if (colorType == PngColorType.Palette) throw new ArgumentException("Palette images are not written", nameof(colorType));
var channels = colorType switch
{
PngColorType.Gray => 1,
@@ -60,6 +63,36 @@ public static class PngEncoder
WriteChunk(output, "IEND", []);
}
+ /// Encodes a linear-light buffer as sRGB-encoded PNG (1 channel → gray, 3 → RGB, 4 → RGBA with linear
+ /// alpha) and tags it with an sRGB chunk.
+ /// 8 or 16 bits per sample.
+ public static byte[] Encode(ImageBuffer image, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize)
+ {
+ using var ms = new MemoryStream();
+ Encode(ms, image, bitDepth, level);
+ return ms.ToArray();
+ }
+
+ public static void Encode(Stream output, ImageBuffer image, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize, IEnumerable<(string Type, byte[] Data)>? extraChunks = null)
+ {
+ if (bitDepth is not (8 or 16)) throw new ArgumentOutOfRangeException(nameof(bitDepth));
+ var channels = image.Channels;
+ var colorType = channels switch { 1 => PngColorType.Gray, 3 => PngColorType.Rgb, _ => PngColorType.Rgba };
+ byte[] pixels;
+ if (bitDepth == 8)
+ {
+ pixels = PixelConvert.ToInterleaved8(image, channels);
+ }
+ else
+ {
+ var words = PixelConvert.ToInterleaved16(image, channels);
+ pixels = new byte[words.Length * 2];
+ for (var i = 0; i < words.Length; i++) BinaryPrimitives.WriteUInt16BigEndian(pixels.AsSpan(2 * i), words[i]);
+ }
+ IEnumerable<(string Type, byte[] Data)> chunks = [("sRGB", [0]), .. extraChunks ?? []];
+ Encode(output, pixels, image.Width, image.Height, colorType, bitDepth, level, chunks);
+ }
+
/// Filters every row (adaptive, minimum sum of absolute differences) and deflates the result.
public static byte[] Compress(ReadOnlySpan pixels, int height, int stride, int bpp, CompressionLevel level)
{
diff --git a/tests/Titano.Core.Tests/Codecs/PngTests.cs b/tests/Titano.Core.Tests/Codecs/PngTests.cs
new file mode 100644
index 00000000..636902a4
--- /dev/null
+++ b/tests/Titano.Core.Tests/Codecs/PngTests.cs
@@ -0,0 +1,278 @@
+using System.Buffers.Binary;
+using System.IO.Compression;
+using Titano.Core.Codecs.Png;
+using Titano.Core.Imaging;
+using Titano.Testing;
+using static Titano.Core.Tests.Codecs.CodecTestData;
+
+namespace Titano.Core.Tests.Codecs;
+
+public sealed class PngTests(TestContext context)
+{
+ [Theory]
+ [Case("png/adam7.png", false)]
+ [Case("png/rgb16.png", true)]
+ [Case("png/adam7-16.png", true)]
+ public void RgbFixturesMatchSource(string name, bool sixteen)
+ {
+ var image = PngDecoder.Decode(Fixture(name));
+ Assert.Equal(3, image.Channels);
+ Assert.Empty(image.Warnings);
+ if (sixteen) Assert.SequenceEqual(ReadPnm(Fixture("src16.ppm")).Words, image.Pixels16!);
+ else Assert.SequenceEqual(ReadPnm(Fixture("src.ppm")).Bytes, image.Pixels8!);
+ }
+
+ [Theory]
+ [Case("gray1", 1)]
+ [Case("gray2", 1)]
+ [Case("gray4", 1)]
+ [Case("gray8", 1)]
+ [Case("graya", 2)]
+ [Case("palette4", 3)]
+ [Case("palette-adam7", 3)]
+ [Case("palette-trns", 4)]
+ [Case("rgba", 4)]
+ public void LibpngFixturesMatchReference(string name, int channels)
+ {
+ var image = PngDecoder.Decode(Fixture($"png/{name}.png"));
+ var reference = ReadPnm(Fixture($"png/{name}.pam"));
+ Assert.Equal(channels, image.Channels);
+ Assert.Empty(image.Warnings);
+ var pixels = image.Pixels8!;
+ for (var i = 0; i < image.Width * image.Height; i++)
+ {
+ for (var c = 0; c < channels; c++)
+ {
+ // ImageMagick expands gray to RGB in PAM; compare against its first channel.
+ var refChannel = reference.Channels == channels ? c : c == channels - 1 && channels == 2 ? reference.Channels - 1 : 0;
+ if (pixels[i * channels + c] != reference.Samples[i * reference.Channels + refChannel])
+ Assert.Fail($"{name}: pixel {i} channel {c}: {pixels[i * channels + c]} vs {reference.Samples[i * reference.Channels + refChannel]}");
+ }
+ }
+ }
+
+ [Theory]
+ [Case(PngColorType.Gray, 8)]
+ [Case(PngColorType.Gray, 16)]
+ [Case(PngColorType.GrayAlpha, 8)]
+ [Case(PngColorType.GrayAlpha, 16)]
+ [Case(PngColorType.Rgb, 8)]
+ [Case(PngColorType.Rgb, 16)]
+ [Case(PngColorType.Rgba, 8)]
+ [Case(PngColorType.Rgba, 16)]
+ public void EncoderRoundTrips(PngColorType type, int depth)
+ {
+ const int w = 37, h = 21;
+ var channels = type switch { PngColorType.Gray => 1, PngColorType.GrayAlpha => 2, PngColorType.Rgb => 3, _ => 4 };
+ var bytes = new byte[w * h * channels * depth / 8];
+ new Random(depth * 10 + channels).NextBytes(bytes.AsSpan(bytes.Length / 2));
+ for (var i = 0; i < bytes.Length / 2; i++) bytes[i] = (byte)(i * 7);
+ var image = PngDecoder.Decode(PngEncoder.Encode(bytes, w, h, type, depth));
+ Assert.Equal(channels, image.Channels);
+ if (depth == 8)
+ {
+ Assert.SequenceEqual(bytes, image.Pixels8!);
+ }
+ else
+ {
+ var words = new ushort[bytes.Length / 2];
+ for (var i = 0; i < words.Length; i++) words[i] = BinaryPrimitives.ReadUInt16BigEndian(bytes.AsSpan(2 * i));
+ Assert.SequenceEqual(words, image.Pixels16!);
+ }
+ }
+
+ [Theory]
+ [Case(0)]
+ [Case(1)]
+ [Case(2)]
+ [Case(3)]
+ [Case(4)]
+ public void EveryFilterTypeDecodes(int filter)
+ {
+ const int w = 23, h = 9;
+ var rgb = TestCard(w, h);
+ var png = RawPng(w, h, PngColorType.Rgb, 8, rgb, filter);
+ Assert.SequenceEqual(rgb, PngDecoder.Decode(png).Pixels8!);
+ var rgba16 = new byte[w * h * 8];
+ new Random(filter).NextBytes(rgba16);
+ var wide = PngDecoder.Decode(RawPng(w, h, PngColorType.Rgba, 16, rgba16, filter, interlaced: true));
+ Assert.Equal((ushort)(rgba16[8 * 5] << 8 | rgba16[8 * 5 + 1]), wide.Pixels16![4 * 5]);
+ }
+
+ [Theory]
+ [Case(1)]
+ [Case(2)]
+ [Case(4)]
+ public void SubBytePaletteWithTransparency(int depth)
+ {
+ const int w = 13, h = 7;
+ var colours = 1 << depth;
+ var indices = new byte[w * h];
+ for (var i = 0; i < indices.Length; i++) indices[i] = (byte)(i * 5 % colours);
+ var packed = Pack(indices, w, h, depth);
+ var plte = new byte[colours * 3];
+ for (var i = 0; i < plte.Length; i++) plte[i] = (byte)(i * 37);
+ var trns = new byte[] { 0, 128 };
+ var png = RawPng(w, h, PngColorType.Palette, depth, packed, 4, interlaced: depth == 2, ("PLTE", plte), ("tRNS", trns));
+ var image = PngDecoder.Decode(png);
+ Assert.Equal(4, image.Channels);
+ for (var i = 0; i < indices.Length; i++)
+ {
+ int idx = indices[i];
+ Assert.Equal(plte[3 * idx + 1], image.Pixels8![4 * i + 1]);
+ Assert.Equal(idx < trns.Length ? trns[idx] : (byte)255, image.Pixels8[4 * i + 3]);
+ }
+ }
+
+ [Test]
+ public void ColourKeyTransparency()
+ {
+ var gray = PngDecoder.Decode(RawPng(4, 1, PngColorType.Gray, 4, [0x0F, 0x3F], 0, false, ("tRNS", [0, 3])));
+ Assert.SequenceEqual(new byte[] { 0, 255, 255, 255, 51, 0, 255, 255 }, gray.Pixels8!);
+ var rgb16 = new byte[12];
+ rgb16[1] = 9;
+ var keyed = PngDecoder.Decode(RawPng(2, 1, PngColorType.Rgb, 16, rgb16, 1, false, ("tRNS", [0, 0, 0, 0, 0, 0])));
+ Assert.Equal(4, keyed.Channels);
+ Assert.Equal(ushort.MaxValue, keyed.Pixels16![3]);
+ Assert.Equal((ushort)0, keyed.Pixels16[7]);
+ }
+
+ [Test]
+ public void CrcMismatchIsToleratedWithWarning()
+ {
+ var png = PngEncoder.Encode(TestCard(8, 8), 8, 8, PngColorType.Rgb);
+ png[^13] ^= 0xFF; // last byte of the IDAT CRC (IEND is the final 12 bytes)
+ var image = PngDecoder.Decode(png);
+ Assert.SequenceEqual(TestCard(8, 8), image.Pixels8!);
+ Assert.Contains("CRC", string.Join(";", image.Warnings));
+ }
+
+ [Test]
+ public void ImageBufferRoundTripsAtSixteenBits()
+ {
+ using var image = new ImageBuffer(33, 17, 4);
+ for (var c = 0; c < 4; c++)
+ {
+ var plane = image.Plane(c);
+ for (var i = 0; i < plane.Length; i++) plane[i] = (i * (c + 1) % 97) / 96f;
+ }
+ var png = PngEncoder.Encode(image, 16);
+ Assert.True(png.AsSpan().IndexOf("sRGB"u8) > 0, "sRGB chunk");
+ using var back = PngDecoder.DecodeToLinear(png, keepAlpha: true);
+ Assert.Equal(4, back.Channels);
+ for (var i = 0; i < image.Data.Length; i += 13) Assert.Approximately(image.Data[i], back.Data[i], 2e-4);
+ using var eight = PngDecoder.DecodeToLinear(PngEncoder.Encode(image));
+ Assert.Equal(3, eight.Channels);
+ Assert.Approximately(image[1, 5, 5], eight[1, 5, 5], 0.01);
+ }
+
+ [Theory]
+ [Case("png/adam7.png")]
+ [Case("png/palette-trns.png")]
+ [Case("png/gray2.png")]
+ [Case("png/adam7-16.png")]
+ public void FuzzedInputOnlyThrowsInvalidData(string name)
+ {
+ int ok = 0, rejected = 0;
+ foreach (var input in Corruptions(Fixture(name), 150, seed: name.Length))
+ {
+ try
+ {
+ var image = PngDecoder.Decode(input);
+ Assert.True(image.Width > 0);
+ ok++;
+ }
+ catch (InvalidDataException)
+ {
+ rejected++;
+ }
+ }
+ context.Log($"{name}: {ok} decoded, {rejected} rejected");
+ }
+
+ [Test]
+ public void StructuralErrorsAreRejected()
+ {
+ Assert.Throws(() => PngDecoder.Decode([]));
+ Assert.Throws(() => PngDecoder.Decode(Fixture("jpeg/b420.jpg")));
+ var palette = Fixture("png/palette4.png");
+ var plte = palette.AsSpan().IndexOf("PLTE"u8);
+ palette[plte] = (byte)'X'; // drop the palette (and make an unknown critical chunk)
+ Assert.Throws(() => PngDecoder.Decode(palette));
+ Assert.Throws(() => PngEncoder.Encode(new byte[4], 2, 2, PngColorType.Palette));
+ }
+
+ /// Builds a PNG with every row filtered by (test-side writer).
+ private static byte[] RawPng(int w, int h, PngColorType type, int depth, byte[] rows, int filter, bool interlaced = false, params (string Type, byte[] Data)[] chunks)
+ {
+ var channels = type switch { PngColorType.Gray or PngColorType.Palette => 1, PngColorType.GrayAlpha => 2, PngColorType.Rgb => 3, _ => 4 };
+ var bits = channels * depth;
+ var bpp = Math.Max(1, bits / 8);
+ var stride = (w * bits + 7) / 8;
+ var passes = interlaced
+ ? new[] { (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) }
+ : [(0, 0, 1, 1)];
+ using var raw = new MemoryStream();
+ foreach (var (px, py, dx, dy) in passes)
+ {
+ if (px >= w || py >= h) continue;
+ var count = (w - px + dx - 1) / dx;
+ var rowBytes = (count * bits + 7) / 8;
+ var prev = new byte[rowBytes];
+ for (var y = py; y < h; y += dy)
+ {
+ // Gather this pass's pixels (bit-exact copy of their samples).
+ var row = new byte[rowBytes];
+ for (int i = 0, x = px; i < count; i++, x += dx)
+ {
+ for (var b = 0; b < bits; b++)
+ {
+ var src = y * stride * 8 + x * bits + b;
+ if ((rows[src >> 3] >> (7 - (src & 7)) & 1) != 0) row[(i * bits + b) >> 3] |= (byte)(0x80 >> ((i * bits + b) & 7));
+ }
+ }
+ raw.WriteByte((byte)filter);
+ for (var i = 0; i < rowBytes; i++)
+ {
+ int a = i >= bpp ? row[i - bpp] : 0, b = prev[i], c = i >= bpp ? prev[i - bpp] : 0;
+ var predicted = filter switch { 0 => 0, 1 => a, 2 => b, 3 => (a + b) >> 1, _ => PngEncoder.Paeth(a, b, c) };
+ raw.WriteByte((byte)(row[i] - predicted));
+ }
+ prev = row;
+ }
+ }
+ using var z = new MemoryStream();
+ using (var deflate = new ZLibStream(z, CompressionLevel.Fastest, leaveOpen: true)) deflate.Write(raw.ToArray());
+ using var png = new MemoryStream();
+ png.Write([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
+ var ihdr = new byte[13];
+ BinaryPrimitives.WriteInt32BigEndian(ihdr, w);
+ BinaryPrimitives.WriteInt32BigEndian(ihdr.AsSpan(4), h);
+ ihdr[8] = (byte)depth;
+ ihdr[9] = (byte)type;
+ ihdr[12] = (byte)(interlaced ? 1 : 0);
+ PngEncoder.WriteChunk(png, "IHDR", ihdr);
+ foreach (var (t, d) in chunks) PngEncoder.WriteChunk(png, t, d);
+ var compressed = z.ToArray();
+ var half = compressed.Length / 2;
+ PngEncoder.WriteChunk(png, "IDAT", compressed.AsSpan(0, half));
+ PngEncoder.WriteChunk(png, "IDAT", compressed.AsSpan(half));
+ PngEncoder.WriteChunk(png, "IEND", []);
+ return png.ToArray();
+ }
+
+ private static byte[] Pack(byte[] values, int w, int h, int depth)
+ {
+ var stride = (w * depth + 7) / 8;
+ var packed = new byte[stride * h];
+ for (var y = 0; y < h; y++)
+ {
+ for (var x = 0; x < w; x++)
+ {
+ var bit = x * depth;
+ packed[y * stride + (bit >> 3)] |= (byte)(values[y * w + x] << (8 - depth - (bit & 7)));
+ }
+ }
+ return packed;
+ }
+}