Files
Febe/src/Febe.Core/Codecs/H264/ParameterSets.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

378 lines
12 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;
/// <summary>A sequence parameter set (§7.3.2.1.1), with the fields Febe uses.</summary>
internal sealed class Sps
{
internal int ProfileIdc;
internal int LevelIdc;
internal int Id;
internal int ChromaFormatIdc = 1;
internal int BitDepthLuma = 8;
internal int BitDepthChroma = 8;
internal bool TransformBypass;
/// <summary>Scaling lists 0–5 (4×4) and 6–11 (8×8) in zig-zag order, after the fall-back rule A.</summary>
internal byte[][] ScalingLists = ScalingMatrix.Flat();
/// <summary>seq_scaling_matrix_present_flag: chooses fall-back rule B (instead of A) for the PPS lists.</summary>
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;
/// <summary>VUI colour description: matrix_coefficients (2 = unspecified) and video_full_range_flag.</summary>
internal int MatrixCoefficients = 2;
internal bool FullRange;
internal int MaxFrameNum => 1 << Log2MaxFrameNum;
internal int HeightInMbs => (2 - (FrameMbsOnly ? 1 : 0)) * HeightInMapUnits;
internal static Sps Parse(RbspReader r)
{
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)
{
r.Skip(1); // separate_colour_plane_flag
}
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();
}
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);
}
if (r.ReadFlag())
{
ParseVuiColour(r, s);
}
return s;
}
/// <summary>The start of the VUI (§E.1.1), up to the colour description; the rest is not needed.</summary>
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);
}
}
}
}
/// <summary>A picture parameter set (§7.3.2.2).</summary>
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;
internal int ChromaQpIndexOffset;
internal int SecondChromaQpIndexOffset;
internal bool DeblockingFilterControlPresent;
internal bool ConstrainedIntraPred;
internal bool RedundantPicCntPresent;
internal bool Transform8x8Mode;
/// <summary>The scaling lists of the picture, null when the PPS has none (those of the SPS apply).</summary>
internal byte[][]? ScalingLists;
internal static Pps Parse(RbspReader r, IReadOnlyDictionary<int, Sps> sequences)
{
var p = new Pps { Id = r.ReadUe(255), SpsId = r.ReadUe(31) };
p.Cabac = r.ReadFlag();
p.BottomFieldPicOrderInFramePresent = r.ReadFlag();
if (r.ReadUe(7) > 0)
{
throw new H264Exception("I gruppi di slice (FMO) non sono gestiti.");
}
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();
r.ReadSe(); // pic_init_qs_minus26
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())
{
var chroma444 = sequences.TryGetValue(p.SpsId, out var sps) && sps.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;
}
}
/// <summary>Scaling lists (§7.3.2.1.1.1, tables 7-2 to 7-4) and the scale factors derived from them (§8.5.9).</summary>
internal static class ScalingMatrix
{
/// <summary>Twelve flat lists (Flat_4x4_16 and Flat_8x8_16).</summary>
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;
}
/// <summary>
/// Parses <paramref name="count"/> lists and applies the fall-back rules: rule A (from the defaults) for the SPS,
/// rule B (from the lists of the SPS, <paramref name="sequenceLists"/>) for the PPS. Lists that are not
/// transmitted at all (8×8 without transform_8x8_mode) keep the SPS ones, or flat.
/// </summary>
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;
}
/// <summary>Reads one list; true when it says «use the default matrix».</summary>
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,
};
/// <summary>Fall-back rule A (<paramref name="sequenceLists"/> null) or B.</summary>
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],
};
/// <summary>
/// LevelScale4x4[m][i] for the six 4×4 lists (raster positions): <c>result[list][m * 16 + pos]</c>.
/// </summary>
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;
}
/// <summary>LevelScale8x8 for the 8×8 lists 6–11 (raster positions): <c>result[list − 6][m * 64 + pos]</c>.</summary>
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;
}
}