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>
277 lines
8.5 KiB
C#
277 lines
8.5 KiB
C#
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];
|
|
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;
|
|
}
|
|
}
|
|
|
|
/// <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;
|
|
}
|
|
}
|
|
}
|