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

@@ -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);
}
}