using Febe.Core.Codecs.H264;
using Febe.Core.Codecs.H265;
using Pps = Febe.Core.Codecs.H265.Pps;
using Sps = Febe.Core.Codecs.H265.Sps;
namespace Febe.Tests.Codecs.H265;
///
/// The HEVC decoder beyond the whole frames of : every decoded picture of every stream
/// of the set, in decoding order and before cropping, against the hash its encoder wrote in the bitstream (so a wrong
/// picture is found where it first goes wrong, also when it is never output); length-prefixed samples; damaged streams.
///
[TestClass]
public sealed class H265DecoderTests
{
public static IEnumerable AllStreams => H265ConformanceStream.Names().Select(n => new object[] { n });
[TestMethod]
[DynamicData(nameof(AllStreams))]
public void EveryPictureMatchesItsHash(string name)
{
var stream = H265ConformanceStream.Load(name);
var data = File.ReadAllBytes(stream.BitstreamPath);
var hashes = H265PictureHashes.Read(data).ToDictionary(h => h.Picture);
var decoder = new H265Decoder();
int decoded = 0, hashed = 0;
var wrong = new List();
decoder.PictureDecoded += picture =>
{
decoded++;
if (!hashes.TryGetValue((int)picture.DecodeIndex, out var hash))
{
return;
}
hashed++;
for (var c = 0; c < hash.Planes.Length; c++)
{
var width = c == 0 ? picture.Width : picture.ChromaWidth;
var height = c == 0 ? picture.Height : picture.ChromaHeight;
var actual = H265PictureHashes.Compute(hash.Type, picture.Planes[c], width, height, width, picture.BitDepth(c));
if (!actual.AsSpan().SequenceEqual(hash.Planes[c]))
{
wrong.Add($"immagine {picture.DecodeIndex} (POC {picture.Poc}), componente {c}");
break;
}
}
};
var frames = 0;
decoder.FrameOutput += _ => frames++;
decoder.DecodeAnnexB(data);
Assert.IsEmpty(wrong, $"{name}: {string.Join("; ", wrong)}");
if (hashes.Count > 0)
{
// Every decoded picture has its hash; the hashes left are those of RASL pictures that are skipped.
Assert.AreEqual(decoded, hashed, $"{name}: immagini decodificate senza hash");
Assert.IsLessThanOrEqualTo(decoder.PicturesDecoded - decoded, hashes.Count - hashed, $"{name}: hash senza immagine");
}
Assert.AreEqual(stream.FrameCount, frames, $"{name}: fotogrammi in uscita");
}
[TestMethod]
public void TheHashesCoverInterPictures()
{
// The check above is worth something for inter prediction only if the hashes cover P and B pictures: count
// them in the streams that carry hashes, decoding a few streams whose names say they are about inter tools.
string[] names = ["MERGE_A_TI_3", "TMVP_A_MS_3", "WP_A_Toshiba_3", "WP_B_Toshiba_3", "PMERGE_A_TI_3", "MVCLIP_A_qualcomm_3", "MVEDGE_A_qualcomm_3", "SAO_A_MediaTek_4", "RAP_B_Bossen_2"];
var none = new List();
foreach (var name in names)
{
var data = File.ReadAllBytes(H265ConformanceStream.Load(name).BitstreamPath);
var hashes = H265PictureHashes.Read(data).Select(h => h.Picture).ToHashSet();
var inter = 0;
var decoder = new H265Decoder();
decoder.PictureDecoded += picture => inter += !picture.IntraOnly && hashes.Contains((int)picture.DecodeIndex) ? 1 : 0;
decoder.DecodeAnnexB(data);
if (inter == 0)
{
none.Add(name);
}
}
Assert.IsEmpty(none, $"nessuna immagine inter con hash: {string.Join(", ", none)}");
}
[TestMethod]
public void TheSetExercisesEveryTool()
{
// The hash checks are worth something for a tool only if some stream of the set turns it on: read the parameter
// sets of every stream and look for each tool the decoder claims to handle.
var seen = new HashSet();
byte[]? buffer = null;
foreach (var name in H265ConformanceStream.Names())
{
var data = File.ReadAllBytes(H265ConformanceStream.Load(name).BitstreamPath);
var position = 0;
while (NalUnits.NextAnnexB(data, ref position, out var unit))
{
var nal = data.AsSpan(unit);
if (nal.Length < 3 || (nal[0] & 1) != 0 || (nal[1] >> 3) != 0)
{
continue;
}
var type = (nal[0] >> 1) & 63;
if (type == 33)
{
var s = Sps.Parse(H265NalUnit.Unescape(nal, ref buffer).Reader());
Mark(seen, "liste di scala", s.ScalingListEnabled);
Mark(seen, "lungo termine", s.LongTermRefsPresent);
Mark(seen, "PCM", s.PcmEnabled);
Mark(seen, "4:0:0", s.ChromaArrayType == 0);
Mark(seen, "4:2:2", s.ChromaArrayType == 2);
Mark(seen, "4:4:4", s.ChromaArrayType == 3);
Mark(seen, "12 bit", s.BitDepthY == 12);
Mark(seen, "rotazione", s.TransformSkipRotationEnabled);
Mark(seen, "contesto del transform skip", s.TransformSkipContextEnabled);
Mark(seen, "RDPCM implicito", s.ImplicitRdpcmEnabled);
Mark(seen, "smoothing intra spento", s.IntraSmoothingDisabled);
Mark(seen, "Rice persistente", s.PersistentRiceAdaptationEnabled);
Mark(seen, "RDPCM esplicito", s.ExplicitRdpcmEnabled);
}
else if (type == 34)
{
var p = Pps.Parse(H265NalUnit.Unescape(nal, ref buffer).Reader());
Mark(seen, "tile", p.TilesEnabled);
Mark(seen, "tile non uniformi", p.TilesEnabled && !p.UniformSpacing);
Mark(seen, "deblocking non attraverso i tile", p.TilesEnabled && !p.LoopFilterAcrossTilesEnabled);
Mark(seen, "WPP", p.EntropyCodingSyncEnabled);
Mark(seen, "segmenti dipendenti", p.DependentSliceSegmentsEnabled);
Mark(seen, "liste di scala nel PPS", p.ScalingList is not null);
Mark(seen, "predizione fra componenti", p.CrossComponentPredictionEnabled);
Mark(seen, "chroma_qp_offset_list", p.ChromaQpOffsetListEnabled);
}
}
}
string[] tools =
[
"liste di scala", "liste di scala nel PPS", "lungo termine", "PCM", "tile", "tile non uniformi",
"deblocking non attraverso i tile", "WPP", "segmenti dipendenti", "4:0:0", "4:2:2", "4:4:4", "12 bit",
"rotazione", "contesto del transform skip", "RDPCM implicito", "smoothing intra spento", "Rice persistente",
"predizione fra componenti", "chroma_qp_offset_list", "RDPCM esplicito",
];
var missing = tools.Where(t => !seen.Contains(t)).ToList();
Assert.IsEmpty(missing, $"strumenti che nessun flusso usa: {string.Join(", ", missing)}");
}
private static void Mark(HashSet seen, string tool, bool used)
{
if (used)
{
seen.Add(tool);
}
}
[TestMethod]
[DataRow("IPRED_A_docomo_2")]
[DataRow("IPRED_C_Mitsubishi_3")]
[DataRow("ipcm_E_NEC_2")]
public void LengthPrefixedSamplesGiveTheSameFrames(string name)
{
// The stream as an MP4 would hold it: VPS, SPS and PPS in an hvcC record, each access unit a sample of NAL
// units with a 4-byte length.
var stream = H265ConformanceStream.Load(name);
var data = File.ReadAllBytes(stream.BitstreamPath);
var parameterSets = new List();
var samples = new List>();
var position = 0;
while (NalUnits.NextAnnexB(data, ref position, out var range))
{
var nal = data[range];
var type = (nal[0] >> 1) & 63;
if (type is >= 32 and <= 34 && samples.Count == 0)
{
parameterSets.Add(nal);
}
else
{
if (samples.Count == 0 || (type < 32 && (nal[2] & 0x80) != 0 && samples[^1].Any(n => ((n[0] >> 1) & 63) < 32)))
{
samples.Add([]);
}
samples[^1].Add(nal);
}
}
var hvcC = new List(new byte[21]) { 0xFC | 3, 1, 0x20, (byte)(parameterSets.Count >> 8), (byte)parameterSets.Count };
hvcC[0] = 1;
foreach (var set in parameterSets)
{
hvcC.AddRange([(byte)(set.Length >> 8), (byte)set.Length, .. set]);
}
var frames = new List();
var decoder = new H265Decoder();
decoder.FrameOutput += frame => frames.Add(frame.ToYuvFile());
Assert.AreEqual(4, decoder.ConfigureHvcC([.. hvcC]));
foreach (var sample in samples)
{
var bytes = new List();
foreach (var nal in sample)
{
bytes.AddRange([(byte)(nal.Length >> 24), (byte)(nal.Length >> 16), (byte)(nal.Length >> 8), (byte)nal.Length, .. nal]);
}
decoder.DecodeSample([.. bytes], 4);
}
decoder.Flush();
Assert.IsNull(stream.Compare(frames));
}
[TestMethod]
[DataRow("IPRED_A_docomo_2", 2701)]
[DataRow("IPRED_C_Mitsubishi_3", 2702)]
[DataRow("ipcm_A_NEC_3", 2703)]
[DataRow("ipcm_E_NEC_2", 2704)]
[DataRow("SAO_H_Parabola_1", 2705)]
[DataRow("MAXBINS_A_TI_5", 2706)]
[DataRow("CAINIT_E_SHARP_3", 2707)]
[DataRow("WPP_C_ericsson_MAIN_2", 2708)]
[DataRow("TILES_B_Cisco_1", 2709)]
[DataRow("DSLICE_A_HHI_5", 2710)]
[DataRow("MVEDGE_A_qualcomm_3", 2711)]
[DataRow("WP_B_Toshiba_3", 2712)]
[DataRow("TMVP_A_MS_3", 2713)]
[DataRow("PMERGE_B_TI_3", 2714)]
public void DamagedStreamsGiveFramesOrAnH265Exception(string name, int seed)
{
var data = File.ReadAllBytes(H265ConformanceStream.Load(name).BitstreamPath);
if (data.Length > 400_000)
{
data = data[..400_000];
}
var random = new Random(seed);
for (var trial = 0; trial < 12; 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 H265Decoder();
decoder.FrameOutput += _ => { };
decoder.DecodeAnnexB(copy);
}
catch (H265Exception)
{
}
catch (Exception ex)
{
Assert.Fail($"{name}, variante {trial} del seme {seed}: {ex.GetType().Name} {ex.Message}\n{ex.StackTrace}");
}
}
}
}