using System.Security.Cryptography;
using System.Text.RegularExpressions;
using Febe.Core.Codecs.H264;
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), slice groups of every map type with slices in any order
/// (FM1_BT_B, FM1_FT_E, FM2_SVA_C), SP slices (sp1_bt_a, sp2_bt_b; sp2 with the deblocking filter on), 4:2:2 at 8 and 10
/// bits with CABAC and CAVLC (Hi422FR10–15_SONY_A, FREXT2/3_TANDBERG_A) and monochrome 4:0:0 (HPCAMOLQ_BRCM_B,
/// HPCVMOLQ_BRCM_B). 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
/// (), SI slices and the rest by
/// , without an official reference. SVC: the target layer of SVCBMT-13 (MGS quality
/// refinement) is verified, the base layer of every SVC stream too. The streams of the parts the decoder does not handle
/// yet (SVC spatial and CGS) or that have no official reconstruction (MVC) are in : 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.
///
[TestClass]
public sealed class H264ConformanceTests
{
[TestMethod]
[DataRow("BA1_Sony_D")]
[DataRow("SVA_BA1_B")]
[DataRow("BA3_SVA_C")]
[DataRow("BASQP1_Sony_C")]
[DataRow("CI_MW_D")]
[DataRow("CABA1_SVA_B")]
[DataRow("CABA2_SVA_B")]
[DataRow("CABA3_SVA_B")]
[DataRow("CANL1_SVA_B")]
[DataRow("FRExt1_Panasonic_D")]
[DataRow("FRExt3_Panasonic_E")]
[DataRow("HCAFR1_HHI_C")]
[DataRow("CVFI1_SVA_C")]
[DataRow("FI1_Sony_E")]
[DataRow("CAFI1_SVA_C")]
[DataRow("Sharp_MP_PAFF_1r2")]
[DataRow("HCAFF1_HHI_B")]
[DataRow("CVMAQP3_Sony_D")]
[DataRow("FREXT02_JVC_C")]
[DataRow("CAMACI3_Sony_C")]
[DataRow("CAMASL3_Sony_B")]
[DataRow("HCAMFF1_HHI_B")]
[DataRow("FREXT01_JVC_D")]
[DataRow("CAPAMA3_Sand_F")]
[DataRow("cama1_vtc_c")]
[DataRow("FRExt2_Panasonic_C")]
[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")]
[DataRow("Hi422FR10_SONY_A")]
[DataRow("Hi422FR11_SONY_A")]
[DataRow("Hi422FR12_SONY_A")]
[DataRow("Hi422FR13_SONY_A")]
[DataRow("Hi422FR14_SONY_A")]
[DataRow("Hi422FR15_SONY_A")]
[DataRow("FREXT2_TANDBERG_A")]
[DataRow("FREXT3_TANDBERG_A")]
[DataRow("HPCAMOLQ_BRCM_B")]
[DataRow("HPCVMOLQ_BRCM_B")]
[DataRow("SVCBMT-13")]
public void FramesMatchTheReference(string name) => AssertMatches(name, "riferimento.md5");
[TestMethod]
[DataRow("SVCBMT-13")]
[DataRow("SVCBST-19")]
[DataRow("SVCBCT-1")]
public void SvcBaseLayerMatchesTheReference(string name)
{
// The base layer of an SVC stream is plain H.264: a decoder that skips NAL units 14, 15 and 20 (prefix, subset
// SPS, slice extension) must give exactly the official reconstruction of layer L0.
AssertStreamMatches(name, File.ReadAllBytes(StreamFile(Folder(name))), "riferimento-base.md5", enhancementLayers: false);
}
[TestMethod]
[DataRow("SVCBST-19")]
[DataRow("SVCBCT-1")]
public void SvcLayersNotWrittenYetLeaveTheBaseLayer(string name)
{
// Spatial scalability and CGS are not written yet: the decoder says so and gives the base layer, exactly.
var data = File.ReadAllBytes(StreamFile(Folder(name)));
var frames = new List();
var decoder = new H264Decoder();
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(data);
Assert.IsNotNull(decoder.EnhancementLayersSkipped);
CollectionAssert.AreEqual(ReadReference(Path.Combine(Folder(name), "riferimento-base.md5"), out _), OutputOrder(frames).Select(Md5).ToList());
}
[TestMethod]
[DataRow("MVCDS-4", 2)]
[DataRow("MVCNV-3", 3)]
public void MvcDecodesEveryView(string name, int views)
{
// Without an official reconstruction: every view decodes, with as many frames as the base view and its size; the
// base view is the same as the one a plain H.264 decoder gives, and the others are pictures of the same scene
// (close to the base view, the difference being the parallax) without the block edges a wrong prediction leaves.
var data = File.ReadAllBytes(StreamFile(Folder(name)));
var all = new List();
var decoder = new H264Decoder();
decoder.FrameDecoded += all.Add;
decoder.DecodeAnnexB(data);
var baseOnly = new List();
var plain = new H264Decoder { DecodeAllViews = false };
plain.FrameDecoded += baseOnly.Add;
plain.DecodeAnnexB(data);
var byView = all.GroupBy(f => f.ViewId).OrderBy(g => g.Key == baseOnly[0].ViewId ? -1 : g.Key).Select(g => OutputOrder(g.ToList())).ToList();
Assert.AreEqual(views, byView.Count, $"{name}: viste");
Assert.AreEqual(9, baseOnly.Count, $"{name}: fotogrammi della vista base");
CollectionAssert.AreEqual(OutputOrder(baseOnly).Select(Md5).ToList(), byView[0].Select(Md5).ToList(), $"{name}: vista base");
foreach (var view in byView.Skip(1))
{
Assert.AreEqual(baseOnly.Count, view.Count, $"{name}: fotogrammi della vista {view[0].ViewId}");
for (var i = 0; i < view.Count; i++)
{
var other = view[i];
var reference = byView[0][i];
Assert.AreEqual((reference.Width, reference.Height, reference.Poc), (other.Width, other.Height, other.Poc), $"{name}: vista {other.ViewId}, fotogramma {i}");
long sum = 0;
for (var k = 0; k < other.Y.Length; k++)
{
sum += Math.Abs(other.Y[k] - reference.Y[k]);
}
var mean = (double)sum / other.Y.Length;
Assert.IsTrue(mean is > 0 and < 40, $"{name}: vista {other.ViewId}, fotogramma {i}: scarto medio {mean:F1} dalla vista base");
var edges = Blockiness(other);
Assert.IsTrue(edges < 1.5, $"{name}: vista {other.ViewId}, fotogramma {i}: bordi dei blocchi {edges:F2}");
}
}
}
[TestMethod]
[DataRow("SVCBST-19", "SVC, scalabilità spaziale e temporale (strato L1, 640×480)")]
[DataRow("SVCBCT-1", "SVC, qualità CGS e scalabilità temporale (strato L1)")]
[DataRow("MVCDS-4", "MVC, due viste")]
[DataRow("MVCNV-3", "MVC, tre viste")]
public void FeaturesStillToDo(string name, string feature)
{
var folder = Folder(name);
var expected = ReadReference(Path.Combine(folder, "riferimento.md5"), out var declared);
Assert.AreEqual(declared, expected.Count, $"{name}: riferimento.md5 non ha tutti i fotogrammi dichiarati");
List actual;
string? skipped;
try
{
actual = Decode(StreamFile(folder), out skipped);
}
catch (H264Exception ex)
{
Assert.Inconclusive($"da fare: {feature} ({ex.Message})");
return;
}
if (expected.Count == 0)
{
// The CI counts as «da fare» only messages that start with it (.gitea/scripts/riepilogo-prove.sh): any other
// inconclusive result is a skipped test, and the CI allows none.
Assert.Inconclusive($"da fare: {feature}, confronto bit per bit; manca la ricostruzione ufficiale (oggi escono {actual.Count} fotogrammi di tutte le viste, vedi {nameof(MvcDecodesEveryView)})");
}
if (skipped is not null)
{
Assert.Inconclusive($"da fare: {feature}; non ancora scritto: {skipped} (oggi esce lo strato base, {actual.Count} fotogrammi)");
}
var same = 0;
for (var i = 0; i < Math.Min(actual.Count, expected.Count); i++)
{
same += actual[i] == expected[i] ? 1 : 0;
}
if (same == expected.Count && actual.Count == expected.Count)
{
Assert.Fail($"{name} ora coincide con il riferimento: spostalo fra i flussi di {nameof(FramesMatchTheReference)}.");
}
Assert.Inconclusive($"da fare: {feature}; oggi {same} fotogrammi su {expected.Count} coincidono ({actual.Count} decodificati)");
}
[TestMethod]
[DataRow("CABA3_SVA_B")]
[DataRow("CANL1_SVA_B")]
[DataRow("FRExt1_Panasonic_D")]
[DataRow("FRExt3_Panasonic_E")]
[DataRow("HCAFR1_HHI_C")]
[DataRow("CAFI1_SVA_C")]
[DataRow("Sharp_MP_PAFF_1r2")]
[DataRow("CAPAMA3_Sand_F")]
[DataRow("cama1_vtc_c")]
[DataRow("HCAMFF1_HHI_B")]
[DataRow("MR9_BT_B")]
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 data = File.ReadAllBytes(StreamFile(Folder(name)));
var all = new List();
var full = new H264Decoder();
full.FrameDecoded += all.Add;
full.DecodeAnnexB(data);
var some = new List();
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.ToPlanar(), frame.ToPlanar(), $"{name}: fotogramma {frame.DecodeIndex}");
}
}
/// The folder of a conformance stream.
internal static string Folder(string name) => Path.Combine(AppContext.BaseDirectory, "Media", "H264", "Conformita", name);
/// The Annex B stream of a folder, whatever extension its authors gave it.
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) =>
AssertStreamMatches(name, File.ReadAllBytes(StreamFile(Folder(name))), reference);
///
/// (the conformance stream , possibly rewritten) must give every frame
/// of the official reconstruction.
///
internal static void AssertStreamMatches(string name, byte[] stream, string reference = "riferimento.md5", bool enhancementLayers = true)
{
var folder = Folder(name);
var expected = ReadReference(Path.Combine(folder, reference), out var declared);
Assert.AreEqual(declared, expected.Count, $"{name}: {reference} non ha tutti i fotogrammi dichiarati");
var frames = new List();
var decoder = new H264Decoder { DecodeEnhancementLayers = enhancementLayers };
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(stream);
var ordered = OutputOrder(frames);
var actual = ordered.Select(Md5).ToList();
for (var i = 0; i < Math.Min(actual.Count, expected.Count); i++)
{
if (actual[i] != expected[i])
{
var f = ordered[i];
Assert.Fail($"{name}: il fotogramma {i} (decodifica {f.DecodeIndex}, POC {f.Poc}, {f.Width}×{f.Height}) è diverso dal riferimento.");
}
}
Assert.AreEqual(expected.Count, actual.Count, $"{name}: numero di fotogrammi");
}
/// The frame MD5s of a riferimento.md5, in output order.
internal static List ReferenceFrames(string name) => ReadReference(Path.Combine(Folder(name), "riferimento.md5"), out _);
/// The MD5 of each frame of a stream, in output order.
internal static List FrameMd5s(byte[] stream)
{
var frames = new List();
var decoder = new H264Decoder();
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(stream);
return OutputOrder(frames).Select(Md5).ToList();
}
private static List Decode(string stream, out string? skipped)
{
var frames = new List();
var decoder = new H264Decoder();
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(File.ReadAllBytes(stream));
skipped = decoder.EnhancementLayersSkipped;
return OutputOrder(frames).Select(Md5).ToList();
}
private static List OutputOrder(List frames) =>
frames.OrderBy(f => f.Period).ThenBy(f => f.Poc).ThenBy(f => f.DecodeIndex).ToList();
/// The mean luma step across 8-sample block edges over the mean step inside the blocks (about 1 for a clean picture).
private static double Blockiness(H264Frame frame)
{
long edge = 0, inside = 0, edges = 0, insides = 0;
for (var y = 0; y < frame.Height; y++)
{
for (var x = 1; x < frame.Width; x++)
{
var step = Math.Abs(frame.Y[(y * frame.Width) + x] - frame.Y[(y * frame.Width) + x - 1]);
if ((x & 7) == 0)
{
edge += step;
edges++;
}
else
{
inside += step;
insides++;
}
}
}
return ((double)edge / edges) / Math.Max(0.01, (double)inside / insides);
}
private static string Md5(H264Frame frame) => Convert.ToHexStringLower(MD5.HashData(frame.ToPlanar()));
///
/// The frame MD5s of a riferimento.md5, in output order, and the number of frames its first line declares (0 when
/// the file only says that there is no official reconstruction).
///
private static List ReadReference(string path, out int declared)
{
var frames = new List();
declared = 0;
foreach (var line in File.ReadAllLines(path))
{
if (frames.Count == 0 && declared == 0 && line.StartsWith('#'))
{
var count = Regex.Match(line, @" (\d+) fotogrammi,");
if (count.Success)
{
declared = int.Parse(count.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);
}
}
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 2 && int.TryParse(parts[0], out var index))
{
Assert.AreEqual(frames.Count, index, "riferimento.md5 fuori ordine");
frames.Add(parts[1]);
}
}
return frames;
}
}