using System.Runtime.CompilerServices;
namespace Febe.Core.Codecs.Images;
///
/// A Huffman table of T.81 (Annex C): the canonical codes built from the counts per length, with a lookup of the
/// first bits for decoding and the code of every symbol for encoding.
///
internal sealed class JpegHuffmanTable
{
/// Bits looked up at once; longer codes take the slow path of T.81 F.2.2.3.
public const int LookupBits = 9;
private JpegHuffmanTable(byte[] counts, byte[] values)
{
Counts = counts;
Values = values;
}
/// Codes of each length 1-16.
public byte[] Counts { get; }
/// The symbols, in code order.
public byte[] Values { get; }
/// For each value of the next bits: (length << 8) | symbol, or 0.
public ushort[] Lookup { get; } = new ushort[1 << LookupBits];
/// Largest code of each length (index 1-16), -1 when there is none.
public int[] MaxCode { get; } = new int[17];
/// For each length, the index in of its first code minus that code.
public int[] ValueOffset { get; } = new int[17];
/// The code of each symbol (encoding).
public ushort[] Codes { get; } = new ushort[256];
/// The length of the code of each symbol, 0 when the table has no code for it (encoding).
public byte[] Sizes { get; } = new byte[256];
/// Builds a table from the 16 counts and the symbols of a DHT segment.
/// The counts describe more codes than fit, or do not match the symbols.
public static JpegHuffmanTable Build(ReadOnlySpan counts, ReadOnlySpan values)
{
if (counts.Length != 16)
{
throw new ImageDecodeException("Tabella di Huffman JPEG non valida.");
}
var total = 0;
foreach (var count in counts)
{
total += count;
}
if (total > 256 || total != values.Length)
{
throw new ImageDecodeException("Tabella di Huffman JPEG non valida: troppi simboli.");
}
var table = new JpegHuffmanTable(counts.ToArray(), values.ToArray());
var code = 0;
var k = 0;
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++)
{
var symbol = values[k];
if (table.Sizes[symbol] == 0)
{
table.Codes[symbol] = (ushort)code;
table.Sizes[symbol] = (byte)length;
}
if (length <= LookupBits)
{
var shift = LookupBits - length;
var first = code << shift;
var entry = (ushort)((length << 8) | symbol);
table.Lookup.AsSpan(first, 1 << shift).Fill(entry);
}
}
table.MaxCode[length] = count == 0 ? -1 : code - 1;
code <<= 1;
}
return table;
}
}
///
/// Reads the bits of an entropy-coded segment (T.81 F.2.2.5): undoes the 0xFF 0x00 stuffing and stops at the first
/// marker or at the end of the data, after which it gives zero bits and counts them, so that a scan that needed bits
/// it did not have can be told apart from one that ended on its last byte.
///
internal ref struct JpegBitReader
{
private readonly ReadOnlySpan _data;
private int _position;
private ulong _bits;
private int _count;
private int _padBits;
public JpegBitReader(ReadOnlySpan data, int position)
{
_data = data;
_position = position;
}
/// Position of the next byte not yet read.
public readonly int Position => _position;
/// Whether the reader ran out of data (not at a marker).
public bool ReachedEnd { get; private set; }
/// Whether a decoded symbol used bits past the end of the segment.
public readonly bool UsedPadding => _padBits > _count;
/// Drops the bits of the current byte and those buffered, for a restart marker or the end of a scan.
public void Reset()
{
_bits = 0;
_count = 0;
_padBits = 0;
ReachedEnd = false;
}
/// Moves to , with no buffered bits.
public void Seek(int position)
{
Reset();
_position = position;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ReadBit()
{
if (_count < 1)
{
Fill();
}
var bit = (int)(_bits >> 63);
_bits <<= 1;
_count--;
return bit;
}
/// The next bits (0-16) as an unsigned number.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ReadBits(int n)
{
if (n == 0)
{
return 0;
}
if (_count < n)
{
Fill();
}
var value = (int)(_bits >> (64 - n));
_bits <<= n;
_count -= n;
return value;
}
/// RECEIVE and EXTEND of T.81 F.2.2.1: bits as a signed value of category s.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ReceiveExtend(int s)
{
if (s == 0)
{
return 0;
}
var value = ReadBits(s);
return value < 1 << (s - 1) ? value - (1 << s) + 1 : value;
}
/// Decodes one symbol with .
/// The bits are no code of the table.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int DecodeHuffman(JpegHuffmanTable table)
{
if (_count < 16)
{
Fill();
}
var entry = table.Lookup[(int)(_bits >> (64 - JpegHuffmanTable.LookupBits))];
if (entry != 0)
{
var length = entry >> 8;
_bits <<= length;
_count -= length;
return entry & 0xFF;
}
return DecodeSlow(table);
}
private int DecodeSlow(JpegHuffmanTable table)
{
for (var length = JpegHuffmanTable.LookupBits + 1; length <= 16; length++)
{
var code = (int)(_bits >> (64 - length));
if (code <= table.MaxCode[length])
{
_bits <<= length;
_count -= length;
return table.Values[table.ValueOffset[length] + code];
}
}
throw new ImageDecodeException("JPEG danneggiato: un codice di Huffman non esiste nella tabella.");
}
private void Fill()
{
while (_count <= 56)
{
int value;
if (_padBits > 0)
{
value = 0;
_padBits += 8;
}
else if (_position >= _data.Length)
{
ReachedEnd = true;
value = 0;
_padBits = 8;
}
else
{
value = _data[_position];
if (value == 0xFF)
{
if (_position + 1 < _data.Length && _data[_position + 1] == 0)
{
_position += 2;
}
else
{
// A marker (or the end of the data right after 0xFF): no more bits in this segment.
if (_position + 1 >= _data.Length)
{
ReachedEnd = true;
}
value = 0;
_padBits = 8;
}
}
else
{
_position++;
}
}
_bits |= (ulong)value << (56 - _count);
_count += 8;
}
}
}