Fotogrammi e contenitori più robusti dopo la revisione: punto di partenza vero, limiti di tempo e di riferimenti, file rovinati tollerati (#58)
Corregge i difetti confermati dalla revisione del decodificatore H.264 e dei lettori di contenitori. - Fotogrammi: un AVI senza idx1 (o OpenDML oltre il primo GB) segna ogni campione come chiave; ora si parte dall'immagine IDR più vicina (entro 300 campioni), altrimenti da un'immagine di slice I o dal primo campione. Oltre 300 campioni vale il fotogramma del punto di partenza; ogni chiamata ha al più 30 secondi, come l'estrattore con ffmpeg che sostituisce. - H.264: una slice P/B senza riferimenti è un errore invece di una predizione da sé stessa; SPS con riferimenti oltre MaxDpbMbs del livello 6.2 rifiutato (1,4 GB da pochi byte); FrameNumOffset dei fotogrammi mancanti di un salto di frame_num; immagini ridondanti saltate e inizio d'immagine secondo §7.4.1.2.4; immagini non di riferimento non chieste non ricostruite; CABAC con finestra di 64 bit; unità NAL in un solo buffer. Il sommario non dice più verificato ciò che nessun MD5 verifica. - Matroska: un blocco rovinato o troncato ferma la lettura e i blocchi letti restano; scala dei tempi esatta per ogni TimecodeScale. - MP4: una traccia con tkhd/elst/mdhd/hdlr/esds rovinati si scarta senza perdere le altre; esds con limiti controllati; nei soli metadati niente copie delle tabelle né campioni dei frammenti. - AVI: durata impossibile ignota senza perdere la data. - Sonda dei metadati davvero asincrona, annullabile fra i frammenti. - Prove nuove: flussi H.264 sintetici scritti bit per bit (salto di frame_num, immagine ridondante, P senza riferimenti, immagini saltate, SPS enormi con PPS e slice), AVI senza indice, blocchi Matroska rovinati, audio MP4 rovinato, durata AVI, TimecodeScale di 3 ms, trun sotto il limite ma oltre il file, limite di run e di tempo, i due MP4 x264 del sito di prova, ffmpeg/ffprobe fuori dal Dockerfile. Provate contro il codice senza le correzioni: falliscono tutte. - decisioni.md: quattro righe del 18 novembre. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
479c95f899
commit
b23632fc96
22 files changed
+1273
-282
No files matched your search
@@ -230,6 +230,23 @@ public sealed class ContainerTests
|
||||
Assert.AreEqual(2020, meta!.CreatedAt!.Value.Year);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(3_000_000u)]
|
||||
[DataRow(1_000_000u)]
|
||||
[DataRow(2_500_000u)]
|
||||
public void MatroskaTimesStayExactWithAnyTimecodeScale(uint timecodeScale)
|
||||
{
|
||||
// A TimecodeScale that does not divide a second (3 ms): the timescale of the track must not be rounded down
|
||||
// (333 ticks a second instead of 333.3), or every time drifts by 0.1% and disagrees with the duration.
|
||||
var es = ElementaryStream.Load("CI_MW_D");
|
||||
var container = Read(TestVideos.Matroska(es, timecodeScale: timecodeScale));
|
||||
var video = container.Video!;
|
||||
var tick = timecodeScale / 1e9;
|
||||
Assert.AreEqual(container.Duration!.Value.TotalSeconds, video.Seconds(video.Duration), 1.0 / video.Timescale, "durata della traccia e del file");
|
||||
var span = video.Samples.Max(s => s.PresentationTime) - video.Samples.Min(s => s.PresentationTime);
|
||||
Assert.AreEqual((es.Count - 1) / 30.0, video.Seconds(span), tick, "dal primo all'ultimo fotogramma");
|
||||
}
|
||||
|
||||
private static MediaContainer Read(byte[] file)
|
||||
{
|
||||
using var stream = new MemoryStream(file);
|
||||
|
||||
@@ -85,14 +85,91 @@ public sealed class MalformedInputTests
|
||||
Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati");
|
||||
Assert.IsEmpty(container!.Video!.Samples, "una tabella impossibile non dà campioni");
|
||||
|
||||
// A trun of two billion samples without per-sample fields.
|
||||
// A trun of almost two million samples without per-sample fields: under the sample limit, but far more than the
|
||||
// file can hold (the trex default size is 0, so each would take at least a byte). That fragment gives nothing,
|
||||
// the others give their samples.
|
||||
var fragmented = TestVideos.FragmentedMp4(es, perFragment: 5);
|
||||
var trun = IndexOf(fragmented, "trun"u8);
|
||||
BinaryPrimitives.WriteUInt32BigEndian(fragmented.AsSpan(trun + 4), 0x000001); // only data_offset
|
||||
BinaryPrimitives.WriteUInt32BigEndian(fragmented.AsSpan(trun + 8), int.MaxValue);
|
||||
BinaryPrimitives.WriteUInt32BigEndian(fragmented.AsSpan(trun + 8), 1_999_999);
|
||||
container = ReadMeasured(fragmented, out allocated);
|
||||
Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati");
|
||||
Assert.IsNotNull(container);
|
||||
Assert.HasCount(es.Count - 5, container!.Video!.Samples, "nessun campione inventato");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AMatroskaFileWithADamagedOrTruncatedBlockKeepsTheBlocksBefore()
|
||||
{
|
||||
var es = ElementaryStream.Load("CI_MW_D");
|
||||
var file = TestVideos.Matroska(es);
|
||||
using var temp = new TempFolder("matroska-rovinato");
|
||||
var intact = await VideoFrameDecoder.Instance.DecodeFrameAsync(TestVideos.Write(temp, "intero.mkv", file), TimeSpan.FromSeconds(1));
|
||||
Assert.IsNotNull(intact);
|
||||
|
||||
// The blocks close the file: each is the ID, an eight-byte size, track, time, flags and the sample.
|
||||
int StartOf(int block) => file.Length - Enumerable.Range(block, es.Count - block).Sum(i => 1 + 8 + 4 + es.LengthPrefixed(i).Length);
|
||||
|
||||
// Cut inside the fixed part of the last block.
|
||||
var truncated = file[..(StartOf(es.Count - 1) + 1 + 8 + 2)];
|
||||
Assert.HasCount(es.Count - 1, ReadMeasured(truncated, out _)!.Video!.Samples);
|
||||
|
||||
// Block 50 says it holds nothing but its own header: the blocks before it stand, the frame at one second too.
|
||||
var damaged = (byte[])file.Clone();
|
||||
var block = StartOf(50);
|
||||
Assert.AreEqual(0xA3, damaged[block]);
|
||||
damaged.AsSpan(block + 2, 7).Clear();
|
||||
damaged[block + 8] = 4;
|
||||
Assert.HasCount(50, ReadMeasured(damaged, out _)!.Video!.Samples);
|
||||
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(TestVideos.Write(temp, "rovinato.mkv", damaged), TimeSpan.FromSeconds(1));
|
||||
CollectionAssert.AreEqual(intact.Rgb, image!.Rgb);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ADamagedAudioTrackDoesNotCostTheVideo()
|
||||
{
|
||||
var es = ElementaryStream.Load("CABA3_SVA_B");
|
||||
|
||||
// The descriptors of the audio esds run to its very end: the ES_Descriptor starts at its last two bytes.
|
||||
var file = TestVideos.Mp4(es, audio: true);
|
||||
var esds = IndexOf(file, "esds"u8);
|
||||
var length = (int)BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(esds - 4)) - 8;
|
||||
var body = file.AsSpan(esds + 4, length);
|
||||
body[4..].Clear();
|
||||
body[4] = 0x7F; // an unknown descriptor that covers the body...
|
||||
body[5] = (byte)(length - 8);
|
||||
body[length - 2] = 0x03; // ...up to an ES_Descriptor with no room for its fields
|
||||
var container = ReadMeasured(file, out _)!;
|
||||
Assert.HasCount(es.Count, container.Video!.Samples);
|
||||
Assert.IsNotNull(container.Audio);
|
||||
Assert.IsNull(container.Audio.AacConfiguration);
|
||||
|
||||
// The audio track header claims version 1, whose fields lie past the end of the box: that track is dropped.
|
||||
file = TestVideos.Mp4(es, audio: true);
|
||||
var audioTkhd = file.AsSpan(IndexOf(file, "tkhd"u8) + 4).IndexOf("tkhd"u8) + IndexOf(file, "tkhd"u8) + 4;
|
||||
file[audioTkhd + 4] = 1;
|
||||
container = ReadMeasured(file, out _)!;
|
||||
Assert.HasCount(es.Count, container.Video!.Samples);
|
||||
Assert.IsNull(container.Audio);
|
||||
using var temp = new TempFolder("audio-rovinato");
|
||||
var metadata = ContainerVideoMetadataProbe.Probe(TestVideos.Write(temp, "video.mp4", file), Now);
|
||||
Assert.AreEqual((es.Width, es.Height), (metadata!.Width, metadata.Height));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AnAviWithAnImpossibleDurationKeepsItsDate()
|
||||
{
|
||||
// One frame per million seconds for a million frames: 10¹² seconds, beyond what a TimeSpan holds.
|
||||
var es = ElementaryStream.Load("BA1_Sony_D");
|
||||
var file = TestVideos.Avi(es, "Thu Mar 04 05:06:07 2021", scale: 1_000_000, rate: 1, length: 1_000_000);
|
||||
var container = ReadMeasured(file, out _)!;
|
||||
Assert.IsNull(container.Duration);
|
||||
Assert.AreEqual(2021, container.CreatedAt!.Value.Year);
|
||||
|
||||
using var temp = new TempFolder("avi-durata");
|
||||
var metadata = ContainerVideoMetadataProbe.Probe(TestVideos.Write(temp, "video.avi", file), Now);
|
||||
Assert.IsNotNull(metadata, "la data scritta nel file non va persa");
|
||||
Assert.AreEqual(2021, metadata.CreatedAt!.Value.Year);
|
||||
Assert.IsNull(metadata.Duration);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -126,6 +126,17 @@ internal sealed class ElementaryStream
|
||||
return new ElementaryStream(Name + "-fermo", units, [.. Enumerable.Range(0, times)], [.. Enumerable.Repeat(true, times)], AvcC, Width, Height);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The same stream with its SPS and PPS repeated in every access unit, as some cameras and recorders write them: a
|
||||
/// decoder started at any of its P or B frames finds its parameter sets.
|
||||
/// </summary>
|
||||
public ElementaryStream WithParameterSetsEverywhere()
|
||||
{
|
||||
var sets = Units[0].Where(n => (n[0] & 0x1F) is 7 or 8).ToList();
|
||||
var units = Units.Select(u => u.Any(n => (n[0] & 0x1F) == 7) ? u : [.. sets, .. u]).ToList();
|
||||
return new ElementaryStream(Name + "-parametri", units, Rank, Key, AvcC, Width, Height);
|
||||
}
|
||||
|
||||
/// <summary>An access unit with 4-byte length prefixes (MP4, Matroska).</summary>
|
||||
public byte[] LengthPrefixed(int index)
|
||||
{
|
||||
@@ -328,8 +339,11 @@ internal static class TestVideos
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>A Matroska file with one video track of SimpleBlocks (times in milliseconds).</summary>
|
||||
public static byte[] Matroska(ElementaryStream es, DateTimeOffset? created = null, bool webm = false)
|
||||
/// <summary>
|
||||
/// A Matroska file with one video track of SimpleBlocks, in a single cluster; block times are in ticks of
|
||||
/// <paramref name="timecodeScale"/> nanoseconds (milliseconds by default).
|
||||
/// </summary>
|
||||
public static byte[] Matroska(ElementaryStream es, DateTimeOffset? created = null, bool webm = false, uint timecodeScale = 1_000_000)
|
||||
{
|
||||
var shift = 0;
|
||||
for (var i = 0; i < es.Count; i++)
|
||||
@@ -340,8 +354,9 @@ internal static class TestVideos
|
||||
var header = Element(0x1A45DFA3,
|
||||
Element(0x4286, [1]), Element(0x42F7, [1]), Element(0x42F2, [4]), Element(0x42F3, [8]),
|
||||
Element(0x4282, Encoding.ASCII.GetBytes(webm ? "webm" : "matroska")), Element(0x4287, [4]), Element(0x4285, [2]));
|
||||
var durationMs = es.Count * 1000.0 / 30;
|
||||
var info = new List<byte[]> { Element(0x2AD7B1, U32(1_000_000)), Element(0x4489, F64(durationMs)), Element(0x4D80, "febe-prove"u8.ToArray()) };
|
||||
var tickMs = timecodeScale / 1e6;
|
||||
var durationTicks = es.Count * 1000.0 / 30 / tickMs;
|
||||
var info = new List<byte[]> { Element(0x2AD7B1, U32(timecodeScale)), Element(0x4489, F64(durationTicks)), Element(0x4D80, "febe-prove"u8.ToArray()) };
|
||||
if (created is { } c)
|
||||
{
|
||||
var ns = (c - new DateTimeOffset(2001, 1, 1, 0, 0, 0, TimeSpan.Zero)).Ticks * 100;
|
||||
@@ -354,7 +369,7 @@ internal static class TestVideos
|
||||
var blocks = new List<byte[]> { Element(0xE7, [0]) };
|
||||
for (var i = 0; i < es.Count; i++)
|
||||
{
|
||||
var pts = (int)Math.Round((es.Rank[i] + shift) * 1000.0 / 30);
|
||||
var pts = (int)Math.Round((es.Rank[i] + shift) * 1000.0 / 30 / tickMs);
|
||||
var payload = es.LengthPrefixed(i);
|
||||
blocks.Add(Element(0xA3, [0x81, (byte)(pts >> 8), (byte)pts, es.Key[i] ? (byte)0x80 : (byte)0, .. payload]));
|
||||
}
|
||||
@@ -363,8 +378,12 @@ internal static class TestVideos
|
||||
return [.. header, .. segment];
|
||||
}
|
||||
|
||||
/// <summary>An AVI file with one H.264 stream in Annex B form, an idx1 index and, when given, an IDIT date.</summary>
|
||||
public static byte[] Avi(ElementaryStream es, string? idit = null, bool index = true)
|
||||
/// <summary>
|
||||
/// An AVI file with one H.264 stream in Annex B form, an idx1 index (unless <paramref name="index"/> is false, as in a
|
||||
/// recording cut short) and, when given, an IDIT date. The stream header says <paramref name="rate"/> /
|
||||
/// <paramref name="scale"/> frames per second and <paramref name="length"/> frames (default: the stream's).
|
||||
/// </summary>
|
||||
public static byte[] Avi(ElementaryStream es, string? idit = null, bool index = true, uint scale = 1, uint rate = 30, uint? length = null)
|
||||
{
|
||||
var avih = new List<byte>();
|
||||
foreach (var v in new uint[] { 33333, 0, 0, 0x10, (uint)es.Count, 0, 1, 0, (uint)es.Width, (uint)es.Height, 0, 0, 0, 0 })
|
||||
@@ -374,7 +393,7 @@ internal static class TestVideos
|
||||
|
||||
var strh = new List<byte>();
|
||||
strh.AddRange("vidsH264"u8.ToArray());
|
||||
foreach (var v in new uint[] { 0, 0, 0, 1, 30, 0, (uint)es.Count, 0, 0xFFFFFFFF, 0 })
|
||||
foreach (var v in new uint[] { 0, 0, 0, scale, rate, 0, length ?? (uint)es.Count, 0, 0xFFFFFFFF, 0 })
|
||||
{
|
||||
strh.AddRange(Le32(v));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
using Febe.Core.Codecs.Containers;
|
||||
using Febe.Core.Codecs.H264;
|
||||
using Febe.Core.Import;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Codecs.Containers;
|
||||
@@ -13,14 +16,22 @@ public sealed class VideoFrameDecoderTests
|
||||
[DataRow("mkv")]
|
||||
[DataRow("avi")]
|
||||
[DataRow("frammentato.mp4")]
|
||||
[DataRow("senza-indice.avi")]
|
||||
[DataRow("senza-indice-con-parametri.avi")]
|
||||
public async Task TheFrameAtOneSecondIsTheOneTheStreamShowsThere(string kind)
|
||||
{
|
||||
var es = ElementaryStream.Load("CABA3_SVA_B");
|
||||
using var temp = new TempFolder("fotogramma");
|
||||
|
||||
// Without idx1 (a recording cut short) every chunk counts as a key frame: decoding must still start from the
|
||||
// IDR picture, also when every chunk carries its own parameter sets (then a decoder started at the P frame itself
|
||||
// would give a corrupt picture rather than none).
|
||||
var data = kind switch
|
||||
{
|
||||
"mkv" => TestVideos.Matroska(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)),
|
||||
"avi" => TestVideos.Avi(es),
|
||||
"senza-indice.avi" => TestVideos.Avi(es, index: false),
|
||||
"senza-indice-con-parametri.avi" => TestVideos.Avi(es.WithParameterSetsEverywhere(), index: false),
|
||||
"frammentato.mp4" => TestVideos.FragmentedMp4(es),
|
||||
_ => TestVideos.Mp4(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)), // a dated file, as from a phone
|
||||
};
|
||||
@@ -32,7 +43,7 @@ public sealed class VideoFrameDecoderTests
|
||||
// The same frame straight from the decoder: the one shown at frame 30 (30 frames per second). AVI has no
|
||||
// presentation times: there frames are shown in decoding order.
|
||||
var position = Math.Min(30, es.Count - 1);
|
||||
var expected = kind == "avi" ? DecodedFrame(es, position) : ShownFrame(es, position);
|
||||
var expected = kind.EndsWith("avi", StringComparison.Ordinal) ? DecodedFrame(es, position) : ShownFrame(es, position);
|
||||
var reference = VideoFrameDecoder.ToImage(expected, 0, 0);
|
||||
Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height));
|
||||
CollectionAssert.AreEqual(reference.Rgb, image.Rgb);
|
||||
@@ -119,6 +130,72 @@ public sealed class VideoFrameDecoderTests
|
||||
Assert.IsFalse(result.IsStill, $"differenza {result.Difference}");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AFrameFarFromWhereDecodingCanStartGivesWayToTheFrameThere()
|
||||
{
|
||||
// At most five samples from the random access point: the frame at one second (sample 30, one IDR at sample 0)
|
||||
// is too far, the IDR picture stands for it instead of decoding the whole run (a damaged time table can put the
|
||||
// frame asked for two million samples after the only key frame).
|
||||
var es = ElementaryStream.Load("CABA3_SVA_B");
|
||||
using var temp = new TempFolder("fotogramma-lontano");
|
||||
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es));
|
||||
var decoder = new VideoFrameDecoder(VideoFrameDecoder.DefaultBudget, maxRun: 5);
|
||||
var image = await decoder.DecodeFrameAsync(path, TimeSpan.FromSeconds(1));
|
||||
CollectionAssert.AreEqual(VideoFrameDecoder.ToImage(DecodedFrame(es, 0), 0, 0).Rgb, image!.Rgb);
|
||||
Assert.IsNotNull(await decoder.AnalyseStillnessAsync(path), "anche l'analisi resta limitata e risponde");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task PastItsBudgetTheDecoderGivesNothingButTheCallerCanStillCancel()
|
||||
{
|
||||
var es = ElementaryStream.Load("CABA3_SVA_B");
|
||||
using var temp = new TempFolder("fotogramma-tempo");
|
||||
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es));
|
||||
var late = new VideoFrameDecoder(TimeSpan.Zero, maxRun: 300);
|
||||
Assert.IsNull(await late.DecodeFrameAsync(path, TimeSpan.FromSeconds(1)), "oltre il tempo concesso: nessun fotogramma");
|
||||
Assert.IsNull(await late.AnalyseStillnessAsync(path));
|
||||
|
||||
// A cancellation asked by the caller is not a missing frame: it stays a cancellation.
|
||||
using var cancelled = new CancellationTokenSource();
|
||||
await cancelled.CancelAsync();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1), 0, cancelled.Token));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("filmato-muto.mp4", false)]
|
||||
[DataRow("filmato-con-audio.mp4", true)]
|
||||
public async Task TheVideosOfARealEncoderAreReadAndDecoded(string name, bool audio)
|
||||
{
|
||||
// The two small MP4s of the test site come from a real muxer and encoder (libavformat, x264 High profile: the
|
||||
// shape of the videos Instagram serves); no official MD5 exists for them, so the frame is checked coarsely.
|
||||
var path = Repository.PathOf("tools", "Febe.SitoDiProva", "Risorse", name);
|
||||
var now = new DateTimeOffset(2026, 11, 18, 12, 0, 0, TimeSpan.Zero);
|
||||
var metadata = ContainerVideoMetadataProbe.Probe(path, now);
|
||||
Assert.IsNotNull(metadata);
|
||||
Assert.IsTrue(metadata.Width > 0 && metadata.Height > 0, $"{metadata.Width}×{metadata.Height}");
|
||||
Assert.IsTrue(metadata.Duration > TimeSpan.Zero && metadata.Duration < TimeSpan.FromMinutes(1), $"{metadata.Duration}");
|
||||
|
||||
var container = ContainerReader.ReadFile(path, now);
|
||||
Assert.AreEqual(VideoCodec.H264, container!.Video!.Codec);
|
||||
Assert.AreEqual(audio, container.Audio is not null);
|
||||
|
||||
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1));
|
||||
Assert.IsNotNull(image, "nessun fotogramma da un video di un codificatore vero");
|
||||
Assert.AreEqual((metadata.Width, metadata.Height), (image.Width, image.Height));
|
||||
|
||||
// A real picture: not a flat field of one value, not out of range.
|
||||
var luma = new double[image.Width * image.Height];
|
||||
for (var i = 0; i < luma.Length; i++)
|
||||
{
|
||||
luma[i] = (0.299 * image.Rgb[i * 3]) + (0.587 * image.Rgb[(i * 3) + 1]) + (0.114 * image.Rgb[(i * 3) + 2]);
|
||||
}
|
||||
|
||||
var mean = luma.Average();
|
||||
Assert.IsTrue(mean is > 2 and < 253, $"luminanza media {mean:F1}");
|
||||
var bmp = await VideoFrameDecoder.Instance.ExtractImageAsync(path);
|
||||
Assert.IsNotNull(bmp);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UnreadableFilesGiveNothing()
|
||||
{
|
||||
|
||||
@@ -5,7 +5,10 @@ namespace Febe.Tests.Codecs.H264;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// MD5 of the corresponding frame of the official reconstruction (see Conformita/LEGGIMI.md). None of these streams uses
|
||||
/// weighted prediction, memory management operations, long-term references, gaps in frame_num, POC type 1, I_PCM or
|
||||
/// CABAC pictures of several slices: those parts of the decoder have no reference MD5 here (some are reached by
|
||||
/// <see cref="H264SyntheticStreamTests"/>, without an official reference).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class H264ConformanceTests
|
||||
@@ -49,6 +52,38 @@ public sealed class H264ConformanceTests
|
||||
Assert.AreEqual(expected.Count, actual.Count, $"{name}: numero di fotogrammi");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("CABA3_SVA_B")]
|
||||
[DataRow("CANL1_SVA_B")]
|
||||
[DataRow("FRExt1_Panasonic_D")]
|
||||
[DataRow("FRExt3_Panasonic_E")]
|
||||
[DataRow("HCAFR1_HHI_C")]
|
||||
public void PicturesLeftOutDoNotChangeTheOthers(string name)
|
||||
{
|
||||
// Pictures nobody refers to and nobody wants are not reconstructed (only their headers count): every frame
|
||||
// handed out must still be the one of the full decoding, in the same place of the output order.
|
||||
var folder = Path.Combine(AppContext.BaseDirectory, "Media", "H264", "Conformita", name);
|
||||
var data = File.ReadAllBytes(Directory.EnumerateFiles(folder).Single(f => Path.GetExtension(f) is ".264" or ".jsv" or ".avc"));
|
||||
var all = new List<H264Frame>();
|
||||
var full = new H264Decoder();
|
||||
full.FrameDecoded += all.Add;
|
||||
full.DecodeAnnexB(data);
|
||||
|
||||
var some = new List<H264Frame>();
|
||||
var partial = new H264Decoder { Wanted = index => index % 3 == 2 };
|
||||
partial.FrameDecoded += some.Add;
|
||||
partial.DecodeAnnexB(data);
|
||||
|
||||
Assert.AreEqual(full.FramesDecoded, partial.FramesDecoded);
|
||||
CollectionAssert.AreEqual(all.Where(f => f.DecodeIndex % 3 == 2).Select(f => f.DecodeIndex).ToArray(), some.Select(f => f.DecodeIndex).ToArray());
|
||||
foreach (var frame in some)
|
||||
{
|
||||
var expected = all.Single(f => f.DecodeIndex == frame.DecodeIndex);
|
||||
Assert.AreEqual((expected.Poc, expected.Period), (frame.Poc, frame.Period), $"{name}: ordine del fotogramma {frame.DecodeIndex}");
|
||||
CollectionAssert.AreEqual(expected.ToI420(), frame.ToI420(), $"{name}: fotogramma {frame.DecodeIndex}");
|
||||
}
|
||||
}
|
||||
|
||||
private static List<string> ReadReference(string path)
|
||||
{
|
||||
var frames = new List<string>();
|
||||
|
||||
@@ -66,14 +66,28 @@ public sealed class H264RobustnessTests
|
||||
[TestMethod]
|
||||
public void APictureLargerThanEveryLevelIsRefusedBeforeItIsAllocated()
|
||||
{
|
||||
// 1024 × 1024 macroblocks (16384 × 16384): what ue(v) allows, a hundred times what level 6.2 does.
|
||||
// 1024 × 1024 macroblocks (16384 × 16384): what ue(v) allows, a hundred times what level 6.2 does. A PPS and the
|
||||
// start of an IDR slice follow, so a decoder without the bound would really allocate its pictures.
|
||||
var huge = new SyntheticStreams.SequenceSettings(WidthInMbs: 1024, HeightInMbs: 1024);
|
||||
byte[] stream = [.. SyntheticStreams.Sps(huge), .. SyntheticStreams.Pps(), .. SyntheticStreams.Idr(huge, 100, macroblocks: 1)];
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
var error = Assert.ThrowsExactly<H264Exception>(() => new H264Decoder().DecodeAnnexB(Sps(widthInMbs: 1024, heightInMbs: 1024)));
|
||||
var error = Assert.ThrowsExactly<H264Exception>(() => new H264Decoder().DecodeAnnexB(stream));
|
||||
StringAssert.Contains(error.Message, "livello");
|
||||
Assert.IsLessThan(1024L * 1024, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
|
||||
// The largest frame of level 6.2 is still accepted.
|
||||
new H264Decoder().DecodeAnnexB(Sps(widthInMbs: 512, heightInMbs: 272));
|
||||
new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 512, HeightInMbs: 272)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MoreReferenceFramesThanTheLargestBufferAreRefused()
|
||||
{
|
||||
// 8192 × 4352 with sixteen reference frames would be 1.4 GB of pictures; level 6.2 holds five of that size.
|
||||
var error = Assert.ThrowsExactly<H264Exception>(() =>
|
||||
new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 512, HeightInMbs: 272, MaxNumRefFrames: 16))));
|
||||
StringAssert.Contains(error.Message, "riferimento");
|
||||
new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 512, HeightInMbs: 272, MaxNumRefFrames: 5)));
|
||||
new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 120, HeightInMbs: 68, MaxNumRefFrames: 16)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -85,83 +99,7 @@ public sealed class H264RobustnessTests
|
||||
Assert.ThrowsExactly<H264Exception>(() => new H264Decoder().DecodeAnnexB(Sps(11, 9, crop: (0, 0, 8192, 0))));
|
||||
}
|
||||
|
||||
/// <summary>A Baseline SPS NAL unit in Annex B form, written bit by bit (§7.3.2.1.1).</summary>
|
||||
private static byte[] Sps(int widthInMbs, int heightInMbs, (int Left, int Right, int Top, int Bottom)? crop = null)
|
||||
{
|
||||
var bits = new BitWriter();
|
||||
bits.Bits(66, 8); // profile_idc: Baseline
|
||||
bits.Bits(0, 8); // constraint flags
|
||||
bits.Bits(30, 8); // level_idc
|
||||
bits.Ue(0); // seq_parameter_set_id
|
||||
bits.Ue(0); // log2_max_frame_num_minus4
|
||||
bits.Ue(2); // pic_order_cnt_type
|
||||
bits.Ue(1); // max_num_ref_frames
|
||||
bits.Bits(0, 1); // gaps_in_frame_num_value_allowed_flag
|
||||
bits.Ue((uint)widthInMbs - 1);
|
||||
bits.Ue((uint)heightInMbs - 1);
|
||||
bits.Bits(1, 1); // frame_mbs_only_flag
|
||||
bits.Bits(1, 1); // direct_8x8_inference_flag
|
||||
bits.Bits(crop is null ? 0u : 1u, 1);
|
||||
if (crop is { } c)
|
||||
{
|
||||
bits.Ue((uint)c.Left);
|
||||
bits.Ue((uint)c.Right);
|
||||
bits.Ue((uint)c.Top);
|
||||
bits.Ue((uint)c.Bottom);
|
||||
}
|
||||
|
||||
bits.Bits(0, 1); // vui_parameters_present_flag
|
||||
bits.Bits(1, 1); // rbsp_stop_one_bit
|
||||
return [0, 0, 0, 1, 0x67, .. 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 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];
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>A Baseline SPS of the given size and crop.</summary>
|
||||
private static byte[] Sps(int widthInMbs, int heightInMbs, (int, int, int, int) crop) =>
|
||||
SyntheticStreams.Sps(new(WidthInMbs: widthInMbs, HeightInMbs: heightInMbs, Crop: crop));
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using Febe.Core.Codecs.H264;
|
||||
using static Febe.Tests.Codecs.H264.SyntheticStreams;
|
||||
|
||||
namespace Febe.Tests.Codecs.H264;
|
||||
|
||||
/// <summary>
|
||||
/// The decoder on tiny streams written by <see cref="SyntheticStreams"/>: the parts of the standard no conformance stream in
|
||||
/// the repository exercises.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class H264SyntheticStreamTests
|
||||
{
|
||||
[TestMethod]
|
||||
[DataRow(16)]
|
||||
[DataRow(2)]
|
||||
public void AGapInFrameNumKeepsTheWrapInThePictureOrder(int maxNumRefFrames)
|
||||
{
|
||||
// POC type 2, MaxFrameNum 16: references 0..14, then frame_num 3. Frames 15, 0, 1 and 2 are missing (§8.2.5.2):
|
||||
// the wrap at 0 is among them, so the frame after the gap has FrameNumOffset 16 and POC 2 × (16 + 3) (§8.2.1.3).
|
||||
// With two reference frames, 15 and 0 are counted without becoming references.
|
||||
var s = new SequenceSettings(MaxNumRefFrames: maxNumRefFrames, GapsAllowed: true);
|
||||
var stream = new List<byte>([.. Sps(s), .. Pps(), .. Idr(s, 100)]);
|
||||
for (var n = 1; n <= 14; n++)
|
||||
{
|
||||
stream.AddRange(SkippedP(s, n));
|
||||
}
|
||||
|
||||
stream.AddRange(SkippedP(s, 3));
|
||||
var frames = Decode([.. stream]);
|
||||
|
||||
Assert.HasCount(16, frames);
|
||||
for (var n = 0; n <= 14; n++)
|
||||
{
|
||||
Assert.AreEqual(2 * n, frames[n].Poc, $"fotogramma {n}");
|
||||
}
|
||||
|
||||
Assert.AreEqual(2 * (16 + 3), frames[15].Poc, "il fotogramma dopo il salto");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ARedundantPictureIsSkipped()
|
||||
{
|
||||
// The primary IDR picture (luma 100) and a redundant copy (redundant_pic_cnt 1) whose slice also starts at
|
||||
// macroblock 0: one frame, the primary one.
|
||||
var s = new SequenceSettings();
|
||||
byte[] stream = [.. Sps(s), .. Pps(redundantPicCntPresent: true), .. Idr(s, 100, redundantPicCnt: 0), .. Idr(s, 200, redundantPicCnt: 1)];
|
||||
var frames = Decode(stream);
|
||||
Assert.HasCount(1, frames);
|
||||
Assert.IsTrue(frames[0].Y.All(v => v == 100), "il fotogramma è quello primario");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void APSliceWithNothingToPredictFromIsRefused()
|
||||
{
|
||||
// Decoding that starts at a P picture (an AVI without index, read from a sample that is not a key frame): the
|
||||
// decoder refuses it instead of predicting the picture from itself.
|
||||
var s = new SequenceSettings();
|
||||
var decoder = new H264Decoder();
|
||||
var frames = new List<H264Frame>();
|
||||
decoder.FrameDecoded += frames.Add;
|
||||
Assert.ThrowsExactly<H264Exception>(() => decoder.DecodeAnnexB([.. Sps(s), .. Pps(), .. SkippedP(s, 1)]));
|
||||
Assert.IsEmpty(frames);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AnUnwantedPictureNobodyRefersToIsNotDecoded()
|
||||
{
|
||||
// The second picture is not a reference and its slice data is broken (a skip run past the picture): decoding it
|
||||
// fails, so a decoder that skips it as unwanted shows it was never reconstructed.
|
||||
var s = new SequenceSettings(PocType: 0);
|
||||
byte[] broken = [.. SkippedP(s with { WidthInMbs = 2 }, 1, reference: false)]; // a run of 2 in a 1-macroblock picture
|
||||
byte[] stream = [.. Sps(s), .. Pps(), .. Idr(s, 100), .. broken, .. SkippedP(s, 1, pocLsb: 4)];
|
||||
Assert.ThrowsExactly<H264Exception>(() => Decode(stream));
|
||||
|
||||
var decoder = new H264Decoder { Wanted = index => index != 1 };
|
||||
var frames = new List<H264Frame>();
|
||||
decoder.FrameDecoded += frames.Add;
|
||||
decoder.DecodeAnnexB(stream);
|
||||
Assert.AreEqual(3, decoder.FramesDecoded);
|
||||
CollectionAssert.AreEqual(new long[] { 0, 2 }, frames.Select(f => f.DecodeIndex).ToArray());
|
||||
Assert.AreEqual(4, frames[1].Poc, "il fotogramma dopo quello saltato ha il suo ordine");
|
||||
Assert.IsTrue(frames[1].Y.All(v => v == 100));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheStartOfDecodingIsRecognised()
|
||||
{
|
||||
var s = new SequenceSettings();
|
||||
Assert.AreEqual(H264AccessPoint.Idr, H264Decoder.AccessPoint([.. Sps(s), .. Pps(), .. Idr(s, 100)], 0));
|
||||
Assert.AreEqual(H264AccessPoint.None, H264Decoder.AccessPoint([.. Sps(s), .. Pps(), .. SkippedP(s, 1)], 0));
|
||||
Assert.AreEqual(H264AccessPoint.None, H264Decoder.AccessPoint([], 0));
|
||||
|
||||
// Length-prefixed (MP4): the same IDR picture without its start code.
|
||||
var idr = Idr(s, 100)[4..];
|
||||
Assert.AreEqual(H264AccessPoint.Idr, H264Decoder.AccessPoint([0, 0, (byte)(idr.Length >> 8), (byte)idr.Length, .. idr], 4));
|
||||
}
|
||||
|
||||
private static List<H264Frame> Decode(byte[] stream)
|
||||
{
|
||||
var decoder = new H264Decoder();
|
||||
var frames = new List<H264Frame>();
|
||||
decoder.FrameDecoded += frames.Add;
|
||||
decoder.DecodeAnnexB(stream);
|
||||
return frames;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
namespace Febe.Tests.Codecs.H264;
|
||||
|
||||
/// <summary>
|
||||
/// Tiny H.264 streams written bit by bit from the syntax of the standard (§7.3): Baseline parameter sets, IDR pictures
|
||||
/// made of I_PCM macroblocks (their samples are written as they are, so every pixel is known) and P pictures made only
|
||||
/// of skipped macroblocks. They reach the parts of the decoder the conformance streams in the repository do not: gaps in
|
||||
/// frame_num, redundant pictures, slices without references, huge parameter sets.
|
||||
/// </summary>
|
||||
internal static class SyntheticStreams
|
||||
{
|
||||
/// <summary>Settings of the sequence parameter set.</summary>
|
||||
internal sealed record SequenceSettings(
|
||||
int WidthInMbs = 1,
|
||||
int HeightInMbs = 1,
|
||||
int PocType = 2,
|
||||
int Log2MaxFrameNum = 4,
|
||||
int MaxNumRefFrames = 1,
|
||||
bool GapsAllowed = false,
|
||||
(int Left, int Right, int Top, int Bottom)? Crop = null);
|
||||
|
||||
/// <summary>A sequence parameter set NAL unit with its start code (§7.3.2.1.1).</summary>
|
||||
internal static byte[] Sps(SequenceSettings s)
|
||||
{
|
||||
var bits = new BitWriter();
|
||||
bits.Bits(66, 8); // profile_idc: Baseline
|
||||
bits.Bits(0, 8); // constraint flags
|
||||
bits.Bits(30, 8); // level_idc
|
||||
bits.Ue(0); // seq_parameter_set_id
|
||||
bits.Ue((uint)s.Log2MaxFrameNum - 4);
|
||||
bits.Ue((uint)s.PocType);
|
||||
if (s.PocType == 0)
|
||||
{
|
||||
bits.Ue(4); // log2_max_pic_order_cnt_lsb_minus4
|
||||
}
|
||||
|
||||
bits.Ue((uint)s.MaxNumRefFrames);
|
||||
bits.Bits(s.GapsAllowed ? 1u : 0u, 1);
|
||||
bits.Ue((uint)s.WidthInMbs - 1);
|
||||
bits.Ue((uint)s.HeightInMbs - 1);
|
||||
bits.Bits(1, 1); // frame_mbs_only_flag
|
||||
bits.Bits(1, 1); // direct_8x8_inference_flag
|
||||
bits.Bits(s.Crop is null ? 0u : 1u, 1);
|
||||
if (s.Crop is { } c)
|
||||
{
|
||||
bits.Ue((uint)c.Left);
|
||||
bits.Ue((uint)c.Right);
|
||||
bits.Ue((uint)c.Top);
|
||||
bits.Ue((uint)c.Bottom);
|
||||
}
|
||||
|
||||
bits.Bits(0, 1); // vui_parameters_present_flag
|
||||
return Nal(0x67, bits);
|
||||
}
|
||||
|
||||
/// <summary>A Baseline picture parameter set (CAVLC, one slice group, deblocking control present, §7.3.2.2).</summary>
|
||||
internal static byte[] Pps(bool redundantPicCntPresent = false)
|
||||
{
|
||||
var bits = new BitWriter();
|
||||
bits.Ue(0); // pic_parameter_set_id
|
||||
bits.Ue(0); // seq_parameter_set_id
|
||||
bits.Bits(0, 1); // entropy_coding_mode_flag: CAVLC
|
||||
bits.Bits(0, 1); // bottom_field_pic_order_in_frame_present_flag
|
||||
bits.Ue(0); // num_slice_groups_minus1
|
||||
bits.Ue(0); // num_ref_idx_l0_default_active_minus1
|
||||
bits.Ue(0); // num_ref_idx_l1_default_active_minus1
|
||||
bits.Bits(0, 1); // weighted_pred_flag
|
||||
bits.Bits(0, 2); // weighted_bipred_idc
|
||||
bits.Se(0); // pic_init_qp_minus26
|
||||
bits.Se(0); // pic_init_qs_minus26
|
||||
bits.Se(0); // chroma_qp_index_offset
|
||||
bits.Bits(1, 1); // deblocking_filter_control_present_flag
|
||||
bits.Bits(0, 1); // constrained_intra_pred_flag
|
||||
bits.Bits(redundantPicCntPresent ? 1u : 0u, 1);
|
||||
return Nal(0x68, bits);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An IDR picture of I_PCM macroblocks whose luma samples are all <paramref name="luma"/> (chroma 128), as one slice.
|
||||
/// </summary>
|
||||
internal static byte[] Idr(SequenceSettings s, byte luma, int idrPicId = 0, int? redundantPicCnt = null, int macroblocks = -1)
|
||||
{
|
||||
var bits = new BitWriter();
|
||||
bits.Ue(0); // first_mb_in_slice
|
||||
bits.Ue(7); // slice_type: I (all slices of the picture)
|
||||
bits.Ue(0); // pic_parameter_set_id
|
||||
bits.Bits(0, s.Log2MaxFrameNum); // frame_num
|
||||
bits.Ue((uint)idrPicId);
|
||||
if (s.PocType == 0)
|
||||
{
|
||||
bits.Bits(0, 8); // pic_order_cnt_lsb
|
||||
}
|
||||
|
||||
if (redundantPicCnt is { } r)
|
||||
{
|
||||
bits.Ue((uint)r);
|
||||
}
|
||||
|
||||
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.Ue(1); // disable_deblocking_filter_idc: off
|
||||
var count = macroblocks < 0 ? s.WidthInMbs * s.HeightInMbs : macroblocks;
|
||||
for (var m = 0; m < count; m++)
|
||||
{
|
||||
bits.Ue(25); // mb_type: I_PCM
|
||||
bits.Align(); // pcm_alignment_zero_bit
|
||||
for (var i = 0; i < 256; i++)
|
||||
{
|
||||
bits.Bits(luma, 8);
|
||||
}
|
||||
|
||||
for (var i = 0; i < 128; i++)
|
||||
{
|
||||
bits.Bits(128, 8);
|
||||
}
|
||||
}
|
||||
|
||||
return Nal(0x65, bits);
|
||||
}
|
||||
|
||||
/// <summary>A P picture whose macroblocks are all skipped (a copy of the newest reference), as one slice.</summary>
|
||||
/// <param name="s">The sequence.</param>
|
||||
/// <param name="frameNum">frame_num.</param>
|
||||
/// <param name="reference">False for nal_ref_idc 0.</param>
|
||||
/// <param name="pocLsb">pic_order_cnt_lsb with POC type 0 (default: twice frame_num).</param>
|
||||
internal static byte[] SkippedP(SequenceSettings s, int frameNum, bool reference = true, int? pocLsb = null)
|
||||
{
|
||||
var bits = new BitWriter();
|
||||
bits.Ue(0); // first_mb_in_slice
|
||||
bits.Ue(5); // slice_type: P (all slices of the picture)
|
||||
bits.Ue(0); // pic_parameter_set_id
|
||||
bits.Bits((uint)frameNum, s.Log2MaxFrameNum);
|
||||
if (s.PocType == 0)
|
||||
{
|
||||
bits.Bits((uint)(pocLsb ?? (2 * frameNum)) & 0xFF, 8); // pic_order_cnt_lsb
|
||||
}
|
||||
|
||||
bits.Bits(0, 1); // num_ref_idx_active_override_flag
|
||||
bits.Bits(0, 1); // ref_pic_list_modification_flag_l0
|
||||
if (reference)
|
||||
{
|
||||
bits.Bits(0, 1); // adaptive_ref_pic_marking_mode_flag
|
||||
}
|
||||
|
||||
bits.Se(0); // slice_qp_delta
|
||||
bits.Ue(1); // disable_deblocking_filter_idc: off
|
||||
bits.Ue((uint)(s.WidthInMbs * s.HeightInMbs)); // mb_skip_run: the whole picture
|
||||
return Nal(reference ? (byte)0x41 : (byte)0x01, 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];
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user