using Febe.Core.Codecs.Images; namespace Febe.Tests.Imaging; /// /// The in-house baseline JPEG encoder: the files it writes read back close to the source with our decoder, quality /// moves size and fidelity the right way, metadata (EXIF, ICC in chunks, XMP, comments) survives the round trip, and /// what cannot be written is refused. /// [TestClass] public sealed class JpegEncoderTests { public TestContext TestContext { get; set; } = null!; [TestMethod] public void TheAnnexKTablesAreComplete() { Assert.AreEqual(12, Sum(JpegTables.LuminanceDcCounts)); Assert.AreEqual(12, Sum(JpegTables.ChrominanceDcCounts)); Assert.AreEqual(162, Sum(JpegTables.LuminanceAcCounts)); Assert.AreEqual(162, Sum(JpegTables.ChrominanceAcCounts)); Assert.HasCount(162, JpegTables.LuminanceAcValues); Assert.HasCount(162, JpegTables.ChrominanceAcValues); // Every (run, size) pair with size 1..10, plus EOB and ZRL: the full AC alphabet. var expected = new HashSet { 0x00, 0xF0 }; for (var run = 0; run < 16; run++) { for (var size = 1; size <= 10; size++) { expected.Add((byte)((run << 4) | size)); } } Assert.IsTrue(expected.SetEquals(JpegTables.LuminanceAcValues.ToArray())); Assert.IsTrue(expected.SetEquals(JpegTables.ChrominanceAcValues.ToArray())); // Zig-zag is a permutation that starts 0, 1, 8, 16, 9, 2 and ends at 63. var zigzag = JpegTables.ZigZag.ToArray(); CollectionAssert.AreEquivalent(Enumerable.Range(0, 64).ToArray(), zigzag.Select(v => (int)v).ToArray()); CollectionAssert.AreEqual(new[] { 0, 1, 8, 16, 9, 2 }, zigzag.Take(6).Select(v => (int)v).ToArray()); Assert.AreEqual(63, (int)zigzag[63]); } [TestMethod] public void QualityScalesTheStandardTables() { var at50 = JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, 50); CollectionAssert.AreEqual(JpegTables.LuminanceQuantization.ToArray().Select(v => (int)v).ToArray(), at50.Select(v => (int)v).ToArray()); Assert.IsTrue(JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, 100).All(v => v == 1)); Assert.IsTrue(JpegTables.ScaledQuantization(JpegTables.ChrominanceQuantization, 1).All(v => v == 255)); // 16 at q50 becomes (16 × 20 + 50) / 100 = 3 at q90. Assert.AreEqual(3, (int)JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, 90)[0]); } public static IEnumerable RoundTrips => [ [JpegSubsampling.Ratio420, false, 90, 38.0], [JpegSubsampling.Ratio444, false, 90, 40.0], [JpegSubsampling.Ratio444, false, 100, 48.0], [JpegSubsampling.Ratio420, true, 85, 40.0], ]; [TestMethod] [DynamicData(nameof(RoundTrips))] public void EncodedImagesReadBackCloseToTheSource(JpegSubsampling subsampling, bool grey, int quality, double minimum) { using var source = Opaque(TestImages.Gradient(97, 61, 21), grey); var file = JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = quality, Subsampling = subsampling, Grayscale = grey }); Assert.IsTrue(JpegDecoder.IsJpeg(file)); using var decoded = JpegDecoder.Decode(file, out var info); Assert.AreEqual((97, 61, false, ImageFormat.Jpeg), (info.Width, info.Height, info.HasAlpha, info.Format)); var result = ImageQuality.Compare(source, decoded); TestContext.WriteLine($"{subsampling}, grigio {grey}, q{quality}: {file.Length} byte, {result}"); Assert.IsGreaterThanOrEqualTo(minimum, result.MinPsnr, result.ToString()); Assert.AreEqual(0.0, result.FarOff, result.ToString()); } [TestMethod] public void HigherQualityMeansLargerFilesAndCloserPixels() { using var source = Opaque(PngDecoder.Decode(ReferenceImages.Get("png-skia-rgb").ReadInput()), false); var lastSize = 0; var lastPsnr = 0.0; foreach (var quality in new[] { 10, 30, 50, 75, 90, 100 }) { // 4:4:4: the image is pixel-level noise in blue, which 4:2:0 cannot keep at any quality. var file = JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = quality, Subsampling = JpegSubsampling.Ratio444 }); using var decoded = JpegDecoder.Decode(file); var result = ImageQuality.Compare(source, decoded); TestContext.WriteLine($"q{quality}: {file.Length} byte, {result}"); Assert.IsGreaterThan(lastSize, file.Length, $"q{quality}"); Assert.IsGreaterThan(lastPsnr, result.MinPsnr, $"q{quality}"); lastSize = file.Length; lastPsnr = result.MinPsnr; } } [TestMethod] public void TheReferenceImagesSurviveReEncoding() { foreach (var reference in ReferenceImages.Of(ReferenceFormat.Jpeg)) { using var original = JpegDecoder.Decode(reference.ReadInput()); var file = JpegEncoder.Encode(original, new JpegEncoderOptions { Quality = 100, Subsampling = JpegSubsampling.Ratio444 }); using var again = JpegDecoder.Decode(file); var result = ImageQuality.Compare(original, again); TestContext.WriteLine($"{reference.Name}: {result}"); ImageQuality.AssertClose(result, reference.Name); } } [TestMethod] public void TinyAndOddSizesWork() { foreach (var (width, height) in new[] { (1, 1), (1, 17), (17, 1), (8, 8), (9, 9), (15, 16), (16, 15), (33, 7) }) { using var source = Opaque(TestImages.Gradient(width, height, width + height), false); foreach (var subsampling in new[] { JpegSubsampling.Ratio420, JpegSubsampling.Ratio444 }) { var file = JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = 100, Subsampling = subsampling }); using var decoded = JpegDecoder.Decode(file); Assert.AreEqual((width, height), (decoded.Width, decoded.Height)); var result = ImageQuality.Compare(source, decoded); if (subsampling == JpegSubsampling.Ratio444) { Assert.IsLessThanOrEqualTo(8, result.MaxDifference, $"{width}×{height} {subsampling}: {result}"); } else { // The source has per-pixel noise: averaged chroma loses some of it. Assert.IsGreaterThanOrEqualTo(25, result.MinPsnr, $"{width}×{height} {subsampling}: {result}"); } } } } [TestMethod] public void RestartIntervalsDoNotChangeThePixels() { using var source = Opaque(TestImages.Gradient(70, 45, 8), false); using var plain = JpegDecoder.Decode(JpegEncoder.Encode(source)); foreach (var interval in new[] { 1, 3, 65535 }) { using var restarted = JpegDecoder.Decode(JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = interval })); ImageAssert.AreEqual(plain, restarted, $"intervallo {interval}"); } } [TestMethod] public void TheStreamOverloadWritesTheSameBytes() { using var source = TestImages.Gradient(20, 20, 1); using var stream = new MemoryStream(); JpegEncoder.Encode(source, stream); CollectionAssert.AreEqual(JpegEncoder.Encode(source), stream.ToArray()); } [TestMethod] public void MetadataSurvivesTheRoundTrip() { using var source = TestImages.Gradient(30, 20, 2); var exif = Tiff(orientation: 6); var random = new Random(66); var icc = new byte[150_000]; random.NextBytes(icc); "acsp"u8.CopyTo(icc.AsSpan(36)); const string xmp = ""; var options = new JpegEncoderOptions { Exif = exif, IccProfile = icc, Xmp = xmp, Comments = ["primo commento", "secondo, con àccenti"] }; var file = JpegEncoder.Encode(source, options); // 150 000 bytes need three APP2 chunks of at most 65 519. Assert.AreEqual(3, CountSegments(file, 0xE2)); var info = JpegDecoder.Identify(file); CollectionAssert.AreEqual(exif, info.Metadata.Exif); Assert.AreEqual(6, info.Metadata.Orientation); CollectionAssert.AreEqual(icc, info.Metadata.IccProfile); Assert.AreEqual(xmp, info.Metadata.Xmp); CollectionAssert.AreEqual(new[] { "primo commento", "secondo, con àccenti" }, info.Metadata.Texts.Select(t => t.Text).ToArray()); // The orientation is reported, not applied: the pixels keep their stored layout. using var decoded = JpegDecoder.Decode(file); Assert.AreEqual((30, 20), (decoded.Width, decoded.Height)); Assert.IsGreaterThan(30, ImageQuality.Compare(Opaque(source, false), decoded).MinPsnr); // Without metadata only JFIF is written. var bare = JpegDecoder.Identify(JpegEncoder.Encode(source)); Assert.IsNull(bare.Metadata.Exif); Assert.IsNull(bare.Metadata.IccProfile); Assert.IsNull(bare.Metadata.Xmp); Assert.IsEmpty(bare.Metadata.Texts); Assert.AreEqual(1, bare.Metadata.Orientation); } [TestMethod] public void WhatCannotBeWrittenIsRefused() { using var source = TestImages.Gradient(8, 8, 1); foreach (var quality in new[] { 0, -5, 101 }) { Assert.ThrowsExactly(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = quality }), $"qualità {quality}"); } Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = -1 })); Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = 65536 })); Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Exif = "non TIFF"u8.ToArray() })); Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Exif = Tiff(1, padding: 70_000) })); Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Xmp = new string('x', 70_000) })); Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { IccProfile = new byte[256 * 65519] })); Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Comments = [new string('c', 70_000)] })); } private static byte[] Tiff(int orientation, int padding = 0) { // Little-endian TIFF header, IFD0 at 8 with one entry: Orientation (0x0112), SHORT, count 1. var tiff = new byte[8 + 2 + 12 + 4 + padding]; "II*\0"u8.CopyTo(tiff); tiff[4] = 8; tiff[8] = 1; tiff[10] = 0x12; tiff[11] = 0x01; tiff[12] = 3; tiff[14] = 1; tiff[18] = (byte)orientation; return tiff; } private static int CountSegments(byte[] file, int marker) { var count = 0; var pos = 2; while (pos + 4 <= file.Length && file[pos] == 0xFF && file[pos + 1] != 0xDA) { if (file[pos + 1] == marker) { count++; } pos += 2 + ((file[pos + 2] << 8) | file[pos + 3]); } return count; } private static int Sum(ReadOnlySpan counts) { var sum = 0; foreach (var c in counts) { sum += c; } return sum; } /// The image with alpha 255 (JPEG has none) and, for grey, R = G = B. private static RgbaImage Opaque(RgbaImage image, bool grey) { var pixels = image.ToArray(); for (var i = 0; i < pixels.Length; i += 4) { if (grey) { var y = (byte)(((pixels[i] * 299) + (pixels[i + 1] * 587) + (pixels[i + 2] * 114) + 500) / 1000); pixels[i] = pixels[i + 1] = pixels[i + 2] = y; } pixels[i + 3] = 255; } return new RgbaImage(image.Width, image.Height, pixels); } }