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

+60 -3
View File
@@ -32,8 +32,15 @@ internal static class ImageDecoding
}
/// <summary>Like <see cref="DecodeUpright(Stream, int?)"/>, from bytes already in memory.</summary>
public static RgbaImage? DecodeUpright(ReadOnlyMemory<byte> data, int? minLongSide = null)
public static RgbaImage? DecodeUpright(ReadOnlyMemory<byte> data, int? minLongSide = null) => DecodeUpright(data, minLongSide, out _);
/// <summary>
/// Like <see cref="DecodeUpright(ReadOnlyMemory{byte}, int?)"/>, and also gives what <see cref="ReadSize(ReadOnlyMemory{byte})"/>
/// would (the full size as shown, even when the picture comes back reduced or not at all), from the same bytes.
/// </summary>
public static RgbaImage? DecodeUpright(ReadOnlyMemory<byte> data, int? minLongSide, out (int Width, int Height)? shownSize)
{
shownSize = null;
if (data.IsEmpty)
{
return null;
@@ -46,6 +53,7 @@ internal static class ImageDecoding
stored = minLongSide is { } min && min > 0
? ImageDecoder.DecodeAtLeast(data, min, out info, Limits, pooled: true)
: ImageDecoder.Decode(data, out info, Limits, pooled: true);
shownSize = ImageOrientation.ShownSize(info.Width, info.Height, info.Metadata.Orientation);
var upright = ImageOrientation.Apply(stored, info.Metadata.Orientation, pooled: true);
if (!ReferenceEquals(upright, stored))
{
@@ -57,6 +65,8 @@ internal static class ImageDecoding
}
catch (ImageDecodeException)
{
// A damaged, truncated or too large picture can still tell its size from its headers.
shownSize ??= ReadSize(data);
return null;
}
finally
@@ -65,11 +75,57 @@ internal static class ImageDecoding
}
}
/// <summary>
/// Bytes read first by <see cref="ReadSize(Stream)"/> for JPEG, GIF and BMP, whose headers (a JPEG EXIF block is
/// at most 64 KiB) fit; when they do not (large ICC profiles) the rest of the file is read as well. PNG and WebP
/// are always read whole.
/// </summary>
internal const int HeaderBytes = 256 * 1024;
/// <summary>Dimensions of an image as displayed (orientation applied), without decoding the pixels.</summary>
public static (int Width, int Height)? ReadSize(Stream stream)
{
ArgumentNullException.ThrowIfNull(stream);
return ReadAll(stream) is { } data ? ReadSize(data) : null;
if (!stream.CanSeek)
{
return ReadAll(stream) is { } all ? ReadSize(all) : null;
}
var remaining = stream.Length - stream.Position;
if (remaining <= 0 || remaining > MaxFileBytes)
{
return null;
}
if (remaining <= HeaderBytes)
{
return ReadSize(ReadAll(stream));
}
var data = new byte[HeaderBytes];
stream.ReadExactly(data);
if (ImageFormatSniffer.Detect(data) is not (ImageFormat.Jpeg or ImageFormat.Gif or ImageFormat.Bmp))
{
// PNG keeps metadata (eXIf) anywhere before IEND and checks every chunk, WebP refuses a RIFF that runs
// past the data: neither can be identified from a prefix.
Array.Resize(ref data, (int)remaining);
stream.ReadExactly(data.AsSpan(HeaderBytes));
return ReadSize(data);
}
try
{
var info = ImageDecoder.Identify(data, Limits);
return ImageOrientation.ShownSize(info.Width, info.Height, info.Metadata.Orientation);
}
catch (ImageDecodeException)
{
// The headers go on past the prefix (or the file is damaged): read the rest and look again.
}
Array.Resize(ref data, (int)remaining);
stream.ReadExactly(data.AsSpan(HeaderBytes));
return ReadSize(data);
}
/// <summary>Like <see cref="ReadSize(Stream)"/>, from bytes already in memory.</summary>
@@ -91,7 +147,8 @@ internal static class ImageDecoding
}
}
private static byte[]? ReadAll(Stream stream)
/// <summary>The rest of <paramref name="stream"/>, or null when it is empty or over <see cref="MaxFileBytes"/>.</summary>
internal static byte[]? ReadAll(Stream stream)
{
if (stream.CanSeek)
{
+4 -4
View File
@@ -278,11 +278,11 @@ public sealed class LibraryIngest(
{
try
{
hash = PerceptualHash.ComputeFromFile(saved.FullPath);
await using var stream = File.OpenRead(saved.FullPath);
if (ImageDecoding.ReadSize(stream) is { } size)
// One read of the file gives both the perceptual hash and the size as shown.
(hash, var size) = PerceptualHash.ComputeWithSizeFromFile(saved.FullPath);
if (size is { } shown)
{
(width, height) = size;
(width, height) = shown;
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+4 -6
View File
@@ -445,13 +445,11 @@ public sealed class LibraryRebuilder(
{
if (!isVideo)
{
phash = PerceptualHash.ComputeFromFile(path);
await using (var stream = File.OpenRead(path))
// One read of the file gives both the perceptual hash and the size as shown.
(phash, var size) = PerceptualHash.ComputeWithSizeFromFile(path);
if (size is { } shown)
{
if (ImageDecoding.ReadSize(stream) is { } size)
{
(width, height) = size;
}
(width, height) = shown;
}
}
}
+22
View File
@@ -64,6 +64,28 @@ public static class PerceptualHash
return Compute(stream);
}
/// <summary>
/// Hash and size as shown of an encoded image from one decode of the same bytes; each null when it cannot be had
/// (a damaged file may still give its size).
/// </summary>
internal static (ulong? Hash, (int Width, int Height)? Size) ComputeWithSize(ReadOnlyMemory<byte> encodedImage)
{
using var image = ImageDecoding.DecodeUpright(encodedImage, MinDecodedSide, out var size);
return (image is null ? null : Compute(image), size);
}
/// <summary>Like <see cref="ComputeWithSize(ReadOnlyMemory{byte})"/> for a file, read once.</summary>
internal static (ulong? Hash, (int Width, int Height)? Size) ComputeWithSizeFromFile(string path)
{
byte[]? data;
using (var stream = File.OpenRead(path))
{
data = ImageDecoding.ReadAll(stream);
}
return data is null ? (null, null) : ComputeWithSize(data);
}
/// <summary>Hash of a decoded image (any size), upright as it is shown.</summary>
internal static ulong Compute(RgbaImage image)
{