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

+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);