using Febe.Core.Codecs.H264; using Febe.Core.Codecs.H265; namespace Febe.Tests.Codecs.H265; /// /// The HEVC decoder beyond the intra-only streams of : every picture made only of I /// slices, in every Main and Main 10 stream, against the MD5 its encoder wrote in the bitstream; the syntax of the P and /// B slices read to the end of every slice; 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 IntraPicturesMatchTheirHashAndEverySliceIsReadToItsEnd(string name) { var stream = H265ConformanceStream.Load(name); var data = File.ReadAllBytes(stream.BitstreamPath); var hashes = H265PictureHashes.Read(data).ToDictionary(h => h.Picture); // Inter prediction is not written: P and B slices are read with their prediction units mid-grey, so only the // pictures of I slices alone can be checked; reading every slice to its end_of_slice_segment_flag without an // error checks the inter syntax. var decoder = new H265Decoder { ParseInterSlices = true }; int decoded = 0, hashed = 0, intra = 0; var wrong = new List(); decoder.PictureDecoded += picture => { decoded++; if (!hashes.TryGetValue((int)picture.DecodeIndex, out var hash)) { return; } hashed++; if (!picture.IntraOnly) { return; } intra++; 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"); if (hashes.Count > 0) { Assert.IsGreaterThan(0, intra, $"{name}: nessuna immagine intra controllata"); } } [TestMethod] public void InterSlicesAreRefusedByDefault() { // BUMPING_A begins with an IDR picture and goes on with P and B slices: the IDR comes out, then the refusal. var data = File.ReadAllBytes(H265ConformanceStream.Load("BUMPING_A_ericsson_1").BitstreamPath); var decoder = new H265Decoder(); var error = Assert.ThrowsExactly(() => decoder.DecodeAnnexB(data)); StringAssert.Contains(error.Message, "inter"); Assert.IsGreaterThanOrEqualTo(1, decoder.PicturesDecoded); } [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)] 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 { ParseInterSlices = true }; 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}"); } } } }