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

@@ -0,0 +1,138 @@
using System.Buffers.Binary;
using Febe.Core.Codecs.Images;
using Febe.Core.Library;
using ImagingTestImages = Febe.Tests.Imaging.TestImages;
namespace Febe.Tests.Library;
/// <summary>
/// How much of a file the library reads for the size and the perceptual hash of a photo: the size from the headers
/// alone where the format allows, and hash and size from one read and one decode.
/// </summary>
[TestClass]
public sealed class ImageDecodingTests
{
[TestMethod]
public void TheSizeOfALargeJpegComesFromItsHeaders()
{
// Noise does not compress: a JPEG well over the prefix, turned by its EXIF tag (orientation 6: shown 600×900).
using var noise = ImagingTestImages.Random(900, 600, 5, opaque: true);
var jpeg = JpegEncoder.Encode(noise, new JpegEncoderOptions { Quality = 98, Exif = Orientation(6) });
Assert.IsGreaterThan(2 * ImageDecoding.HeaderBytes, jpeg.Length);
using var stream = new CountingStream(jpeg);
Assert.AreEqual((600, 900), ImageDecoding.ReadSize(stream));
Assert.AreEqual(ImageDecoding.HeaderBytes, stream.BytesRead, "solo l'inizio del file");
// Headers that do not fit the prefix (an ICC profile of 300 KB before the frame): the rest is read too.
var withProfile = JpegEncoder.Encode(noise, new JpegEncoderOptions { Quality = 98, Exif = Orientation(6), IccProfile = Profile(300_000) });
using var whole = new CountingStream(withProfile);
Assert.AreEqual((600, 900), ImageDecoding.ReadSize(whole));
Assert.AreEqual(withProfile.Length, whole.BytesRead);
// PNG is always read whole (every chunk is checked, eXIf may come late); so is a stream that cannot seek.
var png = PngEncoder.Encode(noise);
Assert.IsGreaterThan(ImageDecoding.HeaderBytes, png.Length);
using var pngStream = new CountingStream(png);
Assert.AreEqual((900, 600), ImageDecoding.ReadSize(pngStream));
Assert.AreEqual(png.Length, pngStream.BytesRead);
using var forward = new CountingStream(jpeg, seekable: false);
Assert.AreEqual((600, 900), ImageDecoding.ReadSize(forward));
// Small files, and what is not an image.
Assert.AreEqual((30, 20), ImageDecoding.ReadSize(new MemoryStream(PngEncoder.Encode(ImagingTestImages.Random(30, 20, 1)))));
Assert.IsNull(ImageDecoding.ReadSize(new MemoryStream(new byte[ImageDecoding.HeaderBytes + 10])));
Assert.IsNull(ImageDecoding.ReadSize(new MemoryStream()));
}
[TestMethod]
public void HashAndSizeComeFromOneDecodeOfTheSameBytes()
{
using var scene = Support.TestImages.Scene(3, 640, 480);
var jpeg = JpegEncoder.Encode(scene, new JpegEncoderOptions { Quality = 85, Exif = Orientation(8) });
var png = PngEncoder.Encode(scene);
foreach (var (name, file) in new[] { ("JPEG", jpeg), ("PNG", png) })
{
var (hash, size) = PerceptualHash.ComputeWithSize(file);
Assert.AreEqual(PerceptualHash.Compute(new MemoryStream(file)), hash, name);
Assert.AreEqual(ImageDecoding.ReadSize(file), size, name);
}
Assert.AreEqual((480, 640), PerceptualHash.ComputeWithSize(jpeg).Size, "le misure come si vede, intere anche se decodificato ridotto");
// A file cut inside its scan has no hash, but its headers still give the size, as ReadSize did.
var cut = jpeg[..(jpeg.Length / 2)];
var (noHash, stillSized) = PerceptualHash.ComputeWithSize(cut);
Assert.IsNull(noHash);
Assert.AreEqual((480, 640), stillSized);
var nothing = PerceptualHash.ComputeWithSize(new byte[100]);
Assert.IsNull(nothing.Hash);
Assert.IsNull(nothing.Size);
// From a file: read once, the same answer.
var path = Path.Combine(Path.GetTempPath(), $"febe-prova-{Guid.NewGuid():N}.jpg");
try
{
File.WriteAllBytes(path, jpeg);
Assert.AreEqual(PerceptualHash.ComputeWithSize(jpeg), PerceptualHash.ComputeWithSizeFromFile(path));
File.WriteAllBytes(path, []);
var empty = PerceptualHash.ComputeWithSizeFromFile(path);
Assert.IsNull(empty.Hash);
Assert.IsNull(empty.Size);
}
finally
{
File.Delete(path);
}
}
/// <summary>A big-endian TIFF with only the Orientation tag.</summary>
private static byte[] Orientation(ushort value)
{
var tiff = new byte[8 + 2 + 12 + 4];
"MM\0*"u8.CopyTo(tiff);
BinaryPrimitives.WriteUInt32BigEndian(tiff.AsSpan(4), 8);
BinaryPrimitives.WriteUInt16BigEndian(tiff.AsSpan(8), 1);
BinaryPrimitives.WriteUInt16BigEndian(tiff.AsSpan(10), 0x0112);
BinaryPrimitives.WriteUInt16BigEndian(tiff.AsSpan(12), 3);
BinaryPrimitives.WriteUInt32BigEndian(tiff.AsSpan(14), 1);
BinaryPrimitives.WriteUInt16BigEndian(tiff.AsSpan(18), value);
return tiff;
}
private static byte[] Profile(int length)
{
var bytes = new byte[length];
for (var i = 0; i < length; i++)
{
bytes[i] = (byte)((i * 13) + (i >> 5));
}
"RGB "u8.CopyTo(bytes.AsSpan(16));
return bytes;
}
/// <summary>A stream over bytes that counts what was read.</summary>
private sealed class CountingStream(byte[] data, bool seekable = true) : MemoryStream(data, writable: false)
{
public long BytesRead { get; private set; }
public override bool CanSeek => seekable && base.CanSeek;
public override long Length => seekable ? base.Length : throw new NotSupportedException();
public override long Position
{
get => seekable ? base.Position : throw new NotSupportedException();
set => base.Position = seekable ? value : throw new NotSupportedException();
}
// A derived MemoryStream sends Read(Span) through Stream.Read(Span), which calls this one: counted once.
public override int Read(byte[] buffer, int offset, int count)
{
var read = base.Read(buffer, offset, count);
BytesRead += read;
return read;
}
}
}