using System.Buffers.Binary;
using System.Text;
namespace Febe.Tests.Imaging;
///
/// Integrity of the reference set in Imaging/Riferimenti: every listed file is there and nothing else, each input starts
/// with the magic of its format and has the listed size, each expected image is a well-formed straight RGBA8 PNG of the
/// listed size. The pixels are not read here: reads them with Febe's own PNG decoder
/// (step 2 of track C1), without SkiaSharp.
///
[TestClass]
public sealed class ReferenceSetTests
{
/// The number of cases SkiaSharp's references were made for (LEGGIMI.md lists them).
private const int CaseCount = 57;
[TestMethod]
public void TheListNamesEveryFileOfTheFolderAndNothingElse()
{
var cases = ReferenceImages.All;
Assert.HasCount(CaseCount, cases);
var expectedFiles = new HashSet(StringComparer.Ordinal) { ReferenceImages.ListFileName, ReferenceImages.ReadmeFileName };
foreach (var reference in cases)
{
Assert.IsTrue(expectedFiles.Add(reference.InputFileName), $"{reference.Name}: input listed twice.");
Assert.IsTrue(expectedFiles.Add(reference.Name + ReferenceImages.ExpectedSuffix), $"{reference.Name}: expected image listed twice.");
Assert.IsTrue(File.Exists(reference.ExpectedPath), $"{reference.Name}: the expected image is missing.");
}
var actualFiles = Directory.EnumerateFiles(ReferenceImages.Folder, "*", SearchOption.AllDirectories)
.Select(path => Path.GetRelativePath(ReferenceImages.Folder, path))
.ToHashSet(StringComparer.Ordinal);
CollectionAssert.AreEquivalent(expectedFiles.Order(StringComparer.Ordinal).ToList(), actualFiles.Order(StringComparer.Ordinal).ToList());
foreach (var (_, format) in ReferenceImages.Extensions)
{
Assert.IsTrue(ReferenceImages.Of(format).Any(), $"No case for {format}.");
}
}
[TestMethod]
public void TheListIsReadTheSameWithWindowsLineEnds()
{
// A checkout with core.autocrlf must not change what the list says (.gitattributes also keeps it LF).
var folder = Path.Combine(Path.GetTempPath(), "febe-riferimenti-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(folder);
try
{
var listed = File.ReadAllText(Path.Combine(ReferenceImages.Folder, ReferenceImages.ListFileName));
File.WriteAllText(Path.Combine(folder, ReferenceImages.ListFileName), listed.ReplaceLineEndings("\r\n"));
foreach (var reference in ReferenceImages.All)
{
File.WriteAllBytes(Path.Combine(folder, reference.InputFileName), []);
}
var again = ReferenceImages.Load(folder);
CollectionAssert.AreEqual(
ReferenceImages.All.Select(c => (c.Name, c.Format, c.Width, c.Height)).ToList(),
again.Select(c => (c.Name, c.Format, c.Width, c.Height)).ToList());
}
finally
{
Directory.Delete(folder, recursive: true);
}
}
[TestMethod]
public void EveryInputStartsWithTheMagicOfItsFormatAndHasTheListedSize()
{
foreach (var reference in ReferenceImages.All)
{
var bytes = reference.ReadInput();
var (width, height) = reference.Format switch
{
ReferenceFormat.Png => PngSize(reference.Name, bytes),
ReferenceFormat.Jpeg => JpegSize(reference, bytes),
ReferenceFormat.WebP => WebPSize(reference.Name, bytes),
ReferenceFormat.Gif => GifSize(reference.Name, bytes),
ReferenceFormat.Bmp => BmpSize(reference.Name, bytes),
_ => throw new AssertFailedException($"{reference.Name}: unknown format."),
};
Assert.AreEqual((reference.StoredWidth, reference.StoredHeight), (width, height), $"{reference.Name}: size of the input.");
}
}
[TestMethod]
public void EveryExpectedImageIsAStraightRgba8PngWithTheListedSize()
{
foreach (var reference in ReferenceImages.All)
{
var bytes = reference.ReadExpectedPng();
var chunks = PngChunks(reference.Name + ReferenceImages.ExpectedSuffix, bytes);
var types = chunks.Select(c => c.Type).Distinct().ToList();
CollectionAssert.AreEqual(new[] { "IHDR", "IDAT", "IEND" }, types, $"{reference.Name}: only IHDR, IDAT and IEND, in this order.");
var ihdr = bytes.AsSpan(chunks[0].Offset, chunks[0].Length);
Assert.AreEqual(13, ihdr.Length, $"{reference.Name}: IHDR length.");
Assert.AreEqual(reference.Width, BinaryPrimitives.ReadInt32BigEndian(ihdr), $"{reference.Name}: width.");
Assert.AreEqual(reference.Height, BinaryPrimitives.ReadInt32BigEndian(ihdr[4..]), $"{reference.Name}: height.");
Assert.AreEqual(8, ihdr[8], $"{reference.Name}: bit depth.");
Assert.AreEqual(6, ihdr[9], $"{reference.Name}: colour type (RGBA).");
Assert.AreEqual(0, ihdr[10] | ihdr[11] | ihdr[12], $"{reference.Name}: compression, filter method and interlace.");
}
}
[TestMethod]
public void TheJpegInputsAreBaselineWithoutRestartIntervalsOrAdobeColour()
{
// LEGGIMI.md says progressive JPEG, restart intervals and CMYK/Adobe have no SkiaSharp reference: they are covered
// by our own encoders in the JPEG tests. This keeps that sentence true if the set is ever regenerated.
foreach (var reference in ReferenceImages.Of(ReferenceFormat.Jpeg))
{
foreach (var (marker, _, _) in JpegSegments(reference.Name, reference.ReadInput()))
{
Assert.IsFalse(marker is >= 0xC1 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC, $"{reference.Name}: SOF marker FF{marker:X2}, not baseline.");
Assert.AreNotEqual(0xDD, marker, $"{reference.Name}: restart interval (DRI).");
Assert.AreNotEqual(0xEE, marker, $"{reference.Name}: Adobe segment (APP14).");
}
}
}
[TestMethod]
public void TheSetStaysSmall()
{
long total = 0;
foreach (var path in Directory.EnumerateFiles(ReferenceImages.Folder))
{
var length = new FileInfo(path).Length;
Assert.IsGreaterThan(0L, length, $"{Path.GetFileName(path)} is empty.");
Assert.IsLessThan(512L * 1024, length, $"{Path.GetFileName(path)} is larger than 512 KiB.");
total += length;
}
Assert.IsLessThan(4L * 1024 * 1024, total, "The whole set should stay under 4 MiB.");
}
[TestMethod]
public void TheCrcOfTheChecksIsTheOneOfThePngSpecification()
{
// PNG specification, annex D: the CRC of "IEND" with no data.
Assert.AreEqual(0xAE426082u, Crc32("IEND"u8, []));
}
private static (int Width, int Height) PngSize(string name, byte[] bytes)
{
var chunks = PngChunks(name, bytes);
Assert.AreEqual("IHDR", chunks[0].Type, $"{name}: the first chunk.");
var ihdr = bytes.AsSpan(chunks[0].Offset, chunks[0].Length);
return (BinaryPrimitives.ReadInt32BigEndian(ihdr), BinaryPrimitives.ReadInt32BigEndian(ihdr[4..]));
}
/// Walks the chunks of a PNG, checking signature, lengths, CRCs and that IEND ends the file.
private static List<(string Type, int Offset, int Length)> PngChunks(string name, byte[] bytes)
{
ReadOnlySpan signature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
Assert.IsTrue(bytes.AsSpan().StartsWith(signature), $"{name}: PNG signature.");
var chunks = new List<(string, int, int)>();
var position = signature.Length;
while (true)
{
Assert.IsLessThanOrEqualTo(bytes.Length, position + 12, $"{name}: truncated chunk at {position}.");
var length = BinaryPrimitives.ReadInt32BigEndian(bytes.AsSpan(position));
Assert.IsTrue(length >= 0 && position + 12 + (long)length <= bytes.Length, $"{name}: chunk length at {position}.");
var type = bytes.AsSpan(position + 4, 4);
var data = bytes.AsSpan(position + 8, length);
var crc = BinaryPrimitives.ReadUInt32BigEndian(bytes.AsSpan(position + 8 + length));
var typeName = Encoding.ASCII.GetString(type);
Assert.AreEqual(Crc32(type, data), crc, $"{name}: CRC of {typeName} at {position}.");
chunks.Add((typeName, position + 8, length));
position += 12 + length;
if (typeName == "IEND")
{
Assert.AreEqual(0, length, $"{name}: IEND has no data.");
Assert.AreEqual(bytes.Length, position, $"{name}: bytes after IEND.");
return chunks;
}
}
}
private static (int Width, int Height) JpegSize(ReferenceCase reference, byte[] bytes)
{
var name = reference.Name;
Assert.IsTrue(bytes is [0xFF, 0xD8, ..] && bytes[^2] == 0xFF && bytes[^1] == 0xD9, $"{name}: SOI at the start and EOI at the end.");
(int, int)? size = null;
var orientation = 1;
foreach (var (marker, offset, length) in JpegSegments(name, bytes))
{
var segment = bytes.AsSpan(offset, length);
if (marker == 0xC0)
{
Assert.IsNull(size, $"{name}: more than one SOF.");
size = (BinaryPrimitives.ReadUInt16BigEndian(segment[3..]), BinaryPrimitives.ReadUInt16BigEndian(segment[1..]));
}
else if (marker == 0xE1 && segment.StartsWith("Exif\0\0"u8))
{
orientation = ExifOrientation(name, segment[6..]);
}
}
Assert.AreEqual(reference.Orientation, orientation, $"{name}: EXIF orientation.");
return size ?? throw new AssertFailedException($"{name}: no baseline SOF.");
}
/// The marker segments of a JPEG up to the start of scan: marker, offset and length of the payload.
private static List<(byte Marker, int Offset, int Length)> JpegSegments(string name, byte[] bytes)
{
var segments = new List<(byte, int, int)>();
var position = 2;
while (true)
{
Assert.IsLessThanOrEqualTo(bytes.Length, position + 4, $"{name}: truncated before the start of scan.");
Assert.AreEqual(0xFF, bytes[position], $"{name}: marker expected at {position}.");
var marker = bytes[position + 1];
var length = BinaryPrimitives.ReadUInt16BigEndian(bytes.AsSpan(position + 2));
Assert.IsTrue(length >= 2 && position + 2 + length <= bytes.Length, $"{name}: segment length at {position}.");
segments.Add((marker, position + 4, length - 2));
if (marker == 0xDA)
{
return segments;
}
position += 2 + length;
}
}
/// The Orientation tag (0x0112) of IFD0 of an EXIF TIFF block, 1 when absent.
private static int ExifOrientation(string name, ReadOnlySpan tiff)
{
var bigEndian = tiff.StartsWith("MM"u8);
Assert.IsTrue(bigEndian || tiff.StartsWith("II"u8), $"{name}: TIFF byte order.");
int U16(ReadOnlySpan s) => bigEndian ? BinaryPrimitives.ReadUInt16BigEndian(s) : BinaryPrimitives.ReadUInt16LittleEndian(s);
var ifd = (int)(bigEndian ? BinaryPrimitives.ReadUInt32BigEndian(tiff[4..]) : BinaryPrimitives.ReadUInt32LittleEndian(tiff[4..]));
Assert.AreEqual(42, U16(tiff[2..]), $"{name}: TIFF magic.");
var count = U16(tiff[ifd..]);
for (var i = 0; i < count; i++)
{
var entry = tiff.Slice(ifd + 2 + (i * 12), 12);
if (U16(entry) == 0x0112)
{
Assert.AreEqual(3, U16(entry[2..]), $"{name}: Orientation is a SHORT.");
return U16(entry[8..]);
}
}
return 1;
}
private static (int Width, int Height) WebPSize(string name, byte[] bytes)
{
Assert.IsTrue(bytes.AsSpan().StartsWith("RIFF"u8) && bytes.AsSpan(8).StartsWith("WEBP"u8), $"{name}: RIFF/WEBP header.");
Assert.AreEqual(bytes.Length - 8, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(4)), $"{name}: RIFF size.");
var chunk = Encoding.ASCII.GetString(bytes, 12, 4);
var data = bytes.AsSpan(20);
switch (chunk)
{
case "VP8 ":
// RFC 9649 §2.5 and RFC 6386 §9.1: 3-byte frame tag, start code, then 14-bit width and height.
Assert.IsTrue(data[3..].StartsWith((ReadOnlySpan)[0x9D, 0x01, 0x2A]), $"{name}: VP8 start code.");
return (BinaryPrimitives.ReadUInt16LittleEndian(data[6..]) & 0x3FFF, BinaryPrimitives.ReadUInt16LittleEndian(data[8..]) & 0x3FFF);
case "VP8L":
// RFC 9649 §3.2: signature 0x2F, then 14 bits of width - 1 and 14 bits of height - 1.
Assert.AreEqual(0x2F, data[0], $"{name}: VP8L signature.");
var bits = BinaryPrimitives.ReadUInt32LittleEndian(data[1..]);
return ((int)(bits & 0x3FFF) + 1, (int)((bits >> 14) & 0x3FFF) + 1);
case "VP8X":
// RFC 9649 §2.7: flags, 3 reserved bytes, 24-bit canvas width - 1 and height - 1.
return (U24(data[4..]) + 1, U24(data[7..]) + 1);
default:
throw new AssertFailedException($"{name}: unknown first chunk '{chunk}'.");
}
static int U24(ReadOnlySpan s) => s[0] | (s[1] << 8) | (s[2] << 16);
}
private static (int Width, int Height) GifSize(string name, byte[] bytes)
{
Assert.IsTrue(bytes.AsSpan().StartsWith("GIF89a"u8), $"{name}: GIF89a signature.");
Assert.AreEqual(0x3B, bytes[^1], $"{name}: trailer.");
return (BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(6)), BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(8)));
}
private static (int Width, int Height) BmpSize(string name, byte[] bytes)
{
Assert.IsTrue(bytes is [(byte)'B', (byte)'M', ..], $"{name}: BM signature.");
Assert.AreEqual(bytes.Length, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(2)), $"{name}: file size in the header.");
var offset = BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(10));
Assert.IsTrue(offset > 14 && offset < bytes.Length, $"{name}: offset of the pixels.");
var height = BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(22));
return (BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(18)), Math.Abs(height));
}
private static readonly uint[] CrcTable = BuildCrcTable();
private static uint[] BuildCrcTable()
{
// PNG specification, annex D (ISO 3309 polynomial, reflected).
var table = new uint[256];
for (uint n = 0; n < 256; n++)
{
var c = n;
for (var k = 0; k < 8; k++)
{
c = (c & 1) != 0 ? 0xEDB88320u ^ (c >> 1) : c >> 1;
}
table[n] = c;
}
return table;
}
private static uint Crc32(ReadOnlySpan type, ReadOnlySpan data)
{
var crc = 0xFFFFFFFFu;
foreach (var b in type)
{
crc = CrcTable[(crc ^ b) & 0xFF] ^ (crc >> 8);
}
foreach (var b in data)
{
crc = CrcTable[(crc ^ b) & 0xFF] ^ (crc >> 8);
}
return crc ^ 0xFFFFFFFFu;
}
}