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:
1 parent
8bf76f18ff
commit
36196526bb
25 files changed
+6411
-14
No files matched your search
@@ -0,0 +1,275 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Febe.Core.Codecs.Images;
|
||||
|
||||
/// <summary>
|
||||
/// A Huffman table of T.81 (Annex C): the canonical codes built from the counts per length, with a lookup of the
|
||||
/// first <see cref="LookupBits"/> bits for decoding and the code of every symbol for encoding.
|
||||
/// </summary>
|
||||
internal sealed class JpegHuffmanTable
|
||||
{
|
||||
/// <summary>Bits looked up at once; longer codes take the slow path of T.81 F.2.2.3.</summary>
|
||||
public const int LookupBits = 9;
|
||||
|
||||
private JpegHuffmanTable(byte[] counts, byte[] values)
|
||||
{
|
||||
Counts = counts;
|
||||
Values = values;
|
||||
}
|
||||
|
||||
/// <summary>Codes of each length 1-16.</summary>
|
||||
public byte[] Counts { get; }
|
||||
|
||||
/// <summary>The symbols, in code order.</summary>
|
||||
public byte[] Values { get; }
|
||||
|
||||
/// <summary>For each value of the next <see cref="LookupBits"/> bits: (length << 8) | symbol, or 0.</summary>
|
||||
public ushort[] Lookup { get; } = new ushort[1 << LookupBits];
|
||||
|
||||
/// <summary>Largest code of each length (index 1-16), -1 when there is none.</summary>
|
||||
public int[] MaxCode { get; } = new int[17];
|
||||
|
||||
/// <summary>For each length, the index in <see cref="Values"/> of its first code minus that code.</summary>
|
||||
public int[] ValueOffset { get; } = new int[17];
|
||||
|
||||
/// <summary>The code of each symbol (encoding).</summary>
|
||||
public ushort[] Codes { get; } = new ushort[256];
|
||||
|
||||
/// <summary>The length of the code of each symbol, 0 when the table has no code for it (encoding).</summary>
|
||||
public byte[] Sizes { get; } = new byte[256];
|
||||
|
||||
/// <summary>Builds a table from the 16 counts and the symbols of a DHT segment.</summary>
|
||||
/// <exception cref="ImageDecodeException">The counts describe more codes than fit, or do not match the symbols.</exception>
|
||||
public static JpegHuffmanTable Build(ReadOnlySpan<byte> counts, ReadOnlySpan<byte> 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];
|
||||
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;
|
||||
if (code > 1 << length)
|
||||
{
|
||||
throw new ImageDecodeException("Tabella di Huffman JPEG non valida: i codici non stanno nella loro lunghezza.");
|
||||
}
|
||||
|
||||
code <<= 1;
|
||||
}
|
||||
|
||||
return table;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal ref struct JpegBitReader
|
||||
{
|
||||
private readonly ReadOnlySpan<byte> _data;
|
||||
private int _position;
|
||||
private ulong _bits;
|
||||
private int _count;
|
||||
private int _padBits;
|
||||
|
||||
public JpegBitReader(ReadOnlySpan<byte> data, int position)
|
||||
{
|
||||
_data = data;
|
||||
_position = position;
|
||||
}
|
||||
|
||||
/// <summary>Position of the next byte not yet read.</summary>
|
||||
public readonly int Position => _position;
|
||||
|
||||
/// <summary>Whether the reader ran out of data (not at a marker).</summary>
|
||||
public bool ReachedEnd { get; private set; }
|
||||
|
||||
/// <summary>Whether a decoded symbol used bits past the end of the segment.</summary>
|
||||
public readonly bool UsedPadding => _padBits > _count;
|
||||
|
||||
/// <summary>Drops the bits of the current byte and those buffered, for a restart marker or the end of a scan.</summary>
|
||||
public void Reset()
|
||||
{
|
||||
_bits = 0;
|
||||
_count = 0;
|
||||
_padBits = 0;
|
||||
ReachedEnd = false;
|
||||
}
|
||||
|
||||
/// <summary>Moves to <paramref name="position"/>, with no buffered bits.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The next <paramref name="n"/> bits (0-16) as an unsigned number.</summary>
|
||||
[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;
|
||||
}
|
||||
|
||||
/// <summary>RECEIVE and EXTEND of T.81 F.2.2.1: <paramref name="s"/> bits as a signed value of category s.</summary>
|
||||
[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;
|
||||
}
|
||||
|
||||
/// <summary>Decodes one symbol with <paramref name="table"/>.</summary>
|
||||
/// <exception cref="ImageDecodeException">The bits are no code of the table.</exception>
|
||||
[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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user