namespace Febe.Core.Codecs.H264;
/// A sequence parameter set (§7.3.2.1.1), with the fields Febe uses.
internal sealed class Sps
{
/// MaxFS of level 6.2 (table A-1), in macroblocks: 8192×4320 fits.
internal const int MaxFrameMbs = 139_264;
/// MaxDpbMbs of level 6.2 (table A-1): the largest decoded picture buffer of any level, in macroblocks.
internal const int MaxDpbMbs = 696_320;
internal int ProfileIdc;
internal int LevelIdc;
internal int Id;
internal int ChromaFormatIdc = 1;
/// separate_colour_plane_flag: the three colour planes of 4:4:4 are coded as three monochrome pictures.
internal bool SeparateColourPlane;
internal int BitDepthLuma = 8;
internal int BitDepthChroma = 8;
/// qpprime_y_zero_transform_bypass_flag: macroblocks with QP′Y 0 are lossless (§8.5.15).
internal bool TransformBypass;
/// ChromaArrayType (§7.4.2.1.1): chroma_format_idc, or 0 when the colour planes are separate.
internal int ChromaArrayType => SeparateColourPlane ? 0 : ChromaFormatIdc;
/// SubWidthC (Table 6-1): 2 for 4:2:0 and 4:2:2, 1 for 4:4:4.
internal int SubWidthC => ChromaFormatIdc == 3 ? 1 : 2;
/// SubHeightC (Table 6-1): 2 for 4:2:0, 1 for 4:2:2 and 4:4:4.
internal int SubHeightC => ChromaFormatIdc == 1 ? 2 : 1;
/// QpBdOffsetY = 6 × bit_depth_luma_minus8.
internal int QpBdOffsetY => 6 * (BitDepthLuma - 8);
/// QpBdOffsetC = 6 × bit_depth_chroma_minus8.
internal int QpBdOffsetC => 6 * (BitDepthChroma - 8);
/// Scaling lists 0–5 (4×4) and 6–11 (8×8) in zig-zag order, after the fall-back rule A.
internal byte[][] ScalingLists = ScalingMatrix.Flat();
/// seq_scaling_matrix_present_flag: chooses fall-back rule B (instead of A) for the PPS lists.
internal bool ScalingMatrixPresent;
internal int Log2MaxFrameNum;
internal int PocType;
internal int Log2MaxPocLsb;
internal bool DeltaPicOrderAlwaysZero;
internal int OffsetForNonRefPic;
internal int OffsetForTopToBottomField;
internal int[] OffsetForRefFrame = [];
internal int MaxNumRefFrames;
internal bool GapsInFrameNumAllowed;
internal int WidthInMbs;
internal int HeightInMapUnits;
internal bool FrameMbsOnly;
internal bool MbAdaptiveFrameField;
internal bool Direct8x8Inference;
internal int CropLeft, CropRight, CropTop, CropBottom;
/// VUI colour description: matrix_coefficients (2 = unspecified) and video_full_range_flag.
internal int MatrixCoefficients = 2;
internal bool FullRange;
internal int MaxFrameNum => 1 << Log2MaxFrameNum;
/// CropUnitX of §7.4.2.1.1: 1 without chroma (or in 4:4:4), else SubWidthC.
internal int CropUnitX => ChromaArrayType == 0 ? 1 : SubWidthC;
/// CropUnitY of §7.4.2.1.1, doubled when the frames may be coded as fields.
internal int CropUnitY => (ChromaArrayType == 0 ? 1 : SubHeightC) * (FrameMbsOnly ? 1 : 2);
internal int HeightInMbs => (2 - (FrameMbsOnly ? 1 : 0)) * HeightInMapUnits;
/// The multiview extension of a subset SPS (profiles 118, 128 and 134), null otherwise.
internal MvcExtension? Mvc;
/// The scalable extension of a subset SPS (profiles 83 and 86), null otherwise.
internal SvcExtension? Svc;
///
/// A subset sequence parameter set (NAL unit 15, §7.3.2.1.3): seq_parameter_set_data() with its whole VUI, then the
/// extension of its profile — scalable (§G.7.3.2.1.4) or multiview (§H.7.3.2.1.4); what follows the parts the decoder
/// uses is not read.
///
internal static Sps ParseSubset(RbspReader r)
{
var s = Parse(r, wholeVui: true);
if (s.ProfileIdc is 83 or 86)
{
s.Svc = SvcExtension.Parse(r, s.ChromaArrayType);
}
else if (s.ProfileIdc is 118 or 128 or 134)
{
r.Skip(1); // bit_equal_to_one
s.Mvc = MvcExtension.Parse(r);
}
return s;
}
internal static Sps Parse(RbspReader r) => Parse(r, wholeVui: false);
private static Sps Parse(RbspReader r, bool wholeVui)
{
var s = new Sps { ProfileIdc = (int)r.Read(8) };
r.Skip(8); // constraint flags and reserved bits
s.LevelIdc = (int)r.Read(8);
s.Id = r.ReadUe(31);
if (s.ProfileIdc is 100 or 110 or 122 or 244 or 44 or 83 or 86 or 118 or 128 or 138 or 139 or 134 or 135)
{
s.ChromaFormatIdc = r.ReadUe(3);
if (s.ChromaFormatIdc == 3)
{
s.SeparateColourPlane = r.ReadFlag();
}
s.BitDepthLuma = r.ReadUe(6) + 8;
s.BitDepthChroma = r.ReadUe(6) + 8;
s.TransformBypass = r.ReadFlag();
if (r.ReadFlag())
{
s.ScalingMatrixPresent = true;
s.ScalingLists = ScalingMatrix.ParseLists(r, s.ChromaFormatIdc == 3 ? 12 : 8, null);
}
}
s.Log2MaxFrameNum = r.ReadUe(12) + 4;
s.PocType = r.ReadUe(2);
if (s.PocType == 0)
{
s.Log2MaxPocLsb = r.ReadUe(12) + 4;
}
else if (s.PocType == 1)
{
s.DeltaPicOrderAlwaysZero = r.ReadFlag();
s.OffsetForNonRefPic = r.ReadSe();
s.OffsetForTopToBottomField = r.ReadSe();
var cycle = r.ReadUe(255);
s.OffsetForRefFrame = new int[cycle];
for (var i = 0; i < cycle; i++)
{
s.OffsetForRefFrame[i] = r.ReadSe();
}
}
s.MaxNumRefFrames = r.ReadUe(16);
s.GapsInFrameNumAllowed = r.ReadFlag();
s.WidthInMbs = r.ReadUe(1023) + 1;
s.HeightInMapUnits = r.ReadUe(1023) + 1;
s.FrameMbsOnly = r.ReadFlag();
if (!s.FrameMbsOnly)
{
s.MbAdaptiveFrameField = r.ReadFlag();
}
// The largest frame of any level (MaxFS of level 6.2, table A-1): a damaged SPS never makes the decoder
// allocate pictures larger than a real stream can have.
if ((long)s.WidthInMbs * s.HeightInMbs > MaxFrameMbs)
{
throw new H264Exception("Immagine più grande di ogni livello H.264.");
}
// The reference frames must fit in the largest buffer of any level (MaxDpbMbs of level 6.2, table A-1; A.3.1
// and A.3.2 bound max_num_ref_frames by it): sixteen frames of the largest size would be 1.4 GB.
if ((long)s.MaxNumRefFrames * s.WidthInMbs * s.HeightInMbs > MaxDpbMbs)
{
throw new H264Exception("Troppe immagini di riferimento per ogni livello H.264.");
}
s.Direct8x8Inference = r.ReadFlag();
if (r.ReadFlag())
{
s.CropLeft = r.ReadUe(8192);
s.CropRight = r.ReadUe(8192);
s.CropTop = r.ReadUe(8192);
s.CropBottom = r.ReadUe(8192);
// §7.4.2.1.1: the cropped frame keeps at least one sample.
if (s.CropUnitX * (s.CropLeft + s.CropRight) >= s.WidthInMbs * 16 || s.CropUnitY * (s.CropTop + s.CropBottom) >= s.HeightInMbs * 16)
{
throw new H264Exception("Ritaglio dell'immagine non valido.");
}
}
if (r.ReadFlag())
{
ParseVuiColour(r, s);
if (wholeVui)
{
SkipVuiRest(r);
}
}
return s;
}
/// The VUI after the colour description (§E.1.1), read only to reach what follows it in a subset SPS.
private static void SkipVuiRest(RbspReader r)
{
if (r.ReadFlag())
{
_ = r.ReadUe(); // chroma_sample_loc_type_top_field
_ = r.ReadUe(); // chroma_sample_loc_type_bottom_field
}
if (r.ReadFlag())
{
r.Skip(65); // num_units_in_tick, time_scale, fixed_frame_rate_flag
}
var nalHrd = r.ReadFlag();
if (nalHrd)
{
SkipHrd(r);
}
var vclHrd = r.ReadFlag();
if (vclHrd)
{
SkipHrd(r);
}
if (nalHrd || vclHrd)
{
r.Skip(1); // low_delay_hrd_flag
}
r.Skip(1); // pic_struct_present_flag
if (r.ReadFlag())
{
r.Skip(1); // motion_vectors_over_pic_boundaries_flag
for (var i = 0; i < 6; i++)
{
_ = r.ReadUe();
}
}
}
/// hrd_parameters() (§E.1.2), skipped.
private static void SkipHrd(RbspReader r)
{
var count = r.ReadUe(31) + 1;
r.Skip(8); // bit_rate_scale, cpb_size_scale
for (var i = 0; i < count; i++)
{
_ = r.ReadUe();
_ = r.ReadUe();
r.Skip(1);
}
r.Skip(20);
}
/// The start of the VUI (§E.1.1), up to the colour description; the rest is not needed.
private static void ParseVuiColour(RbspReader r, Sps s)
{
if (r.ReadFlag())
{
var aspect = r.Read(8);
if (aspect == 255)
{
r.Skip(32); // sar_width, sar_height
}
}
if (r.ReadFlag())
{
r.Skip(1); // overscan_appropriate_flag
}
if (r.ReadFlag())
{
r.Skip(3); // video_format
s.FullRange = r.ReadFlag();
if (r.ReadFlag())
{
r.Skip(16); // colour_primaries, transfer_characteristics
s.MatrixCoefficients = (int)r.Read(8);
}
}
}
}
///
/// seq_parameter_set_mvc_extension() (§H.7.3.2.1.4) up to the dependencies between views: the views in view order, and
/// for each the views its anchor and non-anchor view components may refer to, per list.
///
internal sealed class MvcExtension
{
/// view_id of each view, by view order index (VOIdx).
internal int[] ViewIds = [];
/// anchor_ref_lX[VOIdx][j] by list X: the view_id of each inter-view reference of an anchor view component.
internal int[][][] AnchorRefs = [[], []];
/// non_anchor_ref_lX[VOIdx][j] by list X.
internal int[][][] NonAnchorRefs = [[], []];
/// The view order index of a view, −1 when the sequence does not have it.
internal int OrderOf(int viewId) => Array.IndexOf(ViewIds, viewId);
internal static MvcExtension Parse(RbspReader r)
{
var views = r.ReadUe(1023) + 1;
var m = new MvcExtension { ViewIds = new int[views] };
for (var i = 0; i < views; i++)
{
m.ViewIds[i] = r.ReadUe(1023);
}
for (var list = 0; list < 2; list++)
{
m.AnchorRefs[list] = new int[views][];
m.NonAnchorRefs[list] = new int[views][];
m.AnchorRefs[list][0] = [];
m.NonAnchorRefs[list][0] = [];
}
for (var pass = 0; pass < 2; pass++)
{
var refs = pass == 0 ? m.AnchorRefs : m.NonAnchorRefs;
for (var i = 1; i < views; i++)
{
for (var list = 0; list < 2; list++)
{
var count = r.ReadUe(15);
var ids = new int[count];
for (var j = 0; j < count; j++)
{
ids[j] = r.ReadUe(1023);
}
refs[list][i] = ids;
}
}
}
return m;
}
}
/// seq_parameter_set_svc_extension() (§G.7.3.2.1.4).
internal sealed class SvcExtension
{
internal bool InterLayerDeblockingFilterControlPresent;
internal int ExtendedSpatialScalabilityIdc;
internal bool ChromaPhaseXPlus1;
internal int ChromaPhaseYPlus1 = 1;
internal bool SeqRefLayerChromaPhaseXPlus1;
internal int SeqRefLayerChromaPhaseYPlus1 = 1;
internal int SeqScaledRefLayerLeft;
internal int SeqScaledRefLayerTop;
internal int SeqScaledRefLayerRight;
internal int SeqScaledRefLayerBottom;
internal bool SeqTcoeffLevelPrediction;
internal bool AdaptiveTcoeffLevelPrediction;
internal bool SliceHeaderRestriction;
internal static SvcExtension Parse(RbspReader r, int chromaArrayType)
{
var e = new SvcExtension
{
InterLayerDeblockingFilterControlPresent = r.ReadFlag(),
ExtendedSpatialScalabilityIdc = (int)r.Read(2),
};
if (chromaArrayType is 1 or 2)
{
e.ChromaPhaseXPlus1 = r.ReadFlag();
}
if (chromaArrayType == 1)
{
e.ChromaPhaseYPlus1 = (int)r.Read(2);
}
if (e.ExtendedSpatialScalabilityIdc == 1)
{
if (chromaArrayType > 0)
{
e.SeqRefLayerChromaPhaseXPlus1 = r.ReadFlag();
e.SeqRefLayerChromaPhaseYPlus1 = (int)r.Read(2);
}
e.SeqScaledRefLayerLeft = r.ReadSe();
e.SeqScaledRefLayerTop = r.ReadSe();
e.SeqScaledRefLayerRight = r.ReadSe();
e.SeqScaledRefLayerBottom = r.ReadSe();
}
e.SeqTcoeffLevelPrediction = r.ReadFlag();
if (e.SeqTcoeffLevelPrediction)
{
e.AdaptiveTcoeffLevelPrediction = r.ReadFlag();
}
e.SliceHeaderRestriction = r.ReadFlag();
return e;
}
}
/// A picture parameter set (§7.3.2.2).
internal sealed class Pps
{
internal int Id;
internal int SpsId;
internal bool Cabac;
internal bool BottomFieldPicOrderInFramePresent;
internal int NumRefIdxL0DefaultActive;
internal int NumRefIdxL1DefaultActive;
internal bool WeightedPred;
internal int WeightedBipredIdc;
internal int PicInitQp;
/// 26 + pic_init_qs_minus26: the starting QS of SP and SI slices.
internal int PicInitQs;
/// num_slice_groups_minus1 + 1: more than one is FMO (§8.2.2).
internal int NumSliceGroups = 1;
internal int SliceGroupMapType;
/// run_length_minus1 + 1 of each slice group (map type 0).
internal int[] RunLength = [];
/// top_left and bottom_right of the rectangles of the slice groups but the last (map type 2).
internal int[] TopLeft = [];
internal int[] BottomRight = [];
internal bool SliceGroupChangeDirection;
/// slice_group_change_rate_minus1 + 1 (map types 3–5).
internal int SliceGroupChangeRate;
/// slice_group_id of each map unit (map type 6).
internal byte[] SliceGroupIds = [];
internal int ChromaQpIndexOffset;
internal int SecondChromaQpIndexOffset;
internal bool DeblockingFilterControlPresent;
internal bool ConstrainedIntraPred;
internal bool RedundantPicCntPresent;
internal bool Transform8x8Mode;
/// The scaling lists of the picture, null when the PPS has none (those of the SPS apply).
internal byte[][]? ScalingLists;
/// The RBSP after the NAL unit header.
/// The SPSs read so far.
/// The subset SPSs read so far: a PPS of the enhancement layers or views may refer to one.
internal static Pps Parse(RbspReader r, IReadOnlyDictionary sequences, IReadOnlyDictionary? subsetSequences = null)
{
var p = new Pps { Id = r.ReadUe(255), SpsId = r.ReadUe(31) };
p.Cabac = r.ReadFlag();
p.BottomFieldPicOrderInFramePresent = r.ReadFlag();
p.NumSliceGroups = r.ReadUe(7) + 1;
if (p.NumSliceGroups > 1)
{
ParseSliceGroups(r, p);
}
p.NumRefIdxL0DefaultActive = r.ReadUe(31) + 1;
p.NumRefIdxL1DefaultActive = r.ReadUe(31) + 1;
p.WeightedPred = r.ReadFlag();
p.WeightedBipredIdc = (int)r.Read(2);
p.PicInitQp = 26 + r.ReadSe();
p.PicInitQs = 26 + r.ReadSe();
if (p.PicInitQs is < 0 or > 51)
{
throw new H264Exception("QS iniziale del PPS non valido.");
}
p.ChromaQpIndexOffset = r.ReadSe();
p.DeblockingFilterControlPresent = r.ReadFlag();
p.ConstrainedIntraPred = r.ReadFlag();
p.RedundantPicCntPresent = r.ReadFlag();
p.SecondChromaQpIndexOffset = p.ChromaQpIndexOffset;
if (r.MoreRbspData)
{
p.Transform8x8Mode = r.ReadFlag();
if (r.ReadFlag())
{
if (!sequences.TryGetValue(p.SpsId, out var sps))
{
subsetSequences?.TryGetValue(p.SpsId, out sps);
}
var chroma444 = sps is { ChromaFormatIdc: 3 };
var count = 6 + ((chroma444 ? 6 : 2) * (p.Transform8x8Mode ? 1 : 0));
p.ScalingLists = ScalingMatrix.ParseLists(r, count, sps is { ScalingMatrixPresent: true } ? sps.ScalingLists : null);
}
p.SecondChromaQpIndexOffset = r.ReadSe();
}
return p;
}
/// The slice group map of §7.3.2.2 (num_slice_groups_minus1 above 0), checked against the picture later.
private static void ParseSliceGroups(RbspReader r, Pps p)
{
p.SliceGroupMapType = r.ReadUe(6);
var groups = p.NumSliceGroups;
switch (p.SliceGroupMapType)
{
case 0:
p.RunLength = new int[groups];
for (var i = 0; i < groups; i++)
{
p.RunLength[i] = r.ReadUe(Sps.MaxFrameMbs - 1) + 1;
}
break;
case 2:
p.TopLeft = new int[groups - 1];
p.BottomRight = new int[groups - 1];
for (var i = 0; i < groups - 1; i++)
{
p.TopLeft[i] = r.ReadUe(Sps.MaxFrameMbs - 1);
p.BottomRight[i] = r.ReadUe(Sps.MaxFrameMbs - 1);
}
break;
case 3:
case 4:
case 5:
p.SliceGroupChangeDirection = r.ReadFlag();
p.SliceGroupChangeRate = r.ReadUe(Sps.MaxFrameMbs - 1) + 1;
break;
case 6:
{
var size = r.ReadUe(Sps.MaxFrameMbs - 1) + 1;
var bits = 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)(groups - 1));
p.SliceGroupIds = new byte[size];
for (var i = 0; i < size; i++)
{
var id = (int)r.Read(bits);
if (id >= groups || r.BitsLeft < 0)
{
throw new H264Exception("slice_group_id non valido.");
}
p.SliceGroupIds[i] = (byte)id;
}
break;
}
}
}
}
/// Scaling lists (§7.3.2.1.1.1, tables 7-2 to 7-4) and the scale factors derived from them (§8.5.9).
internal static class ScalingMatrix
{
/// Twelve flat lists (Flat_4x4_16 and Flat_8x8_16).
internal static byte[][] Flat()
{
var lists = new byte[12][];
for (var i = 0; i < 12; i++)
{
lists[i] = new byte[i < 6 ? 16 : 64];
Array.Fill(lists[i], (byte)16);
}
return lists;
}
///
/// Parses lists and applies the fall-back rules: rule A (from the defaults) for the SPS,
/// rule B (from the lists of the SPS, ) for the PPS. Lists that are not
/// transmitted at all (8×8 without transform_8x8_mode) keep the SPS ones, or flat.
///
internal static byte[][] ParseLists(RbspReader r, int count, byte[][]? sequenceLists)
{
var lists = new byte[12][];
for (var i = 0; i < 12; i++)
{
var size = i < 6 ? 16 : 64;
var present = i < count && r.ReadFlag();
if (present)
{
var list = new byte[size];
if (ParseList(r, list))
{
lists[i] = Default(i);
}
else
{
lists[i] = list;
}
}
else if (i < count)
{
lists[i] = FallBack(i, lists, sequenceLists);
}
else
{
lists[i] = sequenceLists?[i] ?? FallBack(i, lists, null);
}
}
return lists;
}
/// Reads one list; true when it says «use the default matrix».
private static bool ParseList(RbspReader r, byte[] list)
{
var last = 8;
var next = 8;
for (var j = 0; j < list.Length; j++)
{
if (next != 0)
{
var delta = r.ReadSe();
if (delta is < -128 or > 127)
{
throw new H264Exception("Matrice di quantizzazione non valida.");
}
next = (last + delta + 256) % 256;
if (j == 0 && next == 0)
{
return true;
}
}
list[j] = (byte)(next == 0 ? last : next);
last = list[j];
}
return false;
}
private static byte[] Default(int i) => i switch
{
< 3 => H264Tables.Default4x4Intra,
< 6 => H264Tables.Default4x4Inter,
_ => (i & 1) == 0 ? H264Tables.Default8x8Intra : H264Tables.Default8x8Inter,
};
/// Fall-back rule A ( null) or B.
private static byte[] FallBack(int i, byte[][] lists, byte[][]? sequenceLists) => i switch
{
0 or 3 => sequenceLists?[i] ?? Default(i),
1 or 2 or 4 or 5 => lists[i - 1],
6 or 7 => sequenceLists?[i] ?? Default(i),
_ => lists[i - 2],
};
///
/// LevelScale4x4[m][i] for the six 4×4 lists (raster positions): result[list][m * 16 + pos].
///
internal static int[][] LevelScale4x4(byte[][] lists)
{
var result = new int[6][];
for (var l = 0; l < 6; l++)
{
var scale = new int[6 * 16];
for (var k = 0; k < 16; k++)
{
var pos = H264Tables.ZigZag4x4[k];
int row = pos >> 2, col = pos & 3;
var cls = (row & 1) == 0 && (col & 1) == 0 ? 0 : (row & 1) == 1 && (col & 1) == 1 ? 1 : 2;
for (var m = 0; m < 6; m++)
{
scale[(m * 16) + pos] = lists[l][k] * H264Tables.NormAdjust4x4[m, cls];
}
}
result[l] = scale;
}
return result;
}
/// LevelScale8x8 for the 8×8 lists 6–11 (raster positions): result[list − 6][m * 64 + pos].
internal static int[][] LevelScale8x8(byte[][] lists)
{
var result = new int[6][];
for (var l = 0; l < 6; l++)
{
var scale = new int[6 * 64];
for (var k = 0; k < 64; k++)
{
var pos = H264Tables.ZigZag8x8[k];
int i = pos >> 3, j = pos & 7;
int cls;
if ((i & 3) == 0 && (j & 3) == 0)
{
cls = 0;
}
else if ((i & 1) == 1 && (j & 1) == 1)
{
cls = 1;
}
else if ((i & 3) == 2 && (j & 3) == 2)
{
cls = 2;
}
else if (((i & 3) == 0 && (j & 1) == 1) || ((i & 1) == 1 && (j & 3) == 0))
{
cls = 3;
}
else if (((i & 3) == 0 && (j & 3) == 2) || ((i & 3) == 2 && (j & 3) == 0))
{
cls = 4;
}
else
{
cls = 5;
}
for (var m = 0; m < 6; m++)
{
scale[(m * 64) + pos] = lists[6 + l][k] * H264Tables.NormAdjust8x8[m, cls];
}
}
result[l] = scale;
}
return result;
}
}