using Febe.Core.Codecs.Images; namespace Febe.Tests.Imaging; /// /// The decoding processes the reference set has no file for, checked at coefficient level: the same quantized /// coefficients are written by the baseline encoder and by the test encoder in every other way (progressive with /// spectral selection and successive approximation, restart intervals, separate scans, DNL, arithmetic coding, /// 12 bits, odd sampling factors), and the decoder must read back exactly those coefficients. Lossless files are /// checked sample by sample; CMYK and YCCK through the colours. /// [TestClass] public sealed class JpegCodingTests { public TestContext TestContext { get; set; } = null!; /// Images and encoder settings the cross-checks run on. public static IEnumerable Sources => [ ["gradiente-420", 61, 37, JpegSubsampling.Ratio420, false], ["gradiente-444", 45, 29, JpegSubsampling.Ratio444, false], ["grigio", 33, 50, JpegSubsampling.Ratio420, true], ["riferimento-420", 0, 0, JpegSubsampling.Ratio420, false], ]; private static RgbaImage SourceImage(int width, int height) { if (width == 0) { // A real-looking picture with edges: the PNG of the reference set. return PngDecoder.Decode(ReferenceImages.Get("png-skia-rgb").ReadInput()); } return TestImages.Gradient(width, height, width * height); } private static JpegEncoderOptions Settings(JpegSubsampling subsampling, bool grey, int quality = 90) => new() { Quality = quality, Subsampling = subsampling, Grayscale = grey }; [TestMethod] [DynamicData(nameof(Sources))] public void TheBaselineFileHoldsExactlyTheEncodersCoefficients(string name, int width, int height, JpegSubsampling subsampling, bool grey) { using var image = SourceImage(width, height); var settings = Settings(subsampling, grey); var expected = JpegEncoder.Transform(image, settings); var file = JpegEncoder.Encode(image, settings); var actual = JpegDecoder.DecodeCoefficients(file); Assert.AreEqual(0xC0, actual.FrameMarker, name); AssertSameCoefficients(expected, actual, name); } [TestMethod] [DynamicData(nameof(Sources))] public void EveryOtherCodingOfTheSameCoefficientsDecodesToThem(string name, int width, int height, JpegSubsampling subsampling, bool grey) { using var image = SourceImage(width, height); var settings = Settings(subsampling, grey); var coefficients = JpegEncoder.Transform(image, settings); using var baseline = JpegDecoder.Decode(JpegEncoder.Encode(image, settings)); var count = coefficients.Components.Count; var variants = new (string What, JpegTestOptions Options, int Marker)[] { ("sequenziale esteso", new JpegTestOptions(), 0xC1), ("scansioni separate", new JpegTestOptions { SeparateScans = true }, 0xC1), ("ripristino ogni 3", new JpegTestOptions { RestartInterval = 3 }, 0xC1), ("altezza in DNL", new JpegTestOptions { HeightInDnl = true }, 0xC1), ("progressivo", new JpegTestOptions { Progressive = true }, 0xC2), ("progressivo con ripristino", new JpegTestOptions { Progressive = true, RestartInterval = 2 }, 0xC2), ("solo selezione spettrale", new JpegTestOptions { Progressive = true, Script = SpectralOnly(count) }, 0xC2), ("approssimazioni fini", new JpegTestOptions { Progressive = true, Script = ManyApproximations(count) }, 0xC2), ("aritmetico", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic }, 0xC9), ("aritmetico con ripristino", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, RestartInterval = 5 }, 0xC9), ("aritmetico condizionato", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, DcConditioning = (2, 4), AcConditioning = 12 }, 0xC9), ("aritmetico progressivo", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = true }, 0xCA), ("aritmetico progressivo fine", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = true, Script = ManyApproximations(count), RestartInterval = 4 }, 0xCA), }; foreach (var (what, options, marker) in variants) { var file = JpegTestEncoder.Write(coefficients, options); var decoded = JpegDecoder.DecodeCoefficients(file); Assert.AreEqual(marker, decoded.FrameMarker, $"{name}, {what}"); AssertSameCoefficients(coefficients, decoded, $"{name}, {what}"); // The same coefficients make the same pixels, whatever the coding. using var pixels = JpegDecoder.Decode(file); ImageAssert.AreEqual(baseline, pixels, $"{name}, {what}"); TestContext.WriteLine($"{name}, {what}: {file.Length} byte"); } } [TestMethod] public void TheProductionEncodersRestartIntervalsChangeNoCoefficient() { using var image = TestImages.Gradient(83, 51, 5); foreach (var interval in new[] { 1, 2, 7, 100 }) { var settings = new JpegEncoderOptions { Quality = 80, RestartInterval = interval }; var file = JpegEncoder.Encode(image, settings); var decoded = JpegDecoder.DecodeCoefficients(file); Assert.AreEqual(interval, decoded.RestartInterval); AssertSameCoefficients(JpegEncoder.Transform(image, settings), decoded, $"intervallo {interval}"); var markers = CountRestartMarkers(file); var mcus = ((83 + 15) / 16) * ((51 + 15) / 16); Assert.AreEqual((mcus - 1) / interval, markers, $"intervallo {interval}"); } } public static IEnumerable TwelveBitCases => [ [JpegTestCoding.Huffman, false], [JpegTestCoding.Huffman, true], [JpegTestCoding.Arithmetic, false], [JpegTestCoding.Arithmetic, true], ]; [TestMethod] [DynamicData(nameof(TwelveBitCases))] public void TwelveBitFilesDecodeToTheirCoefficientsAndCloseToTheirSamples(JpegTestCoding coding, bool progressive) { const int width = 43; const int height = 27; var random = new Random(12); var grey = new int[width * height]; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { grey[(y * width) + x] = Math.Clamp((x * 4095 / (width - 1)) + random.Next(-20, 21), 0, 4095); } } // Fine 16-bit quantization: 12-bit coefficients need categories up to 15 (DC) and 14 (AC). var table = Enumerable.Repeat((ushort)2, 64).ToArray(); table[0] = 1; var coefficients = JpegEncoder.TransformPlanes(width, height, 12, [(1, 1, 1, 0, grey)], [table], 0xC1); var file = JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = coding, Progressive = progressive, RestartInterval = 4 }); var decoded = JpegDecoder.DecodeCoefficients(file); Assert.AreEqual(12, decoded.Precision); AssertSameCoefficients(coefficients, decoded, $"{coding}, progressivo {progressive}"); using var image = JpegDecoder.Decode(file); var worst = 0; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var expected = ((grey[(y * width) + x] * 255) + 2047) / 4095; worst = Math.Max(worst, Math.Abs(image.GetPixel(x, y).R - expected)); } } Assert.IsLessThanOrEqualTo(1, worst, "a 12 bit con quantizzazione fine l'errore resta sotto un livello di 8 bit"); } public static IEnumerable SamplingCases => [ ["4:2:2", 2, 1], ["4:4:0", 1, 2], ["4:1:1", 4, 1], ["4:1:0", 4, 2], ["3×1 (rapporto non intero con 2×1)", 3, 1], ]; [TestMethod] [DynamicData(nameof(SamplingCases))] public void AnySamplingFactorsDecode(string name, int lumaH, int lumaV) { using var image = TestImages.Gradient(57, 41, 9); var (yPlane, cbPlane, crPlane) = YCbCrPlanes(image); const int width = 57; const int height = 41; var chromaH = name.StartsWith('3') ? 2 : 1; var planes = new List<(int Id, int H, int V, int Table, int[] Samples)> { (1, lumaH, lumaV, 0, yPlane), (2, chromaH, 1, 1, Downsample(cbPlane, width, height, lumaH, lumaV, chromaH, 1)), (3, chromaH, 1, 1, Downsample(crPlane, width, height, lumaH, lumaV, chromaH, 1)), }; var fine = Enumerable.Repeat((ushort)1, 64).ToArray(); var coefficients = JpegEncoder.TransformPlanes(width, height, 8, planes, [fine, fine], 0xC1); foreach (var options in new[] { new JpegTestOptions(), new JpegTestOptions { Progressive = true, RestartInterval = 3 }, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic } }) { var file = JpegTestEncoder.Write(coefficients, options); AssertSameCoefficients(coefficients, JpegDecoder.DecodeCoefficients(file), name); using var decoded = JpegDecoder.Decode(file); var quality = ImageQuality.Compare(Opaque(image), decoded); TestContext.WriteLine($"{name}: {quality}"); // The chroma of a smooth gradient survives subsampling well; the luma is lossless but for rounding. Assert.IsGreaterThanOrEqualTo(30, quality.MinPsnr, $"{name}: {quality}"); } } [TestMethod] public void AdobeCmykAndYcckBecomeRgb() { using var image = TestImages.Gradient(40, 24, 3); const int width = 40; const int height = 24; var c = new int[width * height]; var m = new int[width * height]; var yellow = new int[width * height]; var k = new int[width * height]; for (var i = 0; i < c.Length; i++) { var p = image.Pixels.Slice(i * 4, 4); // Adobe's inverted CMYK: stored values are 255 minus the ink, so R = C × K / 255 with K = the brightest. var key = Math.Max(p[0], Math.Max(p[1], Math.Max(p[2], (byte)1))); k[i] = key; c[i] = Math.Min(255, ((p[0] * 255) + (key / 2)) / key); m[i] = Math.Min(255, ((p[1] * 255) + (key / 2)) / key); yellow[i] = Math.Min(255, ((p[2] * 255) + (key / 2)) / key); } var fine = Enumerable.Repeat((ushort)1, 64).ToArray(); var cmyk = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, c), (2, 1, 1, 0, m), (3, 1, 1, 0, yellow), (4, 1, 1, 0, k)], [fine], 0xC1); var cmykFile = JpegTestEncoder.Write(cmyk, new JpegTestOptions { Jfif = false, AdobeTransform = 0 }); using var fromCmyk = JpegDecoder.Decode(cmykFile); var cmykQuality = ImageQuality.Compare(Opaque(image), fromCmyk); TestContext.WriteLine($"CMYK: {cmykQuality}"); Assert.IsGreaterThanOrEqualTo(40, cmykQuality.MinPsnr, cmykQuality.ToString()); // YCCK: the inverted C, M, Y as RGB (255 − stored), to YCbCr; K as it is. var yy = new int[c.Length]; var cb = new int[c.Length]; var cr = new int[c.Length]; for (var i = 0; i < c.Length; i++) { (yy[i], cb[i], cr[i]) = ToYCbCr(255 - c[i], 255 - m[i], 255 - yellow[i]); } var ycck = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, yy), (2, 1, 1, 0, cb), (3, 1, 1, 0, cr), (4, 1, 1, 0, k)], [fine], 0xC1); var ycckFile = JpegTestEncoder.Write(ycck, new JpegTestOptions { Jfif = false, AdobeTransform = 2, Progressive = true }); using var fromYcck = JpegDecoder.Decode(ycckFile); var ycckQuality = ImageQuality.Compare(Opaque(image), fromYcck); TestContext.WriteLine($"YCCK: {ycckQuality}"); Assert.IsGreaterThanOrEqualTo(38, ycckQuality.MinPsnr, ycckQuality.ToString()); } [TestMethod] public void ThreeComponentsAreRgbWithAdobeTransformZeroOrRgbIdentifiers() { using var image = TestImages.Gradient(24, 16, 4); var (r, g, b) = Channels(image); var fine = Enumerable.Repeat((ushort)1, 64).ToArray(); foreach (var (ids, adobe) in new[] { ((1, 2, 3), 0), (('R', 'G', 'B'), -1) }) { var coefficients = JpegEncoder.TransformPlanes(24, 16, 8, [(ids.Item1, 1, 1, 0, r), (ids.Item2, 1, 1, 0, g), (ids.Item3, 1, 1, 0, b)], [fine], 0xC1); using var decoded = JpegDecoder.Decode(JpegTestEncoder.Write(coefficients, new JpegTestOptions { Jfif = false, AdobeTransform = adobe })); var quality = ImageQuality.Compare(Opaque(image), decoded); Assert.IsGreaterThanOrEqualTo(45, quality.MinPsnr, quality.ToString()); } } public static IEnumerable LosslessCases() { foreach (var coding in new[] { JpegTestCoding.Huffman, JpegTestCoding.Arithmetic }) { for (var predictor = 1; predictor <= 7; predictor++) { yield return [coding, 8, predictor, 0, 1, 0]; } yield return [coding, 8, 4, 2, 3, 0]; yield return [coding, 12, 7, 0, 1, 5]; yield return [coding, 16, 4, 0, 3, 0]; yield return [coding, 16, 6, 3, 1, 9]; yield return [coding, 2, 1, 0, 1, 0]; yield return [coding, 8, 5, 0, 3, 4]; } } [TestMethod] [DynamicData(nameof(LosslessCases))] public void LosslessFilesGiveBackTheirSamples(JpegTestCoding coding, int precision, int predictor, int pointTransform, int components, int restart) { const int width = 23; const int height = 14; var random = new Random((precision * 100) + predictor); var max = (1 << precision) - 1; var planes = new List<(int Id, int H, int V, int[] Samples)>(); for (var c = 0; c < components; c++) { var samples = new int[width * height]; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { // A ramp with noise, plus a hard step: large and small differences both occur. var value = ((x + (2 * y) + (c * 7)) * max / (width + (2 * height) + 14)) + random.Next(-3, 4) + (x > 15 ? max / 3 : 0); samples[(y * width) + x] = Math.Clamp(value, 0, max); } } planes.Add(((byte)"RGB"[c % 3] + (c / 3), 1, 1, samples)); } var options = new JpegTestOptions { Coding = coding, Jfif = false, RestartInterval = restart, DcConditioning = restart == 9 ? (1, 3) : (0, 1) }; var file = JpegTestEncoder.WriteLossless(width, height, precision, planes, predictor, pointTransform, options); using var image = JpegDecoder.Decode(file); for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var pixel = image.GetPixel(x, y); for (var c = 0; c < 3; c++) { var sample = planes[components == 1 ? 0 : c].Samples[(y * width) + x]; var restored = (sample >> pointTransform) << pointTransform; var expected = precision == 8 ? restored : (int)(((restored * 255L) + (max >> 1)) / max); var actual = c == 0 ? pixel.R : c == 1 ? pixel.G : pixel.B; Assert.AreEqual(expected, actual, $"({x}, {y}) canale {c}"); } } } if (components == 3) { // The same samples as three separate scans. var separate = JpegTestEncoder.WriteLossless(width, height, precision, planes, predictor, pointTransform, options with { SeparateScans = true }); using var again = JpegDecoder.Decode(separate); ImageAssert.AreEqual(image, again, "scansioni separate"); } } [TestMethod] public void LosslessWithSamplingFactorsAndInterleavedMcus() { // Grey with factors 2×2 (one component: MCU of one sample) and two components... no: three, with a 2×1 luma. const int width = 19; const int height = 11; var random = new Random(4); var luma = Enumerable.Range(0, width * height).Select(_ => random.Next(256)).ToArray(); var chroma = Enumerable.Range(0, 10 * height).Select(_ => 128).ToArray(); var planes = new List<(int Id, int H, int V, int[] Samples)> { (1, 2, 1, luma), (2, 1, 1, chroma), (3, 1, 1, chroma) }; foreach (var coding in new[] { JpegTestCoding.Huffman, JpegTestCoding.Arithmetic }) { var file = JpegTestEncoder.WriteLossless(width, height, 8, planes, 1, 0, new JpegTestOptions { Coding = coding, RestartInterval = 10 }); using var image = JpegDecoder.Decode(file); // Neutral chroma: every pixel is grey with the luma sample. for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var expected = luma[(y * width) + x]; Assert.AreEqual(((byte)expected, (byte)expected, (byte)expected), (image.GetPixel(x, y).R, image.GetPixel(x, y).G, image.GetPixel(x, y).B), $"{coding} ({x}, {y})"); } } } } [TestMethod] public void TheArithmeticCoderRoundTripsLongRandomDecisions() { // Many blocks of random coefficients exercise carries, stacked 0xFF bytes and every state of Table D.2. var random = new Random(31); const int width = 64; const int height = 64; var samples = Enumerable.Range(0, width * height).Select(_ => random.Next(256)).ToArray(); var fine = Enumerable.Repeat((ushort)1, 64).ToArray(); var coefficients = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, samples)], [fine], 0xC9); foreach (var progressive in new[] { false, true }) { var file = JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = progressive }); AssertSameCoefficients(coefficients, JpegDecoder.DecodeCoefficients(file), $"progressivo {progressive}"); } } [TestMethod] public void TheArithmeticTablesHaveOneEntryPerState() { Assert.AreEqual(114, JpegArithmeticTable.Qe.Length); Assert.AreEqual(114, JpegArithmeticTable.NextLps.Length); Assert.AreEqual(114, JpegArithmeticTable.NextMps.Length); for (var i = 0; i < 113; i++) { Assert.IsLessThan(113, (int)JpegArithmeticTable.NextLps[i], $"stato {i}"); Assert.IsLessThan(113, (int)JpegArithmeticTable.NextMps[i], $"stato {i}"); } // A few rows of T.81 Table D.2, checked by hand against the Recommendation. Assert.AreEqual((0x5A1D, 1, 1, true), (JpegArithmeticTable.Qe[0], (int)JpegArithmeticTable.NextLps[0], (int)JpegArithmeticTable.NextMps[0], JpegArithmeticTable.Switches(0))); Assert.AreEqual((0x0001, 12, 13, false), (JpegArithmeticTable.Qe[13], (int)JpegArithmeticTable.NextLps[13], (int)JpegArithmeticTable.NextMps[13], JpegArithmeticTable.Switches(13))); Assert.AreEqual((0x002C, 33, 9, false), (JpegArithmeticTable.Qe[35], (int)JpegArithmeticTable.NextLps[35], (int)JpegArithmeticTable.NextMps[35], JpegArithmeticTable.Switches(35))); Assert.AreEqual((0x2516, 86, 71, false), (JpegArithmeticTable.Qe[87], (int)JpegArithmeticTable.NextLps[87], (int)JpegArithmeticTable.NextMps[87], JpegArithmeticTable.Switches(87))); Assert.AreEqual((0x59EB, 112, 111, true), (JpegArithmeticTable.Qe[112], (int)JpegArithmeticTable.NextLps[112], (int)JpegArithmeticTable.NextMps[112], JpegArithmeticTable.Switches(112))); } internal static void AssertSameCoefficients(JpegCoefficients expected, JpegCoefficients actual, string what) { Assert.AreEqual((expected.Width, expected.Height, expected.Precision), (actual.Width, actual.Height, actual.Precision), what); Assert.HasCount(expected.Components.Count, actual.Components, what); for (var i = 0; i < expected.Components.Count; i++) { var e = expected.Components[i]; var a = actual.Components[i]; Assert.AreEqual((e.Id, e.H, e.V, e.BlocksWide, e.BlocksHigh), (a.Id, a.H, a.V, a.BlocksWide, a.BlocksHigh), $"{what}, componente {i}"); CollectionAssert.AreEqual(e.Quantization, a.Quantization, $"{what}, quantizzazione {i}"); for (var by = 0; by < e.BlocksHigh; by++) { for (var bx = 0; bx < e.BlocksWide; bx++) { var eb = e.Block(bx, by); var ab = a.Block(bx, by); if (!eb.SequenceEqual(ab)) { var k = 0; while (eb[k] == ab[k]) { k++; } Assert.Fail($"{what}: componente {i}, blocco ({bx}, {by}), coefficiente {k}: atteso {eb[k]}, letto {ab[k]}."); } } } } } private static int CountRestartMarkers(byte[] file) { var count = 0; for (var i = 0; i + 1 < file.Length; i++) { if (file[i] == 0xFF && file[i + 1] is >= 0xD0 and <= 0xD7) { count++; } } return count; } private static IReadOnlyList SpectralOnly(int count) { var all = Enumerable.Range(0, count).ToArray(); var scans = new List { new(all, 0, 0, 0, 0) }; foreach (var c in all) { scans.Add(new([c], 1, 1, 0, 0)); scans.Add(new([c], 2, 9, 0, 0)); scans.Add(new([c], 10, 63, 0, 0)); } return scans; } private static IReadOnlyList ManyApproximations(int count) { var all = Enumerable.Range(0, count).ToArray(); var scans = new List { new(all, 0, 0, 0, 4) }; for (var al = 3; al >= 0; al--) { scans.Add(new(all, 0, 0, al + 1, al)); } foreach (var c in all) { scans.Add(new([c], 1, 63, 0, 5)); for (var al = 4; al >= 0; al--) { scans.Add(new([c], 1, 63, al + 1, al)); } } return scans; } private static RgbaImage Opaque(RgbaImage image) { var copy = new RgbaImage(image.Width, image.Height, image.ToArray()); var pixels = copy.Pixels; for (var i = 3; i < pixels.Length; i += 4) { pixels[i] = 255; } return copy; } private static (int[] R, int[] G, int[] B) Channels(RgbaImage image) { var n = image.Width * image.Height; var r = new int[n]; var g = new int[n]; var b = new int[n]; for (var i = 0; i < n; i++) { r[i] = image.Pixels[i * 4]; g[i] = image.Pixels[(i * 4) + 1]; b[i] = image.Pixels[(i * 4) + 2]; } return (r, g, b); } private static (int Y, int Cb, int Cr) ToYCbCr(int r, int g, int b) => ( Math.Clamp((int)Math.Round((0.299 * r) + (0.587 * g) + (0.114 * b)), 0, 255), Math.Clamp((int)Math.Round((-0.168736 * r) - (0.331264 * g) + (0.5 * b) + 128), 0, 255), Math.Clamp((int)Math.Round((0.5 * r) - (0.418688 * g) - (0.081312 * b) + 128), 0, 255)); private static (int[] Y, int[] Cb, int[] Cr) YCbCrPlanes(RgbaImage image) { var (r, g, b) = Channels(image); var y = new int[r.Length]; var cb = new int[r.Length]; var cr = new int[r.Length]; for (var i = 0; i < r.Length; i++) { (y[i], cb[i], cr[i]) = ToYCbCr(r[i], g[i], b[i]); } return (y, cb, cr); } /// A full-resolution plane averaged down to a component with factors (h, v) of a frame with maxima (maxH, maxV). private static int[] Downsample(int[] plane, int width, int height, int maxH, int maxV, int h, int v) { var cw = ((width * h) + maxH - 1) / maxH; var ch = ((height * v) + maxV - 1) / maxV; var result = new int[cw * ch]; for (var y = 0; y < ch; y++) { for (var x = 0; x < cw; x++) { var sum = 0; var count = 0; for (var sy = y * maxV / v; sy < Math.Min(height, (y + 1) * maxV / v); sy++) { for (var sx = x * maxH / h; sx < Math.Min(width, (x + 1) * maxH / h); sx++) { sum += plane[(sy * width) + sx]; count++; } } result[(y * cw) + x] = count == 0 ? 128 : (sum + (count / 2)) / count; } } return result; } }