Decodificatore H.264 per gli strumenti di Baseline ed Extended: FMO, ASO, slice ridondanti, partizionamento dei dati, slice SP e SI (#58)

Il decodificatore rifiutava i flussi con gruppi di slice e con slice SP o SI, e
non leggeva le partizioni A, B e C: ora li gestisce tutti, perché sono parte di
Baseline ed Extended e un file della libreria può usarli.

- Gruppi di slice dal PPS, tipi da 0 a 6, con il cambio per immagine di
  slice_group_change_cycle; il macroblocco successivo segue il gruppo (§8.2.2).
- Slice in ordine qualunque: la disponibilità dei vicini era già per slice, il
  deblocking a fine immagine.
- Slice SP e SI con QS (§8.6): predizione trasformata e riquantizzata in QS, anche
  per P_Skip; sp_for_switch_flag e macroblocchi SI; nel deblocking contano come
  intra.
- Partizionamento: A con intestazione e dati di categoria 2, B con il residuo
  intra (e gli I_PCM), C con quello inter; la regola del nN a zero con la
  predizione intra vincolata (§9.2.1). Una partizione che manca lascia a zero il
  suo residuo e, da lì in poi, quello della partizione che ne dipende.

I cinque flussi FMO, ASO e SP della serie ITU-T (FM2_SVA_C, FM1_FT_E, FM1_BT_B,
sp1_bt_a, sp2_bt_b) passano fra i verificati e coincidono fotogramma per
fotogramma. Partizionamento, slice ridondanti e ASO si provano riscrivendo flussi
verificati senza toccare i bit dei macroblocchi (StreamRewriter) e chiedendo di
nuovo il riferimento ufficiale; le SI con un flusso sintetico calcolato a mano.
Anche i flussi nuovi e quelli partizionati sono provati rovinati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 16:42:11 +01:00
1 parent 9c626f67ec
commit 8d03ca23de
19 files changed
+1738 -169

No files matched your search

@@ -341,7 +341,7 @@ public sealed partial class H264Decoder
private int BoundaryStrength(Picture picture, int pm, int pb, int qm, int qb, bool mbEdge, bool vertical)
{
bool fieldP = picture.MbField[pm], fieldQ = picture.MbField[qm];
if (picture.MbIntra[pm] || picture.MbIntra[qm])
if (picture.MbIntra[pm] || picture.MbIntra[qm] || (anySwitching && (sliceSwitching[mbSlice[pm]] || sliceSwitching[mbSlice[qm]])))
{
return mbEdge && (vertical || (!fieldP && !fieldQ)) ? 4 : 3;
}
@@ -24,18 +24,16 @@ public sealed partial class H264Decoder
switch (sh.Type)
{
case SliceType.I:
return ReadIntraSliceMbType();
case SliceType.SI:
{
var inc = (mbA >= 0 && mbKind[mbA] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0)
+ (mbB >= 0 && mbKind[mbB] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0);
if (cabac.Decision(3 + inc) == 0)
{
return 0;
}
return IntraMbTypeSuffix(3, intraSlice: true);
// The prefix says SI or not (ctxIdx 0–2), then an I slice mb_type follows (§9.3.2.5).
var inc = (mbA >= 0 && mbKind[mbA] != MbKind.SI ? 1 : 0) + (mbB >= 0 && mbKind[mbB] != MbKind.SI ? 1 : 0);
return cabac.Decision(inc) == 0 ? 0 : 1 + ReadIntraSliceMbType();
}
case SliceType.P:
case SliceType.SP:
if (cabac.Decision(14) == 0)
{
if (cabac.Decision(15) == 0)
@@ -91,6 +89,19 @@ public sealed partial class H264Decoder
}
}
/// <summary>mb_type of an I slice (ctxIdxOffset 3).</summary>
private int ReadIntraSliceMbType()
{
var inc = (mbA >= 0 && mbKind[mbA] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0)
+ (mbB >= 0 && mbKind[mbB] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0);
if (cabac.Decision(3 + inc) == 0)
{
return 0;
}
return IntraMbTypeSuffix(3, intraSlice: true);
}
/// <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>
@@ -557,6 +568,12 @@ public sealed partial class H264Decoder
return total;
}
/// <summary>
/// §9.2.1: in a partitioned slice with constrained_intra_pred_flag, an inter neighbour of an intra macroblock counts
/// as available with nN = 0 (its residual is in partition C, which the intra macroblock must not depend on).
/// </summary>
private bool HiddenByPartitioning(int n) => partitioned && pps.ConstrainedIntraPred && !IsIntra(n) && IsIntra(mb);
/// <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)
{
@@ -569,7 +586,7 @@ public sealed partial class H264Decoder
}
else if (Locate(-1, by * 4, 16, out var yM) is var a and >= 0)
{
nA = nz[(a * 24) + (((yM & 15) >> 2) * 4) + 3];
nA = HiddenByPartitioning(a) ? 0 : nz[(a * 24) + (((yM & 15) >> 2) * 4) + 3];
}
else
{
@@ -582,7 +599,7 @@ public sealed partial class H264Decoder
}
else if (Locate(bx * 4, -1, 16, out _) is var b and >= 0)
{
nB = nz[(b * 24) + 12 + bx];
nB = HiddenByPartitioning(b) ? 0 : nz[(b * 24) + 12 + bx];
}
else
{
@@ -604,7 +621,7 @@ public sealed partial class H264Decoder
}
else if (Locate(-1, by * 4, 8, out var yM) is var a and >= 0)
{
nA = nz[(a * 24) + baseIndex + (((yM & 7) >> 2) * 2) + 1];
nA = HiddenByPartitioning(a) ? 0 : nz[(a * 24) + baseIndex + (((yM & 7) >> 2) * 2) + 1];
}
else
{
@@ -617,7 +634,7 @@ public sealed partial class H264Decoder
}
else if (Locate(bx * 4, -1, 8, out _) is var n and >= 0)
{
nB = nz[(n * 24) + baseIndex + 2 + bx];
nB = HiddenByPartitioning(n) ? 0 : nz[(n * 24) + baseIndex + 2 + bx];
}
else
{
@@ -483,7 +483,7 @@ public sealed partial class H264Decoder
private void PrepareWeights()
{
weightMode = sh.Type == SliceType.P ? (pps.WeightedPred ? 1 : 0) : sh.IsB ? pps.WeightedBipredIdc : 0;
weightMode = sh.IsP ? (pps.WeightedPred ? 1 : 0) : sh.IsB ? pps.WeightedBipredIdc : 0;
if (weightMode != 2)
{
return;
@@ -0,0 +1,158 @@
namespace Febe.Core.Codecs.H264;
public sealed partial class H264Decoder
{
// Slice data partitioning (§7.3.2.9, §7.3.2.10, §7.4.2.9): partition A (NAL unit 2) holds the slice header and the
// category 2 syntax elements (macroblock types, prediction, coded_block_pattern, mb_qp_delta), partition B (3) the
// residual of the intra macroblocks (category 3), partition C (4) the residual of the inter ones (category 4). The
// three NAL units come one after the other: A is kept until its B and C have arrived, then the slice is decoded with
// one reader per partition.
/// <summary>A partition A is waiting for its partitions B and C.</summary>
private bool partitionPending;
private byte[] partitionA = [];
private byte[] partitionB = [];
private byte[] partitionC = [];
private NalUnit pendingNal;
private RbspReader? pendingReader;
private SliceHeader? pendingHeader;
private Sps? pendingSps;
private Pps? pendingPps;
private int pendingSliceId;
private RbspReader? pendingB;
private RbspReader? pendingC;
/// <summary>The slice being decoded is partitioned: the residual comes from <see cref="intraResidual"/> and <see cref="interResidual"/>.</summary>
private bool partitioned;
/// <summary>Partition B of the slice being decoded, null when it is missing.</summary>
private RbspReader? intraResidual;
/// <summary>Partition C of the slice being decoded, null when it is missing.</summary>
private RbspReader? interResidual;
/// <summary>
/// For the tests: called after the residual (or the I_PCM samples) of a macroblock has been read, with its first and
/// past-the-end bit in the RBSP of the slice, whether the macroblock is intra and whether it is I_PCM.
/// </summary>
internal Action<int, int, bool, bool>? ResidualRead { get; set; }
/// <summary>Partition A (§7.3.2.9): the slice header and slice_id, kept until partitions B and C have arrived.</summary>
private void StorePartitionA(NalUnit nal)
{
var copy = Keep(nal, ref partitionA);
var reader = copy.Reader();
var header = ParseSliceHeader(reader, copy, out var sps, out var pps);
if (pps.Cabac)
{
throw new H264Exception("Partizionamento dei dati con CABAC: combinazione non ammessa.");
}
var sliceId = reader.ReadUe(Sps.MaxFrameMbs - 1);
if (header.RedundantPicCnt > 0)
{
return; // a redundant picture, skipped with its partitions B and C (no partition is pending for them)
}
pendingNal = copy;
pendingReader = reader;
pendingHeader = header;
pendingSps = sps;
pendingPps = pps;
pendingSliceId = sliceId;
pendingB = pendingC = null;
partitionPending = true;
}
/// <summary>Partition B or C (§7.3.2.10) of the slice waiting in partition A; one of another slice is ignored.</summary>
private void StorePartition(NalUnit nal)
{
if (!partitionPending)
{
return;
}
var copy = nal.Type == 3 ? Keep(nal, ref partitionB) : Keep(nal, ref partitionC);
var reader = copy.Reader();
var sliceId = reader.ReadUe(Sps.MaxFrameMbs - 1);
var redundant = pendingPps!.RedundantPicCntPresent ? reader.ReadUe(127) : 0;
if (sliceId != pendingSliceId || redundant != 0)
{
return;
}
if (nal.Type == 3)
{
pendingB = reader;
}
else
{
pendingC = reader;
}
}
/// <summary>Decodes the slice of the partitions received; a missing B or C leaves the residual it carries at zero.</summary>
private void DecodePartitionedSlice()
{
partitionPending = false;
partitioned = true;
intraResidual = pendingB;
interResidual = pendingC;
try
{
DecodeParsedSlice(pendingNal, pendingReader!, pendingHeader!, pendingSps!, pendingPps!);
}
finally
{
partitioned = false;
intraResidual = interResidual = null;
pendingB = pendingC = null;
pendingReader = null;
}
}
/// <summary>A copy of the RBSP of a partition, which must outlive the shared buffer of the stream.</summary>
private static NalUnit Keep(NalUnit nal, ref byte[] buffer)
{
if (buffer.Length < nal.Length + NalUnits.Padding)
{
buffer = new byte[nal.Length + NalUnits.Padding];
}
nal.Rbsp.AsSpan(0, nal.Length + NalUnits.Padding).CopyTo(buffer);
return nal with { Rbsp = buffer };
}
/// <summary>
/// The reader of the residual of the current macroblock: the slice data, or the partition B (intra) or C (inter) of a
/// partitioned slice — null when that partition is missing.
/// </summary>
/// <remarks>
/// Asked only for a macroblock that has residual. When its partition is missing, the other one can no longer be read
/// from here on: the nC of an inter block counts the coefficients of its intra neighbours, and the nC of an intra
/// block those of its inter neighbours unless constrained_intra_pred makes them count as empty (§9.2.1).
/// </remarks>
private RbspReader? ResidualReader(bool intra)
{
if (!partitioned)
{
return rd;
}
var source = intra ? intraResidual : interResidual;
if (source is null)
{
if (intra)
{
interResidual = null;
}
else if (!pps.ConstrainedIntraPred)
{
intraResidual = null;
}
}
return source;
}
}
+233 -40
View File
@@ -14,6 +14,9 @@ public sealed partial class H264Decoder
BDirect,
PInter,
BInter,
/// <summary>The SI macroblock of SI slices: Intra_4x4 prediction, reconstructed in QS (§8.6.2).</summary>
SI,
}
// Shapes of inter macroblocks and sub-macroblocks.
@@ -107,6 +110,18 @@ public sealed partial class H264Decoder
private readonly bool[] lumaHas = new bool[16];
private readonly int[] chromaCoef = new int[2 * 4 * 16];
private readonly bool[] chromaHas = new bool[8];
/// <summary>The chroma DC levels as parsed (component × 4), for the macroblocks reconstructed in QS.</summary>
private readonly int[] chromaDcLevels = new int[8];
/// <summary>The residual being parsed is kept as levels, not scaled: P macroblocks of SP slices and SI macroblocks.</summary>
private bool rawLevels;
/// <summary>Per slice of the picture: an SP or SI slice, whose macroblocks the deblocking filter treats as intra (§8.7.2.1).</summary>
private readonly List<bool> sliceSwitching = [];
/// <summary>Some slice of the picture is an SP or SI slice.</summary>
private bool anySwitching;
private readonly int[] levels = new int[64];
private readonly int[] levels4 = new int[64];
private readonly int[] subType = new int[4];
@@ -133,7 +148,13 @@ public sealed partial class H264Decoder
subDirect = new bool[mbCount * 4];
}
private bool IsIntra(int m) => mbKind[m] is MbKind.I4x4 or MbKind.I8x8 or MbKind.I16x16 or MbKind.IPcm;
private bool IsIntra(int m) => mbKind[m] is MbKind.I4x4 or MbKind.I8x8 or MbKind.I16x16 or MbKind.IPcm or MbKind.SI;
/// <summary>
/// A neighbour whose samples intra prediction may use under constrained_intra_pred_flag: an intra macroblock, but not
/// an SI one for a macroblock that is not SI (§8.3.1.2).
/// </summary>
private bool IntraUsable(int m) => IsIntra(m) && (mbKind[m] != MbKind.SI || mbKind[mb] == MbKind.SI);
private bool IsSkip(int m) => mbKind[m] is MbKind.PSkip or MbKind.BSkip;
@@ -150,6 +171,12 @@ public sealed partial class H264Decoder
mbaff = s.MbAdaptiveFrameField && !header.FieldPic;
sliceNum = sliceCounter++;
sliceFilters.Add((header.DisableDeblocking, header.AlphaOffset, header.BetaOffset));
sliceSwitching.Add(header.IsSwitching);
anySwitching |= header.IsSwitching;
if (header.IsSwitching && p.Transform8x8Mode)
{
throw new H264Exception("Slice SP o SI con la trasformata 8×8: combinazione non ammessa.");
}
qp = p.PicInitQp + header.QpDelta;
if (qp is < 0 or > 51)
{
@@ -187,7 +214,8 @@ public sealed partial class H264Decoder
cabac.Start(rd);
}
// Macroblock addresses of the slice: those of the field, or of the pairs (two per pair) in an MBAFF frame.
// Macroblock addresses of the slice: those of the field, or of the pairs (two per pair) in an MBAFF frame; with
// slice groups only those of the group of the first one, in order.
var total = fieldPic ? mbCount / 2 : mbCount;
var addr = header.FirstMb * (mbaff ? 2 : 1);
if (addr >= total)
@@ -195,6 +223,8 @@ public sealed partial class H264Decoder
throw new H264Exception("Primo macroblocco fuori dall'immagine.");
}
PrepareSliceGroups(header, s, p);
if (!mbaff)
{
DecodeMacroblocks(addr, total);
@@ -224,7 +254,13 @@ public sealed partial class H264Decoder
for (var i = 0; i < (int)run; i++)
{
BeginMacroblock(addr++);
if (addr >= total)
{
throw new H264Exception("mb_skip_run fuori dal gruppo di slice.");
}
BeginMacroblock(addr);
addr = NextAddress(addr);
DecodeSkip();
}
@@ -234,7 +270,8 @@ public sealed partial class H264Decoder
}
}
BeginMacroblock(addr++);
BeginMacroblock(addr);
addr = NextAddress(addr);
if (!isIntraSlice && cabacMode && ReadMbSkip() != 0)
{
DecodeSkip();
@@ -272,6 +309,11 @@ public sealed partial class H264Decoder
for (var i = 0; i < (int)run; i++)
{
if (addr >= total)
{
throw new H264Exception("mb_skip_run fuori dal gruppo di slice.");
}
if ((addr & 1) == 0)
{
SetPairField(addr, InferPairField(addr));
@@ -281,7 +323,8 @@ public sealed partial class H264Decoder
}
}
BeginMacroblock(addr++);
BeginMacroblock(addr);
addr = NextAddress(addr);
DecodeSkip();
}
@@ -296,7 +339,8 @@ public sealed partial class H264Decoder
SetPairField(addr, rd.ReadFlag());
}
BeginMacroblock(addr++);
BeginMacroblock(addr);
addr = NextAddress(addr);
DecodeMacroblock();
if (!rd.MoreRbspData)
{
@@ -348,7 +392,8 @@ public sealed partial class H264Decoder
bottomSkipKnown = false;
}
BeginMacroblock(addr++);
BeginMacroblock(addr);
addr = NextAddress(addr);
if (skip)
{
DecodeSkip();
@@ -612,7 +657,17 @@ public sealed partial class H264Decoder
{
intraType = type;
}
else if (sh.Type == SliceType.P)
else if (sh.Type == SliceType.SI)
{
if (type == 0)
{
DecodeSi();
return;
}
intraType = type - 1;
}
else if (sh.IsP)
{
intraType = type >= 5 ? type - 5 : -1;
}
@@ -652,6 +707,12 @@ public sealed partial class H264Decoder
{
PredictPSkip();
MotionCompensate(0, 0, 16, 16);
if (sh.Type == SliceType.SP)
{
// Even without residual the prediction of an SP slice is quantised in QS (§8.6.1).
ClearResidual();
ReconstructSwitchingInter();
}
}
}
@@ -703,7 +764,7 @@ public sealed partial class H264Decoder
if (cbp != 0 || intra16)
{
ApplyQpDelta(ReadQpDelta());
ParseResidual(intra16, cbp, intra: true);
ReadResidual(intra16, cbp, intra: true);
}
else
{
@@ -715,6 +776,38 @@ public sealed partial class H264Decoder
ReconstructIntra(predMode16);
}
/// <summary>The SI macroblock (mb_type 0 of an SI slice): Intra_4x4 prediction, levels in QS (§7.4.5, §8.6.2).</summary>
private void DecodeSi()
{
cur!.MbIntra[mb] = true;
mbKind[mb] = MbKind.SI;
ReadIntraModes(false);
chromaModes[mb] = (byte)ReadChromaPredMode();
if (chromaModes[mb] > 3)
{
throw new H264Exception("Modo di predizione della crominanza non valido.");
}
var cbp = ReadCbp(intra: true);
mbCbp[mb] = (byte)cbp;
ClearResidual();
if (cbp != 0)
{
ApplyQpDelta(ReadQpDelta());
rawLevels = true;
ReadResidual(false, cbp, intra: true);
rawLevels = false;
}
else
{
lastQpDelta = 0;
}
mbQp[mb] = (byte)qp;
SetChromaQp();
ReconstructIntra(0);
}
private void ApplyQpDelta(int delta)
{
if (delta is < -26 or > 25)
@@ -776,7 +869,7 @@ public sealed partial class H264Decoder
return 2;
}
modeA = mbKind[a] is MbKind.I4x4 or MbKind.I8x8 ? intraModes[(a * 16) + (((yM & 15) >> 2) * 4) + 3] : 2;
modeA = mbKind[a] is MbKind.I4x4 or MbKind.I8x8 or MbKind.SI ? intraModes[(a * 16) + (((yM & 15) >> 2) * 4) + 3] : 2;
}
if (by > 0)
@@ -791,7 +884,7 @@ public sealed partial class H264Decoder
return 2;
}
modeB = mbKind[b] is MbKind.I4x4 or MbKind.I8x8 ? intraModes[(b * 16) + 12 + bx] : 2;
modeB = mbKind[b] is MbKind.I4x4 or MbKind.I8x8 or MbKind.SI ? intraModes[(b * 16) + 12 + bx] : 2;
}
return Math.Min(modeA, modeB);
@@ -801,30 +894,55 @@ public sealed partial class H264Decoder
{
mbKind[mb] = MbKind.IPcm;
// With CABAC the arithmetic decoder has read exactly up to the end of its flush (§9.3.1.2).
while (!rd.ByteAligned)
{
rd.Skip(1); // pcm_alignment_zero_bit
}
// The samples are category 3: in partition B of a partitioned slice (grey when it is missing).
var main = rd;
var source = ResidualReader(intra: true);
var picture = cur!;
for (var y = 0; y < 16; y++)
if (source is not null)
{
for (var x = 0; x < 16; x++)
{
picture.Y[lumaO + (y * lumaStride) + x] = (byte)rd.Read(8);
}
}
rd = source;
var start = rd.Position;
for (var c = 0; c < 2; c++)
// With CABAC the arithmetic decoder has read exactly up to the end of its flush (§9.3.1.2).
while (!rd.ByteAligned)
{
rd.Skip(1); // pcm_alignment_zero_bit
}
for (var y = 0; y < 16; y++)
{
for (var x = 0; x < 16; x++)
{
picture.Y[lumaO + (y * lumaStride) + x] = (byte)rd.Read(8);
}
}
for (var c = 0; c < 2; c++)
{
var plane = c == 0 ? picture.Cb : picture.Cr;
for (var y = 0; y < 8; y++)
{
for (var x = 0; x < 8; x++)
{
plane[chromaO + (y * chromaStride) + x] = (byte)rd.Read(8);
}
}
}
ResidualRead?.Invoke(start, rd.Position, true, true);
rd = main;
}
else
{
var plane = c == 0 ? picture.Cb : picture.Cr;
for (var y = 0; y < 16; y++)
{
picture.Y.AsSpan(lumaO + (y * lumaStride), 16).Fill(128);
}
for (var y = 0; y < 8; y++)
{
for (var x = 0; x < 8; x++)
{
plane[chromaO + (y * chromaStride) + x] = (byte)rd.Read(8);
}
picture.Cb.AsSpan(chromaO + (y * chromaStride), 8).Fill(128);
picture.Cr.AsSpan(chromaO + (y * chromaStride), 8).Fill(128);
}
}
@@ -981,10 +1099,13 @@ public sealed partial class H264Decoder
}
ClearResidual();
var switching = sh.Type == SliceType.SP;
if (cbp != 0)
{
ApplyQpDelta(ReadQpDelta());
ParseResidual(false, cbp, intra: false);
rawLevels = switching;
ReadResidual(false, cbp, intra: false);
rawLevels = false;
}
else
{
@@ -1069,7 +1190,14 @@ public sealed partial class H264Decoder
}
}
AddInterResidual();
if (switching)
{
ReconstructSwitchingInter();
}
else
{
AddInterResidual();
}
}
private void Partition(int part, out int px, out int py, out int w, out int h)
@@ -1189,6 +1317,27 @@ public sealed partial class H264Decoder
Array.Clear(lumaHas);
Array.Clear(chromaCoef);
Array.Clear(chromaHas);
Array.Clear(chromaDcLevels);
}
/// <summary>
/// The residual of the macroblock, from the slice data or from its partition (§7.3.2.10): a missing partition leaves
/// it at zero.
/// </summary>
private void ReadResidual(bool intra16, int cbp, bool intra)
{
var source = ResidualReader(intra);
if (source is null)
{
return;
}
var main = rd;
rd = source;
var start = rd.Position;
ParseResidual(intra16, cbp, intra);
ResidualRead?.Invoke(start, rd.Position, intra, false);
rd = main;
}
/// <summary>residual() of §7.3.5.3, with the scaling of §8.5 applied as the levels are read.</summary>
@@ -1295,7 +1444,7 @@ public sealed partial class H264Decoder
if (level != 0)
{
var pos = scan4[k];
lumaCoef[(raster * 16) + pos] = Scale4(level, scale4[(qpMod * 16) + pos], qpDiv);
lumaCoef[(raster * 16) + pos] = rawLevels ? level : Scale4(level, scale4[(qpMod * 16) + pos], qpDiv);
lumaHas[raster] = true;
}
}
@@ -1320,6 +1469,12 @@ public sealed partial class H264Decoder
continue;
}
if (rawLevels)
{
levels.AsSpan(0, 4).CopyTo(chromaDcLevels.AsSpan(c * 4, 4));
continue;
}
var qpc = H264Tables.ChromaQp[Math.Clamp(qp + (c == 0 ? pps.ChromaQpIndexOffset : pps.SecondChromaQpIndexOffset), 0, 51)];
var ls = ls4[(intra ? 1 : 4) + c][(qpc % 6) * 16];
int c0 = levels[0], c1 = levels[1], c2 = levels[2], c3 = levels[3];
@@ -1355,7 +1510,7 @@ public sealed partial class H264Decoder
if (level != 0)
{
var pos = scan4[k + 1];
chromaCoef[(((c * 4) + b) * 16) + pos] = Scale4(level, scale[((qpc % 6) * 16) + pos], qpc / 6);
chromaCoef[(((c * 4) + b) * 16) + pos] = rawLevels ? level : Scale4(level, scale[((qpc % 6) * 16) + pos], qpc / 6);
chromaHas[(c * 4) + b] = true;
}
}
@@ -1405,7 +1560,7 @@ public sealed partial class H264Decoder
var all = (1 << maxH) - 1;
if (!mbaff)
{
return mbA >= 0 && (!constrained || IsIntra(mbA)) ? all : 0;
return mbA >= 0 && (!constrained || IntraUsable(mbA)) ? all : 0;
}
if (pairA < 0)
@@ -1422,9 +1577,10 @@ public sealed partial class H264Decoder
for (var r = 0; r < maxH; r++)
{
var n = Locate(-1, r, maxH, out _);
if (n >= 0 && IsIntra(n))
if (n >= 0 && IntraUsable(n))
{
mask |= 1 << r;
}
}
@@ -1441,14 +1597,16 @@ public sealed partial class H264Decoder
var nB = Locate(0, -1, 16, out _);
var nC = Locate(16, -1, 16, out _);
var nD = Locate(-1, -1, 16, out _);
var b = nB >= 0 && (!constrained || IsIntra(nB));
var c = nC >= 0 && (!constrained || IsIntra(nC));
var d = nD >= 0 && (!constrained || IsIntra(nD));
var b = nB >= 0 && (!constrained || IntraUsable(nB));
var c = nC >= 0 && (!constrained || IntraUsable(nC));
var d = nD >= 0 && (!constrained || IntraUsable(nD));
var si = mbKind[mb] == MbKind.SI;
var left = LeftRows(16, constrained);
Span<int> block = stackalloc int[64];
switch (mbKind[mb])
{
case MbKind.I4x4:
case MbKind.SI:
for (var i = 0; i < 16; i++)
{
var raster = H264Tables.BlockToRaster[i];
@@ -1468,7 +1626,11 @@ public sealed partial class H264Decoder
var o = LumaOffset(bx * 4, by * 4);
IntraPrediction.Predict4x4(picture.Y, o, stride, intraModes[(mb * 16) + raster], hasLeft, top, topRight, topLeft);
if (lumaHas[raster])
if (si)
{
SwitchingTransform.Luma4x4(picture.Y, o, stride, lumaCoef.AsSpan(raster * 16, 16), sh.Qs, sh.Qs, levelInQs: true);
}
else if (lumaHas[raster])
{
lumaCoef.AsSpan(raster * 16, 16).CopyTo(block);
Transform.Add4x4(block[..16], picture.Y, o, stride);
@@ -1516,7 +1678,38 @@ public sealed partial class H264Decoder
bool upper = Rows(chromaLeft, 0, 4), lower = Rows(chromaLeft, 4, 4);
IntraPrediction.PredictChroma(picture.Cb, chromaO, chromaStride, chromaModes[mb], upper, lower, b, d);
IntraPrediction.PredictChroma(picture.Cr, chromaO, chromaStride, chromaModes[mb], upper, lower, b, d);
AddChromaResidual();
if (si)
{
SwitchingChroma(levelInQs: true);
}
else
{
AddChromaResidual();
}
}
/// <summary>A P macroblock of an SP slice, its prediction in place: every block is rebuilt in QS (§8.6.1).</summary>
private void ReconstructSwitchingInter()
{
var picture = cur!;
for (var raster = 0; raster < 16; raster++)
{
SwitchingTransform.Luma4x4(picture.Y, LumaOffset((raster & 3) * 4, (raster >> 2) * 4), lumaStride, lumaCoef.AsSpan(raster * 16, 16), mbQp[mb], sh.Qs, sh.SpForSwitch);
}
SwitchingChroma(sh.SpForSwitch);
}
/// <summary>The chroma of a macroblock rebuilt in QS: QPc from the QP of the macroblock, QSc from QS (§8.6.1, §8.6.2).</summary>
private void SwitchingChroma(bool levelInQs)
{
var picture = cur!;
for (var c = 0; c < 2; c++)
{
var offset = c == 0 ? pps.ChromaQpIndexOffset : pps.SecondChromaQpIndexOffset;
var qsc = H264Tables.ChromaQp[Math.Clamp(sh.Qs + offset, 0, 51)];
SwitchingTransform.Chroma(c == 0 ? picture.Cb : picture.Cr, chromaO, chromaStride, chromaCoef.AsSpan(c * 64, 64), chromaDcLevels.AsSpan(c * 4, 4), mbQpC[(mb * 2) + c], qsc, levelInQs);
}
}
private void AddInterResidual()
@@ -0,0 +1,245 @@
namespace Febe.Core.Codecs.H264;
public sealed partial class H264Decoder
{
/// <summary>The picture has more than one slice group (FMO): a slice walks the macroblocks of its group only.</summary>
private bool fmo;
/// <summary>The slice group of each map unit (mapUnitToSliceGroupMap, §8.2.2.1–§8.2.2.7).</summary>
private int[] mapUnitGroup = [];
/// <summary>The slice group of each macroblock address of the picture (mbToSliceGroupMap, §8.2.2.8).</summary>
private byte[] mbGroup = [];
/// <summary>NextMbAddress (§8.2.2): the next address of the same slice group, the picture size after the last one.</summary>
private int[] nextMb = [];
// What the map in the arrays above was computed for.
private Pps? mapPps;
private Sps? mapSps;
private int mapCycle = -1;
private int mapLayout = -1;
/// <summary>The address after <paramref name="addr"/> in the slice (§7.3.4).</summary>
private int NextAddress(int addr) => fmo ? nextMb[addr] : addr + 1;
/// <summary>
/// The slice group map of the slice about to be decoded (§8.2.2), computed again only when the parameter sets,
/// slice_group_change_cycle or the kind of picture (frame, field, MBAFF frame) change.
/// </summary>
private void PrepareSliceGroups(SliceHeader h, Sps s, Pps p)
{
fmo = p.NumSliceGroups > 1;
if (!fmo)
{
return;
}
// 0 frame of frame macroblocks only or a field, 1 MBAFF frame, 2 frame of a stream with fields but no MBAFF.
var layout = s.FrameMbsOnly || h.FieldPic ? 0 : s.MbAdaptiveFrameField ? 1 : 2;
var cycle = p.SliceGroupMapType is >= 3 and <= 5 ? h.SliceGroupChangeCycle : -1;
if (ReferenceEquals(mapPps, p) && ReferenceEquals(mapSps, s) && mapCycle == cycle && mapLayout == layout)
{
return;
}
var w = s.WidthInMbs;
var mapHeight = s.HeightInMapUnits;
var units = w * mapHeight;
if (mapUnitGroup.Length != units)
{
mapUnitGroup = new int[units];
}
BuildMapUnits(p, w, mapHeight, Math.Min(Math.Max(cycle, 0) * p.SliceGroupChangeRate, units));
var total = h.FieldPic ? s.WidthInMbs * s.HeightInMbs / 2 : s.WidthInMbs * s.HeightInMbs;
if (mbGroup.Length != total)
{
mbGroup = new byte[total];
nextMb = new int[total];
}
for (var i = 0; i < total; i++)
{
var unit = layout switch
{
0 => i,
1 => i >> 1,
_ => ((i / (2 * w)) * w) + (i % w),
};
mbGroup[i] = (byte)mapUnitGroup[unit];
}
Span<int> last = stackalloc int[8];
last.Fill(total);
for (var i = total - 1; i >= 0; i--)
{
var g = mbGroup[i];
nextMb[i] = last[g];
last[g] = i;
}
mapPps = p;
mapSps = s;
mapCycle = cycle;
mapLayout = layout;
}
/// <summary>mapUnitToSliceGroupMap for the map type of the PPS (§8.2.2.1–§8.2.2.7).</summary>
private void BuildMapUnits(Pps p, int w, int h, int unitsInGroup0)
{
var map = mapUnitGroup;
var units = map.Length;
var groups = p.NumSliceGroups;
var direction = p.SliceGroupChangeDirection ? 1 : 0;
switch (p.SliceGroupMapType)
{
case 0:
{
// Interleaved: runs of each group in turn.
var i = 0;
do
{
for (var g = 0; g < groups && i < units; i += p.RunLength[g++])
{
for (var j = 0; j < p.RunLength[g] && i + j < units; j++)
{
map[i + j] = g;
}
}
}
while (i < units);
break;
}
case 1:
// Dispersed.
for (var i = 0; i < units; i++)
{
map[i] = ((i % w) + (((i / w) * groups) / 2)) % groups;
}
break;
case 2:
// Foreground rectangles, the last group taking what is left.
Array.Fill(map, groups - 1);
for (var g = groups - 2; g >= 0; g--)
{
int topLeft = p.TopLeft[g], bottomRight = p.BottomRight[g];
if (bottomRight >= units || topLeft > bottomRight || topLeft % w > bottomRight % w)
{
throw new H264Exception("Rettangolo di un gruppo di slice fuori dall'immagine.");
}
for (var y = topLeft / w; y <= bottomRight / w; y++)
{
for (var x = topLeft % w; x <= bottomRight % w; x++)
{
map[(y * w) + x] = g;
}
}
}
break;
case 3:
BoxOut(map, w, h, direction, unitsInGroup0);
break;
case 4:
{
// Raster scan.
var upperLeft = direction != 0 ? units - unitsInGroup0 : unitsInGroup0;
for (var i = 0; i < units; i++)
{
map[i] = i < upperLeft ? direction : 1 - direction;
}
break;
}
case 5:
{
// Wipe: column by column.
var upperLeft = direction != 0 ? units - unitsInGroup0 : unitsInGroup0;
var k = 0;
for (var x = 0; x < w; x++)
{
for (var y = 0; y < h; y++)
{
map[(y * w) + x] = k++ < upperLeft ? direction : 1 - direction;
}
}
break;
}
default:
// Explicit.
if (p.SliceGroupIds.Length != units)
{
throw new H264Exception("Mappa esplicita dei gruppi di slice di dimensione sbagliata.");
}
for (var i = 0; i < units; i++)
{
map[i] = p.SliceGroupIds[i];
}
break;
}
}
/// <summary>Box-out (§8.2.2.4): group 0 grows as a spiral from the centre, clockwise or counter-clockwise.</summary>
private static void BoxOut(int[] map, int w, int h, int direction, int unitsInGroup0)
{
Array.Fill(map, 1);
var x = (w - direction) / 2;
var y = (h - direction) / 2;
int left = x, top = y, right = x, bottom = y;
int xDir = direction - 1, yDir = direction;
for (var k = 0; k < unitsInGroup0;)
{
var vacant = map[(y * w) + x] == 1;
if (vacant)
{
map[(y * w) + x] = 0;
k++;
}
if (xDir == -1 && x == left)
{
left = Math.Max(left - 1, 0);
x = left;
xDir = 0;
yDir = (2 * direction) - 1;
}
else if (xDir == 1 && x == right)
{
right = Math.Min(right + 1, w - 1);
x = right;
xDir = 0;
yDir = 1 - (2 * direction);
}
else if (yDir == -1 && y == top)
{
top = Math.Max(top - 1, 0);
y = top;
xDir = 1 - (2 * direction);
yDir = 0;
}
else if (yDir == 1 && y == bottom)
{
bottom = Math.Min(bottom + 1, h - 1);
y = bottom;
xDir = (2 * direction) - 1;
yDir = 0;
}
else
{
x += xDir;
y += yDir;
}
}
}
}
+54 -18
View File
@@ -14,14 +14,17 @@ public enum H264AccessPoint
}
/// <summary>
/// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Main and High profiles in
/// 4:2:0 with 8-bit samples — CAVLC and CABAC, I, P and B slices, 8×8 transform and scaling matrices, spatial and
/// temporal direct prediction, list modification, memory management operations and long-term references, deblocking —
/// for progressive frames and for interlaced video: field pictures, frames and fields mixed picture by picture (PAFF),
/// frames of frame and field macroblock pairs (MBAFF). Frames come out whole: the two fields of a pair are interleaved.
/// Written from the standard but not yet checked against a conformance stream: explicit and implicit weighted
/// prediction, gaps in frame_num, I_PCM. Not handled (an <see cref="H264Exception"/>): slice groups, SP/SI slices, data
/// partitioning, 4:2:2/4:4:4 and depths above 8 bits. Redundant coded pictures are skipped.
/// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Extended, Main and High
/// profiles in 4:2:0 with 8-bit samples — CAVLC and CABAC, I, P and B slices, 8×8 transform and scaling matrices, spatial
/// and temporal direct prediction, list modification, memory management operations and long-term references,
/// deblocking — for progressive frames and for interlaced video: field pictures, frames and fields mixed picture by
/// picture (PAFF), frames of frame and field macroblock pairs (MBAFF). Frames come out whole: the two fields of a pair are
/// interleaved. The tools of Baseline and Extended: slice groups (FMO, map types 0–6), slices in any order (ASO), SP and
/// SI slices (switching pictures), slice data partitioning (NAL units 2–4); redundant coded pictures are skipped, the
/// primary one is decoded. Written from the standard but not yet checked against a conformance stream: explicit and
/// implicit weighted prediction, gaps in frame_num, I_PCM, SI macroblocks and sp_for_switch_flag, data partitioning
/// (checked only on conformance streams split into partitions). Not handled (an <see cref="H264Exception"/>):
/// 4:2:2/4:4:4 and depths above 8 bits.
/// </summary>
public sealed partial class H264Decoder
{
@@ -174,12 +177,13 @@ public sealed partial class H264Decoder
case 5:
return H264AccessPoint.Idr;
case 1:
case 2: // partition A starts like a slice
try
{
// first_mb_in_slice and slice_type: a few bytes of the header are enough.
var reader = NalUnits.Parse(nal[..Math.Min(nal.Length, 16)]).Reader();
_ = reader.ReadUe();
return reader.ReadUe(9) % 5 == (int)SliceType.I ? H264AccessPoint.IntraPicture : H264AccessPoint.None;
return (SliceType)(reader.ReadUe(9) % 5) is SliceType.I or SliceType.SI ? H264AccessPoint.IntraPicture : H264AccessPoint.None;
}
catch (H264Exception)
{
@@ -217,6 +221,11 @@ public sealed partial class H264Decoder
{
try
{
if (partitionPending)
{
DecodePartitionedSlice();
}
CompletePicture();
}
catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException or NullReferenceException)
@@ -228,10 +237,19 @@ public sealed partial class H264Decoder
}
}
/// <summary>Decodes one NAL unit (with its header, without start code) and leaves the picture open: for the tests.</summary>
internal void DecodeUnit(ReadOnlySpan<byte> nal) => Decode(NalUnits.Unescape(nal, ref rbsp));
private void Decode(NalUnit nal)
{
try
{
// The partitions B and C of a slice follow its partition A: anything else completes it.
if (partitionPending && nal.Type is not (3 or 4))
{
DecodePartitionedSlice();
}
switch (nal.Type)
{
case 1:
@@ -239,9 +257,12 @@ public sealed partial class H264Decoder
DecodeSlice(nal);
break;
case 2:
StorePartitionA(nal);
break;
case 3:
case 4:
throw new H264Exception("Il partizionamento dei dati non è gestito.");
StorePartition(nal);
break;
case 7:
{
var sps = Sps.Parse(nal.Reader());
@@ -270,7 +291,20 @@ public sealed partial class H264Decoder
private void DecodeSlice(NalUnit nal)
{
var reader = nal.Reader();
var header = SliceHeader.Parse(reader, nal, sequences, pictures, out var sps, out var pps);
var header = ParseSliceHeader(reader, nal, out var sps, out var pps);
// A redundant coded picture (§7.4.3) repeats the primary one, which is decoded: it is skipped.
if (header.RedundantPicCnt > 0)
{
return;
}
DecodeParsedSlice(nal, reader, header, sps, pps);
}
private SliceHeader ParseSliceHeader(RbspReader reader, NalUnit nal, out Sps sps, out Pps pps)
{
var header = SliceHeader.Parse(reader, nal, sequences, pictures, out sps, out pps);
if (sps.ChromaFormatIdc != 1 || sps.BitDepthLuma != 8 || sps.BitDepthChroma != 8)
{
throw new H264Exception("Solo video 4:2:0 a 8 bit.");
@@ -281,12 +315,12 @@ public sealed partial class H264Decoder
throw new H264Exception("La codifica senza perdita non è gestita.");
}
// A redundant coded picture (§7.4.3) repeats the primary one, which is decoded: it is skipped.
if (header.RedundantPicCnt > 0)
{
return;
}
return header;
}
/// <summary>A slice whose header is read: the picture it belongs to, then its macroblocks.</summary>
private void DecodeParsedSlice(NalUnit nal, RbspReader reader, SliceHeader header, Sps sps, Pps pps)
{
if (cur is null || picHeader is null || StartsNewPicture(header, nal) || FirstMacroblockDone(header, sps))
{
FinishPicture();
@@ -444,6 +478,8 @@ public sealed partial class H264Decoder
picture.Decoded |= structure == 0 ? 3 : structure;
sliceCounter = 0;
sliceFilters.Clear();
sliceSwitching.Clear();
anySwitching = false;
Array.Fill(mbSlice, -1);
// A picture nobody refers to and nobody wants: its header has set the state above, its slices are not decoded.
@@ -1165,7 +1201,7 @@ public sealed partial class H264Decoder
longTerm.Sort((a, b) => a.LongTermPicNum.CompareTo(b.LongTermPicNum));
List<RefEntry> init0 = [], init1 = [];
if (h.Type == SliceType.P)
if (h.IsP)
{
shortTerm.Sort((a, b) => b.PicNum.CompareTo(a.PicNum));
foreach (var p in shortTerm)
@@ -1223,7 +1259,7 @@ public sealed partial class H264Decoder
longTerm.Sort((a, b) => a.LongTermFrameIdx.CompareTo(b.LongTermFrameIdx));
List<RefEntry> init0 = [], init1 = [];
if (h.Type == SliceType.P)
if (h.IsP)
{
shortTerm.Sort((a, b) => b.FrameNumWrap.CompareTo(a.FrameNumWrap));
Alternate(shortTerm, parity, longTerm: false, init0);
+86 -3
View File
@@ -181,6 +181,31 @@ internal sealed class Pps
internal bool WeightedPred;
internal int WeightedBipredIdc;
internal int PicInitQp;
/// <summary>26 + pic_init_qs_minus26: the starting QS of SP and SI slices.</summary>
internal int PicInitQs;
/// <summary>num_slice_groups_minus1 + 1: more than one is FMO (§8.2.2).</summary>
internal int NumSliceGroups = 1;
internal int SliceGroupMapType;
/// <summary>run_length_minus1 + 1 of each slice group (map type 0).</summary>
internal int[] RunLength = [];
/// <summary>top_left and bottom_right of the rectangles of the slice groups but the last (map type 2).</summary>
internal int[] TopLeft = [];
internal int[] BottomRight = [];
internal bool SliceGroupChangeDirection;
/// <summary>slice_group_change_rate_minus1 + 1 (map types 3–5).</summary>
internal int SliceGroupChangeRate;
/// <summary>slice_group_id of each map unit (map type 6).</summary>
internal byte[] SliceGroupIds = [];
internal int ChromaQpIndexOffset;
internal int SecondChromaQpIndexOffset;
internal bool DeblockingFilterControlPresent;
@@ -196,9 +221,10 @@ internal sealed class Pps
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)
p.NumSliceGroups = r.ReadUe(7) + 1;
if (p.NumSliceGroups > 1)
{
throw new H264Exception("I gruppi di slice (FMO) non sono gestiti.");
ParseSliceGroups(r, p);
}
p.NumRefIdxL0DefaultActive = r.ReadUe(31) + 1;
@@ -206,7 +232,12 @@ internal sealed class Pps
p.WeightedPred = r.ReadFlag();
p.WeightedBipredIdc = (int)r.Read(2);
p.PicInitQp = 26 + r.ReadSe();
r.ReadSe(); // pic_init_qs_minus26
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();
@@ -227,6 +258,58 @@ internal sealed class Pps
return p;
}
/// <summary>The slice group map of §7.3.2.2 (num_slice_groups_minus1 above 0), checked against the picture later.</summary>
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;
}
}
}
}
/// <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>
+39 -6
View File
@@ -56,8 +56,23 @@ internal sealed class SliceHeader
internal int AlphaOffset;
internal int BetaOffset;
/// <summary>sp_for_switch_flag of an SP slice: its P macroblocks decode as those of a switching picture (§8.6.1).</summary>
internal bool SpForSwitch;
/// <summary>QS_Y of an SP or SI slice: pic_init_qs_minus26 + 26 + slice_qs_delta.</summary>
internal int Qs;
/// <summary>slice_group_change_cycle (map types 3–5 of FMO).</summary>
internal int SliceGroupChangeCycle;
internal bool IsIntra => Type is SliceType.I or SliceType.SI;
/// <summary>A P or SP slice: both are parsed and predicted alike (an SP slice differs in the reconstruction).</summary>
internal bool IsP => Type is SliceType.P or SliceType.SP;
/// <summary>An SP or SI slice: switching pictures (§8.6).</summary>
internal bool IsSwitching => Type is SliceType.SP or SliceType.SI;
internal bool IsB => Type == SliceType.B;
/// <summary>0 frame, 1 top field, 2 bottom field.</summary>
@@ -74,11 +89,6 @@ internal sealed class SliceHeader
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)
{
@@ -151,7 +161,7 @@ internal sealed class SliceHeader
h.NumRefIdxActiveL0 = 0;
}
if ((pps.WeightedPred && h.Type == SliceType.P) || (pps.WeightedBipredIdc == 1 && h.IsB))
if ((pps.WeightedPred && h.IsP) || (pps.WeightedBipredIdc == 1 && h.IsB))
{
ParseWeights(r, h, sps);
}
@@ -205,6 +215,20 @@ internal sealed class SliceHeader
}
h.QpDelta = r.ReadSe();
if (h.Type is SliceType.SP or SliceType.SI)
{
if (h.Type == SliceType.SP)
{
h.SpForSwitch = r.ReadFlag();
}
h.Qs = pps.PicInitQs + r.ReadSe();
if (h.Qs is < 0 or > 51)
{
throw new H264Exception("QS della slice non valido.");
}
}
if (pps.DeblockingFilterControlPresent)
{
h.DisableDeblocking = r.ReadUe(2);
@@ -215,6 +239,15 @@ internal sealed class SliceHeader
}
}
if (pps.NumSliceGroups > 1 && pps.SliceGroupMapType is >= 3 and <= 5)
{
// Ceil(Log2(PicSizeInMapUnits ÷ SliceGroupChangeRate + 1)) bits (§7.4.3).
var size = sps.WidthInMbs * sps.HeightInMapUnits;
var units = (size + pps.SliceGroupChangeRate - 1) / pps.SliceGroupChangeRate;
var bits = 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)units);
h.SliceGroupChangeCycle = (int)r.Read(bits);
}
return h;
}
@@ -0,0 +1,161 @@
namespace Febe.Core.Codecs.H264;
/// <summary>
/// The reconstruction of the P macroblocks of SP slices and of the SI macroblocks (§8.6): the prediction is transformed
/// and quantised with QS together with the received levels, so that a switching picture rebuilds exactly the same
/// samples whichever stream it was reached from. The block is then decoded with QS as usual, and the result replaces the
/// prediction instead of being added to it.
/// </summary>
internal static class SwitchingTransform
{
/// <summary>Quantisation factors (the inverse of normAdjust4x4) by QS % 6 and class of position (0 even-even, 1 odd-odd, 2 others).</summary>
private static readonly int[,] Quant =
{
{ 13107, 5243, 8066 }, { 11916, 4660, 7490 }, { 10082, 4194, 6554 }, { 9362, 3647, 5825 }, { 8192, 3355, 5243 }, { 7282, 2893, 4559 },
};
/// <summary>A<sub>ij</sub> of §8.6.1 by class of position.</summary>
private static readonly int[] Norm = [16, 25, 20];
/// <summary>The class of each raster position of a 4×4 block (0 even row and column, 1 both odd, 2 the others).</summary>
private static readonly byte[] Class = [0, 2, 0, 2, 2, 1, 2, 1, 0, 2, 0, 2, 2, 1, 2, 1];
/// <summary>
/// A luma 4×4 block: the prediction at <paramref name="o"/> is replaced by the reconstruction from it and the levels
/// (raster order, not scaled). <paramref name="levelInQs"/> is set for SI macroblocks and for SP slices with
/// sp_for_switch_flag: the levels are then added to the quantised prediction (§8.6.2) instead of the scaled ones to the
/// transformed prediction (§8.6.1).
/// </summary>
internal static void Luma4x4(byte[] plane, int o, int stride, ReadOnlySpan<int> levels, int qp, int qs, bool levelInQs)
{
Span<int> c = stackalloc int[16];
Forward(plane, o, stride, c);
int qpMod = qp % 6, qpDiv = qp / 6, qsMod = qs % 6, qsDiv = qs / 6;
for (var pos = 0; pos < 16; pos++)
{
var cls = Class[pos];
var level = Requantise(c[pos], levels[pos], cls, qpMod, qpDiv, qsMod, qsDiv, levelInQs, dc: false);
c[pos] = (level * H264Tables.NormAdjust4x4[qsMod, cls]) << qsDiv;
}
Store4x4(c, plane, o, stride);
}
/// <summary>
/// One chroma component (four 4×4 blocks): <paramref name="ac"/> holds the AC levels of the four blocks (block × 16
/// + raster position; position 0 is ignored), <paramref name="dc"/> the four DC levels in the order they are parsed.
/// </summary>
internal static void Chroma(byte[] plane, int o, int stride, ReadOnlySpan<int> ac, ReadOnlySpan<int> dc, int qpc, int qsc, bool levelInQs)
{
Span<int> c = stackalloc int[64];
for (var b = 0; b < 4; b++)
{
Forward(plane, BlockOffset(o, stride, b), stride, c.Slice(b * 16, 16));
}
int qpMod = qpc % 6, qpDiv = qpc / 6, qsMod = qsc % 6, qsDiv = qsc / 6;
// The DC terms of the prediction through the 2×2 transform, combined with the levels, back through it (§8.6.1).
int p0 = c[0], p1 = c[16], p2 = c[32], p3 = c[48];
Span<int> q = [p0 + p1 + p2 + p3, p0 - p1 + p2 - p3, p0 + p1 - p2 - p3, p0 - p1 - p2 + p3];
for (var k = 0; k < 4; k++)
{
q[k] = Requantise(q[k], dc[k], 0, qpMod, qpDiv, qsMod, qsDiv, levelInQs, dc: true);
}
int f0 = q[0] + q[1] + q[2] + q[3], f1 = q[0] - q[1] + q[2] - q[3], f2 = q[0] + q[1] - q[2] - q[3], f3 = q[0] - q[1] - q[2] + q[3];
var scaleDc = 16 * H264Tables.NormAdjust4x4[qsMod, 0];
c[0] = ((f0 * scaleDc) << qsDiv) >> 5;
c[16] = ((f1 * scaleDc) << qsDiv) >> 5;
c[32] = ((f2 * scaleDc) << qsDiv) >> 5;
c[48] = ((f3 * scaleDc) << qsDiv) >> 5;
for (var b = 0; b < 4; b++)
{
var block = c.Slice(b * 16, 16);
for (var pos = 1; pos < 16; pos++)
{
var cls = Class[pos];
var level = Requantise(block[pos], ac[(b * 16) + pos], cls, qpMod, qpDiv, qsMod, qsDiv, levelInQs, dc: false);
block[pos] = (level * H264Tables.NormAdjust4x4[qsMod, cls]) << qsDiv;
}
Store4x4(block, plane, BlockOffset(o, stride, b), stride);
}
}
/// <summary>
/// The level in QS of one coefficient from the transformed prediction <paramref name="predicted"/> and the received
/// level: equations 8-401 to 8-404 of §8.6.1 (with QP), or 8-410 to 8-411 of §8.6.2 (in QS). The DC terms of
/// chroma carry one bit more of scaling.
/// </summary>
private static int Requantise(int predicted, int level, int cls, int qpMod, int qpDiv, int qsMod, int qsDiv, bool levelInQs, bool dc)
{
var extra = dc ? 1 : 0;
var shift = 15 + qsDiv + extra;
var round = 1L << (shift - 1);
var quant = Quant[qsMod, cls];
if (levelInQs)
{
var magnitude = (int)(((Math.Abs((long)predicted) * quant) + round) >> shift);
return level + (predicted < 0 ? -magnitude : magnitude);
}
var sum = predicted + ((((long)level * H264Tables.NormAdjust4x4[qpMod, cls] * Norm[cls]) << qpDiv) >> (6 - extra));
var result = (int)Math.Min(((Math.Abs(sum) * quant) + round) >> shift, int.MaxValue / 64);
return sum < 0 ? -result : result;
}
private static int BlockOffset(int o, int stride, int b) => o + ((b >> 1) * 4 * stride) + ((b & 1) * 4);
/// <summary>The forward 4×4 core transform of the samples at <paramref name="o"/> (§8.6.1, c<sup>p</sup>), raster order.</summary>
private static void Forward(byte[] plane, int o, int stride, Span<int> c)
{
for (var i = 0; i < 4; i++)
{
var row = o + (i * stride);
int x0 = plane[row], x1 = plane[row + 1], x2 = plane[row + 2], x3 = plane[row + 3];
int a = x0 + x3, b = x1 + x2, d = x1 - x2, e = x0 - x3;
c[i * 4] = a + b;
c[(i * 4) + 1] = (2 * e) + d;
c[(i * 4) + 2] = a - b;
c[(i * 4) + 3] = e - (2 * d);
}
for (var j = 0; j < 4; j++)
{
int x0 = c[j], x1 = c[4 + j], x2 = c[8 + j], x3 = c[12 + j];
int a = x0 + x3, b = x1 + x2, d = x1 - x2, e = x0 - x3;
c[j] = a + b;
c[4 + j] = (2 * e) + d;
c[8 + j] = a - b;
c[12 + j] = e - (2 * d);
}
}
/// <summary>The inverse 4×4 transform of scaled coefficients (§8.5.12), stored at <paramref name="o"/> in place of the prediction.</summary>
private static void Store4x4(Span<int> d, byte[] plane, int o, int stride)
{
for (var i = 0; i < 4; i++)
{
var r = d.Slice(i * 4, 4);
int e0 = r[0] + r[2], e1 = r[0] - r[2], e2 = (r[1] >> 1) - r[3], e3 = r[1] + (r[3] >> 1);
r[0] = e0 + e3;
r[1] = e1 + e2;
r[2] = e1 - e2;
r[3] = e0 - e3;
}
for (var j = 0; j < 4; j++)
{
int f0 = d[j], f1 = d[4 + j], f2 = d[8 + j], f3 = d[12 + j];
int g0 = f0 + f2, g1 = f0 - f2, g2 = (f1 >> 1) - f3, g3 = f1 + (f3 >> 1);
plane[o + j] = Clip((g0 + g3 + 32) >> 6);
plane[o + stride + j] = Clip((g1 + g2 + 32) >> 6);
plane[o + (2 * stride) + j] = Clip((g1 - g2 + 32) >> 6);
plane[o + (3 * stride) + j] = Clip((g0 - g3 + 32) >> 6);
}
}
private static byte Clip(int v) => (byte)(v < 0 ? 0 : v > 255 ? 255 : v);
}