Lettore e scrittore JPEG di casa (C1, passo 3)

Febe deve leggere e scrivere JPEG senza SkiaSharp né altri componenti
esterni (decisione del 18 novembre 2026), quindi il codec è scritto dalla
specifica ITU-T T.81.

Lettore (JpegDecoder): sequenziale di base ed esteso, progressivo (selezione
spettrale e approssimazioni successive), senza perdita (predittori 1-7),
ognuno con Huffman e con codifica aritmetica; 8 e 12 bit (senza perdita da 2
a 16); qualunque campionamento, ripristino, DNL; grigio, YCbCr, RGB, CMYK e
YCCK con il segmento Adobe. IDCT esatta e crominanza con il filtro
triangolare. EXIF, ICC a pezzi, XMP e commenti; l'orientamento EXIF va in
ImageMetadata.Orientation (anche per PNG) e non si applica ai pixel. I file
gerarchici e quelli a 2 componenti si rifiutano come formato non letto; i
dati troncati dentro una scansione sono un file danneggiato.

Scrittore (JpegEncoder): sequenziale di base, qualità 1-100 sulle tabelle
dell'allegato K, 4:2:0, 4:4:4 e grigio, intervallo di ripristino, EXIF, ICC,
XMP e commenti.

Prove: contro le letture di SkiaSharp i JPEG dell'insieme di riferimento
stanno fra 59 e 67 dB di PSNR per canale, scarto massimo 3 (soglia 40 dB e
0,1% di pixel oltre 16). Un codificatore di prova scrive gli stessi
coefficienti in progressivo, aritmetico, 12 bit, con ripristino, scansioni
separate e DNL, e il lettore deve ridarli identici; senza perdita si
confronta campione per campione. Più andata e ritorno dello scrittore, file
danneggiati e mutazioni casuali con seme fisso. La facciata ImageDecoder
ora legge i JPEG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 14:14:20 +01:00
1 parent 8bf76f18ff
commit 36196526bb
25 files changed
+6411 -14

No files matched your search

@@ -0,0 +1,459 @@
namespace Febe.Core.Codecs.Images;
/// <summary>Huffman-coded scans: sequential (T.81 F.2), progressive (G.2) and lossless (H.2).</summary>
internal sealed partial class JpegFile
{
private enum BlockPass
{
Sequential,
DcFirst,
DcRefine,
AcFirst,
AcRefine,
}
private static BlockPass PassOf(bool progressive, in Scan scan) =>
!progressive ? BlockPass.Sequential
: scan.Ss == 0 ? (scan.Ah == 0 ? BlockPass.DcFirst : BlockPass.DcRefine)
: scan.Ah == 0 ? BlockPass.AcFirst : BlockPass.AcRefine;
private int DecodeHuffmanScan(Scan scan, int start)
{
var data = Data;
var reader = new JpegBitReader(data, start);
var pass = PassOf(Progressive, scan);
var (perRow, total) = McuLayout(scan);
var single = scan.Components.Length == 1;
var zigzag = JpegTables.ZigZag;
ReadOnlySpan<byte> to8 = Precision == 12 ? Twelve.ToEight : [];
var temp = new short[64];
var dcTables = new JpegHuffmanTable?[scan.Components.Length];
var acTables = new JpegHuffmanTable?[scan.Components.Length];
for (var i = 0; i < scan.Components.Length; i++)
{
var c = scan.Components[i];
if (pass is BlockPass.Sequential or BlockPass.DcFirst)
{
dcTables[i] = DcTable(c.DcTable);
}
if (pass is BlockPass.Sequential or BlockPass.AcFirst or BlockPass.AcRefine)
{
acTables[i] = AcTable(c.AcTable);
}
}
var eobRun = 0;
for (var mcu = 0; mcu < total; mcu++)
{
if (_restartInterval > 0 && mcu > 0 && mcu % _restartInterval == 0)
{
if (reader.UsedPadding)
{
throw InterruptedScan();
}
reader.Seek(SkipRestartMarker(reader.Position));
foreach (var c in scan.Components)
{
c.DcPredictor = 0;
}
eobRun = 0;
}
var mx = mcu % perRow;
var my = mcu / perRow;
for (var ci = 0; ci < scan.Components.Length; ci++)
{
var c = scan.Components[ci];
var wide = single ? 1 : c.H;
var high = single ? 1 : c.V;
for (var v = 0; v < high; v++)
{
for (var h = 0; h < wide; h++)
{
var bx = single ? mx : (mx * c.H) + h;
var by = single ? my : (my * c.V) + v;
Span<short> block;
if (c.Coefficients is { } coefficients)
{
block = coefficients.AsSpan(((by * c.PaddedUnitsWide) + bx) * 64, 64);
}
else
{
block = temp;
block.Clear();
}
switch (pass)
{
case BlockPass.Sequential:
DecodeSequential(ref reader, dcTables[ci]!, acTables[ci]!, ref c.DcPredictor, block, zigzag);
if (c.Plane is { } plane && bx < c.UnitsWide && by < c.UnitsHigh)
{
JpegDct.Inverse(block, c.Quantization, plane.AsSpan((by * 8 * c.PlaneStride) + (bx * 8)), c.PlaneStride, Precision, to8);
}
break;
case BlockPass.DcFirst:
{
var s = reader.DecodeHuffman(dcTables[ci]!);
if (s > 16)
{
throw BadValue();
}
c.DcPredictor += reader.ReceiveExtend(s);
block[0] = (short)(c.DcPredictor << scan.Al);
break;
}
case BlockPass.DcRefine:
if (reader.ReadBit() != 0)
{
block[0] |= (short)(1 << scan.Al);
}
break;
case BlockPass.AcFirst:
DecodeAcFirst(ref reader, acTables[ci]!, scan, ref eobRun, block, zigzag);
break;
default:
DecodeAcRefine(ref reader, acTables[ci]!, scan, ref eobRun, block, zigzag);
break;
}
}
}
}
}
if (reader.UsedPadding)
{
throw reader.ReachedEnd ? new ImageDecodeException("JPEG troncato: i dati compressi finiscono prima dell'ultimo blocco.") : InterruptedScan();
}
return FindNextMarker(reader.Position);
}
private static ImageDecodeException InterruptedScan() =>
new("JPEG danneggiato: i dati compressi di una scansione si interrompono prima dell'ultimo blocco.");
private static ImageDecodeException BadValue() => new("JPEG danneggiato: valore compresso non valido.");
private static void DecodeSequential(ref JpegBitReader reader, JpegHuffmanTable dc, JpegHuffmanTable ac, ref int predictor, Span<short> block, ReadOnlySpan<byte> zigzag)
{
var s = reader.DecodeHuffman(dc);
if (s > 16)
{
throw BadValue();
}
predictor += reader.ReceiveExtend(s);
block[0] = (short)predictor;
for (var k = 1; k < 64; k++)
{
var rs = reader.DecodeHuffman(ac);
var run = rs >> 4;
s = rs & 15;
if (s == 0)
{
if (run != 15)
{
break;
}
k += 15;
continue;
}
k += run;
if (k > 63)
{
throw BadValue();
}
block[zigzag[k]] = (short)reader.ReceiveExtend(s);
}
}
private static void DecodeAcFirst(ref JpegBitReader reader, JpegHuffmanTable ac, in Scan scan, ref int eobRun, Span<short> block, ReadOnlySpan<byte> zigzag)
{
if (eobRun > 0)
{
eobRun--;
return;
}
for (var k = scan.Ss; k <= scan.Se; k++)
{
var rs = reader.DecodeHuffman(ac);
var run = rs >> 4;
var s = rs & 15;
if (s == 0)
{
if (run < 15)
{
eobRun = (1 << run) - 1;
if (run > 0)
{
eobRun += reader.ReadBits(run);
}
break;
}
k += 15;
continue;
}
k += run;
if (k > scan.Se)
{
throw BadValue();
}
block[zigzag[k]] = (short)(reader.ReceiveExtend(s) * (1 << scan.Al));
}
}
private static void DecodeAcRefine(ref JpegBitReader reader, JpegHuffmanTable ac, in Scan scan, ref int eobRun, Span<short> block, ReadOnlySpan<byte> zigzag)
{
var plus = 1 << scan.Al;
var minus = -1 << scan.Al;
var k = scan.Ss;
if (eobRun == 0)
{
for (; k <= scan.Se; k++)
{
var rs = reader.DecodeHuffman(ac);
var run = rs >> 4;
var s = rs & 15;
var value = 0;
if (s != 0)
{
if (s != 1)
{
throw BadValue();
}
value = reader.ReadBit() != 0 ? plus : minus;
}
else if (run != 15)
{
eobRun = 1 << run;
if (run > 0)
{
eobRun += reader.ReadBits(run);
}
break;
}
// Skip `run` coefficients that are still zero, refining the nonzero ones met on the way, then place the
// new coefficient (none for ZRL) on the next zero.
for (; k <= scan.Se; k++)
{
ref var coefficient = ref block[zigzag[k]];
if (coefficient != 0)
{
Refine(ref reader, ref coefficient, plus, minus);
}
else
{
if (run == 0)
{
if (value != 0)
{
coefficient = (short)value;
}
break;
}
run--;
}
}
}
}
if (eobRun > 0)
{
// Inside an end-of-band run: only the coefficients that are already nonzero get a correction bit.
for (; k <= scan.Se; k++)
{
ref var coefficient = ref block[zigzag[k]];
if (coefficient != 0)
{
Refine(ref reader, ref coefficient, plus, minus);
}
}
eobRun--;
}
}
private static void Refine(ref JpegBitReader reader, ref short coefficient, int plus, int minus)
{
if (reader.ReadBit() != 0 && (coefficient & plus) == 0)
{
coefficient = (short)(coefficient >= 0 ? coefficient + plus : coefficient + minus);
}
}
private int DecodeLosslessHuffmanScan(Scan scan, int start)
{
var reader = new JpegBitReader(Data, start);
var tables = new JpegHuffmanTable[scan.Components.Length];
for (var i = 0; i < tables.Length; i++)
{
tables[i] = DcTable(scan.Components[i].DcTable);
}
var predictor = new LosslessPredictor(this, scan);
var (perRow, total) = McuLayout(scan);
var single = scan.Components.Length == 1;
for (var mcu = 0; mcu < total; mcu++)
{
var mx = mcu % perRow;
var my = mcu / perRow;
if (_restartInterval > 0 && mcu > 0 && mcu % _restartInterval == 0)
{
if (reader.UsedPadding)
{
throw InterruptedScan();
}
reader.Seek(SkipRestartMarker(reader.Position));
predictor.Restart(my);
}
for (var ci = 0; ci < scan.Components.Length; ci++)
{
var c = scan.Components[ci];
var wide = single ? 1 : c.H;
var high = single ? 1 : c.V;
for (var v = 0; v < high; v++)
{
for (var h = 0; h < wide; h++)
{
var x = single ? mx : (mx * c.H) + h;
var y = single ? my : (my * c.V) + v;
var s = reader.DecodeHuffman(tables[ci]);
int difference = s switch
{
0 => 0,
16 => 32768,
> 16 => throw BadValue(),
_ => reader.ReceiveExtend(s),
};
predictor.Store(c, x, y, difference);
}
}
}
}
if (reader.UsedPadding)
{
throw reader.ReachedEnd ? new ImageDecodeException("JPEG troncato: i dati compressi finiscono prima dell'ultimo campione.") : InterruptedScan();
}
predictor.Finish();
return FindNextMarker(reader.Position);
}
/// <summary>The predictors of T.81 H.1.2.1 and the samples they reconstruct.</summary>
private sealed class LosslessPredictor
{
private readonly JpegFile _file;
private readonly Scan _scan;
private readonly int[] _firstRow;
private readonly int _initial;
private readonly bool _single;
public LosslessPredictor(JpegFile file, Scan scan)
{
_file = file;
_scan = scan;
_firstRow = new int[scan.Components.Length];
_initial = 1 << (file.Precision - scan.Al - 1);
_single = scan.Components.Length == 1;
}
/// <summary>A restart interval starts at MCU row <paramref name="mcuRow"/>: its first line predicts like the first line of the scan.</summary>
public void Restart(int mcuRow)
{
for (var i = 0; i < _scan.Components.Length; i++)
{
_firstRow[i] = _single ? mcuRow : mcuRow * _scan.Components[i].V;
}
}
/// <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)];
public int Predict(JpegComponent c, int x, int y)
{
var samples = c.Samples!;
var stride = c.PlaneStride;
var i = (y * stride) + x;
if (IsFirstLine(c, y))
{
return x == 0 ? _initial : samples[i - 1];
}
if (x == 0)
{
return samples[i - stride];
}
int a = samples[i - 1];
int b = samples[i - stride];
int cc = samples[i - stride - 1];
return _scan.Ss switch
{
1 => a,
2 => b,
3 => cc,
4 => a + b - cc,
5 => a + ((b - cc) >> 1),
6 => b + ((a - cc) >> 1),
_ => (a + b) >> 1,
};
}
public void Store(JpegComponent c, int x, int y, int difference)
{
var predicted = Predict(c, x, y);
c.Samples![(y * c.PlaneStride) + x] = (ushort)((predicted + difference) & 0xFFFF);
}
/// <summary>Undoes the point transform and writes the 8-bit planes.</summary>
public void Finish() => _file.FinishLossless(_scan);
}
private void FinishLossless(in Scan scan)
{
if (_mode != Mode.Pixels)
{
return;
}
var max = (1 << Precision) - 1;
var shift = scan.Al;
foreach (var c in scan.Components)
{
var samples = c.Samples!;
var plane = c.Plane!;
for (var y = 0; y < c.Height; y++)
{
var row = y * c.PlaneStride;
for (var x = 0; x < c.Width; x++)
{
var value = Math.Min(samples[row + x] << shift, max);
plane[row + x] = Precision == 8 ? (byte)value : (byte)(((value * 255L) + (max >> 1)) / max);
}
}
}
}
}