Files
Febe/tests/Febe.Tests/Media/H265/H265ConformanceTests.cs
T
Alby96andClaude Opus 5.5 d5e1282261 Decodificatore HEVC, seconda parte: predizione inter, tutti i flussi Main e Main 10 coincidono (#58)
La predizione inter scritta dalla norma ITU-T H.265 (§8.3.4, §8.5.3): liste di
riferimento con le modifiche, merge con candidati spaziali, temporale,
bi-predittivi combinati e nulli e livello di merge parallelo, AMVP con la scala
per distanza di POC, TMVP sull'immagine co-locata, interpolazione a 8 prese per
la luma e 4 per il croma, predizione pesata di base ed esplicita. Il deblocking
prende l'intensità 1 anche dal moto; ogni immagine conserva il moto dei blocchi
4x4, la slice di ogni CTB e le liste delle sue slice per chi la usa come
co-locata. Un riferimento mancante diventa un'immagine grigia fuori dal DPB.
I filtri d'interpolazione usano i vettori della BCL (Vector128).

Perché: senza inter nessun video HEVC reale si decodifica. Ora i 136 flussi
Main, Main 10 e Main Still Picture della serie ITU-T H.265.1 danno esattamente
il YUV ufficiale e ogni immagine il suo hash SEI; questo conferma anche il
numero di fotogrammi e gli MD5 scelti per i flussi senza YUV. Restano
inconcludenti solo i 10 flussi RExt, in attesa della decisione di Alberto.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 16:18:32 +01:00

157 lines
7.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Security.Cryptography;
using Febe.Core.Codecs.H265;
namespace Febe.Tests.Codecs.H265;
/// <summary>
/// The streams of the ITU-T H.265.1 conformance set in Media/H265/Conformita (see LEGGIMI.md there). Every Main, Main 10
/// and Main Still Picture stream must give exactly the frames of its official YUV (the MD5 of each frame where the YUV
/// came with the stream, of the whole YUV for all); the range extension streams (4:0:0, 4:2:2, 4:4:4, 12 bits, RExt
/// tools) stay inconclusive until Alberto says whether «HEVC» covers them.
/// </summary>
[TestClass]
public sealed class H265ConformanceTests
{
public static IEnumerable<object[]> Streams => H265ConformanceStream.Names().Select(n => new object[] { n });
[TestMethod]
[DynamicData(nameof(Streams))]
public void FramesMatchTheReference(string name)
{
var stream = H265ConformanceStream.Load(name);
if (stream.IsRangeExtension)
{
Assert.Inconclusive($"{name}: estensione di formato (RExt, {stream.Chroma} a {stream.LumaBitDepth} bit), da decodificare solo se Alberto la vuole.");
}
var frames = new List<byte[]>();
var decoder = new H265Decoder();
decoder.FrameOutput += frame => frames.Add(frame.ToYuvFile());
decoder.DecodeAnnexB(File.ReadAllBytes(stream.BitstreamPath));
decoder.Flush();
Assert.IsNull(stream.Compare(frames));
}
[TestMethod]
public void TheSetIsTheOneTheReadmeDescribes()
{
var names = H265ConformanceStream.Names().ToList();
Assert.HasCount(146, names);
Assert.AreEqual(10, names.Count(n => H265ConformanceStream.Load(n).IsRangeExtension));
var readme = File.ReadAllText(Path.Combine(H265ConformanceStream.Root, "LEGGIMI.md"));
var missing = names.Where(n => !readme.Contains($"`{n}`", StringComparison.Ordinal)).ToList();
Assert.IsEmpty(missing, $"LEGGIMI.md non descrive: {string.Join(", ", missing)}");
Assert.AreEqual(15, names.Count(n => H265ConformanceStream.Load(n).FrameMd5.Count > 0), "flussi con il YUV ufficiale");
}
[TestMethod]
[DynamicData(nameof(Streams))]
public void TheReferenceIsComplete(string name)
{
var stream = H265ConformanceStream.Load(name);
Assert.IsGreaterThan(0, stream.FrameCount);
Assert.AreEqual(32, stream.TotalMd5.Length, $"{name}: manca la riga «tutto»");
Assert.IsTrue(stream.FrameMd5.Count == 0 || stream.FrameMd5.Count == stream.FrameCount, $"{name}: righe per fotogramma");
Assert.IsTrue(stream.LumaBitDepth is >= 8 and <= 12 && stream.ChromaBitDepth is >= 8 and <= 12, $"{name}: profondità");
if (stream.Size is var (width, height))
{
Assert.AreEqual(stream.FrameCount * stream.FrameBytes(width, height), stream.ByteCount, $"{name}: byte del YUV");
}
else
{
// A stream that changes size: at least the bytes are a sum of frames of the sizes it lists.
Assert.IsGreaterThan(1, stream.Sizes.Count);
Assert.IsTrue(stream.Sizes.Any(s => stream.ByteCount >= stream.FrameBytes(s.Width, s.Height)), $"{name}: byte del YUV");
}
if (!stream.IsRangeExtension)
{
Assert.AreEqual("4:2:0", stream.Chroma, $"{name}: i profili Main, Main 10 e Main Still Picture sono 4:2:0");
Assert.IsLessThanOrEqualTo(10, Math.Max(stream.LumaBitDepth, stream.ChromaBitDepth), name);
}
var data = File.ReadAllBytes(stream.BitstreamPath);
CollectionAssert.AreEqual(new byte[] { 0, 0, 1 }, data.AsSpan(data[2] == 1 ? 0 : 1, 3).ToArray(), $"{name}: non comincia con un codice d'inizio (Annex B)");
}
[TestMethod]
[DynamicData(nameof(Streams))]
public void EveryDecodedPictureHasOneHashOrNoneHas(string name)
{
// Counted independently from the bitstream: either no picture carries a decoded picture hash, or every coded
// picture carries exactly one, with one value per colour component. NUT_A is the exception: its two RASL
// pictures after a BLA, which a decoder skips, have none.
var stream = H265ConformanceStream.Load(name);
var data = File.ReadAllBytes(stream.BitstreamPath);
var hashes = H265PictureHashes.Read(data);
if (hashes.Count == 0)
{
return;
}
var pictures = CountPictures(data);
var expected = name == "NUT_A_ericsson_5" ? pictures - 2 : pictures;
Assert.HasCount(expected, hashes, $"{name}: {pictures} immagini");
Assert.AreEqual(hashes.Count, hashes.Select(h => h.Picture).Distinct().Count(), name);
var planes = stream.Chroma == "4:0:0" ? 1 : 3;
Assert.IsTrue(hashes.All(h => h.Planes.Length == planes), $"{name}: componenti per hash");
var type = name is "HRD_A_Fujitsu_3" or "PICSIZE_C_Bossen_1" or "PICSIZE_D_Bossen_1" ? H265HashType.Checksum : H265HashType.Md5;
Assert.IsTrue(hashes.All(h => h.Type == type), $"{name}: tipo di hash");
}
[TestMethod]
public void PictureHashesFollowTheDefinition()
{
// 3×2 samples in a stride of 4; the fourth column must be left out.
ushort[] samples = [1, 2, 3, 999, 4, 5, 6, 999];
CollectionAssert.AreEqual(MD5.HashData(new byte[] { 1, 2, 3, 4, 5, 6 }), H265PictureHashes.Compute(H265HashType.Md5, samples, 3, 2, 4, 8));
ushort[] wide = [0x3FF, 0x100];
CollectionAssert.AreEqual(MD5.HashData(new byte[] { 0xFF, 0x03, 0x00, 0x01 }), H265PictureHashes.Compute(H265HashType.Md5, wide, 2, 1, 2, 10));
// Checksum (D.3.19): every sample xored with (x & 0xFF) ^ (y & 0xFF) ^ (x >> 8) ^ (y >> 8), high byte too above 8 bits.
var expected = (1 ^ 0) + (2 ^ 1) + (3 ^ 2) + (4 ^ 1) + (5 ^ 0) + (6 ^ 3);
CollectionAssert.AreEqual(new byte[] { 0, 0, 0, (byte)expected }, H265PictureHashes.Compute(H265HashType.Checksum, samples, 3, 2, 4, 8));
var expectedWide = (0xFF ^ 0) + (0x03 ^ 0) + (0x00 ^ 1) + (0x01 ^ 1);
CollectionAssert.AreEqual(new byte[] { 0, 0, (byte)(expectedWide >> 8), (byte)expectedWide }, H265PictureHashes.Compute(H265HashType.Checksum, wide, 2, 1, 2, 10));
// CRC (D.3.19): bit by bit from 0xFFFF with the polynomial 0x1021 over the bytes and two zero bytes, which is
// CRC-16/AUG-CCITT: 0x1D0F over no bytes, 0xE5CC over "123456789" (the check value of that CRC).
CollectionAssert.AreEqual(new byte[] { 0x1D, 0x0F }, H265PictureHashes.Compute(H265HashType.Crc, ReadOnlySpan<ushort>.Empty, 0, 0, 0, 8));
ushort[] digits = [.. "123456789".Select(c => (ushort)c)];
CollectionAssert.AreEqual(new byte[] { 0xE5, 0xCC }, H265PictureHashes.Compute(H265HashType.Crc, digits, 9, 1, 9, 8));
}
[TestMethod]
public void AStreamOfOnePictureHasItsHash()
{
// IPRED_B (Main Still Picture, one 1920×1080 picture): one MD5 per component, decoding index 0.
var data = File.ReadAllBytes(H265ConformanceStream.Load("IPRED_B_Nokia_3").BitstreamPath);
var hash = H265PictureHashes.Read(data).Single();
Assert.AreEqual(0, hash.Picture);
Assert.AreEqual(H265HashType.Md5, hash.Type);
Assert.IsTrue(hash.Planes.All(p => p.Length == 16));
}
/// <summary>Coded pictures of layer 0: VCL NAL units whose slice segment header starts with first_slice_segment_in_pic_flag = 1.</summary>
private static int CountPictures(byte[] data)
{
var count = 0;
for (var i = 0; i + 5 < data.Length; i++)
{
if (data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1)
{
var type = (data[i + 3] >> 1) & 63;
var layer = ((data[i + 3] & 1) << 5) | (data[i + 4] >> 3);
if (type < 32 && layer == 0 && (data[i + 5] & 0x80) != 0)
{
count++;
}
i += 2;
}
}
return count;
}
}