using Febe.Core.Codecs.H264; using Febe.Core.Codecs.H265; namespace Febe.Tests.Codecs.H265; /// /// The HEVC decoder beyond the whole frames of : every decoded picture of every Main and /// Main 10 stream, 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 MainStreams => H265ConformanceStream.Names() .Where(n => !H265ConformanceStream.Load(n).IsRangeExtension) .Select(n => new object[] { n }); [TestMethod] [DynamicData(nameof(MainStreams))] 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] [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}"); } } } }