Files
Febe/src/Febe.Core/Codecs/H264/CabacEngine.cs
T
Alby96andClaude Opus 5.5 b23632fc96 Fotogrammi e contenitori più robusti dopo la revisione: punto di partenza vero, limiti di tempo e di riferimenti, file rovinati tollerati (#58)
Corregge i difetti confermati dalla revisione del decodificatore H.264 e dei lettori
di contenitori.

- Fotogrammi: un AVI senza idx1 (o OpenDML oltre il primo GB) segna ogni campione
  come chiave; ora si parte dall'immagine IDR più vicina (entro 300 campioni),
  altrimenti da un'immagine di slice I o dal primo campione. Oltre 300 campioni vale
  il fotogramma del punto di partenza; ogni chiamata ha al più 30 secondi, come
  l'estrattore con ffmpeg che sostituisce.
- H.264: una slice P/B senza riferimenti è un errore invece di una predizione da sé
  stessa; SPS con riferimenti oltre MaxDpbMbs del livello 6.2 rifiutato (1,4 GB da
  pochi byte); FrameNumOffset dei fotogrammi mancanti di un salto di frame_num;
  immagini ridondanti saltate e inizio d'immagine secondo §7.4.1.2.4; immagini non di
  riferimento non chieste non ricostruite; CABAC con finestra di 64 bit; unità NAL in
  un solo buffer. Il sommario non dice più verificato ciò che nessun MD5 verifica.
- Matroska: un blocco rovinato o troncato ferma la lettura e i blocchi letti restano;
  scala dei tempi esatta per ogni TimecodeScale.
- MP4: una traccia con tkhd/elst/mdhd/hdlr/esds rovinati si scarta senza perdere le
  altre; esds con limiti controllati; nei soli metadati niente copie delle tabelle né
  campioni dei frammenti.
- AVI: durata impossibile ignota senza perdere la data.
- Sonda dei metadati davvero asincrona, annullabile fra i frammenti.
- Prove nuove: flussi H.264 sintetici scritti bit per bit (salto di frame_num, immagine
  ridondante, P senza riferimenti, immagini saltate, SPS enormi con PPS e slice),
  AVI senza indice, blocchi Matroska rovinati, audio MP4 rovinato, durata AVI,
  TimecodeScale di 3 ms, trun sotto il limite ma oltre il file, limite di run e di
  tempo, i due MP4 x264 del sito di prova, ffmpeg/ffprobe fuori dal Dockerfile.
  Provate contro il codice senza le correzioni: falliscono tutte.
- decisioni.md: quattro righe del 18 novembre.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:13:45 +01:00

170 lines
4.7 KiB
C#

using System.Buffers.Binary;
using System.Numerics;
namespace Febe.Core.Codecs.H264;
/// <summary>
/// The arithmetic decoding engine of CABAC (§9.3.1.2 and §9.3.3.2), with the context variables of the slice. The slice
/// data is read through a 64-bit window refilled four bytes at a time, and renormalisation shifts all its bits at once
/// (the count of leading zeros of the range): the arithmetic is the one of the standard, bit for bit.
/// </summary>
internal sealed class CabacEngine
{
private readonly byte[] state = new byte[CabacTables.ContextCount];
private readonly byte[] mps = new byte[CabacTables.ContextCount];
private RbspReader reader = null!;
private byte[] data = [];
private int range;
private int offset;
/// <summary>The next bits of the slice data, from the most significant bit.</summary>
private ulong window;
/// <summary>Valid bits at the top of <see cref="window"/>.</summary>
private int bits;
/// <summary>The next byte of <see cref="data"/> to load into the window.</summary>
private int next;
/// <summary>Initialises the context variables (§9.3.1.1).</summary>
internal void InitContexts(SliceHeader header, int sliceQp)
{
var table = header.IsIntra ? CabacTables.InitI : CabacTables.InitPB[header.CabacInitIdc];
var qp = Math.Clamp(sliceQp, 0, 51);
for (var i = 0; i < CabacTables.ContextCount; i++)
{
int m = table[i * 2], n = table[(i * 2) + 1];
var pre = Math.Clamp(((m * qp) >> 4) + n, 1, 126);
if (pre <= 63)
{
state[i] = (byte)(63 - pre);
mps[i] = 0;
}
else
{
state[i] = (byte)(pre - 64);
mps[i] = 1;
}
}
}
/// <summary>Initialises the decoding engine at the current, byte-aligned position (§9.3.1.2).</summary>
internal void Start(RbspReader source)
{
reader = source;
data = source.Data;
var position = source.Position;
next = position >> 3;
window = 0;
bits = 0;
Refill();
var skip = position & 7;
window <<= skip;
bits -= skip;
range = 510;
offset = Take(9);
if (offset >= range)
{
throw new H264Exception("Dati CABAC non validi.");
}
}
internal int Decision(int ctx)
{
var s = state[ctx];
var lps = CabacTables.RangeLps[(s << 2) + ((range >> 6) & 3)];
range -= lps;
int bin;
if (offset >= range)
{
bin = mps[ctx] ^ 1;
offset -= range;
range = lps;
if (s == 0)
{
mps[ctx] ^= 1;
}
state[ctx] = CabacTables.NextStateLps[s];
}
else
{
bin = mps[ctx];
if (s < 62)
{
state[ctx] = (byte)(s + 1);
}
}
if (range < 256)
{
// RenormD (§9.3.3.2.2): as many single-bit steps as the range has leading zeros below bit 8.
var shift = BitOperations.LeadingZeroCount((uint)range) - 23;
range <<= shift;
offset = (offset << shift) | Take(shift);
}
return bin;
}
internal int Bypass()
{
offset = (offset << 1) | Take(1);
if (offset >= range)
{
offset -= range;
return 1;
}
return 0;
}
internal int Terminate()
{
range -= 2;
if (offset >= range)
{
// The end of the slice or an I_PCM macroblock: the reader goes on exactly after the bits read here.
reader.Position = (next * 8) - bits;
return 1;
}
if (range < 256)
{
range <<= 1;
offset = (offset << 1) | Take(1);
}
return 0;
}
/// <summary>The next <paramref name="count"/> bits (1 to 32) of the slice data.</summary>
private int Take(int count)
{
if (bits < count)
{
Refill();
}
var value = (int)(window >> (64 - count));
window <<= count;
bits -= count;
return value;
}
/// <summary>
/// Loads four bytes below the valid bits. Past the payload the buffer holds zero padding (see
/// <see cref="RbspReader"/>); a damaged slice that reads beyond the padding fails as the bit reader would.
/// </summary>
private void Refill()
{
while (bits <= 32)
{
window |= (ulong)BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(next, 4)) << (32 - bits);
next += 4;
bits += 32;
}
}
}