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

+7 -2
View File
@@ -34,7 +34,11 @@ public static class BmpDecoder
return png with { Format = ImageFormat.Bmp };
}
return new ImageInfo(ImageFormat.Bmp, header.Width, header.Height, 1, header.AlphaMask != 0, ImageMetadata.Empty);
var widest = Math.Max(Math.Max(BitOperations.PopCount(header.RedMask), BitOperations.PopCount(header.GreenMask)), Math.Max(BitOperations.PopCount(header.BlueMask), BitOperations.PopCount(header.AlphaMask)));
return new ImageInfo(ImageFormat.Bmp, header.Width, header.Height, 1, header.AlphaMask != 0, ImageMetadata.Empty)
{
BitsPerSample = Math.Max(8, widest),
};
}
/// <summary>Decodes a BMP to straight RGBA8, top row first.</summary>
@@ -143,7 +147,8 @@ public static class BmpDecoder
if (infoSize == 12)
{
width = BinaryPrimitives.ReadUInt16LittleEndian(info[4..]);
height = BinaryPrimitives.ReadInt16LittleEndian(info[6..]);
// bcHeight is an unsigned WORD and core bitmaps are always bottom-up (the sign test below keeps them so).
height = BinaryPrimitives.ReadUInt16LittleEndian(info[6..]);
planes = BinaryPrimitives.ReadUInt16LittleEndian(info[8..]);
header.BitsPerPixel = BinaryPrimitives.ReadUInt16LittleEndian(info[10..]);
header.Compression = BiRgb;
+2 -2
View File
@@ -294,7 +294,7 @@ public static class GifDecoder
var frameBytes = (long)frameWidth * frameHeight;
limits.CheckWorkingBytes(frameBytes);
var indices = ArrayPool<byte>.Shared.Rent((int)frameBytes);
var indices = ImageBuffers.Rent<byte>((int)frameBytes);
try
{
var decoded = DecodeLzw(data, file.FrameDataStart, file.FrameCodeSize, indices.AsSpan(0, (int)frameBytes));
@@ -361,7 +361,7 @@ public static class GifDecoder
}
finally
{
ArrayPool<byte>.Shared.Return(indices);
ImageBuffers.Return(indices);
}
}
@@ -0,0 +1,44 @@
using System.Buffers;
using System.Runtime.CompilerServices;
namespace Febe.Core.Codecs.Images;
/// <summary>
/// Working arrays of the codecs: from <see cref="ArrayPool{T}.Shared"/> up to <see cref="PooledBytes"/>, plain arrays
/// above it.
/// </summary>
/// <remarks>
/// The shared pool rounds every request up to a power of two and keeps arrays up to 1 GiB in its per-thread and
/// per-core slots after they are given back, until a full collection trims them: a 100-megapixel picture (400 MB)
/// would leave a 512 MiB array behind for each decoder that ran in parallel. Picture-sized arrays above the threshold
/// are therefore allocated and left to the collector, which frees them at once; the copy they save is small next to
/// the decoding itself.
/// </remarks>
internal static class ImageBuffers
{
/// <summary>Largest array, in bytes, taken from the shared pool (a power of two, so a pooled array never exceeds it).</summary>
public const int PooledBytes = 16 * 1024 * 1024;
/// <summary>An array of at least <paramref name="length"/> elements, contents undefined.</summary>
public static T[] Rent<T>(int length)
{
if ((long)length * Unsafe.SizeOf<T>() <= PooledBytes)
{
return ArrayPool<T>.Shared.Rent(length);
}
return GC.AllocateUninitializedArray<T>(length);
}
/// <summary>Gives back an array from <see cref="Rent{T}"/>; those above the threshold are left to the collector.</summary>
public static void Return<T>(T[] array)
{
if ((long)array.Length * Unsafe.SizeOf<T>() <= PooledBytes)
{
ArrayPool<T>.Shared.Return(array);
}
}
/// <summary>Whether <paramref name="array"/> of <see cref="Rent{T}"/> came from the shared pool.</summary>
public static bool IsPooled<T>(T[] array) => (long)array.Length * Unsafe.SizeOf<T>() <= PooledBytes;
}
+64 -10
View File
@@ -27,7 +27,10 @@ public sealed record ImageConversionOptions
/// <param name="Target">The format written.</param>
/// <param name="Width">Width as stored (the orientation is not applied: the tag is copied).</param>
/// <param name="Height">Height as stored.</param>
/// <param name="Lossy">Whether pixels may differ from the source's (a JPEG target).</param>
/// <param name="Lossy">
/// Whether pixels may differ from the source's: a JPEG target, or a source with more than 8 bits per sample (the
/// decoders keep 8).
/// </param>
/// <param name="Metadata">The metadata written.</param>
/// <param name="NotCarried">What of the source's metadata the target could not take, in Italian, for the interface.</param>
public sealed record ImageConversionResult(
@@ -42,12 +45,15 @@ public sealed record ImageConversionResult(
/// <summary>
/// Turns a picture into another format with the same pixels and the same metadata, so that the converted file is
/// the same photo with another extension (exports, decision of 18 November 2026): PNG and WebP losslessly, JPEG at
/// the quality of the options. The EXIF block (dates, camera, the orientation tag), the ICC profile and the XMP
/// packet are copied as they are; the pixels stay as stored, not turned by the orientation, which the copied tag
/// still describes. Texts go where the target can hold them: PNG text chunks, JPEG comments; WebP has none, and
/// what cannot be carried is listed in <see cref="ImageConversionResult.NotCarried"/>. Animations keep their first
/// frame only, and say so.
/// the same photo with another extension (exports, decision of 18 November 2026): PNG and WebP without further loss,
/// JPEG at the quality of the options. The pixels written are always 8-bit RGB(A): a source with more bits per
/// sample (16-bit PNG, 12-bit or lossless JPEG) loses that precision, which the result reports as lossy. The EXIF
/// block (dates, camera, the orientation tag) and the XMP packet are copied as they are, the ICC profile only when it
/// describes RGB data (a CMYK or grey profile would no longer fit the RGB pixels); the pixels stay as stored, not
/// turned by the orientation, which the copied tag still describes. Texts go where the target can hold them: PNG
/// text chunks, JPEG comments; WebP has none. The PNG colour chunks (gAMA, cHRM, sRGB) are not written. Whatever
/// cannot be carried is listed in <see cref="ImageConversionResult.NotCarried"/>. Animations keep their first frame
/// only, and say so.
/// </summary>
public static class ImageConverter
{
@@ -72,9 +78,34 @@ public static class ImageConverter
notCarried.Add($"l'animazione: resta solo il primo fotogramma di {info.FrameCount}");
}
var lossy = target == ImageFormat.Jpeg;
if (info.BitsPerSample > 8)
{
notCarried.Add($"la profondità di {info.BitsPerSample} bit per campione (i pixel sono scritti a 8 bit)");
lossy = true;
}
var metadata = info.Metadata;
var exif = metadata.Exif;
var icc = metadata.IccProfile;
var iccName = metadata.IccProfileName;
if (icc is not null && IccColorSpace(icc) != "RGB ")
{
notCarried.Add(IccColorSpace(icc) switch
{
"CMYK" => "il profilo colore CMYK (i pixel sono stati convertiti in RGB)",
"GRAY" => "il profilo colore in scala di grigi (i pixel sono scritti in RGB)",
_ => "il profilo colore (non descrive pixel RGB)",
});
icc = null;
iccName = null;
}
foreach (var chunk in metadata.ColorChunks)
{
notCarried.Add($"il blocco di colore {chunk} del PNG (non viene scritto)");
}
var xmp = metadata.Xmp;
var texts = metadata.Texts;
byte[] data;
@@ -85,7 +116,7 @@ public static class ImageConverter
{
Exif = exif,
IccProfile = icc,
IccProfileName = ValidIccName(metadata.IccProfileName) ?? PngEncoderOptions.Default.IccProfileName,
IccProfileName = ValidIccName(iccName) ?? PngEncoderOptions.Default.IccProfileName,
Xmp = xmp,
Texts = PngTexts(texts, notCarried),
});
@@ -147,11 +178,34 @@ public static class ImageConverter
Exif = exif,
Orientation = metadata.Orientation,
IccProfile = icc,
IccProfileName = metadata.IccProfileName,
IccProfileName = icc is null ? null : iccName,
Xmp = xmp,
Texts = target == ImageFormat.WebP ? [] : texts,
};
return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, target == ImageFormat.Jpeg, written, notCarried);
return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, lossy, written, notCarried);
}
/// <summary>The data colour space of an ICC profile (bytes 16-19 of its header: «RGB », «GRAY», «CMYK»...), or null.</summary>
internal static string? IccColorSpace(ReadOnlySpan<byte> profile)
{
if (profile.Length < 20)
{
return null;
}
Span<char> name = stackalloc char[4];
for (var i = 0; i < 4; i++)
{
var b = profile[16 + i];
if (b is < 32 or > 126)
{
return null;
}
name[i] = (char)b;
}
return new string(name);
}
/// <summary>Bytes of payload in one JPEG marker segment (65535 less the two of the length).</summary>
+14 -1
View File
@@ -33,6 +33,12 @@ public sealed class ImageMetadata
/// <summary>The texts, in file order (the XMP packet is in <see cref="Xmp"/>, not here).</summary>
public IReadOnlyList<ImageText> Texts { get; init; } = [];
/// <summary>
/// The PNG chunks that describe the colour of the pixels (gAMA, cHRM, sRGB) the file has, in file order. They are
/// not applied to the pixels and no encoder writes them, so a conversion says they are left behind.
/// </summary>
public IReadOnlyList<string> ColorChunks { get; init; } = [];
}
/// <summary>What a file says about its image, read without decoding the pixels.</summary>
@@ -42,4 +48,11 @@ public sealed class ImageMetadata
/// <param name="FrameCount">Frames of an animation (GIF images, APNG frames); 1 for a still image.</param>
/// <param name="HasAlpha">Whether the format of the pixels can carry transparency (not whether any pixel is transparent).</param>
/// <param name="Metadata">The metadata.</param>
public sealed record ImageInfo(ImageFormat Format, int Width, int Height, int FrameCount, bool HasAlpha, ImageMetadata Metadata);
public sealed record ImageInfo(ImageFormat Format, int Width, int Height, int FrameCount, bool HasAlpha, ImageMetadata Metadata)
{
/// <summary>
/// Bits of one sample as the file stores them (PNG bit depth, JPEG precision, BMP mask width; 8 for palettes and
/// for GIF and WebP). The decoders give 8-bit samples, so above 8 the decoded pixels have lost precision.
/// </summary>
public int BitsPerSample { get; init; } = 8;
}
+82 -19
View File
@@ -75,10 +75,17 @@ internal static class JpegDct
/// <summary>
/// Like <see cref="Inverse"/>, but writes the block reduced by 2^<paramref name="shift"/> (1 to 3) in each
/// direction: every output sample is the rounded mean of a square of the full block's samples. At an eighth that
/// mean is the DC term alone (S00 / 8 plus the level shift: the AC basis functions sum to zero over the block), so
/// no transform is computed.
/// direction: every output sample is the mean of a square of the full block's samples (before rounding and
/// clamping), computed directly from the coefficients without the full transform.
/// </summary>
/// <remarks>
/// Averaging two neighbours of the eight-point inverse x[n] = Σ C(k) X[k] cos((2n+1)kπ/16) gives
/// Σ C(k) X[k] cos(kπ/16) cos((2m+1)kπ/8). Coefficient 4 drops out (cos((2m+1)π/2) = 0) and coefficient 8 − k
/// folds onto k with weight −sin(kπ/16), so the half-size block is a four-point inverse of
/// Y0 = C(0) X0, Yk = Xk cos(kπ/16) − X(8−k) sin(kπ/16). Averaging pairs of that once more leaves
/// Y0 ± ((C2 + C6) Y1 + (C6 − C2) Y3) / 2, and at an eighth only the DC term remains (S00 / 8 plus the level
/// shift: the AC basis functions sum to zero over the block).
/// </remarks>
public static void InverseReduced(ReadOnlySpan<short> block, ReadOnlySpan<ushort> quantization, Span<byte> output, int stride, int precision, ReadOnlySpan<byte> to8Bit, int shift)
{
var max = precision == 12 ? 4095 : 255;
@@ -91,32 +98,88 @@ internal static class JpegDct
return;
}
Span<byte> full = stackalloc byte[64];
Inverse(block, quantization, full, 8, precision, to8Bit);
var n = 8 >> shift;
var side = 1 << shift;
var area = side * side;
var half = area >> 1;
for (var y = 0; y < n; y++)
Span<float> column = stackalloc float[8];
Span<float> work = stackalloc float[32];
Span<float> reduced = stackalloc float[4];
for (var c = 0; c < 8; c++)
{
var o = output.Slice(y * stride, n);
for (var x = 0; x < n; x++)
if (block[8 + c] == 0 && block[24 + c] == 0 && block[40 + c] == 0 && block[56 + c] == 0
&& (shift == 2 || (block[16 + c] == 0 && block[48 + c] == 0)))
{
var sum = 0;
for (var dy = 0; dy < side; dy++)
// Only the coefficients that reach the reduced samples are tested (rows 4, and 2 and 6 at a quarter, drop out).
var dc = block[c] * quantization[c] * C4;
for (var r = 0; r < n; r++)
{
var row = full.Slice((((y * side) + dy) * 8) + (x * side), side);
for (var dx = 0; dx < side; dx++)
{
sum += row[dx];
}
work[(r * 8) + c] = dc;
}
o[x] = (byte)((sum + half) / area);
continue;
}
for (var r = 0; r < 8; r++)
{
column[r] = block[(r * 8) + c] * quantization[(r * 8) + c];
}
Reduce1D(column, reduced, shift);
for (var r = 0; r < n; r++)
{
work[(r * 8) + c] = reduced[r];
}
}
// Each pass doubles the T.81 values, as in Inverse: a quarter brings them back.
var levelShift = precision == 12 ? 2048.5f : 128.5f;
for (var r = 0; r < n; r++)
{
Reduce1D(work.Slice(r * 8, 8), reduced, shift);
var o = output.Slice(r * stride, n);
for (var c = 0; c < n; c++)
{
var value = (int)((reduced[c] * 0.25f) + levelShift);
if ((uint)value > (uint)max)
{
value = value < 0 ? 0 : max;
}
o[c] = precision == 12 ? to8Bit[value] : (byte)value;
}
}
}
/// <summary>
/// The means of 2^<paramref name="shift"/> neighbouring points (shift 1 or 2) of the eight-point inverse of
/// <paramref name="x"/> (twice the T.81 inverse, like <see cref="Inverse1D"/>): four or two values.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void Reduce1D(ReadOnlySpan<float> x, Span<float> output, int shift)
{
var y0 = C4 * x[0];
var y1 = (C1 * x[1]) - (C7 * x[7]);
var y3 = (C3 * x[3]) - (C5 * x[5]);
if (shift == 2)
{
var d = (HalfC2PlusC6 * y1) + (HalfC6MinusC2 * y3);
output[0] = y0 + d;
output[1] = y0 - d;
return;
}
var y2 = (C2 * x[2]) - (C6 * x[6]);
var e0 = y0 + (C4 * y2);
var e1 = y0 - (C4 * y2);
var o0 = (C2 * y1) + (C6 * y3);
var o1 = (C6 * y1) - (C2 * y3);
output[0] = e0 + o0;
output[1] = e1 + o1;
output[2] = e1 - o1;
output[3] = e0 - o0;
}
private const float HalfC2PlusC6 = (C2 + C6) / 2;
private const float HalfC6MinusC2 = (C6 - C2) / 2;
/// <summary>
/// The forward transform of a block of level-shifted samples (natural order) into DCT coefficients, natural order,
/// not yet quantized.
@@ -321,12 +321,12 @@ internal sealed partial class JpegFile
// At the start of a line the left difference counts as zero, on the first line of the scan or
// of a restart interval the one above does.
var classA = x == 0 ? 0 : cls[i - 1];
var classB = predictor.IsFirstLine(c, y) ? 0 : cls[i - c.PlaneStride];
var classB = predictor.IsFirstLine(ci, y) ? 0 : cls[i - c.PlaneStride];
var s0 = (20 * classB) + (4 * classA);
var x1 = classB >= 3 ? 129 : 100;
var difference = DecodeValue(ref decoder, stats, s0, x1);
cls[i] = (byte)Classify(difference, low, up);
predictor.Store(c, x, y, difference);
predictor.Store(ci, c, x, y, difference);
}
}
}
@@ -46,6 +46,14 @@ internal sealed partial class JpegFile
var eobRun = 0;
for (var mcu = 0; mcu < total; mcu++)
{
// Past the end the reader gives zero bits, which are valid codes: without this check a file cut after
// its headers would be decoded to the last MCU before failing. Padding once used stays used until a
// restart, so failing at the first MCU row that needed it changes only when the error comes.
if (mcu > 0 && mcu % perRow == 0 && reader.UsedPadding)
{
throw Truncated(reader.ReachedEnd, "blocco");
}
if (_restartInterval > 0 && mcu > 0 && mcu % _restartInterval == 0)
{
if (reader.UsedPadding)
@@ -130,12 +138,16 @@ internal sealed partial class JpegFile
if (reader.UsedPadding)
{
throw reader.ReachedEnd ? new ImageDecodeException("JPEG troncato: i dati compressi finiscono prima dell'ultimo blocco.") : InterruptedScan();
throw Truncated(reader.ReachedEnd, "blocco");
}
return FindNextMarker(reader.Position);
}
/// <summary>The error for a scan that needed bits it did not have: cut short (<paramref name="reachedEnd"/>) or interrupted by a marker.</summary>
private static ImageDecodeException Truncated(bool reachedEnd, string unit) =>
reachedEnd ? new ImageDecodeException($"JPEG troncato: i dati compressi finiscono prima dell'ultimo {unit}.") : InterruptedScan();
private static ImageDecodeException InterruptedScan() =>
new("JPEG danneggiato: i dati compressi di una scansione si interrompono prima dell'ultimo blocco.");
@@ -317,6 +329,12 @@ internal sealed partial class JpegFile
{
var mx = mcu % perRow;
var my = mcu / perRow;
if (mx == 0 && mcu > 0 && reader.UsedPadding)
{
// As in DecodeHuffmanScan: fail at the first MCU row that ran out of data, not after the last one.
throw Truncated(reader.ReachedEnd, "campione");
}
if (_restartInterval > 0 && mcu > 0 && mcu % _restartInterval == 0)
{
if (reader.UsedPadding)
@@ -347,7 +365,7 @@ internal sealed partial class JpegFile
> 16 => throw BadValue(),
_ => reader.ReceiveExtend(s),
};
predictor.Store(c, x, y, difference);
predictor.Store(ci, c, x, y, difference);
}
}
}
@@ -355,7 +373,7 @@ internal sealed partial class JpegFile
if (reader.UsedPadding)
{
throw reader.ReachedEnd ? new ImageDecodeException("JPEG troncato: i dati compressi finiscono prima dell'ultimo campione.") : InterruptedScan();
throw Truncated(reader.ReachedEnd, "campione");
}
predictor.Finish();
@@ -389,15 +407,16 @@ internal sealed partial class JpegFile
}
}
/// <summary>Whether (x, y) of component <paramref name="c"/> is on the first line of the scan or restart interval.</summary>
public bool IsFirstLine(JpegComponent c, int y) => y == _firstRow[Array.IndexOf(_scan.Components, c)];
/// <summary>Whether row <paramref name="y"/> of scan component <paramref name="ci"/> is the first line of the scan or restart interval.</summary>
public bool IsFirstLine(int ci, int y) => y == _firstRow[ci];
public int Predict(JpegComponent c, int x, int y)
/// <summary>The prediction for (x, y) of <paramref name="c"/>, the scan's component <paramref name="ci"/>.</summary>
public int Predict(int ci, JpegComponent c, int x, int y)
{
var samples = c.Samples!;
var stride = c.PlaneStride;
var i = (y * stride) + x;
if (IsFirstLine(c, y))
if (y == _firstRow[ci])
{
return x == 0 ? _initial : samples[i - 1];
}
@@ -422,9 +441,9 @@ internal sealed partial class JpegFile
};
}
public void Store(JpegComponent c, int x, int y, int difference)
public void Store(int ci, JpegComponent c, int x, int y, int difference)
{
var predicted = Predict(c, x, y);
var predicted = Predict(ci, c, x, y);
c.Samples![(y * c.PlaneStride) + x] = (ushort)((predicted + difference) & 0xFFFF);
}
+7 -7
View File
@@ -323,7 +323,7 @@ internal sealed partial class JpegFile : IDisposable
Xmp = _xmp,
Texts = _texts ?? [],
};
return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata);
return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata) { BitsPerSample = Precision };
}
public JpegCoefficients ToCoefficients()
@@ -353,19 +353,19 @@ internal sealed partial class JpegFile : IDisposable
{
if (c.Plane is { } plane)
{
ArrayPool<byte>.Shared.Return(plane);
ImageBuffers.Return(plane);
c.Plane = null;
}
if (c.Coefficients is { } coefficients)
{
ArrayPool<short>.Shared.Return(coefficients);
ImageBuffers.Return(coefficients);
c.Coefficients = null;
}
if (c.Samples is { } samples)
{
ArrayPool<ushort>.Shared.Return(samples);
ImageBuffers.Return(samples);
c.Samples = null;
}
}
@@ -822,19 +822,19 @@ internal sealed partial class JpegFile : IDisposable
var samples = c.PlaneStride * c.PaddedUnitsHigh * unit;
if (_mode == Mode.Pixels)
{
c.Plane = ArrayPool<byte>.Shared.Rent(c.PlaneStride * c.PaddedUnitsHigh * planeUnit);
c.Plane = ImageBuffers.Rent<byte>(c.PlaneStride * c.PaddedUnitsHigh * planeUnit);
}
if (Lossless)
{
c.Samples = _pooledArrays ? ArrayPool<ushort>.Shared.Rent(samples) : new ushort[samples];
c.Samples = _pooledArrays ? ImageBuffers.Rent<ushort>(samples) : new ushort[samples];
}
else if (keepCoefficients)
{
var length = c.PaddedUnitsWide * c.PaddedUnitsHigh * 64;
if (_pooledArrays)
{
c.Coefficients = ArrayPool<short>.Shared.Rent(length);
c.Coefficients = ImageBuffers.Rent<short>(length);
c.Coefficients.AsSpan(0, length).Clear();
}
else
+6 -5
View File
@@ -64,6 +64,12 @@ internal sealed class JpegHuffmanTable
for (var length = 1; length <= 16; length++)
{
int count = counts[length - 1];
if (code + count > 1 << length)
{
// Checked before any entry is written: an oversubscribed length would otherwise index past the lookup.
throw new ImageDecodeException("Tabella di Huffman JPEG non valida: i codici non stanno nella loro lunghezza.");
}
table.ValueOffset[length] = k - code;
for (var i = 0; i < count; i++, k++, code++)
{
@@ -84,11 +90,6 @@ internal sealed class JpegHuffmanTable
}
table.MaxCode[length] = count == 0 ? -1 : code - 1;
if (code > 1 << length)
{
throw new ImageDecodeException("Tabella di Huffman JPEG non valida: i codici non stanno nella loro lunghezza.");
}
code <<= 1;
}
+23 -2
View File
@@ -87,6 +87,7 @@ public static class PngDecoder
public string? IccName;
public string? Xmp;
public List<ImageText>? Texts;
public List<string>? ColorChunks;
public int Channels => ColorType switch { 2 => 3, 4 => 2, 6 => 4, _ => 1 };
@@ -98,9 +99,21 @@ public static class PngDecoder
Height,
FrameCount,
ColorType is 4 or 6 || HasColorKey || HasPaletteAlpha,
Exif is null && Icc is null && Xmp is null && Texts is null
Exif is null && Icc is null && Xmp is null && Texts is null && ColorChunks is null
? ImageMetadata.Empty
: new ImageMetadata { Exif = Exif, Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif), IccProfile = Icc, IccProfileName = IccName, Xmp = Xmp, Texts = Texts ?? [] });
: new ImageMetadata
{
Exif = Exif,
Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif),
IccProfile = Icc,
IccProfileName = IccName,
Xmp = Xmp,
Texts = Texts ?? [],
ColorChunks = ColorChunks ?? [],
})
{
BitsPerSample = ColorType == 3 ? 8 : BitDepth,
};
}
private static PngFile Parse(ReadOnlyMemory<byte> memory, ImageLimits limits, bool readMetadata)
@@ -226,6 +239,14 @@ public static class PngDecoder
break;
case "gAMA" or "cHRM" or "sRGB":
if (readMetadata && !(file.ColorChunks ??= []).Contains(name))
{
file.ColorChunks.Add(name);
}
break;
case "tEXt" or "zTXt" or "iTXt" or "iCCP" or "eXIf":
if (readMetadata)
{
+10 -9
View File
@@ -7,9 +7,10 @@ namespace Febe.Core.Codecs.Images;
/// (8 bits each, alpha not premultiplied: the colour under an alpha of 0 is kept as the file had it).
/// </summary>
/// <remarks>
/// The pixels live either in an array of exactly the right size (<see cref="RgbaImage(int, int)"/>) or in an array
/// rented from <see cref="ArrayPool{T}.Shared"/> (<see cref="Rent"/>), which <see cref="Dispose"/> gives back; a pooled
/// image must not be used after that. Disposing an image that owns its array does nothing, so callers can always
/// The pixels live either in an array of exactly the right size (<see cref="RgbaImage(int, int)"/>) or in a rented
/// array (<see cref="Rent"/>: from <see cref="ArrayPool{T}.Shared"/> up to 16 MiB, a plain array above, so that very
/// large pictures are not kept by the pool), which <see cref="Dispose"/> gives back; a rented image must not be used
/// after that. Disposing an image that owns its array does nothing, so callers can always
/// dispose.
/// </remarks>
public sealed class RgbaImage : IDisposable
@@ -46,13 +47,13 @@ public sealed class RgbaImage : IDisposable
}
/// <summary>
/// A new image whose pixels come from the shared array pool, every pixel (0, 0, 0, 0). Give it back with
/// <see cref="Dispose"/>.
/// A new image whose pixels are rented (the shared array pool up to 16 MiB), every pixel (0, 0, 0, 0). Give it
/// back with <see cref="Dispose"/>.
/// </summary>
public static RgbaImage Rent(int width, int height)
{
var length = CheckedLength(width, height);
var buffer = ArrayPool<byte>.Shared.Rent(length);
var buffer = ImageBuffers.Rent<byte>(length);
buffer.AsSpan(0, length).Clear();
return new RgbaImage(width, height, buffer, pooled: true);
}
@@ -76,7 +77,7 @@ public sealed class RgbaImage : IDisposable
/// <summary>Bytes of the whole image.</summary>
public int Length { get; }
/// <summary>Whether the pixels come from the array pool.</summary>
/// <summary>Whether the pixels were rented with <see cref="Rent"/> (and must not be used after <see cref="Dispose"/>).</summary>
public bool IsPooled => _pooled;
/// <summary>All the pixels, row after row.</summary>
@@ -118,13 +119,13 @@ public sealed class RgbaImage : IDisposable
/// <summary>A copy of the pixels in an array of exactly <see cref="Length"/> bytes.</summary>
public byte[] ToArray() => Pixels.ToArray();
/// <summary>Gives a pooled array back to the pool; the image cannot be used afterwards.</summary>
/// <summary>Gives a rented array back; the image cannot be used afterwards.</summary>
public void Dispose()
{
if (_pooled && _buffer is { } buffer)
{
_buffer = null;
ArrayPool<byte>.Shared.Return(buffer);
ImageBuffers.Return(buffer);
}
}
+20 -11
View File
@@ -200,14 +200,13 @@ internal sealed class Vp8Decoder
ParseHeader(ref header);
SetUpPartitions(_start + 10 + firstSize, _length - 10 - firstSize);
var pool = ArrayPool<byte>.Shared;
_y = pool.Rent((int)lumaBytes);
_u = pool.Rent((int)(lumaBytes / 4));
_v = pool.Rent((int)(lumaBytes / 4));
_mbSegment = pool.Rent(_mbWidth * _mbHeight);
_mbFlags = pool.Rent(_mbWidth * _mbHeight);
_intraTop = pool.Rent(_mbWidth * 4);
_nzTop = pool.Rent(_mbWidth * 9);
_y = ImageBuffers.Rent<byte>((int)lumaBytes);
_u = ImageBuffers.Rent<byte>((int)(lumaBytes / 4));
_v = ImageBuffers.Rent<byte>((int)(lumaBytes / 4));
_mbSegment = ImageBuffers.Rent<byte>(_mbWidth * _mbHeight);
_mbFlags = ImageBuffers.Rent<byte>(_mbWidth * _mbHeight);
_intraTop = ImageBuffers.Rent<byte>(_mbWidth * 4);
_nzTop = ImageBuffers.Rent<byte>(_mbWidth * 9);
_intraTop.AsSpan(0, _mbWidth * 4).Fill(Vp8Tables.BDc);
_nzTop.AsSpan(0, _mbWidth * 9).Clear();
@@ -237,17 +236,19 @@ internal sealed class Vp8Decoder
}
}
Vp8LoopFilter.Apply(this);
if (_filterLevel > 0)
{
Vp8LoopFilter.Apply(this);
}
}
private void Release()
{
var pool = ArrayPool<byte>.Shared;
foreach (var array in new[] { _y, _u, _v, _mbSegment, _mbFlags, _intraTop, _nzTop })
{
if (array.Length > 0)
{
pool.Return(array);
ImageBuffers.Return(array);
}
}
@@ -358,6 +359,14 @@ internal sealed class Vp8Decoder
private void ComputeFilterParams()
{
if (_filterLevel == 0)
{
// A frame loop_filter_level of 0 turns the filter off for the whole frame, whatever the segment levels and
// the deltas would give (as libvpx, libwebp and the RFC 6386 reference decoder do).
Array.Clear(_filterParams);
return;
}
for (var s = 0; s < 4; s++)
{
var baseLevel = !_segmentation ? _filterLevel : _absoluteDeltas ? _segmentFilter[s] : _filterLevel + _segmentFilter[s];
+39 -10
View File
@@ -103,7 +103,7 @@ internal sealed class Vp8LDecoder
}
finally
{
ArrayPool<uint>.Shared.Return(argb);
ImageBuffers.Return(argb);
}
}
@@ -125,7 +125,7 @@ internal sealed class Vp8LDecoder
}
finally
{
ArrayPool<uint>.Shared.Return(argb);
ImageBuffers.Return(argb);
}
}
@@ -194,7 +194,7 @@ internal sealed class Vp8LDecoder
CheckStream();
}
var argb = ArrayPool<uint>.Shared.Rent((int)pixelCount);
var argb = ImageBuffers.Rent<uint>((int)pixelCount);
try
{
DecodeSpatial(xsize, height, argb, allowMeta: true);
@@ -222,7 +222,7 @@ internal sealed class Vp8LDecoder
}
catch
{
ArrayPool<uint>.Shared.Return(argb);
ImageBuffers.Return(argb);
throw;
}
}
@@ -253,6 +253,8 @@ internal sealed class Vp8LDecoder
uint[]? meta = null;
var metaWidth = 0;
var groupCount = 1;
var codedGroups = 1;
int[]? remap = null;
if (allowMeta && _br.ReadBits(1) == 1)
{
metaBits = _br.ReadBits(3) + 2;
@@ -266,7 +268,24 @@ internal sealed class Vp8LDecoder
max = Math.Max(max, g);
}
groupCount = max + 1;
// The stream holds the codes of groups 0 to max, but the meta image may name only a few of them (one
// pixel of value 65535 asks for 65,536 groups): only the groups it names are built, renumbered densely;
// the codes of the others are read and checked, then dropped, as libwebp does.
codedGroups = max + 1;
Charge(codedGroups * 4L);
remap = new int[codedGroups];
remap.AsSpan().Fill(-1);
groupCount = 0;
for (var i = 0; i < meta.Length; i++)
{
ref var dense = ref remap[(int)meta[i]];
if (dense < 0)
{
dense = groupCount++;
}
meta[i] = (uint)dense;
}
}
CheckStream();
@@ -274,13 +293,17 @@ internal sealed class Vp8LDecoder
var groups = new Vp8LHuffman[groupCount * 5];
Span<int> alphabets = [256 + NumLengthCodes + cacheSize, 256, 256, 256, NumDistanceCodes];
var lengths = new byte[alphabets[0]];
for (var g = 0; g < groupCount; g++)
for (var g = 0; g < codedGroups; g++)
{
var dense = remap is null ? g : remap[g];
for (var k = 0; k < 5; k++)
{
var code = ReadCode(alphabets[k], lengths);
Charge(code.TableSize * 4L);
groups[(g * 5) + k] = code;
var code = ReadCode(alphabets[k], lengths, build: dense >= 0);
if (code is not null)
{
Charge(code.TableSize * 4L);
groups[(dense * 5) + k] = code;
}
}
CheckStream();
@@ -289,7 +312,8 @@ internal sealed class Vp8LDecoder
DecodePixels(width, height, output, groups, meta, metaBits, metaWidth, cacheBits);
}
private Vp8LHuffman ReadCode(int alphabet, byte[] buffer)
/// <summary>Reads one prefix code; with <paramref name="build"/> false it is only checked, and null comes back.</summary>
private Vp8LHuffman? ReadCode(int alphabet, byte[] buffer, bool build = true)
{
var lengths = buffer.AsSpan(0, alphabet);
lengths.Clear();
@@ -379,6 +403,11 @@ internal sealed class Vp8LDecoder
throw Truncated();
}
if (!build)
{
return Vp8LHuffman.IsValid(lengths) ? null : throw Damaged();
}
return Vp8LHuffman.Build(lengths) ?? throw Damaged();
}
@@ -101,6 +101,32 @@ internal sealed class Vp8LHuffman
/// <summary>Entries of the decoding tables, for the memory budget.</summary>
public int TableSize => _table.Length;
/// <summary>
/// Whether <see cref="Build"/> would accept <paramref name="lengths"/>, without building any table: for the codes
/// of groups that no pixel uses.
/// </summary>
public static bool IsValid(ReadOnlySpan<byte> lengths)
{
var space = 1 << MaxCodeLength;
var used = 0;
foreach (var len in lengths)
{
if (len > MaxCodeLength)
{
return false;
}
if (len > 0)
{
used++;
space -= 1 << (MaxCodeLength - len);
}
}
// One symbol is a code of zero bits; more must fill the code space exactly (Kraft).
return used == 1 || (used > 1 && space == 0);
}
/// <summary>
/// The code given by the code lengths of each symbol (0 = not used), or null when the lengths are not a complete
/// prefix code (or use no symbol at all). A single used symbol is a code of zero bits.
+6 -7
View File
@@ -274,9 +274,8 @@ internal static class Vp8LEncoder
private static void WriteCoded(Vp8LBitWriter writer, uint[] pixels, int width, int height, Vp8LEncoderSettings settings, bool mainImage)
{
var count = width * height;
var pool = ArrayPool<int>.Shared;
var lengths = pool.Rent(count);
var distances = pool.Rent(count);
var lengths = ImageBuffers.Rent<int>(count);
var distances = ImageBuffers.Rent<int>(count);
try
{
var tokens = settings.Lz77 ? FindMatches(pixels, width, count, settings.ChainLength, lengths, distances) : Literals(count, lengths);
@@ -399,8 +398,8 @@ internal static class Vp8LEncoder
}
finally
{
pool.Return(lengths);
pool.Return(distances);
ImageBuffers.Return(lengths);
ImageBuffers.Return(distances);
}
}
@@ -415,7 +414,7 @@ internal static class Vp8LEncoder
private static int FindMatches(uint[] pixels, int width, int count, int chainLength, int[] lengths, int[] distances)
{
var head = ArrayPool<int>.Shared.Rent(1 << HashBits);
var previous = ArrayPool<int>.Shared.Rent(count);
var previous = ImageBuffers.Rent<int>(count);
try
{
head.AsSpan(0, 1 << HashBits).Fill(-1);
@@ -475,7 +474,7 @@ internal static class Vp8LEncoder
finally
{
ArrayPool<int>.Shared.Return(head);
ArrayPool<int>.Shared.Return(previous);
ImageBuffers.Return(previous);
}
}
+2 -2
View File
@@ -429,7 +429,7 @@ internal static class WebPAlpha
var count = width * height;
limits.CheckWorkingBytes(count);
var alpha = ArrayPool<byte>.Shared.Rent(count);
var alpha = ImageBuffers.Rent<byte>(count);
try
{
var plane = alpha.AsSpan(0, count);
@@ -456,7 +456,7 @@ internal static class WebPAlpha
}
finally
{
ArrayPool<byte>.Shared.Return(alpha);
ImageBuffers.Return(alpha);
}
}