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

@@ -1,18 +1,23 @@
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). There is no HEVC
/// decoder yet: every stream is inconclusive until it exists, and 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. The reference data and the
/// reader of the decoded picture hashes are checked now.
/// The streams of the ITU-T H.265.1 conformance set in Media/H265/Conformita (see LEGGIMI.md there). The decoder has no
/// inter prediction yet: the streams with only I slices must match their YUV exactly, the others are inconclusive (their
/// intra pictures are checked in <see cref="H265DecoderTests"/>), and 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
{
/// <summary>Streams the decoder is expected to reproduce exactly; empty while the decoder is not written.</summary>
private static readonly HashSet<string> s_supported = [];
/// <summary>Streams the decoder is expected to reproduce exactly: those of Main, Main 10 and Main Still Picture made only of I slices.</summary>
private static readonly HashSet<string> s_supported =
[
"IPRED_A_docomo_2", "IPRED_B_Nokia_3", "IPRED_C_Mitsubishi_3", "ipcm_A_NEC_3", "ipcm_B_NEC_3", "ipcm_C_NEC_3",
"ipcm_D_NEC_3", "ipcm_E_NEC_2", "MAXBINS_A_TI_5", "POC_A_Bossen_3", "SAO_H_Parabola_1", "VPSSPSPPS_A_MainConcept_1",
];
public static IEnumerable<object[]> Streams => H265ConformanceStream.Names().Select(n => new object[] { n });
@@ -28,11 +33,15 @@ public sealed class H265ConformanceTests
if (!s_supported.Contains(name))
{
Assert.Inconclusive($"{name}: il decodificatore HEVC non è ancora scritto.");
Assert.Inconclusive($"{name}: ha slice P o B, e la predizione inter HEVC non è ancora scritta.");
}
// The decoder goes here: frames in output order, in the layout of the official YUV file.
Assert.Fail($"{name}: manca la decodifica.");
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]
@@ -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}");
}
}
}
}
@@ -0,0 +1,190 @@
using Febe.Core.Codecs.H265;
namespace Febe.Tests.Codecs.H265;
/// <summary>The tables of the HEVC decoder against values read in ITU-T H.265, independently of how the code builds them.</summary>
[TestClass]
public sealed class H265TablesTests
{
[TestMethod]
public void TheDctMatrixHasTheRowsOfTheStandard()
{
// §8.6.4.2: row 0 is 64 everywhere; the odd rows of the 32-, 16-, 8- and 4-point matrices start as listed.
short[] row1 = [90, 90, 88, 85, 82, 78, 73, 67, 61, 54, 46, 38, 31, 22, 13, 4];
short[] row2 = [90, 87, 80, 70, 57, 43, 25, 9];
short[] row4 = [89, 75, 50, 18];
short[] row8 = [83, 36];
for (var n = 0; n < 32; n++)
{
Assert.AreEqual(64, H265Tables.DctMatrix[n]);
}
CollectionAssert.AreEqual(row1, H265Tables.DctMatrix.AsSpan(32, 16).ToArray());
CollectionAssert.AreEqual(row2, H265Tables.DctMatrix.AsSpan(2 * 32, 8).ToArray());
CollectionAssert.AreEqual(row4, H265Tables.DctMatrix.AsSpan(4 * 32, 4).ToArray());
CollectionAssert.AreEqual(row8, H265Tables.DctMatrix.AsSpan(8 * 32, 2).ToArray());
// The 4-point matrix: rows 0, 8, 16 and 24, first four columns.
short[] four = [64, 64, 64, 64, 83, 36, -36, -83, 64, -64, -64, 64, 36, -83, 83, -36];
for (var k = 0; k < 4; k++)
{
CollectionAssert.AreEqual(four.AsSpan(k * 4, 4).ToArray(), H265Tables.DctMatrix.AsSpan(k * 8 * 32, 4).ToArray(), $"riga {k}");
}
// Even rows are symmetric, odd rows antisymmetric.
for (var k = 0; k < 32; k++)
{
for (var n = 0; n < 16; n++)
{
var sign = (k & 1) == 0 ? 1 : -1;
Assert.AreEqual(H265Tables.DctMatrix[(k * 32) + n], sign * H265Tables.DctMatrix[(k * 32) + 31 - n], $"k {k}, n {n}");
}
}
}
[TestMethod]
public void TheDstAndTheSmallTablesAreThoseOfTheStandard()
{
CollectionAssert.AreEqual(new short[] { 29, 55, 74, 84, 74, 74, 0, -74, 84, -29, -74, 55, 55, -84, 74, -29 }, H265Tables.DstMatrix);
CollectionAssert.AreEqual(new[] { 40, 45, 51, 57, 64, 72 }, H265Tables.LevelScale);
CollectionAssert.AreEqual(new byte[] { 29, 30, 31, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37 }, H265Tables.ChromaQp30To43);
// Table 8-12: β′ is 0 up to Q 15, 6 at 16, 64 at 51; tC′ is 0 up to 17, 1 at 18, 24 at 53.
Assert.HasCount(52, H265Tables.Beta);
Assert.HasCount(54, H265Tables.Tc);
Assert.AreEqual(0, H265Tables.Beta[15]);
Assert.AreEqual(6, H265Tables.Beta[16]);
Assert.AreEqual(18, H265Tables.Beta[28]);
Assert.AreEqual(20, H265Tables.Beta[29]);
Assert.AreEqual(64, H265Tables.Beta[51]);
Assert.AreEqual(0, H265Tables.Tc[17]);
Assert.AreEqual(1, H265Tables.Tc[18]);
Assert.AreEqual(4, H265Tables.Tc[37]);
Assert.AreEqual(24, H265Tables.Tc[53]);
// Tables 8-4 and 8-5.
Assert.AreEqual(32, H265Tables.IntraPredAngle[2]);
Assert.AreEqual(0, H265Tables.IntraPredAngle[10]);
Assert.AreEqual(-32, H265Tables.IntraPredAngle[18]);
Assert.AreEqual(0, H265Tables.IntraPredAngle[26]);
Assert.AreEqual(32, H265Tables.IntraPredAngle[34]);
Assert.AreEqual(-4096, H265Tables.InvAngle[11 - 11]);
Assert.AreEqual(-256, H265Tables.InvAngle[18 - 11]);
Assert.AreEqual(-4096, H265Tables.InvAngle[25 - 11]);
for (var mode = 11; mode <= 25; mode++)
{
// invAngle = Round(256 × 32 ÷ intraPredAngle).
Assert.AreEqual((int)Math.Round(8192.0 / H265Tables.IntraPredAngle[mode]), H265Tables.InvAngle[mode - 11], $"modo {mode}");
}
// Table 7-6.
Assert.AreEqual(16, H265Tables.DefaultScalingIntra[0]);
Assert.AreEqual(17, H265Tables.DefaultScalingIntra[10]);
Assert.AreEqual(115, H265Tables.DefaultScalingIntra[63]);
Assert.AreEqual(17, H265Tables.DefaultScalingInter[10]);
Assert.AreEqual(91, H265Tables.DefaultScalingInter[63]);
}
[TestMethod]
public void TheScansArePermutationsInTheOrderOfTheStandard()
{
for (var log2 = 0; log2 < 6; log2++)
{
var size = 1 << log2;
for (var scanIdx = 0; scanIdx < 3; scanIdx++)
{
var scan = H265Tables.ScanOrder[log2][scanIdx];
if (scan is null)
{
continue;
}
var positions = scan.Select(p => (p >> 8) * size + (p & 0xFF)).ToList();
Assert.HasCount(size * size, positions, $"log2 {log2}, scanIdx {scanIdx}");
Assert.AreEqual(size * size, positions.Distinct().Count(), $"log2 {log2}, scanIdx {scanIdx}");
}
}
// §6.5.3: the up-right diagonal starts (0,0), (0,1), (1,0), (0,2), (1,1), (2,0) as (x, y).
var diagonal = H265Tables.ScanOrder[2][0];
(int X, int Y)[] start = [(0, 0), (0, 1), (1, 0), (0, 2), (1, 1), (2, 0)];
for (var i = 0; i < start.Length; i++)
{
Assert.AreEqual(start[i], (diagonal[i] & 0xFF, diagonal[i] >> 8), $"posizione {i}");
}
// Horizontal goes along the rows, vertical along the columns.
Assert.AreEqual((1, 0), (H265Tables.ScanOrder[2][1][1] & 0xFF, H265Tables.ScanOrder[2][1][1] >> 8));
Assert.AreEqual((0, 1), (H265Tables.ScanOrder[2][2][1] & 0xFF, H265Tables.ScanOrder[2][2][1] >> 8));
for (var scanIdx = 0; scanIdx < 3; scanIdx++)
{
var scan = H265Tables.ScanOrder[2][scanIdx];
for (var i = 0; i < 16; i++)
{
Assert.AreEqual(i, H265Tables.ScanPosition4x4[scanIdx][((scan[i] >> 8) * 4) + (scan[i] & 0xFF)]);
}
}
}
[TestMethod]
public void TheCabacInitialValuesAreThoseOfTheStandard()
{
Assert.HasCount(173, CabacTables.InitValues[0]);
Assert.HasCount(3, CabacTables.InitValues);
Assert.IsTrue(CabacTables.InitValues.All(t => t.Length == CabacTables.ContextCount));
// Spot values of tables 9-5 to 9-37, by initType.
(int Context, byte I, byte P, byte B)[] spots =
[
(CabacTables.SaoTypeIdx, 200, 185, 160),
(CabacTables.SplitCuFlag + 2, 157, 126, 126),
(CabacTables.CuSkipFlag + 1, 154, 185, 185),
(CabacTables.PredModeFlag, 154, 149, 134),
(CabacTables.PartMode, 184, 154, 154),
(CabacTables.PartMode + 1, 154, 139, 139),
(CabacTables.PrevIntraLumaPredFlag, 184, 154, 183),
(CabacTables.IntraChromaPredMode, 63, 152, 152),
(CabacTables.MergeFlag, 154, 110, 154),
(CabacTables.MergeIdx, 154, 122, 137),
(CabacTables.InterPredIdc + 3, 154, 31, 31),
(CabacTables.SplitTransformFlag, 153, 124, 224),
(CabacTables.CbfLuma + 1, 141, 111, 111),
(CabacTables.CbfChroma + 1, 138, 107, 92),
(CabacTables.AbsMvdGreater0Flag, 154, 140, 169),
(CabacTables.LastSigCoeffXPrefix + 5, 153, 79, 94),
(CabacTables.LastSigCoeffYPrefix + 17, 63, 108, 93),
(CabacTables.CodedSubBlockFlag + 2, 134, 61, 61),
(CabacTables.SigCoeffFlag, 111, 155, 170),
(CabacTables.SigCoeffFlag + 41, 111, 140, 140),
(CabacTables.CoeffAbsLevelGreater1Flag + 21, 227, 167, 152),
(CabacTables.CoeffAbsLevelGreater2Flag + 3, 167, 122, 107),
];
foreach (var (context, i, p, b) in spots)
{
Assert.AreEqual(i, CabacTables.InitValues[0][context], $"contesto {context}, I");
Assert.AreEqual(p, CabacTables.InitValues[1][context], $"contesto {context}, P");
Assert.AreEqual(b, CabacTables.InitValues[2][context], $"contesto {context}, B");
}
}
[TestMethod]
public void ContextsAreInitialisedWithTheFormulaOfTheStandard()
{
// §9.3.2.2, m = slopeIdx × 5 − 45 and n = (offsetIdx << 3) − 16. 154: m = 0, n = 64, so preCtxState 64 at any
// QP: valMps 1, pStateIdx 0.
var engine = new CabacEngine();
engine.InitContexts(0, 26);
Assert.AreEqual((0 << 1) | 1, engine.Contexts[CabacTables.CuTransquantBypassFlag]);
// 63 (intra_chroma_pred_mode, I): m = −30, n = 104; at QP 26 ((−30 × 26) >> 4) + 104 = 55: valMps 0, pStateIdx 8.
Assert.AreEqual(8 << 1, engine.Contexts[CabacTables.IntraChromaPredMode]);
// 139 (split_cu_flag, ctxInc 0, I): m = −5, n = 72; at QP 26 ((−5 × 26) >> 4) + 72 = 63: valMps 0, pStateIdx 0.
Assert.AreEqual(0, engine.Contexts[CabacTables.SplitCuFlag]);
// At QP 51 the same context: ((−5 × 51) >> 4) + 72 = 56: pStateIdx 7. Clip3(0, 51, SliceQpY) for QP above 51.
engine.InitContexts(0, 51);
Assert.AreEqual(7 << 1, engine.Contexts[CabacTables.SplitCuFlag]);
}
}