namespace Febe.Core.Codecs.Images;
/// Huffman-coded scans: sequential (T.81 F.2), progressive (G.2) and lossless (H.2).
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 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++)
{
// 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)
{
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 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)
{
TransformBlock(c, plane, block, bx, by, 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 Truncated(reader.ReachedEnd, "blocco");
}
return FindNextMarker(reader.Position);
}
/// The error for a scan that needed bits it did not have: cut short () or interrupted by a marker.
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.");
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 block, ReadOnlySpan 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 block, ReadOnlySpan 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 block, ReadOnlySpan 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 (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)
{
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(ci, c, x, y, difference);
}
}
}
}
if (reader.UsedPadding)
{
throw Truncated(reader.ReachedEnd, "campione");
}
predictor.Finish();
return FindNextMarker(reader.Position);
}
/// The predictors of T.81 H.1.2.1 and the samples they reconstruct.
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;
}
/// A restart interval starts at MCU row : its first line predicts like the first line of the scan.
public void Restart(int mcuRow)
{
for (var i = 0; i < _scan.Components.Length; i++)
{
_firstRow[i] = _single ? mcuRow : mcuRow * _scan.Components[i].V;
}
}
/// Whether row of scan component is the first line of the scan or restart interval.
public bool IsFirstLine(int ci, int y) => y == _firstRow[ci];
/// The prediction for (x, y) of , the scan's component .
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 (y == _firstRow[ci])
{
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(int ci, JpegComponent c, int x, int y, int difference)
{
var predicted = Predict(ci, c, x, y);
c.Samples![(y * c.PlaneStride) + x] = (ushort)((predicted + difference) & 0xFFFF);
}
/// Undoes the point transform and writes the 8-bit planes.
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);
}
}
}
}
}