using Febe.Core.Codecs.H264;
namespace Febe.Tests.Codecs.H264;
///
/// Damaged H.264 streams: the decoder reads bytes of any file the library holds, so whatever they are it must end with
/// frames or an , and a damaged parameter set must never make it allocate huge pictures.
///
[TestClass]
public sealed class H264RobustnessTests
{
[TestMethod]
[DataRow("BA1_Sony_D", 2641)]
[DataRow("SVA_BA1_B", 2642)]
[DataRow("BA3_SVA_C", 2643)]
[DataRow("BASQP1_Sony_C", 2644)]
[DataRow("CI_MW_D", 2645)]
[DataRow("CABA1_SVA_B", 2646)]
[DataRow("CABA2_SVA_B", 2647)]
[DataRow("CABA3_SVA_B", 2648)]
[DataRow("CANL1_SVA_B", 2649)]
[DataRow("FRExt1_Panasonic_D", 2650)]
[DataRow("FRExt3_Panasonic_E", 2651)]
[DataRow("HCAFR1_HHI_C", 2652)]
public void DamagedStreamsGiveFramesOrAnH264Exception(string name, int seed)
{
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 random = new Random(seed);
for (var trial = 0; trial < 60; trial++)
{
var copy = (byte[])data.Clone();
var changes = 1 + random.Next(20);
for (var k = 0; k < changes; k++)
{
var p = random.Next(copy.Length);
copy[p] = random.Next(3) switch
{
0 => (byte)random.Next(256),
1 => (byte)(copy[p] ^ (1 << random.Next(8))),
_ => 0xFF,
};
}
if (random.Next(4) == 0)
{
copy = copy[..random.Next(copy.Length)];
}
try
{
var decoder = new H264Decoder();
decoder.FrameDecoded += _ => { };
decoder.DecodeAnnexB(copy);
}
catch (H264Exception)
{
}
catch (Exception ex)
{
Assert.Fail($"{name}, variante {trial} del seme {seed}: {ex.GetType().Name} {ex.Message}\n{ex.StackTrace}");
}
}
}
[TestMethod]
public void APictureLargerThanEveryLevelIsRefusedBeforeItIsAllocated()
{
// 1024 × 1024 macroblocks (16384 × 16384): what ue(v) allows, a hundred times what level 6.2 does.
var before = GC.GetAllocatedBytesForCurrentThread();
var error = Assert.ThrowsExactly(() => new H264Decoder().DecodeAnnexB(Sps(widthInMbs: 1024, heightInMbs: 1024)));
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));
}
[TestMethod]
public void ACropThatLeavesNoPictureIsRefused()
{
// 176 × 144 (11 × 9 macroblocks): crop units are two samples in 4:2:0 frames.
new H264Decoder().DecodeAnnexB(Sps(11, 9, crop: (4, 4, 2, 2)));
Assert.ThrowsExactly(() => new H264Decoder().DecodeAnnexB(Sps(11, 9, crop: (44, 44, 0, 0))));
Assert.ThrowsExactly(() => new H264Decoder().DecodeAnnexB(Sps(11, 9, crop: (0, 0, 8192, 0))));
}
/// A Baseline SPS NAL unit in Annex B form, written bit by bit (§7.3.2.1.1).
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 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();
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];
}
}
}