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
@@ -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