Files
Febe/src/Febe.Core/Codecs/Images/JpegDct.cs
T
Alby96andClaude Opus 5.5 7e8296e790 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>
2026-11-18 16:52:17 +01:00

258 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Runtime.CompilerServices;
namespace Febe.Core.Codecs.Images;
/// <summary>
/// The 8×8 discrete cosine transforms of T.81 (A.3.3), separable, in single precision. Each one-dimensional pass
/// splits the eight points into an even half (a four-point transform on coefficients 0, 2, 4, 6) and an odd half
/// (coefficients 1, 3, 5, 7), which is the textbook factorisation of the defining sums: accurate to well under one
/// level, which is what the "accurate" integer IDCT of other decoders gives too.
/// </summary>
internal static class JpegDct
{
private const float C1 = 0.98078528040323044913f; // cos(1π/16)
private const float C2 = 0.92387953251128675613f; // cos(2π/16)
private const float C3 = 0.83146961230254523708f; // cos(3π/16)
private const float C4 = 0.70710678118654752440f; // cos(4π/16)
private const float C5 = 0.55557023301960222474f; // cos(5π/16)
private const float C6 = 0.38268343236508977173f; // cos(6π/16)
private const float C7 = 0.19509032201612826785f; // cos(7π/16)
/// <summary>
/// Dequantizes a block (natural order) and writes its 8×8 samples to <paramref name="output"/>, row after row
/// <paramref name="stride"/> bytes apart. With <paramref name="precision"/> 12 the samples are 12-bit and are
/// reduced to 8 bits through <paramref name="to8Bit"/> (4096 entries); with 8 they are written as they are.
/// </summary>
public static void Inverse(ReadOnlySpan<short> block, ReadOnlySpan<ushort> quantization, Span<byte> output, int stride, int precision, ReadOnlySpan<byte> to8Bit)
{
Span<float> work = stackalloc float[64];
for (var c = 0; c < 8; c++)
{
if (block[8 + c] == 0 && block[16 + c] == 0 && block[24 + c] == 0 && block[32 + c] == 0
&& block[40 + c] == 0 && block[48 + c] == 0 && block[56 + c] == 0)
{
var dc = block[c] * quantization[c] * C4;
for (var r = 0; r < 8; r++)
{
work[(r * 8) + c] = dc;
}
continue;
}
float x0 = block[c] * quantization[c];
float x1 = block[8 + c] * quantization[8 + c];
float x2 = block[16 + c] * quantization[16 + c];
float x3 = block[24 + c] * quantization[24 + c];
float x4 = block[32 + c] * quantization[32 + c];
float x5 = block[40 + c] * quantization[40 + c];
float x6 = block[48 + c] * quantization[48 + c];
float x7 = block[56 + c] * quantization[56 + c];
Inverse1D(x0, x1, x2, x3, x4, x5, x6, x7, work, c, 8);
}
// The column pass left every value doubled, the row pass doubles again: a quarter brings them back.
var shift = precision == 12 ? 2048.5f : 128.5f;
var max = precision == 12 ? 4095 : 255;
Span<float> row = stackalloc float[8];
for (var r = 0; r < 8; r++)
{
var w = work.Slice(r * 8, 8);
Inverse1D(w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7], row, 0, 1);
var o = output.Slice(r * stride, 8);
for (var c = 0; c < 8; c++)
{
var value = (int)((row[c] * 0.25f) + shift);
if ((uint)value > (uint)max)
{
value = value < 0 ? 0 : max;
}
o[c] = precision == 12 ? to8Bit[value] : (byte)value;
}
}
}
/// <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 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;
if (shift >= 3)
{
var level = precision == 12 ? 2048 : 128;
var value = (int)Math.Floor((block[0] * quantization[0] / 8.0) + level + 0.5);
value = Math.Clamp(value, 0, max);
output[0] = precision == 12 ? to8Bit[value] : (byte)value;
return;
}
var n = 8 >> shift;
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++)
{
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)))
{
// 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++)
{
work[(r * 8) + c] = dc;
}
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.
/// </summary>
public static void Forward(ReadOnlySpan<float> samples, Span<float> coefficients)
{
Span<float> work = stackalloc float[64];
for (var r = 0; r < 8; r++)
{
var s = samples.Slice(r * 8, 8);
Forward1D(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], work, r * 8, 1);
}
for (var c = 0; c < 8; c++)
{
Forward1D(work[c], work[8 + c], work[16 + c], work[24 + c], work[32 + c], work[40 + c], work[48 + c], work[56 + c], coefficients, c, 8);
}
for (var i = 0; i < 64; i++)
{
coefficients[i] *= 0.25f;
}
}
/// <summary>Eight points of x[n] = Σ C(k) X[k] cos((2n+1)kπ/16), C(0) = 1/√2, C(k) = 1: twice the T.81 inverse.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void Inverse1D(float x0, float x1, float x2, float x3, float x4, float x5, float x6, float x7, Span<float> output, int start, int step)
{
var t0 = C4 * (x0 + x4);
var t1 = C4 * (x0 - x4);
var t2 = (C2 * x2) + (C6 * x6);
var t3 = (C6 * x2) - (C2 * x6);
var e0 = t0 + t2;
var e3 = t0 - t2;
var e1 = t1 + t3;
var e2 = t1 - t3;
var o0 = (C1 * x1) + (C3 * x3) + (C5 * x5) + (C7 * x7);
var o1 = (C3 * x1) - (C7 * x3) - (C1 * x5) - (C5 * x7);
var o2 = (C5 * x1) - (C1 * x3) + (C7 * x5) + (C3 * x7);
var o3 = (C7 * x1) - (C5 * x3) + (C3 * x5) - (C1 * x7);
output[start] = e0 + o0;
output[start + step] = e1 + o1;
output[start + (2 * step)] = e2 + o2;
output[start + (3 * step)] = e3 + o3;
output[start + (4 * step)] = e3 - o3;
output[start + (5 * step)] = e2 - o2;
output[start + (6 * step)] = e1 - o1;
output[start + (7 * step)] = e0 - o0;
}
/// <summary>Eight points of X[k] = C(k) Σ x[n] cos((2n+1)kπ/16): twice the T.81 forward transform.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void Forward1D(float x0, float x1, float x2, float x3, float x4, float x5, float x6, float x7, Span<float> output, int start, int step)
{
var s0 = x0 + x7;
var s1 = x1 + x6;
var s2 = x2 + x5;
var s3 = x3 + x4;
var d0 = x0 - x7;
var d1 = x1 - x6;
var d2 = x2 - x5;
var d3 = x3 - x4;
output[start] = C4 * (s0 + s1 + s2 + s3);
output[start + (4 * step)] = C4 * (s0 - s1 - s2 + s3);
output[start + (2 * step)] = (C2 * (s0 - s3)) + (C6 * (s1 - s2));
output[start + (6 * step)] = (C6 * (s0 - s3)) - (C2 * (s1 - s2));
output[start + step] = (C1 * d0) + (C3 * d1) + (C5 * d2) + (C7 * d3);
output[start + (3 * step)] = (C3 * d0) - (C7 * d1) - (C1 * d2) - (C5 * d3);
output[start + (5 * step)] = (C5 * d0) - (C1 * d1) + (C7 * d2) + (C3 * d3);
output[start + (7 * step)] = (C7 * d0) - (C5 * d1) + (C3 * d2) - (C1 * d3);
}
}