using System.Buffers.Binary; using System.IO.Compression; using Chronos.Core.Codecs.Png; using Chronos.Core.Imaging; using Chronos.Testing; using static Chronos.Core.Tests.Codecs.CodecTestData; namespace Chronos.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; } }