namespace Febe.Core.Codecs.H264;
/// Slice types (slice_type modulo 5).
internal enum SliceType
{
P = 0,
B = 1,
I = 2,
SP = 3,
SI = 4,
}
/// A slice header (ยง7.3.3), with the reference list modifications, weights and marking it carries.
internal sealed class SliceHeader
{
internal int FirstMb;
internal SliceType Type;
internal int PpsId;
internal int FrameNum;
internal bool FieldPic;
internal int IdrPicId;
internal int PocLsb;
internal int DeltaPocBottom;
internal int DeltaPoc0;
internal int DeltaPoc1;
internal bool DirectSpatialMvPred;
internal int NumRefIdxActiveL0;
internal int NumRefIdxActiveL1;
/// ref_pic_list_modification: (modification_of_pic_nums_idc, value) per list.
internal List<(int Idc, int Value)>[] Modifications = [[], []];
internal int LumaLog2WeightDenom;
internal int ChromaLog2WeightDenom;
/// Explicit weights [list][refIdx * 3 + component] and offsets; null when there is no pred_weight_table.
internal int[][]? Weights;
internal int[][]? Offsets;
internal bool NoOutputOfPriorPics;
internal bool LongTermReference;
internal bool AdaptiveMarking;
/// memory_management_control_operation entries: (operation, value 1, value 2).
internal List<(int Op, int A, int B)> Mmco = [];
internal int CabacInitIdc;
internal int QpDelta;
internal int DisableDeblocking;
internal int AlphaOffset;
internal int BetaOffset;
internal bool IsIntra => Type is SliceType.I or SliceType.SI;
internal bool IsB => Type == SliceType.B;
internal static SliceHeader Parse(RbspReader r, NalUnit nal, IReadOnlyDictionary sequences, IReadOnlyDictionary pictures, out Sps sps, out Pps pps)
{
var h = new SliceHeader { FirstMb = (int)r.ReadUe() };
var type = r.ReadUe(9);
h.Type = (SliceType)(type % 5);
h.PpsId = r.ReadUe(255);
if (!pictures.TryGetValue(h.PpsId, out pps!) || !sequences.TryGetValue(pps.SpsId, out sps!))
{
throw new H264Exception("Slice senza i suoi insiemi di parametri.");
}
if (h.Type is SliceType.SP or SliceType.SI)
{
throw new H264Exception("Le slice SP e SI non sono gestite.");
}
h.FrameNum = (int)r.Read(sps.Log2MaxFrameNum);
if (!sps.FrameMbsOnly)
{
h.FieldPic = r.ReadFlag();
if (h.FieldPic)
{
throw new H264Exception("I video interlacciati non sono gestiti.");
}
}
if (nal.Type == 5)
{
h.IdrPicId = (int)r.ReadUe();
}
if (sps.PocType == 0)
{
h.PocLsb = (int)r.Read(sps.Log2MaxPocLsb);
if (pps.BottomFieldPicOrderInFramePresent && !h.FieldPic)
{
h.DeltaPocBottom = r.ReadSe();
}
}
else if (sps.PocType == 1 && !sps.DeltaPicOrderAlwaysZero)
{
h.DeltaPoc0 = r.ReadSe();
if (pps.BottomFieldPicOrderInFramePresent && !h.FieldPic)
{
h.DeltaPoc1 = r.ReadSe();
}
}
if (pps.RedundantPicCntPresent)
{
r.ReadUe(); // redundant_pic_cnt
}
if (h.IsB)
{
h.DirectSpatialMvPred = r.ReadFlag();
}
h.NumRefIdxActiveL0 = pps.NumRefIdxL0DefaultActive;
h.NumRefIdxActiveL1 = pps.NumRefIdxL1DefaultActive;
if (!h.IsIntra)
{
if (r.ReadFlag())
{
h.NumRefIdxActiveL0 = r.ReadUe(31) + 1;
if (h.IsB)
{
h.NumRefIdxActiveL1 = r.ReadUe(31) + 1;
}
}
ParseModifications(r, h.Modifications[0]);
if (h.IsB)
{
ParseModifications(r, h.Modifications[1]);
}
}
if (!h.IsB)
{
h.NumRefIdxActiveL1 = 0;
}
if (h.IsIntra)
{
h.NumRefIdxActiveL0 = 0;
}
if ((pps.WeightedPred && h.Type == SliceType.P) || (pps.WeightedBipredIdc == 1 && h.IsB))
{
ParseWeights(r, h, sps);
}
if (nal.RefIdc != 0)
{
if (nal.Type == 5)
{
h.NoOutputOfPriorPics = r.ReadFlag();
h.LongTermReference = r.ReadFlag();
}
else if ((h.AdaptiveMarking = r.ReadFlag()))
{
for (var guard = 0; guard < 100; guard++)
{
var op = r.ReadUe(6);
if (op == 0)
{
break;
}
int a = 0, b = 0;
if (op is 1 or 3)
{
a = (int)r.ReadUe(); // difference_of_pic_nums_minus1
}
if (op == 2)
{
a = (int)r.ReadUe(); // long_term_pic_num
}
if (op is 3 or 6)
{
b = (int)r.ReadUe(); // long_term_frame_idx
}
if (op == 4)
{
a = (int)r.ReadUe(); // max_long_term_frame_idx_plus1
}
h.Mmco.Add((op, a, b));
}
}
}
if (pps.Cabac && !h.IsIntra)
{
h.CabacInitIdc = r.ReadUe(2);
}
h.QpDelta = r.ReadSe();
if (pps.DeblockingFilterControlPresent)
{
h.DisableDeblocking = r.ReadUe(2);
if (h.DisableDeblocking != 1)
{
h.AlphaOffset = r.ReadSe() * 2;
h.BetaOffset = r.ReadSe() * 2;
}
}
return h;
}
private static void ParseModifications(RbspReader r, List<(int, int)> list)
{
if (!r.ReadFlag())
{
return;
}
for (var guard = 0; guard < 100; guard++)
{
var idc = r.ReadUe(5);
if (idc == 3)
{
return;
}
if (idc > 2)
{
throw new H264Exception("Modifica della lista di riferimento non gestita.");
}
list.Add((idc, (int)r.ReadUe()));
}
throw new H264Exception("Modifiche della lista di riferimento senza fine.");
}
private static void ParseWeights(RbspReader r, SliceHeader h, Sps sps)
{
h.LumaLog2WeightDenom = r.ReadUe(7);
var chroma = sps.ChromaFormatIdc != 0;
if (chroma)
{
h.ChromaLog2WeightDenom = r.ReadUe(7);
}
h.Weights = new int[2][];
h.Offsets = new int[2][];
for (var list = 0; list < (h.IsB ? 2 : 1); list++)
{
var count = list == 0 ? h.NumRefIdxActiveL0 : h.NumRefIdxActiveL1;
var weights = new int[count * 3];
var offsets = new int[count * 3];
for (var i = 0; i < count; i++)
{
weights[i * 3] = 1 << h.LumaLog2WeightDenom;
weights[(i * 3) + 1] = weights[(i * 3) + 2] = 1 << h.ChromaLog2WeightDenom;
if (r.ReadFlag())
{
weights[i * 3] = r.ReadSe();
offsets[i * 3] = r.ReadSe();
}
if (chroma && r.ReadFlag())
{
for (var c = 1; c <= 2; c++)
{
weights[(i * 3) + c] = r.ReadSe();
offsets[(i * 3) + c] = r.ReadSe();
}
}
}
h.Weights[list] = weights;
h.Offsets[list] = offsets;
}
h.Weights[1] ??= [];
h.Offsets[1] ??= [];
}
}