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

+92
View File
@@ -0,0 +1,92 @@
namespace Febe.Tests.Codecs.H264;
/// <summary>The bits of an RBSP written one by one (§7.2): fixed-length fields, Exp-Golomb codes, bits copied from another RBSP.</summary>
internal sealed class BitWriter
{
private readonly List<bool> bits = [];
/// <summary>Bits written so far.</summary>
public int Count => bits.Count;
public void Bits(uint value, int count)
{
for (var i = count - 1; i >= 0; i--)
{
bits.Add(((value >> i) & 1) != 0);
}
}
public void Ue(uint value)
{
var code = value + 1;
var length = 32 - System.Numerics.BitOperations.LeadingZeroCount(code);
Bits(0, length - 1);
Bits(code, length);
}
public void Se(int value) => Ue(value <= 0 ? (uint)(-2 * value) : (uint)((2 * value) - 1));
/// <summary>Zero bits up to the next byte.</summary>
public void Align()
{
while (bits.Count % 8 != 0)
{
bits.Add(false);
}
}
/// <summary>One bits up to the next byte (cabac_alignment_one_bit).</summary>
public void AlignWithOnes()
{
while (bits.Count % 8 != 0)
{
bits.Add(true);
}
}
/// <summary>Bits <paramref name="from"/> (included) to <paramref name="to"/> (excluded) of <paramref name="data"/>, most significant first.</summary>
public void Copy(byte[] data, int from, int to)
{
for (var i = from; i < to; i++)
{
bits.Add(((data[i >> 3] >> (7 - (i & 7))) & 1) != 0);
}
}
/// <summary>rbsp_trailing_bits(): the stop bit and zeros up to the byte.</summary>
public void Trailing()
{
bits.Add(true);
Align();
}
/// <summary>The bytes, padded with zeros to the byte, with emulation prevention (§7.4.1).</summary>
public byte[] ToArray()
{
var bytes = new byte[(bits.Count + 7) / 8];
for (var i = 0; i < bits.Count; i++)
{
if (bits[i])
{
bytes[i / 8] |= (byte)(0x80 >> (i % 8));
}
}
// Emulation prevention (§7.4.1): never two zero bytes followed by a byte up to 3.
var output = new List<byte>(bytes.Length + 16);
var zeros = 0;
foreach (var b in bytes)
{
if (zeros >= 2 && b <= 3)
{
output.Add(3);
zeros = 0;
}
output.Add(b);
zeros = b == 0 ? zeros + 1 : 0;
}
return [.. output];
}
}
@@ -80,8 +80,31 @@ rimasto senza il suo compagno esce da solo, con le righe dell'altro campo grigie
| `MR6_BT_B` | Extended, 192×128, 60 | campi, CAVLC, POC di tipo 1, MMCO, riordino, numero di slice variabile |
| `MR9_BT_B` | Main, 192×128, 58 | MBAFF e PAFF, CABAC, slice B, POC di tipo 1, MMCO, riordino |
Strumenti di Baseline ed Extended, QCIF 4:2:0 a 8 bit:
| Flusso | Profilo, formato | Che cosa prova |
|---|---|---|
| `FM2_SVA_C` | Baseline, 17 | FMO con 3 gruppi di slice di tipo 0, ASO, POC di tipo 1 |
| `FM1_FT_E` | Baseline, 300 | FMO di tipo 1, 2, 3 e 4 che cambiano lungo il flusso (11 PPS), POC di tipo 2, SEI di recupero graduale |
| `FM1_BT_B` | Baseline, 400 | FMO di tutti i tipi da 0 a 6, ASO (lo zip non ha `readme`) |
| `sp1_bt_a` | Extended, 400 | slice SP (39 immagini) con QS diverso da QP e deblocking spento, POC di tipo 1 (lo zip non ha `readme`) |
| `sp2_bt_b` | Extended, 400 | slice SP con deblocking attivo (lo zip non ha `readme`) |
Nessuno di questi flussi usa la predizione pesata, i salti di `frame_num` o gli I_PCM: quelle parti del decodificatore
non hanno qui un riferimento ufficiale.
non hanno qui un riferimento ufficiale. Le slice SP dei due flussi hanno tutte `sp_for_switch_flag` a 0.
Per gli strumenti che nessun flusso della serie usa, `H264ExtendedToolsTests` riscrive flussi verificati con
`StreamRewriter`, lasciando intatti i bit dei macroblocchi, e chiede di nuovo il riferimento ufficiale:
- **partizionamento dei dati**: ogni slice P, B, SP o I non IDR divisa nelle partizioni A, B e C (`BA3_SVA_C`,
`sp1_bt_a`, `FM1_FT_E`, `MR6_BT_B`, `CVMAQP3_Sony_D`, `SVA_BA1_B`); senza B o senza C il flusso si decodifica ancora,
senza il residuo che mancava;
- **slice ridondanti**: dopo ogni immagine una copia ridondante con dati a caso, che il decodificatore deve saltare
(CAVLC, CABAC, campi, MBAFF, FMO, SP, e anche partizionate);
- **ASO**: le slice di ogni immagine in ordine inverso (`BASQP1_Sony_C`, `FM1_FT_E`, `CAMASL3_Sony_B`).
Le slice SI e `sp_for_switch_flag` a 1 non hanno flussi: le prova un flusso sintetico di
`H264SyntheticStreamTests`, con i valori calcolati a mano dalle equazioni di §8.6.2.
`H264ConformanceTests.SvcBaseLayerMatchesTheReference`: lo strato base dei tre flussi SVC qui sotto, con
`riferimento-base.md5`.
@@ -93,16 +116,6 @@ e MVC, dà solo lo strato o la vista base), e la prova è **inconclusiva** con i
resta verde e il vuoto si vede. Quando una di queste coincide con il riferimento la prova **fallisce** apposta, per
ricordare di spostarla fra i flussi verificati.
**Strumenti di Baseline ed Extended**, QCIF 4:2:0 a 8 bit:
| Flusso | Profilo, formato | Che cosa prova |
|---|---|---|
| `FM2_SVA_C` | Baseline, 17 | FMO con 3 gruppi di slice di tipo 0, ASO, POC di tipo 1 |
| `FM1_FT_E` | Baseline, 300 | FMO di tipo 1, 2, 3 e 4 che cambiano lungo il flusso (11 PPS), POC di tipo 2, SEI di recupero graduale |
| `FM1_BT_B` | Baseline, 400 | FMO di tutti i tipi da 0 a 6, ASO (lo zip non ha `readme`) |
| `sp1_bt_a` | Extended, 400 | slice SP (39 immagini), POC di tipo 1 (lo zip non ha `readme`) |
| `sp2_bt_b` | Extended, 400 | slice SP (lo zip non ha `readme`) |
**4:2:2, 8 e 10 bit** (High 4:2:2), CIF, 5 fotogrammi ciascuno:
| Flusso | Che cosa prova |
@@ -136,7 +149,7 @@ senza riferimento.
i flussi di tutti gli zip di `AVCv1` e `FRExt` (tranne `FREH10-1` e `FREH10-2`, High 10, profilo che quegli strumenti
non li ammette): nessuna unità NAL di tipo 2, 3 o 4, nessun PPS con
`redundant_pic_cnt_present_flag`, nessuna slice SI. I soli flussi Extended sono `BA3_SVA_C`, `sp1_bt_a`, `sp2_bt_b` e
`MR6_BT_B`, `MR7_BT_B`, `MR8_BT_B`.
`MR6_BT_B`, `MR7_BT_B`, `MR8_BT_B`. Si provano riscrivendo i flussi verificati (vedi sopra).
- **High 10 in 4:2:0**: `FREH10-1` e `FREH10-2` (1920×1088, flussi da 98 e 34 MB) e `PPH10I1`–`PPH10I7` (High 10 Intra)
non hanno la ricostruzione. I 10 bit si provano con `Hi422FR13`–`Hi422FR15`.
- **High 4:2:2 Intra e altri 4:2:2**: `PPH422I1`–`PPH422I7`, `Hi422FR1`–`Hi422FR9` e `Hi422FREXT16`–`Hi422FREXT19` non
@@ -8,12 +8,15 @@ namespace Febe.Tests.Codecs.H264;
/// The decoder against streams of the ITU-T H.264.1 conformance suite: every output frame, in output order, must have the
/// MD5 of the corresponding frame of the official reconstruction (see Conformita/LEGGIMI.md). The verified streams include
/// interlaced video — field pictures, PAFF, MBAFF, both together — with memory management operations, long-term
/// references and POC type 1 on fields (MR6_BT_B, MR9_BT_B). None of them uses weighted prediction, gaps in frame_num or
/// I_PCM: those parts of the decoder have no reference MD5 here (some are reached by <see cref="H264SyntheticStreamTests"/>,
/// without an official reference). The streams of the parts the decoder does not handle yet (FMO and ASO, SP slices,
/// 4:2:2, more than 8 bits, 4:0:0, SVC, MVC) are in
/// <see cref="FeaturesStillToDo"/>: they are inconclusive until the feature is written, and fail as soon as one of them
/// matches its reference without having been moved among the verified ones.
/// references and POC type 1 on fields (MR6_BT_B, MR9_BT_B), slice groups of every map type with slices in any order
/// (FM1_BT_B, FM1_FT_E, FM2_SVA_C) and SP slices (sp1_bt_a, sp2_bt_b; sp2 with the deblocking filter on). None of them
/// uses weighted prediction, gaps in frame_num, I_PCM, SI slices, sp_for_switch_flag, data partitioning or redundant
/// slices: data partitioning, redundant slices and other slice orders are checked on conformance streams rewritten by
/// <see cref="StreamRewriter"/> (<see cref="H264ExtendedToolsTests"/>), SI slices and the rest by
/// <see cref="H264SyntheticStreamTests"/>, without an official reference. The streams of the parts the decoder does not
/// handle yet (4:2:2, more than 8 bits, 4:0:0, SVC, MVC) are in <see cref="FeaturesStillToDo"/>: they are inconclusive
/// until the feature is written, and fail as soon as one of them matches its reference without having been moved among
/// the verified ones.
/// </summary>
[TestClass]
public sealed class H264ConformanceTests
@@ -48,6 +51,11 @@ public sealed class H264ConformanceTests
[DataRow("FRExt4_Panasonic_B")]
[DataRow("MR6_BT_B")]
[DataRow("MR9_BT_B")]
[DataRow("FM2_SVA_C")]
[DataRow("FM1_FT_E")]
[DataRow("FM1_BT_B")]
[DataRow("sp1_bt_a")]
[DataRow("sp2_bt_b")]
public void FramesMatchTheReference(string name) => AssertMatches(name, "riferimento.md5");
[TestMethod]
@@ -62,11 +70,6 @@ public sealed class H264ConformanceTests
}
[TestMethod]
[DataRow("FM2_SVA_C", "FMO (gruppi di slice di tipo 0) e ASO")]
[DataRow("FM1_FT_E", "FMO (gruppi di slice di tipo 1, 2, 3 e 4)")]
[DataRow("FM1_BT_B", "FMO (gruppi di slice di tipo 0-6) e ASO")]
[DataRow("sp1_bt_a", "slice SP (Extended)")]
[DataRow("sp2_bt_b", "slice SP (Extended)")]
[DataRow("Hi422FR10_SONY_A", "4:2:2 a 8 bit, solo slice I (CABAC)")]
[DataRow("Hi422FR11_SONY_A", "4:2:2 a 8 bit con slice P (CABAC)")]
[DataRow("Hi422FR12_SONY_A", "4:2:2 a 8 bit con slice B (CABAC)")]
@@ -162,7 +165,14 @@ public sealed class H264ConformanceTests
internal static string StreamFile(string folder) =>
Directory.EnumerateFiles(folder).Single(f => Path.GetExtension(f).ToLowerInvariant() is ".264" or ".jsv" or ".avc" or ".h264" or ".jvt");
private static void AssertMatches(string name, string reference)
private static void AssertMatches(string name, string reference) =>
AssertStreamMatches(name, File.ReadAllBytes(StreamFile(Folder(name))), reference);
/// <summary>
/// <paramref name="stream"/> (the conformance stream <paramref name="name"/>, possibly rewritten) must give every frame
/// of the official reconstruction.
/// </summary>
internal static void AssertStreamMatches(string name, byte[] stream, string reference = "riferimento.md5")
{
var folder = Folder(name);
var expected = ReadReference(Path.Combine(folder, reference), out var declared);
@@ -171,7 +181,7 @@ public sealed class H264ConformanceTests
var frames = new List<H264Frame>();
var decoder = new H264Decoder();
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(File.ReadAllBytes(StreamFile(folder)));
decoder.DecodeAnnexB(stream);
var ordered = OutputOrder(frames);
var actual = ordered.Select(Md5).ToList();
@@ -187,6 +197,19 @@ public sealed class H264ConformanceTests
Assert.AreEqual(expected.Count, actual.Count, $"{name}: numero di fotogrammi");
}
/// <summary>The frame MD5s of a riferimento.md5, in output order.</summary>
internal static List<string> ReferenceFrames(string name) => ReadReference(Path.Combine(Folder(name), "riferimento.md5"), out _);
/// <summary>The MD5 of each frame of a stream, in output order.</summary>
internal static List<string> FrameMd5s(byte[] stream)
{
var frames = new List<H264Frame>();
var decoder = new H264Decoder();
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(stream);
return OutputOrder(frames).Select(Md5).ToList();
}
private static List<string> Decode(string stream)
{
var frames = new List<H264Frame>();
@@ -0,0 +1,93 @@
using Febe.Core.Codecs.H264;
namespace Febe.Tests.Codecs.H264;
/// <summary>
/// Tools of the Baseline and Extended profiles that no stream of the ITU-T series uses — slice data partitioning,
/// redundant slices — and slices in another order than the one of the series, on conformance streams rewritten by
/// <see cref="StreamRewriter"/>: the macroblocks keep their bits, so every frame must still be the official one.
/// </summary>
[TestClass]
public sealed class H264ExtendedToolsTests
{
[TestMethod]
[DataRow("BA3_SVA_C")] // Extended, B slices
[DataRow("sp1_bt_a")] // SP slices
[DataRow("FM1_FT_E")] // slice groups of types 1–4
[DataRow("MR6_BT_B")] // Extended, field pictures
[DataRow("CVMAQP3_Sony_D")] // MBAFF
[DataRow("SVA_BA1_B")] // non-IDR I slices: residual in partition B only
public void DataPartitionsGiveTheOfficialFrames(string name)
{
var stream = StreamRewriter.Partition(Original(name));
var types = NalTypes(stream);
Assert.IsFalse(types.Contains(1), "restano slice non partizionate");
Assert.IsTrue(types.Contains(2), "manca la partizione A");
Assert.IsTrue(types.Contains(3) || types.Contains(4), "mancano le partizioni B e C");
H264ConformanceTests.AssertStreamMatches(name, stream);
}
[TestMethod]
[DataRow(false, true)]
[DataRow(true, false)]
[DataRow(false, false)]
public void MissingPartitionsLeaveTheirResidualOut(bool keepB, bool keepC)
{
// Without partition B or C a slice still decodes, without the residual of its intra or inter macroblocks: every
// picture comes out, and the IDR picture (never partitioned) is still the official one.
var name = "BA3_SVA_C";
var complete = H264ConformanceTests.FrameMd5s(StreamRewriter.Partition(Original(name)));
var partial = H264ConformanceTests.FrameMd5s(StreamRewriter.Partition(Original(name), keepB, keepC));
var expected = H264ConformanceTests.ReferenceFrames(name);
Assert.HasCount(expected.Count, partial);
Assert.AreEqual(expected[0], partial[0], "l'immagine IDR");
Assert.IsTrue(partial.Where((md5, i) => md5 != complete[i]).Any(), "togliere una partizione cambia qualcosa");
}
[TestMethod]
[DataRow("BA3_SVA_C", 4101)] // CAVLC
[DataRow("CABA3_SVA_B", 4102)] // CABAC
[DataRow("MR6_BT_B", 4103)] // fields, POC type 1
[DataRow("CAPAMA3_Sand_F", 4104)] // CABAC, MBAFF and fields
[DataRow("FM1_FT_E", 4105)] // slice groups, several PPS
[DataRow("sp1_bt_a", 4106)] // SP slices
public void RedundantSlicesAreSkipped(string name, int seed)
{
var stream = StreamRewriter.AddRedundantSlices(Original(name), seed);
Assert.IsGreaterThan(Original(name).Length, stream.Length);
H264ConformanceTests.AssertStreamMatches(name, stream);
}
[TestMethod]
public void RedundantSlicesAreSkippedAlsoWhenPartitioned()
{
// The redundant slices become partitions A (header and random bits) with slice_id and redundant_pic_cnt.
var name = "BA3_SVA_C";
H264ConformanceTests.AssertStreamMatches(name, StreamRewriter.Partition(StreamRewriter.AddRedundantSlices(Original(name), 4107)));
}
[TestMethod]
[DataRow("BASQP1_Sony_C")] // twenty slices per picture
[DataRow("FM1_FT_E")] // slice groups
[DataRow("CAMASL3_Sony_B")] // CABAC, MBAFF, four slices per picture
public void SlicesInReverseOrderGiveTheOfficialFrames(string name)
{
var original = Original(name);
var stream = StreamRewriter.ReverseSlices(original);
CollectionAssert.AreNotEqual(original, stream, "il flusso ha più slice per immagine");
H264ConformanceTests.AssertStreamMatches(name, stream);
}
[TestMethod]
[DataRow("FM1_FT_E", 4201)]
[DataRow("sp2_bt_b", 4202)]
[DataRow("BA3_SVA_C", 4203)]
public void DamagedPartitionedStreamsGiveFramesOrAnH264Exception(string name, int seed)
{
H264RobustnessTests.AssertDamagedCopiesDecode(name, StreamRewriter.Partition(Original(name)), seed, trials: 30);
}
private static byte[] Original(string name) => File.ReadAllBytes(H264ConformanceTests.StreamFile(H264ConformanceTests.Folder(name)));
private static HashSet<int> NalTypes(byte[] stream) => StreamRewriter.Units(stream).Select(u => u[0] & 0x1F).ToHashSet();
}
@@ -29,11 +29,22 @@ public sealed class H264RobustnessTests
[DataRow("MR6_BT_B", 2657)]
[DataRow("MR9_BT_B", 2658)]
[DataRow("CAPAMA3_Sand_F", 2659)]
public void DamagedStreamsGiveFramesOrAnH264Exception(string name, int seed)
[DataRow("FM2_SVA_C", 2660)]
[DataRow("FM1_FT_E", 2661)]
[DataRow("FM1_BT_B", 2662)]
[DataRow("sp1_bt_a", 2663)]
[DataRow("sp2_bt_b", 2664)]
public void DamagedStreamsGiveFramesOrAnH264Exception(string name, int seed) =>
AssertDamagedCopiesDecode(name, File.ReadAllBytes(H264ConformanceTests.StreamFile(H264ConformanceTests.Folder(name))), seed, trials: 60);
/// <summary>
/// Copies of <paramref name="data"/> with a few bytes changed (and some cut short), from a fixed seed: each must give
/// frames or an <see cref="H264Exception"/>, never another exception.
/// </summary>
internal static void AssertDamagedCopiesDecode(string name, byte[] data, int seed, int trials)
{
var data = File.ReadAllBytes(H264ConformanceTests.StreamFile(H264ConformanceTests.Folder(name)));
var random = new Random(seed);
for (var trial = 0; trial < 60; trial++)
for (var trial = 0; trial < trials; trial++)
{
var copy = (byte[])data.Clone();
var changes = 1 + random.Next(20);
@@ -49,6 +49,38 @@ public sealed class H264SyntheticStreamTests
Assert.IsTrue(frames[0].Y.All(v => v == 100), "il fotogramma è quello primario");
}
[TestMethod]
[DataRow(0, 127, 49, 128)]
[DataRow(12, 130, 52, 126)]
public void AnSiPictureIsRebuiltInQs(int qsDelta, int first, int third, int chroma)
{
// Three macroblocks: SI, I_PCM (luma 50), SI; the SI ones without residual, every block predicted in DC mode. Each
// 4×4 block of an SI macroblock is its prediction transformed, quantised in QS and decoded in QS (§8.6.2), so a
// flat block of 128 comes back as 127 with QS 26 (DC 2048 → level 39 → 8112 → 127) and as 130 with QS 38; next to
// the I_PCM samples (50) the blocks give 49 and 52. Chroma: the DC of the four blocks through the 2×2 transform
// (8192 → level 79 with QSc 26, 28 with QSc 35), back to 128 and 126. Worked out by hand from the equations.
var s = new SequenceSettings(WidthInMbs: 3);
var frames = Decode([.. Sps(s), .. Pps(), .. SiIdr(s, qsDelta, pcm: [1], pcmLuma: 50)]);
Assert.HasCount(1, frames);
var f = frames[0];
for (var y = 0; y < 16; y++)
{
for (var x = 0; x < 48; x++)
{
var expected = x < 16 ? first : x < 32 ? 50 : third;
Assert.AreEqual(expected, f.Y[(y * 48) + x], $"luma ({x}, {y})");
}
}
for (var i = 0; i < f.Cb.Length; i++)
{
var x = i % 24;
var expected = x is >= 8 and < 16 ? 128 : chroma;
Assert.AreEqual(expected, f.Cb[i], $"Cb {i}");
Assert.AreEqual(expected, f.Cr[i], $"Cr {i}");
}
}
[TestMethod]
public void APSliceWithNothingToPredictFromIsRefused()
{
@@ -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()];
}
}
+55 -60
View File
@@ -148,69 +148,64 @@ internal static class SyntheticStreams
return Nal(reference ? (byte)0x41 : (byte)0x01, bits);
}
/// <summary>
/// An IDR picture of one SI slice (§7.3.3, §7.3.5) with QS = 26 + <paramref name="qsDelta"/>: every macroblock is an SI
/// macroblock without residual (Intra_4x4, every block with the predicted mode, chroma DC), except those listed in
/// <paramref name="pcm"/>, which are I_PCM (mb_type 26 in an SI slice) with luma <paramref name="pcmLuma"/> and chroma 128.
/// </summary>
internal static byte[] SiIdr(SequenceSettings s, int qsDelta, int[] pcm, byte pcmLuma)
{
var bits = new BitWriter();
bits.Ue(0); // first_mb_in_slice
bits.Ue(9); // slice_type: SI (all slices of the picture)
bits.Ue(0); // pic_parameter_set_id
bits.Bits(0, s.Log2MaxFrameNum); // frame_num
bits.Ue(0); // idr_pic_id
if (s.PocType == 0)
{
bits.Bits(0, 8); // pic_order_cnt_lsb
}
bits.Bits(0, 1); // no_output_of_prior_pics_flag
bits.Bits(0, 1); // long_term_reference_flag
bits.Se(0); // slice_qp_delta
bits.Se(qsDelta); // slice_qs_delta
bits.Ue(1); // disable_deblocking_filter_idc: off
for (var m = 0; m < s.WidthInMbs * s.HeightInMbs; m++)
{
if (Array.IndexOf(pcm, m) >= 0)
{
bits.Ue(26); // mb_type: I_PCM (25 + 1 in an SI slice)
bits.Align(); // pcm_alignment_zero_bit
for (var i = 0; i < 256; i++)
{
bits.Bits(pcmLuma, 8);
}
for (var i = 0; i < 128; i++)
{
bits.Bits(128, 8);
}
continue;
}
bits.Ue(0); // mb_type: SI
for (var i = 0; i < 16; i++)
{
bits.Bits(1, 1); // prev_intra4x4_pred_mode_flag
}
bits.Ue(0); // intra_chroma_pred_mode: DC
bits.Ue(3); // coded_block_pattern: codeNum 3 is 0 for intra prediction modes (table 9-4)
}
return Nal(0x65, bits);
}
private static byte[] Nal(byte header, BitWriter bits)
{
bits.Bits(1, 1); // rbsp_stop_one_bit
return [0, 0, 0, 1, header, .. bits.ToArray()];
}
private sealed class BitWriter
{
private readonly List<bool> bits = [];
public void Bits(uint value, int count)
{
for (var i = count - 1; i >= 0; i--)
{
bits.Add(((value >> i) & 1) != 0);
}
}
public void Ue(uint value)
{
var code = value + 1;
var length = 32 - System.Numerics.BitOperations.LeadingZeroCount(code);
Bits(0, length - 1);
Bits(code, length);
}
public void Se(int value) => Ue(value <= 0 ? (uint)(-2 * value) : (uint)((2 * value) - 1));
public void Align()
{
while (bits.Count % 8 != 0)
{
bits.Add(false);
}
}
public byte[] ToArray()
{
var bytes = new byte[(bits.Count + 7) / 8];
for (var i = 0; i < bits.Count; i++)
{
if (bits[i])
{
bytes[i / 8] |= (byte)(0x80 >> (i % 8));
}
}
// Emulation prevention (§7.4.1): never two zero bytes followed by a byte up to 3.
var output = new List<byte>();
var zeros = 0;
foreach (var b in bytes)
{
if (zeros >= 2 && b <= 3)
{
output.Add(3);
zeros = 0;
}
output.Add(b);
zeros = b == 0 ? zeros + 1 : 0;
}
return [.. output];
}
}
}