using System.Buffers.Binary;
using System.Numerics;
namespace Febe.Core.Codecs.H264;
///
/// 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.
///
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;
/// The next bits of the slice data, from the most significant bit.
private ulong window;
/// Valid bits at the top of .
private int bits;
/// The next byte of to load into the window.
private int next;
/// Initialises the context variables (§9.3.1.1).
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;
}
}
}
/// Initialises the decoding engine at the current, byte-aligned position (§9.3.1.2).
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;
}
/// The next bits (1 to 32) of the slice data.
private int Take(int count)
{
if (bits < count)
{
Refill();
}
var value = (int)(window >> (64 - count));
window <<= count;
bits -= count;
return value;
}
///
/// Loads four bytes below the valid bits. Past the payload the buffer holds zero padding (see
/// ); a damaged slice that reads beyond the padding fails as the bit reader would.
///
private void Refill()
{
while (bits <= 32)
{
window |= (ulong)BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(next, 4)) << (32 - bits);
next += 4;
bits += 32;
}
}
}