Correzioni della revisione dei codec di casa (C1)

Correggo i difetti confermati dalla revisione di funzione/codec-immagini e
aggiungo le prove che li avrebbero trovati.

- JPEG: una tabella di Huffman con troppi codici corti dava
  ArgumentOutOfRangeException invece di ImageDecodeException, e un file
  rovinato faceva fallire importazione e ricostruzione; ora il controllo si
  fa prima di scrivere le voci. La prova che diceva di coprirlo cadeva invece
  su «tabella troncata»: ora tiene il totale giusto e controlla il messaggio.
- JPEG: il troncamento delle scansioni di Huffman si vede a ogni riga di MCU,
  non dopo l'ultimo MCU (un file tagliato dopo le intestazioni costava 6,7 s).
- JPEG: IDCT ridotta a 1/2 e 1/4 calcolata dai coefficienti; miniatura di una
  foto 4000x3000 da 126 a 59 ms in Release. Il predittore senza perdita non
  cerca più l'indice della componente a ogni campione.
- WebP: con livello del filtro del fotogramma 0 il filtro è spento, come nei
  decodificatori di riferimento; VP8L costruisce solo i gruppi nominati dai
  meta codici (prima fino a 335 MB di tabelle da 160 KB di file).
- BMP OS/2: altezza senza segno e sempre dal basso.
- Array di lavoro dei codec oltre 16 MiB fuori dal pool condiviso, che li
  avrebbe tenuti dopo l'uso.
- Conversione: profilo ICC copiato solo se RGB, profondità oltre 8 bit e
  blocchi gAMA/cHRM/sRGB dichiarati in NotCarried, Lossy vero quando si perde
  precisione.
- Impronta e misure di una foto da una sola lettura e decodifica; ReadSize
  legge solo l'inizio di JPEG, GIF e BMP.
- docs: decisioni (righe aggiunte, con la correzione dei 2,0 MB del set di
  riferimento) e windows.md (Febe.exe rimisurato: 85,6 MB, a capo sistemato).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 16:52:17 +01:00
1 parent d6a6a68496
commit 7e8296e790
32 files changed
+1120 -132

No files matched your search

@@ -205,6 +205,74 @@ public sealed class ImageProcessingTests
}
}
[TestMethod]
public void TheReducedTransformIsTheMeanOfTheFullOne()
{
// InverseReduced computes the means of 2×2 and 4×4 squares of the full inverse straight from the
// coefficients; checked against the T.81 definition in double precision, averaged, then rounded and clamped.
var random = new Random(91);
var quantization = new ushort[64];
var block = new short[64];
Span<byte> output = stackalloc byte[16];
for (var round = 0; round < 400; round++)
{
for (var i = 0; i < 64; i++)
{
quantization[i] = (ushort)random.Next(1, 24);
// Mostly small coefficients, some zero rows and columns, now and then a large one.
var zero = random.Next(4) == 0 || (round % 5 == 0 && i >= 8);
block[i] = zero ? (short)0 : (short)random.Next(-40, 41);
}
block[0] = (short)random.Next(-60, 61);
var full = new double[64];
for (var y = 0; y < 8; y++)
{
for (var x = 0; x < 8; x++)
{
double sum = 0;
for (var v = 0; v < 8; v++)
{
for (var u = 0; u < 8; u++)
{
var cu = u == 0 ? 1 / Math.Sqrt(2) : 1;
var cv = v == 0 ? 1 / Math.Sqrt(2) : 1;
sum += cu * cv * block[(v * 8) + u] * quantization[(v * 8) + u]
* Math.Cos(((2 * x) + 1) * u * Math.PI / 16) * Math.Cos(((2 * y) + 1) * v * Math.PI / 16);
}
}
full[(y * 8) + x] = (sum / 4) + 128;
}
}
foreach (var shift in new[] { 1, 2 })
{
var n = 8 >> shift;
var side = 1 << shift;
JpegDct.InverseReduced(block, quantization, output, n, 8, [], shift);
for (var y = 0; y < n; y++)
{
for (var x = 0; x < n; x++)
{
double mean = 0;
for (var dy = 0; dy < side; dy++)
{
for (var dx = 0; dx < side; dx++)
{
mean += full[(((y * side) + dy) * 8) + (x * side) + dx];
}
}
var expected = Math.Clamp((int)Math.Floor((mean / (side * side)) + 0.5), 0, 255);
Assert.IsLessThanOrEqualTo(1, Math.Abs(expected - output[(y * n) + x]), $"giro {round}, 1/{side}, ({x}, {y})");
}
}
}
}
}
[TestMethod]
public void DecodeAtLeastShrinksOnlyWhileTheLongSideIsEnough()
{
@@ -294,6 +362,84 @@ public sealed class ImageProcessingTests
Assert.IsLessThanOrEqualTo(6, Math.Abs(back.GetPixel(63, 10).R - expected));
}
[TestMethod]
public void AProfileThatDoesNotDescribeRgbIsLeftBehind()
{
// Adobe CMYK, every pixel the same inks: the decoder writes RGB, so a CMYK profile no longer fits.
const int width = 16;
const int height = 8;
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
int[] Plane(int value) => Enumerable.Repeat(value, width * height).ToArray();
var cmyk = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, Plane(200)), (2, 1, 1, 0, Plane(120)), (3, 1, 1, 0, Plane(60)), (4, 1, 1, 0, Plane(230))], [fine], 0xC1);
var cmykFile = WithIcc(JpegTestEncoder.Write(cmyk, new JpegTestOptions { Jfif = false, AdobeTransform = 0 }), Profile(400, "CMYK"));
Assert.AreEqual("CMYK", ImageConverter.IccColorSpace(JpegDecoder.Identify(cmykFile).Metadata.IccProfile));
// A grey JPEG with a grey profile: the encoders write RGB.
using var scene = Scenes.Scene(8, 48, 32);
var greyFile = JpegEncoder.Encode(scene, new JpegEncoderOptions { Grayscale = true, IccProfile = Profile(300, "GRAY") });
foreach (var (file, space) in new[] { (cmykFile, "CMYK"), (greyFile, "grigi") })
{
foreach (var target in new[] { ImageFormat.Png, ImageFormat.WebP, ImageFormat.Jpeg })
{
var result = ImageConverter.Convert(file, target);
var said = string.Join("; ", result.NotCarried);
Assert.IsNull(result.Metadata.IccProfile, $"{space} in {target}");
Assert.IsNull(result.Metadata.IccProfileName, $"{space} in {target}");
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("profilo colore", StringComparison.Ordinal) && n.Contains(space, StringComparison.Ordinal)), $"{space} in {target}: {said}");
Assert.IsNull(ImageDecoder.Identify(result.Data).Metadata.IccProfile, $"{space} in {target}: il file scritto non ha il profilo");
}
}
// An RGB profile travels (the other converter tests check it byte for byte); one too short to have a
// colour space does not.
Assert.AreEqual("RGB ", ImageConverter.IccColorSpace(Profile(200)));
Assert.IsNull(ImageConverter.IccColorSpace(new byte[12]));
var garbled = JpegEncoder.Encode(scene, new JpegEncoderOptions { IccProfile = new byte[12] });
var dropped = ImageConverter.Convert(garbled, ImageFormat.Png);
Assert.IsNull(dropped.Metadata.IccProfile);
Assert.IsTrue(dropped.NotCarried.Any(n => n.Contains("profilo colore", StringComparison.Ordinal)));
}
[TestMethod]
public void SixteenBitSamplesAndPngColourChunksAreReported()
{
// A 2×2 16-bit RGB PNG with gAMA and sRGB: decoded to 8 bits, so not lossless, and the colour chunks stay
// behind; both are said.
var raw = new byte[2 * (1 + (2 * 6))];
for (var i = 0; i < raw.Length; i++)
{
raw[i] = i % 13 == 0 ? (byte)0 : (byte)(i * 37);
}
var gamma = new byte[4];
BinaryPrimitives.WriteUInt32BigEndian(gamma, 45455);
var png = TestImages.Png(("IHDR", TestImages.Ihdr(2, 2, 16, 2)), ("gAMA", gamma), ("sRGB", [0]), ("IDAT", TestImages.Zlib(raw)), ("IEND", []));
var info = PngDecoder.Identify(png);
Assert.AreEqual(16, info.BitsPerSample);
CollectionAssert.AreEqual(new[] { "gAMA", "sRGB" }, info.Metadata.ColorChunks.ToArray());
foreach (var target in new[] { ImageFormat.Png, ImageFormat.WebP })
{
var result = ImageConverter.Convert(png, target);
var said = string.Join("; ", result.NotCarried);
Assert.IsTrue(result.Lossy, $"{target}: 16 bit diventano 8");
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("16 bit", StringComparison.Ordinal)), said);
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("gAMA", StringComparison.Ordinal)), said);
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("sRGB", StringComparison.Ordinal)), said);
}
// An 8-bit PNG without colour chunks converts losslessly and says nothing.
var plain = PngEncoder.Encode(TestImages.Random(5, 4, 2, opaque: true));
Assert.AreEqual(8, PngDecoder.Identify(plain).BitsPerSample);
var clean = ImageConverter.Convert(plain, ImageFormat.WebP);
Assert.IsFalse(clean.Lossy);
Assert.IsEmpty(clean.NotCarried);
// The precision of a 12-bit JPEG is reported too.
var twelve = JpegEncoder.TransformPlanes(8, 8, 12, [(1, 1, 1, 0, new int[64])], [Enumerable.Repeat((ushort)1, 64).ToArray()], 0xC1);
Assert.AreEqual(12, JpegDecoder.Identify(JpegTestEncoder.Write(twelve, new JpegTestOptions())).BitsPerSample);
}
[TestMethod]
public void OnlyJpegPngAndWebPAreWritten()
{
@@ -515,7 +661,8 @@ public sealed class ImageProcessingTests
}
/// <summary>Bytes standing in for an ICC profile (the codecs carry it without reading it).</summary>
private static byte[] Profile(int length)
/// <summary>A stand-in ICC profile: arbitrary bytes with the data colour space of its header (bytes 16-19) set.</summary>
private static byte[] Profile(int length, string colorSpace = "RGB ")
{
var bytes = new byte[length];
for (var i = 0; i < length; i++)
@@ -523,6 +670,19 @@ public sealed class ImageProcessingTests
bytes[i] = (byte)((i * 7) + (i >> 3));
}
Encoding.ASCII.GetBytes(colorSpace, bytes.AsSpan(16, 4));
return bytes;
}
/// <summary>A JPEG with an APP2 ICC_PROFILE segment (one chunk) right after SOI.</summary>
private static byte[] WithIcc(byte[] jpeg, byte[] profile)
{
byte[] payload = [.. Encoding.ASCII.GetBytes("ICC_PROFILE"), 0, 1, 1, .. profile];
var segment = new byte[4 + payload.Length];
segment[0] = 0xFF;
segment[1] = 0xE2;
BinaryPrimitives.WriteUInt16BigEndian(segment.AsSpan(2), (ushort)(payload.Length + 2));
payload.CopyTo(segment, 4);
return [.. jpeg.AsSpan(0, 2), .. segment, .. jpeg.AsSpan(2)];
}
}