Files
Febe/src/Febe.Core/Codecs/Images/Vp8LHuffman.cs
T
Alby96andClaude Opus 5.5 7e8296e790 Correzioni della revisione dei codec di casa (C1)
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>
2026-11-18 16:52:17 +01:00

302 lines
8.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
namespace Febe.Core.Codecs.Images;
/// <summary>
/// The bit reader of WebP lossless (RFC 9649 §3): bits are read from the least significant bit of each byte, and
/// past the end of the data it reads zeros and remembers it.
/// </summary>
internal sealed class Vp8LBitReader
{
private readonly byte[] _data;
private readonly int _end;
private int _pos;
private ulong _buffer;
private int _count;
public Vp8LBitReader(byte[] data, int start, int length)
{
_data = data;
_pos = start;
_end = start + length;
Fill();
}
/// <summary>Whether bits past the end of the data were consumed.</summary>
public bool EndOfStream { get; private set; }
/// <summary>Reads <paramref name="n"/> bits (0-24), least significant first.</summary>
public int ReadBits(int n)
{
if (_count < n)
{
Fill();
if (_count < n)
{
EndOfStream = true;
_count = n; // the missing bits are zeros
}
}
var value = (int)(_buffer & ((1UL << n) - 1));
_buffer >>= n;
_count -= n;
return value;
}
/// <summary>At least 32 bits ready for <see cref="Peek"/> when the data has them; zeros past the end.</summary>
public ulong Peek()
{
if (_count < 32)
{
Fill();
}
return _buffer;
}
public void Skip(int n)
{
if (_count < n)
{
EndOfStream = true;
_buffer = 0;
_count = 0;
return;
}
_buffer >>= n;
_count -= n;
}
private void Fill()
{
while (_count <= 56 && _pos < _end)
{
_buffer |= (ulong)_data[_pos++] << _count;
_count += 8;
}
}
}
/// <summary>
/// A canonical prefix code of WebP lossless (the codes of DEFLATE: shorter codes first, then by symbol; read from the
/// first bit of the code), decoded with a table of 8 bits and second-level tables for longer codes.
/// </summary>
internal sealed class Vp8LHuffman
{
public const int MaxCodeLength = 15;
private const int RootBits = 8;
// Entry: symbol (or offset of the second-level table) | bits << 16 | second-level bits << 24.
private readonly uint[] _table;
private Vp8LHuffman(uint[] table, int singleSymbol)
{
_table = table;
SingleSymbol = singleSymbol;
}
/// <summary>The symbol of a code that has only one (read with zero bits), or −1.</summary>
public int SingleSymbol { get; }
/// <summary>Entries of the decoding tables, for the memory budget.</summary>
public int TableSize => _table.Length;
/// <summary>
/// Whether <see cref="Build"/> would accept <paramref name="lengths"/>, without building any table: for the codes
/// of groups that no pixel uses.
/// </summary>
public static bool IsValid(ReadOnlySpan<byte> lengths)
{
var space = 1 << MaxCodeLength;
var used = 0;
foreach (var len in lengths)
{
if (len > MaxCodeLength)
{
return false;
}
if (len > 0)
{
used++;
space -= 1 << (MaxCodeLength - len);
}
}
// One symbol is a code of zero bits; more must fill the code space exactly (Kraft).
return used == 1 || (used > 1 && space == 0);
}
/// <summary>
/// The code given by the code lengths of each symbol (0 = not used), or null when the lengths are not a complete
/// prefix code (or use no symbol at all). A single used symbol is a code of zero bits.
/// </summary>
public static Vp8LHuffman? Build(ReadOnlySpan<byte> lengths)
{
Span<int> counts = stackalloc int[MaxCodeLength + 1];
var used = 0;
var last = -1;
for (var s = 0; s < lengths.Length; s++)
{
var len = lengths[s];
if (len > MaxCodeLength)
{
return null;
}
if (len > 0)
{
counts[len]++;
used++;
last = s;
}
}
if (used == 0)
{
return null;
}
if (used == 1)
{
var single = new uint[1 << RootBits];
single.AsSpan().Fill((uint)last);
return new Vp8LHuffman(single, last);
}
// Kraft: the code must be complete, neither over- nor under-subscribed.
var space = 1 << MaxCodeLength;
for (var len = 1; len <= MaxCodeLength; len++)
{
space -= counts[len] << (MaxCodeLength - len);
if (space < 0)
{
return null;
}
}
if (space != 0)
{
return null;
}
Span<int> next = stackalloc int[MaxCodeLength + 2];
var code = 0;
for (var len = 1; len <= MaxCodeLength; len++)
{
code = (code + counts[len - 1]) << 1;
next[len] = code;
}
// Longest code under each root prefix, to size the second-level tables.
Span<byte> longest = stackalloc byte[1 << RootBits];
longest.Clear();
var codes = new int[lengths.Length];
{
Span<int> assign = stackalloc int[MaxCodeLength + 2];
next.CopyTo(assign);
for (var s = 0; s < lengths.Length; s++)
{
var len = lengths[s];
if (len == 0)
{
continue;
}
var reversed = Reverse(assign[len]++, len);
codes[s] = reversed;
if (len > RootBits)
{
var prefix = reversed & ((1 << RootBits) - 1);
longest[prefix] = Math.Max(longest[prefix], len);
}
}
}
Span<int> offsets = stackalloc int[1 << RootBits];
var size = 1 << RootBits;
for (var prefix = 0; prefix < longest.Length; prefix++)
{
if (longest[prefix] > 0)
{
offsets[prefix] = size;
size += 1 << (longest[prefix] - RootBits);
}
}
var table = new uint[size];
for (var prefix = 0; prefix < longest.Length; prefix++)
{
if (longest[prefix] > 0)
{
table[prefix] = (uint)offsets[prefix] | (uint)(longest[prefix] - RootBits) << 24;
}
}
for (var s = 0; s < lengths.Length; s++)
{
var len = lengths[s];
if (len == 0)
{
continue;
}
var reversed = codes[s];
if (len <= RootBits)
{
var entry = (uint)s | (uint)len << 16;
for (var i = reversed; i < (1 << RootBits); i += 1 << len)
{
table[i] = entry;
}
}
else
{
var prefix = reversed & ((1 << RootBits) - 1);
var subBits = longest[prefix] - RootBits;
var entry = (uint)s | (uint)(len - RootBits) << 16;
for (var i = reversed >> RootBits; i < (1 << subBits); i += 1 << (len - RootBits))
{
table[offsets[prefix] + i] = entry;
}
}
}
return new Vp8LHuffman(table, -1);
}
/// <summary>Reads one symbol.</summary>
public int Read(Vp8LBitReader reader)
{
if (SingleSymbol >= 0)
{
return SingleSymbol;
}
var bits = reader.Peek();
var entry = _table[(int)(bits & ((1 << RootBits) - 1))];
var sub = (int)(entry >> 24);
if (sub == 0)
{
reader.Skip((int)(entry >> 16) & 0xFF);
return (int)(entry & 0xFFFF);
}
var second = _table[(int)(entry & 0xFFFF) + (int)((bits >> RootBits) & ((1UL << sub) - 1))];
reader.Skip(RootBits + ((int)(second >> 16) & 0xFF));
return (int)(second & 0xFFFF);
}
internal static int Reverse(int code, int length)
{
var r = 0;
for (var i = 0; i < length; i++)
{
r = (r << 1) | (code & 1);
code >>= 1;
}
return r;
}
}