Files
Febe/tests/Febe.Tests/Media/H265/H265DecoderTests.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

207 lines
7.8 KiB
C#

using Febe.Core.Codecs.H264;
using Febe.Core.Codecs.H265;
namespace Febe.Tests.Codecs.H265;
/// <summary>
/// The HEVC decoder beyond the whole frames of <see cref="H265ConformanceTests"/>: 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.
/// </summary>
[TestClass]
public sealed class H265DecoderTests
{
public static IEnumerable<object[]> 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<string>();
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<string>();
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<byte[]>();
var samples = new List<List<byte[]>>();
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<byte>(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<byte[]>();
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<byte>();
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}");
}
}
}
}