Files
Febe/tests/Febe.Tests/Media/H264/StreamRewriter.cs
Alby96andClaude Opus 5.5 cdc3cc11b9 Correzioni dopo la revisione del decodificatore H.264, dei lettori FLV e della CI (#58)
- CI: le due prove MVC di FeaturesStillToDo finivano con «da verificare: …», che
  riepilogo-prove.sh contava come saltate: ogni verifica del ramo sarebbe fallita.
  Ora cominciano con «da fare: », e lo script esenta solo le inconclusive di
  FeaturesStillToDo il cui motivo comincia con «da fare: » subito dopo la cornice
  di MSTest (prima bastava la parola in qualunque punto di qualunque prova).
  PipelineTests prova lo script su .trx con le cornici inglese e italiana;
  processo.md, Sviluppo.md e verifica.yml descrivono la categoria.
- Partizionamento dei dati: una partizione B o C sperduta (partizione A persa)
  sovrascriveva il buffer delle partizioni della slice in attesa. Ora slice_id e
  redundant_pic_cnt si leggono prima di copiare, e contano l'ordine A, B, C.
- MVC: le viste tengono insieme al massimo 2 × MaxDpbMbs di immagini, e il
  decodificatore di una vista nuova si tiene solo dopo il controllo dell'SPS di
  sottoinsieme; Wanted vale per ogni vista.
- FLV: senza durata nei metadati la durata arriva alla fine dell'ultimo
  fotogramma, come per MPEG; «solo audio» solo con una prova vera nella testa
  (un onMetaData grande non fa più scartare un video).
- Flussi di conformità: tolti i 48 readme e schede di terzi (decisione di
  Alberto: nel repository solo flussi e MD5).
- Prove nuove: partizioni A perse, limite delle viste e Wanted in MVC, unità di
  estensione troncate, flussi rovinati 4:2:2, 10 bit, 4:0:0, SVC e MVC.
- Commenti sulla provenienza che citano i file di ricostruzione ufficiali e
  §8.7 invece del decodificatore di riferimento; commento di
  ImportEnvironment.VideoProbe aggiornato; righe nuove in decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 19:30:45 +01:00

449 lines
16 KiB
C#

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>
/// A partitioned stream (<see cref="Partition"/>) with the partition A of some slices lost: of every other slice
/// whose partitions B or C come right after those of the slice before, when that slice is still waiting for nothing
/// a decoder could take them for (a slice_id of its own, or the slice before already has both B and C). With
/// <paramref name="alsoBAndC"/> the whole slice is lost instead, its B and C with it. <paramref name="dropped"/> is the
/// number of slices that lost their partition A.
/// </summary>
internal static byte[] DropPartitionsA(byte[] partitioned, bool alsoBAndC, out int dropped)
{
var units = Units(partitioned);
var output = new List<byte[]>();
dropped = 0;
var candidates = 0;
(int Start, int End)? previous = null;
var i = 0;
while (i < units.Count)
{
if ((units[i][0] & 0x1F) != 2)
{
output.Add(units[i]);
previous = null;
i++;
continue;
}
var end = i + 1;
while (end < units.Count && (units[end][0] & 0x1F) is 3 or 4)
{
end++;
}
var drop = false;
if (previous is { } before && end > i + 1 && end - i - 1 <= 2)
{
var full = before.End - before.Start == 3;
var id = SliceIdOf(units[i + 1]);
var beforeId = before.End > before.Start + 1 ? SliceIdOf(units[before.Start + 1]) : id;
drop = (full || id != beforeId) && candidates++ % 2 == 0;
}
if (drop)
{
dropped++;
if (!alsoBAndC)
{
output.AddRange(units.GetRange(i + 1, end - i - 1));
}
}
else
{
output.AddRange(units.GetRange(i, end - i));
}
// A slice that lost its partition A is no slice the next one can follow: the decoder still waits for the
// one before it.
previous = drop ? null : (i, end);
i = end;
}
return Join(output);
}
/// <summary>slice_id, the first syntax element of a partition B or C.</summary>
private static int SliceIdOf(byte[] unit) => NalUnits.Parse(unit).Reader().ReadUe(Sps.MaxFrameMbs - 1);
/// <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()];
}
}