Decodificatore HEVC scritto in casa, prima parte: le immagini intra coincidono coi flussi di conformità (#58)

Per leggere i video HEVC senza ffmpeg serve un decodificatore nostro, scritto dalla
norma ITU-T H.265. Questa prima parte copre tutto ciò che serve alle immagini intra:
unità NAL Annex B e hvcC, VPS/SPS/PPS (liste di scala, VUI, indicatori RExt),
intestazione di slice, POC, RPS, DPB con uscita e bumping (C.5.2), CABAC con tutte
le tabelle d'inizio, albero di codifica, unità di predizione, residui con sign data
hiding e transform skip, predizione intra, DCT/DST e dequantizzazione, PCM,
deblocking e SAO, tile, WPP e segmenti dipendenti.

I 12 flussi di sole slice I dei profili Main, Main 10 e Main Still Picture coincidono
col YUV ufficiale. Nei 136 flussi Main e Main 10 ogni immagine di sole slice I
coincide con l'MD5 SEI del codificatore, dove il flusso lo porta. Le slice P e B si
rifiutano finché manca la predizione inter (tappa successiva). Le prove ne leggono
comunque la sintassi fino alla fine di ogni slice, con le unità di predizione grigie.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 15:39:56 +01:00
1 parent 6274c4ee03
commit f77b5e4db6
17 files changed
+5708 -9

No files matched your search

@@ -0,0 +1,202 @@
using Febe.Core.Codecs.H264;
using Febe.Core.Codecs.H265;
namespace Febe.Tests.Codecs.H265;
/// <summary>
/// The HEVC decoder beyond the intra-only streams of <see cref="H265ConformanceTests"/>: 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.
/// </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 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<string>();
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<H265Exception>(() => 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<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)]
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}");
}
}
}
}