Lettore e scrittore JPEG di casa (C1, passo 3)

Febe deve leggere e scrivere JPEG senza SkiaSharp né altri componenti
esterni (decisione del 18 novembre 2026), quindi il codec è scritto dalla
specifica ITU-T T.81.

Lettore (JpegDecoder): sequenziale di base ed esteso, progressivo (selezione
spettrale e approssimazioni successive), senza perdita (predittori 1-7),
ognuno con Huffman e con codifica aritmetica; 8 e 12 bit (senza perdita da 2
a 16); qualunque campionamento, ripristino, DNL; grigio, YCbCr, RGB, CMYK e
YCCK con il segmento Adobe. IDCT esatta e crominanza con il filtro
triangolare. EXIF, ICC a pezzi, XMP e commenti; l'orientamento EXIF va in
ImageMetadata.Orientation (anche per PNG) e non si applica ai pixel. I file
gerarchici e quelli a 2 componenti si rifiutano come formato non letto; i
dati troncati dentro una scansione sono un file danneggiato.

Scrittore (JpegEncoder): sequenziale di base, qualità 1-100 sulle tabelle
dell'allegato K, 4:2:0, 4:4:4 e grigio, intervallo di ripristino, EXIF, ICC,
XMP e commenti.

Prove: contro le letture di SkiaSharp i JPEG dell'insieme di riferimento
stanno fra 59 e 67 dB di PSNR per canale, scarto massimo 3 (soglia 40 dB e
0,1% di pixel oltre 16). Un codificatore di prova scrive gli stessi
coefficienti in progressivo, aritmetico, 12 bit, con ripristino, scansioni
separate e DNL, e il lettore deve ridarli identici; senza perdita si
confronta campione per campione. Più andata e ritorno dello scrittore, file
danneggiati e mutazioni casuali con seme fisso. La facciata ImageDecoder
ora legge i JPEG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 14:14:20 +01:00
1 parent 8bf76f18ff
commit 36196526bb
25 files changed
+6411 -14

No files matched your search

@@ -18,6 +18,7 @@ public sealed class ImageFuzzTests
[ReferenceFormat.Png],
[ReferenceFormat.Gif],
[ReferenceFormat.Bmp],
[ReferenceFormat.Jpeg],
];
[TestMethod]
+106
View File
@@ -0,0 +1,106 @@
using System.Globalization;
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>How close a lossy decode is to its reference: PSNR per channel and the share of pixels far off.</summary>
/// <param name="PsnrRed">PSNR of the red channel, dB (infinity when identical).</param>
/// <param name="PsnrGreen">PSNR of the green channel, dB.</param>
/// <param name="PsnrBlue">PSNR of the blue channel, dB.</param>
/// <param name="PsnrAlpha">PSNR of the alpha channel, dB.</param>
/// <param name="FarOff">Share (0-1) of pixels with some channel off by more than <see cref="ImageQuality.FarThreshold"/>.</param>
/// <param name="MaxDifference">Largest difference of any channel.</param>
internal sealed record ImageQualityResult(double PsnrRed, double PsnrGreen, double PsnrBlue, double PsnrAlpha, double FarOff, int MaxDifference)
{
/// <summary>The smallest PSNR of the colour channels.</summary>
public double MinPsnr => Math.Min(PsnrRed, Math.Min(PsnrGreen, PsnrBlue));
public override string ToString() => string.Create(
CultureInfo.InvariantCulture,
$"PSNR R {PsnrRed:F2} G {PsnrGreen:F2} B {PsnrBlue:F2} A {PsnrAlpha:F2} dB, oltre {ImageQuality.FarThreshold}: {FarOff * 100:F3}%, scarto massimo {MaxDifference}");
}
/// <summary>Measures and orientation helpers for comparing decoded images.</summary>
internal static class ImageQuality
{
/// <summary>A pixel counts as far off when one of its channels differs by more than this.</summary>
public const int FarThreshold = 16;
/// <summary>Lossy decodes must reach this PSNR on every colour channel (SPECIFICA §14.1, proposal of C1).</summary>
public const double MinimumPsnr = 40;
/// <summary>Lossy decodes may have at most this share of pixels far off.</summary>
public const double MaximumFarOff = 0.001;
public static ImageQualityResult Compare(RgbaImage expected, RgbaImage actual)
{
Assert.AreEqual((expected.Width, expected.Height), (actual.Width, actual.Height), "misura diversa");
var e = expected.Pixels;
var a = actual.Pixels;
Span<double> squares = stackalloc double[4];
var far = 0;
var max = 0;
for (var i = 0; i < e.Length; i += 4)
{
var isFar = false;
for (var ch = 0; ch < 4; ch++)
{
var d = Math.Abs(e[i + ch] - a[i + ch]);
squares[ch] += d * d;
max = Math.Max(max, d);
isFar |= d > FarThreshold;
}
if (isFar)
{
far++;
}
}
var pixels = e.Length / 4;
return new ImageQualityResult(Psnr(squares[0], pixels), Psnr(squares[1], pixels), Psnr(squares[2], pixels), Psnr(squares[3], pixels), (double)far / pixels, max);
}
/// <summary>Asserts the thresholds of a lossy decode.</summary>
public static void AssertClose(ImageQualityResult result, string what)
{
Assert.IsGreaterThanOrEqualTo(MinimumPsnr, result.MinPsnr, $"{what}: {result}");
Assert.IsLessThanOrEqualTo(MaximumFarOff, result.FarOff, $"{what}: {result}");
}
private static double Psnr(double squares, int pixels) =>
squares == 0 ? double.PositiveInfinity : 10 * Math.Log10(255.0 * 255.0 / (squares / pixels));
/// <summary>
/// The image as it should be shown for EXIF orientation <paramref name="orientation"/> (1-8): mirrored, rotated
/// or transposed from the stored pixels.
/// </summary>
public static RgbaImage Orient(RgbaImage stored, int orientation)
{
var w = stored.Width;
var h = stored.Height;
var swap = orientation >= 5;
var result = new RgbaImage(swap ? h : w, swap ? w : h);
for (var dy = 0; dy < result.Height; dy++)
{
var row = result.GetRow(dy);
for (var dx = 0; dx < result.Width; dx++)
{
var (sx, sy) = orientation switch
{
2 => (w - 1 - dx, dy),
3 => (w - 1 - dx, h - 1 - dy),
4 => (dx, h - 1 - dy),
5 => (dy, dx),
6 => (dy, h - 1 - dx),
7 => (w - 1 - dy, h - 1 - dx),
8 => (w - 1 - dy, dx),
_ => (dx, dy),
};
stored.GetRow(sy).Slice(sx * 4, 4).CopyTo(row[(dx * 4)..]);
}
}
return result;
}
}
+5 -5
View File
@@ -85,11 +85,11 @@ public sealed class ImagingBaseTests
[TestMethod]
public void TheFacadeSaysWhichFormatsItCannotReadYet()
{
var jpeg = ReferenceImages.Of(ReferenceFormat.Jpeg).First().ReadInput();
var error = Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Decode(jpeg));
Assert.Contains("JPEG", error.Message);
var webp = ReferenceImages.Of(ReferenceFormat.WebP).First().ReadInput();
var error = Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Decode(webp));
Assert.Contains("WEBP", error.Message);
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Identify(Encoding.ASCII.GetBytes("testo qualsiasi")));
Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.Png) && ImageDecoder.CanDecode(ImageFormat.Gif) && ImageDecoder.CanDecode(ImageFormat.Bmp));
Assert.IsFalse(ImageDecoder.CanDecode(ImageFormat.Jpeg) || ImageDecoder.CanDecode(ImageFormat.WebP) || ImageDecoder.CanDecode(ImageFormat.Unknown));
Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.Png) && ImageDecoder.CanDecode(ImageFormat.Gif) && ImageDecoder.CanDecode(ImageFormat.Bmp) && ImageDecoder.CanDecode(ImageFormat.Jpeg));
Assert.IsFalse(ImageDecoder.CanDecode(ImageFormat.WebP) || ImageDecoder.CanDecode(ImageFormat.Unknown));
}
}
+549
View File
@@ -0,0 +1,549 @@
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// 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.
/// </summary>
[TestClass]
public sealed class JpegCodingTests
{
public TestContext TestContext { get; set; } = null!;
/// <summary>Images and encoder settings the cross-checks run on.</summary>
public static IEnumerable<object[]> 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<object[]> 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<object[]> 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<object[]> 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<JpegTestScan> SpectralOnly(int count)
{
var all = Enumerable.Range(0, count).ToArray();
var scans = new List<JpegTestScan> { 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<JpegTestScan> ManyApproximations(int count)
{
var all = Enumerable.Range(0, count).ToArray();
var scans = new List<JpegTestScan> { 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);
}
/// <summary>A full-resolution plane averaged down to a component with factors (h, v) of a frame with maxima (maxH, maxV).</summary>
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;
}
}
@@ -0,0 +1,275 @@
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// 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.
/// </summary>
[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<byte> { 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<object[]> 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 = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF/></x:xmpmeta>";
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<ArgumentOutOfRangeException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = quality }), $"qualità {quality}");
}
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = -1 }));
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = 65536 }));
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Exif = "non TIFF"u8.ToArray() }));
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Exif = Tiff(1, padding: 70_000) }));
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Xmp = new string('x', 70_000) }));
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { IccProfile = new byte[256 * 65519] }));
Assert.Throws<ArgumentException>(() => 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<byte> counts)
{
var sum = 0;
foreach (var c in counts)
{
sum += c;
}
return sum;
}
/// <summary>The image with alpha 255 (JPEG has none) and, for grey, R = G = B.</summary>
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);
}
}
@@ -0,0 +1,353 @@
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// Damaged and unusual JPEG files: the decoder reads what T.81 and common practice allow (no EOI, bytes after EOI,
/// no DHT as in Motion JPEG), refuses what it cannot read with the right exception, and never fails in any other way.
/// </summary>
[TestClass]
public sealed class JpegMalformedTests
{
private static readonly ImageLimits Small = new() { MaxPixels = 1_000_000, MaxWorkingBytes = 16 * 1024 * 1024, MaxMetadataBytes = 64 * 1024 };
private static byte[] Baseline(int width = 37, int height = 21, int restart = 0) =>
JpegEncoder.Encode(TestImages.Gradient(width, height, 3), new JpegEncoderOptions { Quality = 80, RestartInterval = restart });
[TestMethod]
public void ABaselineFileCutInsideItsScanIsDamaged()
{
foreach (var restart in new[] { 0, 2 })
{
var file = Baseline(restart: restart);
// Identify needs the headers up to the frame, not the scan.
var sof = SegmentOffset(file, 0xC0);
var frameEnd = sof + 2 + ((file[sof + 2] << 8) | file[sof + 3]);
using var whole = JpegDecoder.Decode(file);
for (var length = 0; length < file.Length - 2; length++)
{
var cut = file[..length];
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(cut), $"ripristino {restart}, {length} di {file.Length} byte");
if (length < frameEnd)
{
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Identify(cut), $"Identify, {length} byte");
}
}
// Only the EOI missing: complete scans are accepted.
using var withoutEoi = JpegDecoder.Decode(file[..^2]);
ImageAssert.AreEqual(whole, withoutEoi, $"senza EOI, ripristino {restart}");
}
}
[TestMethod]
public void BytesAfterTheEndAreIgnored()
{
var file = Baseline();
using var whole = JpegDecoder.Decode(file);
var random = new Random(5);
var tail = new byte[300];
random.NextBytes(tail);
byte[] longer = [.. file, .. tail];
using var withTail = JpegDecoder.Decode(longer);
ImageAssert.AreEqual(whole, withTail, "byte dopo EOI");
}
[TestMethod]
public void FillBytesAndGarbageBetweenSegmentsAreSkipped()
{
var file = Baseline();
using var whole = JpegDecoder.Decode(file);
var dqt = SegmentOffset(file, 0xDB);
// T.81 B.1.1.2: any marker may be preceded by fill bytes 0xFF.
byte[] padded = [.. file[..dqt], 0xFF, 0xFF, 0xFF, .. file[dqt..]];
using var filled = JpegDecoder.Decode(padded);
ImageAssert.AreEqual(whole, filled, "byte di riempimento");
}
[TestMethod]
public void WithoutDhtTheAnnexKTablesAreUsed()
{
// Motion JPEG frames omit DHT and rely on the tables of Annex K, which are the ones our encoder writes.
var file = Baseline();
using var whole = JpegDecoder.Decode(file);
var stripped = RemoveSegments(file, 0xC4);
Assert.IsLessThan(file.Length, stripped.Length);
using var decoded = JpegDecoder.Decode(stripped);
ImageAssert.AreEqual(whole, decoded, "senza DHT");
}
[TestMethod]
public void HierarchicalAndTwoComponentFilesAreNotSupported()
{
var file = Baseline();
foreach (var marker in new byte[] { 0xC5, 0xC6, 0xC7, 0xCD, 0xCE, 0xCF })
{
var changed = file.ToArray();
changed[SegmentOffset(file, 0xC0) + 1] = marker;
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => JpegDecoder.Decode(changed), $"SOF 0x{marker:X2}");
}
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
var samples = new int[16 * 16];
var two = JpegEncoder.TransformPlanes(16, 16, 8, [(1, 1, 1, 0, samples), (2, 1, 1, 0, samples)], [fine], 0xC1);
var twoFile = JpegTestEncoder.Write(two, new JpegTestOptions());
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => JpegDecoder.Decode(twoFile));
}
[TestMethod]
public void DamagedHeadersAreRefused()
{
var file = Baseline();
var sof = SegmentOffset(file, 0xC0);
var sos = SegmentOffset(file, 0xDA);
// Width 0.
var zeroWidth = file.ToArray();
zeroWidth[sof + 7] = 0;
zeroWidth[sof + 8] = 0;
AssertDamaged(zeroWidth, "larghezza 0");
// Height 0 and no DNL segment after the first scan.
var zeroHeight = file.ToArray();
zeroHeight[sof + 5] = 0;
zeroHeight[sof + 6] = 0;
AssertDamaged(zeroHeight, "altezza 0 senza DNL");
// Precision 7.
var precision = file.ToArray();
precision[sof + 4] = 7;
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(precision), "precisione 7");
// Sampling factor 0 and 5.
foreach (var factor in new byte[] { 0x01, 0x10, 0x51, 0x15 })
{
var sampling = file.ToArray();
sampling[sof + 11] = factor;
AssertDamaged(sampling, $"campionamento 0x{factor:X2}");
}
// A scan naming a component the frame does not have.
var unknown = file.ToArray();
unknown[sos + 5] = 99;
AssertDamaged(unknown, "componente sconosciuto");
// A scan referring to a Huffman table that was never defined (slot 3).
var table = file.ToArray();
table[sos + 6] = 0x33;
AssertDamaged(table, "tabella di Huffman assente");
// No quantization table.
AssertDamaged(RemoveSegments(file, 0xDB), "senza DQT");
// A Huffman table with more codes than its lengths allow (two codes of length 1, then more).
var dht = SegmentOffset(file, 0xC4);
var badTable = file.ToArray();
badTable[dht + 5] = 3;
AssertDamaged(badTable, "tabella di Huffman impossibile");
// A segment length that runs past the end.
var longSegment = file.ToArray();
longSegment[sof + 2] = 0xFF;
AssertDamaged(longSegment, "segmento oltre la fine");
// No SOI, no frame, no scan.
AssertDamaged(file[2..], "senza SOI");
AssertDamaged([0xFF, 0xD8, 0xFF, 0xD9], "solo SOI ed EOI");
AssertDamaged(file[..sos], "senza scansioni");
}
[TestMethod]
public void TheLimitsAreEnforcedBeforeDecoding()
{
var file = Baseline(200, 150);
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(file, new ImageLimits { MaxPixels = 10_000 }));
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(file, new ImageLimits { MaxWidth = 100 }));
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(file, new ImageLimits { MaxWorkingBytes = 40_000 }));
// A header claiming 65535 × 65535 is refused at once, not after allocating.
var huge = file.ToArray();
var sof = SegmentOffset(file, 0xC0);
huge[sof + 5] = huge[sof + 6] = huge[sof + 7] = huge[sof + 8] = 0xFF;
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(huge, Small));
}
[TestMethod]
public void AnIccProfileWithAMissingChunkIsDropped()
{
var icc = new byte[140_000];
new Random(8).NextBytes(icc);
var file = JpegEncoder.Encode(TestImages.Gradient(10, 10, 1), new JpegEncoderOptions { IccProfile = icc });
CollectionAssert.AreEqual(icc, JpegDecoder.Identify(file).Metadata.IccProfile);
// Remove the second of three APP2 chunks.
var second = SegmentOffsets(file, 0xE2)[1];
var length = (file[second + 2] << 8) | file[second + 3];
byte[] missing = [.. file[..second], .. file[(second + 2 + length)..]];
Assert.IsNull(JpegDecoder.Identify(missing).Metadata.IccProfile);
using var image = JpegDecoder.Decode(missing);
Assert.AreEqual(10, image.Width);
}
[TestMethod]
public void OtherFormatsAreNotJpeg()
{
var png = ReferenceImages.Of(ReferenceFormat.Png).First().ReadInput();
Assert.IsFalse(JpegDecoder.IsJpeg(png));
Assert.IsFalse(JpegDecoder.IsJpeg([0xFF, 0xD8]));
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(png));
}
[TestMethod]
public void ChangedBytesInEveryCodingNeverBreakTheDecoder()
{
using var image = TestImages.Gradient(45, 30, 6);
var coefficients = JpegEncoder.Transform(image, new JpegEncoderOptions { Quality = 75 });
var lossless = new List<(int Id, int H, int V, int[] Samples)>
{
(1, 2, 2, Enumerable.Range(0, 45 * 30).Select(i => i % 251).ToArray()),
(2, 1, 1, Enumerable.Range(0, 23 * 15).Select(i => i % 13).ToArray()),
(3, 1, 1, Enumerable.Range(0, 23 * 15).Select(i => i % 7).ToArray()),
};
var files = new (string Name, byte[] File)[]
{
("progressivo", JpegTestEncoder.Write(coefficients, new JpegTestOptions { Progressive = true, RestartInterval = 3 })),
("aritmetico", JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, RestartInterval = 4 })),
("aritmetico progressivo", JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = true })),
("DNL", JpegTestEncoder.Write(coefficients, new JpegTestOptions { HeightInDnl = true })),
("senza perdita", JpegTestEncoder.WriteLossless(45, 30, 8, lossless, 4, 0, new JpegTestOptions { RestartInterval = 7 })),
("senza perdita aritmetico", JpegTestEncoder.WriteLossless(45, 30, 12, lossless, 7, 1, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic })),
};
var random = new Random(2026);
foreach (var (name, file) in files)
{
using (JpegDecoder.Decode(file, Small))
{
}
for (var i = 0; i < 150; i++)
{
var mutated = Mutate(file, random);
TryDecode(mutated, $"{name}, modifica {i}");
}
// Every cut of the file, as the network would leave it.
for (var length = 0; length < file.Length; length += 1 + (file.Length / 200))
{
TryDecode(file[..length], $"{name}, {length} byte");
}
}
}
private static void TryDecode(byte[] bytes, string what)
{
try
{
using var decoded = JpegDecoder.Decode(bytes, Small);
Assert.IsGreaterThan(0, decoded.Width, what);
}
catch (ImageDecodeException)
{
}
catch (Exception ex)
{
Assert.Fail($"{what}: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
}
try
{
JpegDecoder.Identify(bytes, Small);
}
catch (ImageDecodeException)
{
}
catch (Exception ex)
{
Assert.Fail($"{what} (Identify): {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
}
}
private static byte[] Mutate(byte[] original, Random random)
{
var bytes = original.ToArray();
switch (random.Next(3))
{
case 0:
for (var k = random.Next(1, 9); k > 0; k--)
{
bytes[random.Next(2, bytes.Length)] = (byte)random.Next(256);
}
return bytes;
case 1:
// Headers: the first segments hold the tables and the frame.
bytes[random.Next(2, Math.Min(bytes.Length, 700))] = (byte)(random.Next(3) switch { 0 => 0, 1 => 0xFF, _ => random.Next(256) });
return bytes;
default:
var start = random.Next(2, bytes.Length);
var length = Math.Min(bytes.Length - start, random.Next(1, 64));
for (var k = 0; k < length; k++)
{
bytes[start + k] ^= 0x5A;
}
return bytes;
}
}
private static void AssertDamaged(byte[] file, string what)
{
var error = Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(file), what);
Assert.IsNotInstanceOfType<ImageLimitException>(error, what);
Assert.IsFalse(string.IsNullOrWhiteSpace(error.Message), what);
}
/// <summary>Offset of the first marker segment of type <paramref name="marker"/> (the 0xFF byte).</summary>
private static int SegmentOffset(byte[] file, int marker) => SegmentOffsets(file, marker)[0];
private static List<int> SegmentOffsets(byte[] file, int marker)
{
var found = new List<int>();
var pos = 2;
while (pos + 4 <= file.Length && file[pos] == 0xFF)
{
if (file[pos + 1] == marker)
{
found.Add(pos);
}
if (file[pos + 1] == 0xDA)
{
break;
}
pos += 2 + ((file[pos + 2] << 8) | file[pos + 3]);
}
return found;
}
private static byte[] RemoveSegments(byte[] file, int marker)
{
var result = new List<byte>(file.Length);
result.AddRange(file.AsSpan(0, 2));
var pos = 2;
while (file[pos + 1] != 0xDA)
{
var length = 2 + ((file[pos + 2] << 8) | file[pos + 3]);
if (file[pos + 1] != marker)
{
result.AddRange(file.AsSpan(pos, length));
}
pos += length;
}
result.AddRange(file.AsSpan(pos));
return [.. result];
}
}
@@ -0,0 +1,56 @@
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// The in-house JPEG decoder against the SkiaSharp (libjpeg-turbo) reads of the reference set. JPEG is lossy and two
/// correct decoders differ by the rounding of their IDCT and upsampling, so the comparison has thresholds instead of
/// equality: every colour channel at least <see cref="ImageQuality.MinimumPsnr"/> dB and at most
/// <see cref="ImageQuality.MaximumFarOff"/> of the pixels off by more than <see cref="ImageQuality.FarThreshold"/>.
/// </summary>
[TestClass]
public sealed class JpegReferenceTests
{
public TestContext TestContext { get; set; } = null!;
public static IEnumerable<object[]> JpegCases => ReferenceImages.NamesOf(ReferenceFormat.Jpeg);
[TestMethod]
[DynamicData(nameof(JpegCases))]
public void TheJpegDecoderIsCloseToTheReference(string name)
{
var reference = ReferenceImages.Get(name);
var input = reference.ReadInput();
using var stored = JpegDecoder.Decode(input, out var info);
Assert.AreEqual((reference.StoredWidth, reference.StoredHeight), (stored.Width, stored.Height), name);
Assert.AreEqual(reference.Orientation, info.Metadata.Orientation, name);
Assert.IsTrue(stored.IsOpaque(), name);
using var shown = ImageQuality.Orient(stored, info.Metadata.Orientation);
using var expected = PngDecoder.Decode(reference.ReadExpectedPng());
var result = ImageQuality.Compare(expected, shown);
TestContext.WriteLine($"{name}: {result}");
ImageQuality.AssertClose(result, name);
}
[TestMethod]
public void TheFacadeReadsJpegAndIdentifyAgreesWithDecode()
{
foreach (var reference in ReferenceImages.Of(ReferenceFormat.Jpeg))
{
var input = reference.ReadInput();
using var viaFacade = ImageDecoder.Decode(input);
using var direct = JpegDecoder.Decode(input, pooled: true);
ImageAssert.AreEqual(direct, viaFacade, reference.Name);
var info = ImageDecoder.Identify(input);
Assert.AreEqual((ImageFormat.Jpeg, reference.StoredWidth, reference.StoredHeight, 1, false), (info.Format, info.Width, info.Height, info.FrameCount, info.HasAlpha), reference.Name);
Assert.AreEqual(reference.Orientation, info.Metadata.Orientation, reference.Name);
if (reference.Orientation != 1)
{
Assert.IsNotNull(info.Metadata.Exif, reference.Name);
Assert.IsTrue(info.Metadata.Exif.AsSpan().StartsWith("II*\0"u8) || info.Metadata.Exif.AsSpan().StartsWith("MM\0*"u8), reference.Name);
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -64,6 +64,12 @@ public sealed class ReferenceDecodeTests
continue;
}
if (reference.Format == ReferenceFormat.Jpeg)
{
// Lossy: JpegReferenceTests compares it with thresholds, and with the EXIF orientation applied.
continue;
}
using var image = ImageDecoder.Decode(input);
using var expectedImage = PngDecoder.Decode(reference.ReadExpectedPng());
ImageAssert.AreEqual(expectedImage, image, reference.Name);
@@ -66,8 +66,10 @@ Ogni PNG costruito a mano usa a turno i cinque filtri di riga (nessuno, Sub, Up,
fotogramma l'immagine attesa è trasparente (0, 0, 0, 0).
- Alfa non premoltiplicata: per i PNG il colore sotto un'alfa 0 resta quello del file.
- JPEG e WebP con perdita: l'immagine attesa è la lettura di libjpeg-turbo e libwebp dentro SkiaSharp (IDCT,
ricampionamento della crominanza, conversione dei colori). Il nostro lettore potrà differire di poco: la tolleranza
la fissano le prove di quei lettori. PNG, GIF, BMP e WebP senza perdita devono coincidere byte per byte.
ricampionamento della crominanza, conversione dei colori). Il nostro lettore può differire di poco: per JPEG la
tolleranza è almeno 40 dB di PSNR per canale e al più lo 0,1% dei pixel con uno scarto oltre 16 (il lettore di casa
sta fra 59 e 67 dB, scarto massimo 3, nessun pixel oltre 16). PNG, GIF, BMP e WebP senza perdita devono coincidere
byte per byte.
## Che cosa qui non c'è
@@ -91,7 +93,12 @@ lettore ricava prima della trasformata inversa, poi i pixel di un'immagine sempl
attesa è un PNG RGBA a 8 bit ben formato (CRC di ogni blocco) della misura elencata; l'insieme resta piccolo.
- `Imaging/ReferenceDecodeTests.cs` (dalla tappa C1, passo 2): ogni immagine attesa si legge uguale con il lettore PNG
di casa e con un lettore minimo indipendente; i lettori PNG, GIF e BMP di casa danno, per ogni caso del loro formato,
esattamente i pixel dell'immagine attesa; la facciata `ImageDecoder` sceglie il lettore dai primi byte e per JPEG e
WebP dice che non li legge ancora.
esattamente i pixel dell'immagine attesa; la facciata `ImageDecoder` sceglie il lettore dai primi byte e per WebP
dice che non lo legge ancora; i JPEG li confronta con la tolleranza sopra `Imaging/JpegReferenceTests.cs` (dal
passo 3), che applica anche l'orientamento EXIF riportato dal lettore.
- `Imaging/JpegCodingTests.cs`, `JpegEncoderTests.cs`, `JpegMalformedTests.cs` (dal passo 3): i casi qui assenti
(progressivo, ripristino, codifica aritmetica, 12 bit, senza perdita, CMYK e YCCK, campionamenti insoliti) scritti
dal codificatore di prova `JpegTestEncoder.cs` e confrontati coefficiente per coefficiente con la codifica di base
delle stesse immagini; il codificatore di casa; i file danneggiati.
- `Febe.Tests.csproj` copia la cartella nell'uscita delle prove; `.gitattributes` segna le estensioni delle immagini
come binarie e tiene `elenco.txt` con le righe Unix.