Files
Febe/src/Febe.Core/Codecs/H264/H264Decoder.Entropy.cs
T
Alby96andClaude Opus 5.5 697de97ec3 Decodificatore H.264 scritto in casa, provato sui flussi di conformità (#58)
Decodifica Baseline, Main e High a fotogrammi progressivi 4:2:0 a 8 bit (CAVLC e CABAC, slice I/P/B, trasformata 8x8 e matrici di quantizzazione, predizione pesata, diretta spaziale e temporale, gestione dei riferimenti, filtro di deblocco), scritta dallo standard ITU-T H.264 senza codice di terzi. I dodici flussi della suite ITU-T H.264.1 in tests/Febe.Tests/Media/H264/Conformita danno, fotogramma per fotogramma, gli MD5 della ricostruzione ufficiale. Le tabelle di inizializzazione CABAC sono trascritte dal testo della Raccomandazione (03/2005): quelle a memoria per cabac_init_idc 1 e 2 erano sbagliate e le prove le hanno scoperte.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:08:23 +01:00

827 lines
22 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.H264;
public sealed partial class H264Decoder
{
private static readonly byte[] CbfCatOffset = [0, 4, 8, 12, 16];
private static readonly byte[] SigCatOffset = [0, 15, 29, 44, 47];
private static readonly byte[] AbsCatOffset = [0, 10, 20, 30, 39];
private static int B8OfRaster(int blk) => ((blk >> 3) << 1) | ((blk >> 1) & 1);
private int ReadMbSkip()
{
var inc = (availA && !IsSkip(mb - 1) ? 1 : 0) + (availB && !IsSkip(mb - widthInMbs) ? 1 : 0);
return cabac.Decision((sh.IsB ? 24 : 11) + inc);
}
private int ReadMbType()
{
if (!cabacMode)
{
return rd.ReadUe(48);
}
switch (sh.Type)
{
case SliceType.I:
{
var inc = (availA && mbKind[mb - 1] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0)
+ (availB && mbKind[mb - widthInMbs] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0);
if (cabac.Decision(3 + inc) == 0)
{
return 0;
}
return IntraMbTypeSuffix(3, intraSlice: true);
}
case SliceType.P:
if (cabac.Decision(14) == 0)
{
if (cabac.Decision(15) == 0)
{
return 3 * cabac.Decision(16);
}
return 2 - cabac.Decision(17);
}
return 5 + (cabac.Decision(17) == 0 ? 0 : IntraMbTypeSuffix(17, intraSlice: false));
default:
{
var inc = (availA && mbKind[mb - 1] is not (MbKind.BSkip or MbKind.BDirect) ? 1 : 0)
+ (availB && mbKind[mb - widthInMbs] is not (MbKind.BSkip or MbKind.BDirect) ? 1 : 0);
if (cabac.Decision(27 + inc) == 0)
{
return 0;
}
if (cabac.Decision(27 + 3) == 0)
{
return 1 + cabac.Decision(27 + 5);
}
var bits = cabac.Decision(27 + 4) << 3;
bits |= cabac.Decision(27 + 5) << 2;
bits |= cabac.Decision(27 + 5) << 1;
bits |= cabac.Decision(27 + 5);
if (bits < 8)
{
return bits + 3;
}
if (bits == 13)
{
return 23 + (cabac.Decision(32) == 0 ? 0 : IntraMbTypeSuffix(32, intraSlice: false));
}
if (bits == 14)
{
return 11;
}
if (bits == 15)
{
return 22;
}
bits = (bits << 1) | cabac.Decision(27 + 5);
return bits - 4;
}
}
}
/// <summary>
/// The part of an intra mb_type after its first bin (which said «not I_NxN»): I_PCM or one of the I_16x16 types.
/// </summary>
private int IntraMbTypeSuffix(int offset, bool intraSlice)
{
if (cabac.Terminate() != 0)
{
return 25;
}
var state = intraSlice ? offset + 2 : offset;
var type = 1 + (12 * cabac.Decision(state + 1));
if (cabac.Decision(state + 2) != 0)
{
type += 4 + (4 * cabac.Decision(state + 2 + (intraSlice ? 1 : 0)));
}
type += 2 * cabac.Decision(state + 3 + (intraSlice ? 1 : 0));
type += cabac.Decision(state + 3 + (intraSlice ? 2 : 0));
return type;
}
private int ReadSubMbType()
{
if (!cabacMode)
{
return rd.ReadUe(12);
}
if (!sh.IsB)
{
if (cabac.Decision(21) != 0)
{
return 0;
}
if (cabac.Decision(22) == 0)
{
return 1;
}
return cabac.Decision(23) != 0 ? 2 : 3;
}
if (cabac.Decision(36) == 0)
{
return 0;
}
if (cabac.Decision(37) == 0)
{
return 1 + cabac.Decision(39);
}
var type = 3;
if (cabac.Decision(38) != 0)
{
if (cabac.Decision(39) != 0)
{
return 11 + cabac.Decision(39);
}
type += 4;
}
type += 2 * cabac.Decision(39);
type += cabac.Decision(39);
return type;
}
private int ReadRefIdx(int list, int px, int py, int active)
{
if (!cabacMode)
{
return active == 2 ? 1 - rd.ReadBit() : rd.ReadUe(31);
}
var inc = RefIdxCond(list, px - 1, py) + (2 * RefIdxCond(list, px, py - 1));
var value = 0;
var ctx = 54 + inc;
while (cabac.Decision(ctx) != 0)
{
value++;
ctx = value == 1 ? 58 : 59;
if (value > 31)
{
throw new H264Exception("ref_idx non valido.");
}
}
return value;
}
private int RefIdxCond(int list, int xN, int yN)
{
if (Neighbor(xN, yN, out var n, out var blk) == 0)
{
return 0;
}
if (IsSkip(n) || IsIntra(n) || mbKind[n] == MbKind.BDirect)
{
return 0;
}
var b8 = B8OfRaster(blk);
if (subDirect[(n * 4) + b8])
{
return 0;
}
return cur!.RefIdx[(((list * mbCount) + n) * 4) + b8] > 0 ? 1 : 0;
}
private int ReadMvd(int list, int comp, int px, int py)
{
if (!cabacMode)
{
return rd.ReadSe();
}
var sum = MvdAbs(list, comp, px - 1, py) + MvdAbs(list, comp, px, py - 1);
var baseCtx = comp == 0 ? 40 : 47;
var inc = sum < 3 ? 0 : sum <= 32 ? 1 : 2;
if (cabac.Decision(baseCtx + inc) == 0)
{
return 0;
}
var value = 1;
var k = 1;
while (value < 9 && cabac.Decision(baseCtx + (k < 4 ? k + 2 : 6)) != 0)
{
value++;
k++;
}
if (value >= 9)
{
var bits = 3;
while (cabac.Bypass() != 0)
{
value += 1 << bits;
if (++bits > 24)
{
throw new H264Exception("mvd non valido.");
}
}
while (bits-- > 0)
{
value += cabac.Bypass() << bits;
}
}
return cabac.Bypass() != 0 ? -value : value;
}
private int MvdAbs(int list, int comp, int xN, int yN)
{
if (Neighbor(xN, yN, out var n, out var blk) == 0)
{
return 0;
}
return mvdAbs[(((((list * mbCount) + n) * 16) + blk) * 2) + comp];
}
private bool ReadTransform8x8()
{
if (!cabacMode)
{
return rd.ReadFlag();
}
var inc = (availA && mbT8[mb - 1] ? 1 : 0) + (availB && mbT8[mb - widthInMbs] ? 1 : 0);
return cabac.Decision(399 + inc) != 0;
}
private (bool Prev, int Rem) ReadIntraPredMode()
{
if (!cabacMode)
{
return rd.ReadFlag() ? (true, 0) : (false, (int)rd.Read(3));
}
if (cabac.Decision(68) != 0)
{
return (true, 0);
}
var rem = cabac.Decision(69);
rem |= cabac.Decision(69) << 1;
rem |= cabac.Decision(69) << 2;
return (false, rem);
}
private int ReadChromaPredMode()
{
if (!cabacMode)
{
return rd.ReadUe(3);
}
var inc = ChromaModeCond(availA, mb - 1) + ChromaModeCond(availB, mb - widthInMbs);
if (cabac.Decision(64 + inc) == 0)
{
return 0;
}
if (cabac.Decision(67) == 0)
{
return 1;
}
return cabac.Decision(67) == 0 ? 2 : 3;
}
private int ChromaModeCond(bool available, int n) =>
available && IsIntra(n) && mbKind[n] != MbKind.IPcm && chromaModes[n] != 0 ? 1 : 0;
private int ReadCbp(bool intra)
{
if (!cabacMode)
{
var code = rd.ReadUe(47);
return intra ? H264Tables.CbpIntra[code] : H264Tables.CbpInter[code];
}
var cbp = 0;
for (var b8 = 0; b8 < 4; b8++)
{
int bx = b8 & 1, by = b8 >> 1;
int condA, condB;
if (bx == 1)
{
condA = ((cbp >> (b8 - 1)) & 1) == 0 ? 1 : 0;
}
else
{
condA = availA && ((mbCbp[mb - 1] >> (b8 + 1)) & 1) == 0 ? 1 : 0;
}
if (by == 1)
{
condB = ((cbp >> (b8 - 2)) & 1) == 0 ? 1 : 0;
}
else
{
condB = availB && ((mbCbp[mb - widthInMbs] >> (b8 + 2)) & 1) == 0 ? 1 : 0;
}
cbp |= cabac.Decision(73 + condA + (2 * condB)) << b8;
}
var a = availA ? mbCbp[mb - 1] >> 4 : 0;
var b = availB ? mbCbp[mb - widthInMbs] >> 4 : 0;
var inc = (a != 0 ? 1 : 0) + (b != 0 ? 2 : 0);
if (cabac.Decision(77 + inc) != 0)
{
inc = (a == 2 ? 1 : 0) + (b == 2 ? 2 : 0);
cbp |= (1 + cabac.Decision(77 + 4 + inc)) << 4;
}
return cbp;
}
private int ReadQpDelta()
{
if (!cabacMode)
{
return rd.ReadSe();
}
var ctx = 60 + (lastQpDelta != 0 ? 1 : 0);
var k = 0;
while (cabac.Decision(ctx) != 0)
{
k++;
ctx = k == 1 ? 62 : 63;
if (k > 104)
{
throw new H264Exception("mb_qp_delta non valido.");
}
}
return (k & 1) != 0 ? (k + 1) / 2 : -(k / 2);
}
/// <summary>
/// residual_block() of category <paramref name="cat"/> (0 luma DC, 1 luma AC, 2 luma 4×4, 3 chroma DC, 4 chroma AC,
/// 5 luma 8×8): the levels by coefficient index into <paramref name="output"/>; returns the number of non-zero ones.
/// </summary>
private int ReadBlock(int cat, int blk, int comp, int[] output, int maxNum)
{
Array.Clear(output, 0, maxNum);
return cabacMode ? ReadCabacBlock(cat, blk, comp, output, maxNum) : ReadCavlcBlock(cat, blk, comp, output, maxNum);
}
private int ReadCavlcBlock(int cat, int blk, int comp, int[] output, int maxNum)
{
int nC;
if (cat == 3)
{
nC = -1;
}
else if (cat == 4)
{
nC = ChromaNc(blk, comp);
}
else
{
nC = LumaNc(blk);
}
var table = nC switch
{
-1 => CavlcTables.CoeffTokenLookup[4],
< 2 => CavlcTables.CoeffTokenLookup[0],
< 4 => CavlcTables.CoeffTokenLookup[1],
< 8 => CavlcTables.CoeffTokenLookup[2],
_ => CavlcTables.CoeffTokenLookup[3],
};
var entry = table[rd.Peek(16)];
if (entry == 0)
{
throw new H264Exception("coeff_token non valido.");
}
rd.Skip(entry >> 8);
var token = entry & 0xFF;
var total = token >> 2;
var ones = token & 3;
if (total == 0)
{
return 0;
}
if (total > maxNum)
{
throw new H264Exception("Troppi coefficienti.");
}
Span<int> levelVal = stackalloc int[16];
var suffixLength = total > 10 && ones < 3 ? 1 : 0;
for (var i = 0; i < total; i++)
{
if (i < ones)
{
levelVal[i] = rd.ReadBit() != 0 ? -1 : 1;
continue;
}
var prefix = 0;
while (rd.ReadBit() == 0)
{
if (++prefix > 32)
{
throw new H264Exception("level_prefix non valido.");
}
}
var levelCode = Math.Min(15, prefix) << suffixLength;
if (suffixLength > 0 || prefix >= 14)
{
var size = prefix == 14 && suffixLength == 0 ? 4 : prefix >= 15 ? prefix - 3 : suffixLength;
if (size > 0)
{
levelCode += (int)rd.Read(size);
}
}
if (prefix >= 15 && suffixLength == 0)
{
levelCode += 15;
}
if (prefix >= 16)
{
levelCode += (1 << (prefix - 3)) - 4096;
}
if (i == ones && ones < 3)
{
levelCode += 2;
}
levelVal[i] = (levelCode & 1) == 0 ? (levelCode + 2) >> 1 : (-levelCode - 1) >> 1;
if (suffixLength == 0)
{
suffixLength = 1;
}
if (Math.Abs(levelVal[i]) > (3 << (suffixLength - 1)) && suffixLength < 6)
{
suffixLength++;
}
}
var zerosLeft = 0;
if (total < maxNum)
{
var tz = cat == 3 ? CavlcTables.TotalZerosChromaDcLookup[total - 1] : CavlcTables.TotalZerosLookup[total - 1];
var e = tz[rd.Peek(16)];
if (e == 0)
{
throw new H264Exception("total_zeros non valido.");
}
rd.Skip(e >> 8);
zerosLeft = e & 0xFF;
}
if (total + zerosLeft > maxNum)
{
throw new H264Exception("total_zeros fuori dal blocco.");
}
Span<int> run = stackalloc int[16];
for (var i = 0; i < total - 1; i++)
{
if (zerosLeft > 0)
{
var rb = CavlcTables.RunBeforeLookup[Math.Min(zerosLeft, 7) - 1][rd.Peek(16)];
if (rb == 0)
{
throw new H264Exception("run_before non valido.");
}
rd.Skip(rb >> 8);
run[i] = rb & 0xFF;
if (run[i] > zerosLeft)
{
throw new H264Exception("run_before fuori dal blocco.");
}
zerosLeft -= run[i];
}
else
{
run[i] = 0;
}
}
run[total - 1] = zerosLeft;
var coeffNum = -1;
for (var i = total - 1; i >= 0; i--)
{
coeffNum += run[i] + 1;
output[coeffNum] = levelVal[i];
}
return total;
}
/// <summary>nC of a luma 4×4 block (raster index) from the blocks to its left and above (§9.2.1).</summary>
private int LumaNc(int raster)
{
int bx = raster & 3, by = raster >> 2;
bool hasA = true, hasB = true;
int nA = 0, nB = 0;
if (bx > 0)
{
nA = nz[(mb * 24) + raster - 1];
}
else if (availA)
{
nA = nz[((mb - 1) * 24) + raster + 3];
}
else
{
hasA = false;
}
if (by > 0)
{
nB = nz[(mb * 24) + raster - 4];
}
else if (availB)
{
nB = nz[((mb - widthInMbs) * 24) + raster + 12];
}
else
{
hasB = false;
}
return hasA && hasB ? (nA + nB + 1) >> 1 : hasA ? nA : hasB ? nB : 0;
}
private int ChromaNc(int b, int comp)
{
int bx = b & 1, by = b >> 1;
var baseIndex = 16 + (comp * 4);
bool hasA = true, hasB = true;
int nA = 0, nB = 0;
if (bx > 0)
{
nA = nz[(mb * 24) + baseIndex + b - 1];
}
else if (availA)
{
nA = nz[((mb - 1) * 24) + baseIndex + b + 1];
}
else
{
hasA = false;
}
if (by > 0)
{
nB = nz[(mb * 24) + baseIndex + b - 2];
}
else if (availB)
{
nB = nz[((mb - widthInMbs) * 24) + baseIndex + b + 2];
}
else
{
hasB = false;
}
return hasA && hasB ? (nA + nB + 1) >> 1 : hasA ? nA : hasB ? nB : 0;
}
private int ReadCabacBlock(int cat, int blk, int comp, int[] output, int maxNum)
{
if (cat != 5)
{
var inc = CbfCond(cat, blk, comp, left: true) + (2 * CbfCond(cat, blk, comp, left: false)) + CbfCatOffset[cat];
if (cabac.Decision(85 + inc) == 0)
{
return 0;
}
if (cat == 0)
{
cbfDc[mb] |= 1;
}
else if (cat == 3)
{
cbfDc[mb] |= (byte)(2 << comp);
}
}
int sigBase, lastBase, absBase;
if (cat == 5)
{
(sigBase, lastBase, absBase) = (402, 417, 426);
}
else
{
sigBase = 105 + SigCatOffset[cat];
lastBase = 166 + SigCatOffset[cat];
absBase = 227 + AbsCatOffset[cat];
}
Span<bool> significant = stackalloc bool[64];
significant.Clear();
var last = -1;
for (var i = 0; i < maxNum - 1; i++)
{
var ctx = cat == 5 ? H264Tables.SignificantContext8x8[i] : cat == 3 ? Math.Min(i, 2) : i;
if (cabac.Decision(sigBase + ctx) == 0)
{
continue;
}
significant[i] = true;
var lastCtx = cat == 5 ? H264Tables.LastContext8x8[i] : cat == 3 ? Math.Min(i, 2) : i;
if (cabac.Decision(lastBase + lastCtx) != 0)
{
last = i;
break;
}
}
if (last < 0)
{
last = maxNum - 1;
significant[last] = true;
}
int gt1 = 0, eq1 = 0, count = 0;
var maxGt1 = cat == 3 ? 3 : 4;
for (var i = last; i >= 0; i--)
{
if (!significant[i])
{
continue;
}
int abs;
if (cabac.Decision(absBase + (gt1 != 0 ? 0 : Math.Min(4, 1 + eq1))) == 0)
{
abs = 1;
}
else
{
var ctx = absBase + 5 + Math.Min(maxGt1, gt1);
var v = 1;
while (v < 14 && cabac.Decision(ctx) != 0)
{
v++;
}
if (v == 14)
{
var k = 0;
while (cabac.Bypass() != 0)
{
v += 1 << k;
if (++k > 24)
{
throw new H264Exception("coeff_abs_level_minus1 non valido.");
}
}
while (k-- > 0)
{
v += cabac.Bypass() << k;
}
}
abs = v + 1;
}
if (abs == 1)
{
eq1++;
}
else
{
gt1++;
}
output[i] = cabac.Bypass() != 0 ? -abs : abs;
count++;
}
return count;
}
/// <summary>condTermFlagN of coded_block_flag (§9.3.3.1.1.9) for the block to the left or above.</summary>
private int CbfCond(int cat, int blk, int comp, bool left)
{
var currentIntra = IsIntra(mb);
int n;
int index;
switch (cat)
{
case 0:
if (!(left ? availA : availB))
{
return currentIntra ? 1 : 0;
}
n = left ? mb - 1 : mb - widthInMbs;
if (mbKind[n] == MbKind.IPcm)
{
return 1;
}
return mbKind[n] == MbKind.I16x16 ? cbfDc[n] & 1 : 0;
case 3:
if (!(left ? availA : availB))
{
return currentIntra ? 1 : 0;
}
n = left ? mb - 1 : mb - widthInMbs;
if (mbKind[n] == MbKind.IPcm)
{
return 1;
}
return (cbfDc[n] >> (1 + comp)) & 1;
case 4:
{
int bx = blk & 1, by = blk >> 1;
if (left ? bx > 0 : by > 0)
{
n = mb;
index = left ? blk - 1 : blk - 2;
}
else
{
if (!(left ? availA : availB))
{
return currentIntra ? 1 : 0;
}
n = left ? mb - 1 : mb - widthInMbs;
index = left ? blk + 1 : blk + 2;
}
if (mbKind[n] == MbKind.IPcm)
{
return 1;
}
return nz[(n * 24) + 16 + (comp * 4) + index] != 0 ? 1 : 0;
}
default:
{
int bx = blk & 3, by = blk >> 2;
if (left ? bx > 0 : by > 0)
{
n = mb;
index = left ? blk - 1 : blk - 4;
}
else
{
if (!(left ? availA : availB))
{
return currentIntra ? 1 : 0;
}
n = left ? mb - 1 : mb - widthInMbs;
index = left ? blk + 3 : blk + 12;
}
if (mbKind[n] == MbKind.IPcm)
{
return 1;
}
return nz[(n * 24) + index] != 0 ? 1 : 0;
}
}
}
}