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

@@ -0,0 +1,383 @@
using Febe.Core.Codecs.H264;
namespace Febe.Tests.Codecs.H264;
/// <summary>
/// Conformance streams rewritten with the tools of the Extended and Baseline profiles that no stream of the ITU-T series
/// uses: the same pictures split into data partitions, with redundant slices, with the slices of each picture in another
/// order. The macroblocks and their bits do not change, so the official reconstruction stays the expected result.
/// </summary>
internal static class StreamRewriter
{
/// <summary>
/// Every non-IDR slice (NAL unit 1) as partitions A, B and C (§7.3.2.8–§7.3.2.10): the decoder reads the original
/// stream and says where the residual of each macroblock lies; A keeps the header and everything else, B the residual
/// of the intra macroblocks, C that of the inter ones. A partition with nothing in it is left out, as are those that
/// <paramref name="keepB"/> and <paramref name="keepC"/> drop. Only CAVLC without constrained intra prediction and
/// without I_PCM: with them the bits would not stay the same (§9.2.1, pcm_alignment_zero_bit).
/// </summary>
internal static byte[] Partition(byte[] stream, bool keepB = true, bool keepC = true)
{
var decoder = new H264Decoder();
var residual = new List<(int Start, int End, bool Intra, bool Pcm)>();
decoder.ResidualRead = (start, end, intra, pcm) => residual.Add((start, end, intra, pcm));
var sequences = new Dictionary<int, Sps>();
var pictures = new Dictionary<int, Pps>();
var output = new List<byte[]>();
var sliceId = 0;
foreach (var unit in Units(stream))
{
var nal = NalUnits.Parse(unit);
Remember(nal, sequences, pictures);
residual.Clear();
decoder.DecodeUnit(unit);
if (nal.Type != 1)
{
output.Add(unit);
continue;
}
var reader = nal.Reader();
var header = SliceHeader.Parse(reader, nal, sequences, pictures, out _, out var pps);
if (pps.Cabac || pps.ConstrainedIntraPred || residual.Exists(r => r.Pcm))
{
throw new InvalidOperationException("Flusso non adatto: CABAC, predizione intra vincolata o I_PCM.");
}
// slice_id: 0 for the first slice of each picture, then one more per slice (the streams are in order).
sliceId = header.FirstMb == 0 ? 0 : sliceId + 1;
var a = new BitWriter();
a.Copy(nal.Rbsp, 8, reader.Position);
a.Ue((uint)sliceId);
var b = PartitionStart(sliceId, pps, header);
var c = PartitionStart(sliceId, pps, header);
var position = reader.Position;
foreach (var (start, end, intra, _) in residual)
{
a.Copy(nal.Rbsp, position, start);
(intra ? b : c).Copy(nal.Rbsp, start, end);
position = end;
}
a.Copy(nal.Rbsp, position, StopBit(nal));
var refIdc = (byte)(nal.RefIdc << 5);
output.Add(Unit((byte)(refIdc | 2), a));
if (keepB && residual.Exists(r => r.Intra))
{
output.Add(Unit((byte)(refIdc | 3), b));
}
if (keepC && residual.Exists(r => !r.Intra))
{
output.Add(Unit((byte)(refIdc | 4), c));
}
}
return Join(output);
}
/// <summary>
/// The same stream with redundant_pic_cnt_present_flag set in every PPS (§7.3.2.2) and, after the slices of each
/// picture, a redundant copy of them (redundant_pic_cnt 1) whose header is the primary one and whose data are random
/// bits: a decoder that decodes a redundant slice cannot give the official reconstruction.
/// </summary>
internal static byte[] AddRedundantSlices(byte[] stream, int seed)
{
var random = new Random(seed);
var sequences = new Dictionary<int, Sps>();
var pictures = new Dictionary<int, Pps>();
var output = new List<byte[]>();
var redundant = new List<byte[]>();
foreach (var unit in Units(stream))
{
var nal = NalUnits.Parse(unit);
var slice = nal.Type is 1 or 5;
var header = slice ? SliceHeader.Parse(nal.Reader(), nal, sequences, pictures, out _, out _) : null;
if (!slice || header!.FirstMb == 0)
{
output.AddRange(redundant);
redundant.Clear();
}
if (nal.Type == 8)
{
Remember(nal, sequences, pictures);
output.Add(SetRedundantFlag(nal));
continue;
}
Remember(nal, sequences, pictures);
if (!slice)
{
output.Add(unit);
continue;
}
var reader = nal.Reader();
SliceHeader.Parse(reader, nal, sequences, pictures, out var sps, out var pps);
var headerEnd = reader.Position;
var insert = RedundantPicCntPosition(nal, sps, pps);
output.Add(WithRedundantPicCnt(nal, insert, headerEnd, pps.Cabac, 0, null));
var garbage = new byte[16 + random.Next(48)];
random.NextBytes(garbage);
redundant.Add(WithRedundantPicCnt(nal, insert, headerEnd, pps.Cabac, 1, garbage));
}
output.AddRange(redundant);
return Join(output);
}
/// <summary>
/// The slices of each picture in reverse order (arbitrary slice order, §7.4.3: Baseline and Extended). A picture ends
/// at a NAL unit that is not a slice or at a slice whose header differs as in §7.4.1.2.4: the source may already send
/// its slices out of order.
/// </summary>
internal static byte[] ReverseSlices(byte[] stream)
{
var sequences = new Dictionary<int, Sps>();
var pictures = new Dictionary<int, Pps>();
var output = new List<byte[]>();
var picture = new List<byte[]>();
var current = "";
foreach (var unit in Units(stream))
{
var nal = NalUnits.Parse(unit);
Remember(nal, sequences, pictures);
var slice = nal.Type is 1 or 5;
var key = "";
if (slice)
{
var h = SliceHeader.Parse(nal.Reader(), nal, sequences, pictures, out _, out _);
key = $"{h.FrameNum} {h.PpsId} {h.Structure} {nal.RefIdc == 0} {nal.Type} {h.IdrPicId} {h.PocLsb} {h.DeltaPocBottom} {h.DeltaPoc0} {h.DeltaPoc1}";
}
if (!slice || key != current)
{
current = key;
picture.Reverse();
output.AddRange(picture);
picture.Clear();
}
if (slice)
{
picture.Add(unit);
}
else
{
output.Add(unit);
}
}
picture.Reverse();
output.AddRange(picture);
return Join(output);
}
/// <summary>The NAL units of an Annex B stream, each with its header and without start code.</summary>
internal static List<byte[]> Units(byte[] stream)
{
var units = new List<byte[]>();
var position = 0;
while (NalUnits.NextAnnexB(stream, ref position, out var range))
{
units.Add(stream[range]);
}
return units;
}
internal static byte[] Join(IEnumerable<byte[]> units)
{
var output = new List<byte>();
foreach (var unit in units)
{
output.AddRange((byte[])[0, 0, 0, 1]);
output.AddRange(unit);
}
return [.. output];
}
private static void Remember(NalUnit nal, Dictionary<int, Sps> sequences, Dictionary<int, Pps> pictures)
{
if (nal.Type == 7)
{
var sps = Sps.Parse(nal.Reader());
sequences[sps.Id] = sps;
}
else if (nal.Type == 8)
{
var pps = Pps.Parse(nal.Reader(), sequences);
pictures[pps.Id] = pps;
}
}
/// <summary>slice_id, then redundant_pic_cnt when the PPS has it (§7.3.2.10).</summary>
private static BitWriter PartitionStart(int sliceId, Pps pps, SliceHeader header)
{
var bits = new BitWriter();
bits.Ue((uint)sliceId);
if (pps.RedundantPicCntPresent)
{
bits.Ue((uint)header.RedundantPicCnt);
}
return bits;
}
private static byte[] Unit(byte header, BitWriter bits)
{
bits.Trailing();
return [header, .. bits.ToArray()];
}
/// <summary>The position of the rbsp_stop_one_bit: the last bit set of the payload.</summary>
private static int StopBit(NalUnit nal)
{
var last = nal.Length - 1;
while (nal.Rbsp[last] == 0)
{
last--;
}
return (last * 8) + 7 - System.Numerics.BitOperations.TrailingZeroCount(nal.Rbsp[last]);
}
/// <summary>Where redundant_pic_cnt goes in a slice header: after the picture order count fields (§7.3.3).</summary>
private static int RedundantPicCntPosition(NalUnit nal, Sps sps, Pps pps)
{
var r = nal.Reader();
r.ReadUe(); // first_mb_in_slice
r.ReadUe(); // slice_type
r.ReadUe(); // pic_parameter_set_id
r.Read(sps.Log2MaxFrameNum);
var field = false;
if (!sps.FrameMbsOnly && (field = r.ReadFlag()))
{
r.ReadFlag(); // bottom_field_flag
}
if (nal.Type == 5)
{
r.ReadUe(); // idr_pic_id
}
if (sps.PocType == 0)
{
r.Read(sps.Log2MaxPocLsb);
if (pps.BottomFieldPicOrderInFramePresent && !field)
{
r.ReadSe();
}
}
else if (sps.PocType == 1 && !sps.DeltaPicOrderAlwaysZero)
{
r.ReadSe();
if (pps.BottomFieldPicOrderInFramePresent && !field)
{
r.ReadSe();
}
}
return r.Position;
}
/// <summary>
/// The slice with redundant_pic_cnt inserted at <paramref name="insert"/>; with <paramref name="garbage"/> its slice
/// data are those bytes instead of the original ones (CABAC data start again at a byte, after cabac_alignment_one_bit).
/// </summary>
private static byte[] WithRedundantPicCnt(NalUnit nal, int insert, int headerEnd, bool cabac, int count, byte[]? garbage)
{
var bits = new BitWriter();
bits.Copy(nal.Rbsp, 8, insert);
bits.Ue((uint)count);
bits.Copy(nal.Rbsp, insert, headerEnd);
if (cabac)
{
bits.AlignWithOnes();
if (garbage is null)
{
bits.Copy(nal.Rbsp, (headerEnd + 7) / 8 * 8, nal.Length * 8);
return [nal.Rbsp[0], .. bits.ToArray()];
}
}
if (garbage is null)
{
bits.Copy(nal.Rbsp, headerEnd, StopBit(nal));
}
else
{
bits.Copy(garbage, 0, garbage.Length * 8);
}
bits.Trailing();
return [nal.Rbsp[0], .. bits.ToArray()];
}
/// <summary>The PPS with redundant_pic_cnt_present_flag set: the fields before it read again (§7.3.2.2).</summary>
private static byte[] SetRedundantFlag(NalUnit nal)
{
var r = nal.Reader();
r.ReadUe(); // pic_parameter_set_id
r.ReadUe(); // seq_parameter_set_id
r.ReadFlag(); // entropy_coding_mode_flag
r.ReadFlag(); // bottom_field_pic_order_in_frame_present_flag
var groups = (int)r.ReadUe() + 1;
if (groups > 1)
{
var type = r.ReadUe();
switch (type)
{
case 0:
for (var i = 0; i < groups; i++)
{
r.ReadUe();
}
break;
case 2:
for (var i = 0; i < 2 * (groups - 1); i++)
{
r.ReadUe();
}
break;
case 3 or 4 or 5:
r.ReadFlag();
r.ReadUe();
break;
case 6:
{
var size = (int)r.ReadUe() + 1;
var bitsPerId = 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)(groups - 1));
r.Skip(size * bitsPerId);
break;
}
}
}
r.ReadUe(); // num_ref_idx_l0_default_active_minus1
r.ReadUe(); // num_ref_idx_l1_default_active_minus1
r.ReadFlag(); // weighted_pred_flag
r.Read(2); // weighted_bipred_idc
r.ReadSe(); // pic_init_qp_minus26
r.ReadSe(); // pic_init_qs_minus26
r.ReadSe(); // chroma_qp_index_offset
r.ReadFlag(); // deblocking_filter_control_present_flag
r.ReadFlag(); // constrained_intra_pred_flag
var flag = r.Position;
if (r.ReadFlag())
{
throw new InvalidOperationException("Il PPS ha già redundant_pic_cnt_present_flag.");
}
var bits = new BitWriter();
bits.Copy(nal.Rbsp, 8, flag);
bits.Bits(1, 1);
bits.Copy(nal.Rbsp, flag + 1, StopBit(nal));
bits.Trailing();
return [nal.Rbsp[0], .. bits.ToArray()];
}
}