Decodificatore H.264 per MVC e per le qualità MGS di SVC (#58)

MVC (Annex H): SPS di sottoinsieme, prefissi NAL 14 e slice NAL 20, un
decodificatore per vista con il suo stato, predizione fra viste (riferimenti
della stessa unità di accesso in coda alle liste, modifiche 4 e 5). Escono
tutte le viste, ciascuna con il suo ViewId; VideoFrameDecoder chiede solo la
vista base, che è il video 2D, per le miniature. I flussi MVC della serie non
hanno ricostruzione ufficiale: le prove controllano che ogni vista si
decodifichi pulita e che la vista base resti identica a quella di H.264 puro.

SVC (Annex G): lo strato base sempre; sopra, gli strati di qualità della
stessa risoluzione in CAVLC, decodificati uno sull'altro. Un macroblocco
intra con base_mode_flag somma il residuo accumulato alla ricostruzione dello
strato in cui era intra e per i vicini conta come I_BL. SVCBMT-13 coincide
ora con lo strato L2 ufficiale in tutti i 20 fotogrammi. Scalabilità
spaziale, CGS e CABAC negli strati di miglioramento non sono ancora scritti:
il decodificatore dà lo strato base esatto e dice perché, e SVCBST-19 e
SVCBCT-1 restano inconclusivi con l'elenco di ciò che manca.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 18:15:19 +01:00
1 parent da84c79f7e
commit 898e9d60e7
13 files changed
+1754 -59

No files matched your search

@@ -36,7 +36,7 @@ del riferimento.
dare un decodificatore H.264 che salta le unità NAL 14, 15 e 20, e lo si prova già.
- **MVC**: la cartella MVC dell'ITU-T contiene solo i flussi, senza ricostruzione né `readme` (gli zip che l'indice del
2010 elenca non sono sul server). `riferimento.md5` lo dice e non ha fotogrammi; il riferimento atteso, quando ci sarà, è
quello di tutte le viste. Per ora la prova controlla solo che la vista base si decodifichi.
quello di tutte le viste. Per ora le prove controllano che tutte le viste si decodifichino (vedi sotto).
## I flussi verificati
@@ -131,25 +131,42 @@ perdita con la sua DPCM, profondità da 11 a 14 bit, 10 bit in 4:2:0) le prova `
di I_PCM e di Intra_16x16 senza perdita, i cui campioni si conoscono esattamente. Il CABAC in 4:4:4 con i piani insieme
non è gestito (mancano i contesti 460–1023) e il decodificatore lo rifiuta.
`H264ConformanceTests.SvcBaseLayerMatchesTheReference`: lo strato base dei tre flussi SVC qui sotto, con
`riferimento-base.md5`.
**SVC** (Scalable Baseline; lo strato base è Baseline). `H264ConformanceTests.SvcBaseLayerMatchesTheReference`: lo
strato base dei tre flussi qui sotto, con `riferimento-base.md5`, chiesto al decodificatore con
`DecodeEnhancementLayers = false`. In `FramesMatchTheReference` c'è anche lo strato di destinazione di:
| Flusso | Formato | Che cosa prova |
|---|---|---|
| `SVCBMT-13` | 352×240, 20 fotogrammi | qualità MGS su tre livelli (L0, L1, L2, CAVLC), slice I e P, `adaptive_base_mode_flag`, `adaptive_motion_prediction_flag` e `adaptive_residual_prediction_flag`; strato L2 |
## I flussi delle parti ancora da fare
`H264ConformanceTests.FeaturesStillToDo`: per SVC e MVC il decodificatore dà solo lo strato o la vista base, e la
prova è **inconclusiva** con il messaggio «da fare: …», così la serie resta verde e il vuoto si vede. Quando una di queste coincide con il riferimento la prova **fallisce** apposta, per
ricordare di spostarla fra i flussi verificati.
`H264ConformanceTests.FeaturesStillToDo`: la prova è **inconclusiva** con il messaggio «da fare: …» (o «da
verificare: …» quando manca il riferimento), così la serie resta verde e il vuoto si vede. Quando uno di questi flussi
coincide con il riferimento la prova **fallisce** apposta, per ricordare di spostarlo fra i flussi verificati.
**SVC** (Scalable Baseline; lo strato base è Baseline):
**SVC**: per questi due il decodificatore dà lo strato base e dice perché non va oltre
(`EnhancementLayersSkipped`); `SvcLayersNotWrittenYetLeaveTheBaseLayer` controlla che lo strato base esca esatto anche
dal flusso intero.
| Flusso | Formato | Che cosa prova |
|---|---|---|
| `SVCBMT-13` | 352×240, 20 fotogrammi | qualità MGS su tre livelli (L0, L1, L2) e scalabilità temporale, SEI, `adaptive_base_mode_flag` e `adaptive_motion_prediction_flag` |
| `SVCBST-19` | 320×240 (30) e 640×480 (60) | scalabilità spaziale di rapporto 2 e temporale: P gerarchiche nello strato base, B gerarchiche in CABAC sopra |
| `SVCBCT-1` | 320×240, 150 e 300 | qualità CGS e scalabilità temporale: P gerarchiche nello strato base, B gerarchiche in CABAC sopra |
**MVC** (Multiview High; la vista base è High, 640×480, 9 fotogrammi): `MVCDS-4` (due viste) e `MVCNV-3` (tre viste),
senza riferimento.
Mancano, per questi due: `dependency_id` maggiore di 0 (la predizione fra strati di §G.8.6 con il sovracampionamento
di tessitura, residuo e moto, e per CGS la stessa senza cambio di risoluzione), i contesti CABAC di `base_mode_flag`,
`motion_prediction_flag_l0`/`_l1` e `residual_prediction_flag` (i loro valori iniziali non sono ancora trascritti
dallo standard); le slice B negli strati di qualità sono scritte ma senza un flusso che le verifichi. Non li usa nessuno dei tre flussi, e il decodificatore li
lascia allo strato base: immagini chiave (`store_ref_base_pic_flag`, `use_ref_base_pic_flag`), `scan_idx_start` e
`scan_idx_end` diversi da 0 e 15, `tcoeff_level_prediction_flag`, trasformata 8×8, interlacciato e formati diversi dal
4:2:0 a 8 bit negli strati di qualità.
**MVC** (Multiview High; la vista base è High, 640×480, 9 fotogrammi): `MVCDS-4` (due viste, `view_id` 0 e 2) e
`MVCNV-3` (tre viste), senza riferimento. `MvcDecodesEveryView` controlla che ogni vista dia 9 fotogrammi della misura
della vista base, che la vista base sia identica a quella che dà il decodificatore con `DecodeAllViews = false` (H.264
puro) e che le altre viste siano immagini pulite della stessa scena (scarto medio dalla vista base fra 0 e 40, bordi
dei blocchi sotto 1,5 volte la media interna); l'esattezza resta da verificare.
## Lasciati fuori, e perché
@@ -15,10 +15,11 @@ namespace Febe.Tests.Codecs.H264;
/// uses weighted prediction, gaps in frame_num, I_PCM, SI slices, sp_for_switch_flag, data partitioning or redundant
/// slices: data partitioning, redundant slices and other slice orders are checked on conformance streams rewritten by
/// <see cref="StreamRewriter"/> (<see cref="H264ExtendedToolsTests"/>), SI slices and the rest by
/// <see cref="H264SyntheticStreamTests"/>, without an official reference. The streams of the parts the decoder does not
/// handle yet (SVC, MVC) are in <see cref="FeaturesStillToDo"/>: they are inconclusive
/// until the feature is written, and fail as soon as one of them matches its reference without having been moved among
/// the verified ones.
/// <see cref="H264SyntheticStreamTests"/>, without an official reference. SVC: the target layer of SVCBMT-13 (MGS quality
/// refinement) is verified, the base layer of every SVC stream too. The streams of the parts the decoder does not handle
/// yet (SVC spatial and CGS) or that have no official reconstruction (MVC) are in <see cref="FeaturesStillToDo"/>: they
/// are inconclusive until the feature is written, and fail as soon as one of them matches its reference without having
/// been moved among the verified ones.
/// </summary>
[TestClass]
public sealed class H264ConformanceTests
@@ -68,6 +69,7 @@ public sealed class H264ConformanceTests
[DataRow("FREXT3_TANDBERG_A")]
[DataRow("HPCAMOLQ_BRCM_B")]
[DataRow("HPCVMOLQ_BRCM_B")]
[DataRow("SVCBMT-13")]
public void FramesMatchTheReference(string name) => AssertMatches(name, "riferimento.md5");
[TestMethod]
@@ -78,11 +80,71 @@ public sealed class H264ConformanceTests
{
// The base layer of an SVC stream is plain H.264: a decoder that skips NAL units 14, 15 and 20 (prefix, subset
// SPS, slice extension) must give exactly the official reconstruction of layer L0.
AssertMatches(name, "riferimento-base.md5");
AssertStreamMatches(name, File.ReadAllBytes(StreamFile(Folder(name))), "riferimento-base.md5", enhancementLayers: false);
}
[TestMethod]
[DataRow("SVCBST-19")]
[DataRow("SVCBCT-1")]
public void SvcLayersNotWrittenYetLeaveTheBaseLayer(string name)
{
// Spatial scalability and CGS are not written yet: the decoder says so and gives the base layer, exactly.
var data = File.ReadAllBytes(StreamFile(Folder(name)));
var frames = new List<H264Frame>();
var decoder = new H264Decoder();
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(data);
Assert.IsNotNull(decoder.EnhancementLayersSkipped);
CollectionAssert.AreEqual(ReadReference(Path.Combine(Folder(name), "riferimento-base.md5"), out _), OutputOrder(frames).Select(Md5).ToList());
}
[TestMethod]
[DataRow("MVCDS-4", 2)]
[DataRow("MVCNV-3", 3)]
public void MvcDecodesEveryView(string name, int views)
{
// Without an official reconstruction: every view decodes, with as many frames as the base view and its size; the
// base view is the same as the one a plain H.264 decoder gives, and the others are pictures of the same scene
// (close to the base view, the difference being the parallax) without the block edges a wrong prediction leaves.
var data = File.ReadAllBytes(StreamFile(Folder(name)));
var all = new List<H264Frame>();
var decoder = new H264Decoder();
decoder.FrameDecoded += all.Add;
decoder.DecodeAnnexB(data);
var baseOnly = new List<H264Frame>();
var plain = new H264Decoder { DecodeAllViews = false };
plain.FrameDecoded += baseOnly.Add;
plain.DecodeAnnexB(data);
var byView = all.GroupBy(f => f.ViewId).OrderBy(g => g.Key == baseOnly[0].ViewId ? -1 : g.Key).Select(g => OutputOrder(g.ToList())).ToList();
Assert.AreEqual(views, byView.Count, $"{name}: viste");
Assert.AreEqual(9, baseOnly.Count, $"{name}: fotogrammi della vista base");
CollectionAssert.AreEqual(OutputOrder(baseOnly).Select(Md5).ToList(), byView[0].Select(Md5).ToList(), $"{name}: vista base");
foreach (var view in byView.Skip(1))
{
Assert.AreEqual(baseOnly.Count, view.Count, $"{name}: fotogrammi della vista {view[0].ViewId}");
for (var i = 0; i < view.Count; i++)
{
var other = view[i];
var reference = byView[0][i];
Assert.AreEqual((reference.Width, reference.Height, reference.Poc), (other.Width, other.Height, other.Poc), $"{name}: vista {other.ViewId}, fotogramma {i}");
long sum = 0;
for (var k = 0; k < other.Y.Length; k++)
{
sum += Math.Abs(other.Y[k] - reference.Y[k]);
}
var mean = (double)sum / other.Y.Length;
Assert.IsTrue(mean is > 0 and < 40, $"{name}: vista {other.ViewId}, fotogramma {i}: scarto medio {mean:F1} dalla vista base");
var edges = Blockiness(other);
Assert.IsTrue(edges < 1.5, $"{name}: vista {other.ViewId}, fotogramma {i}: bordi dei blocchi {edges:F2}");
}
}
}
[TestMethod]
[DataRow("SVCBMT-13", "SVC, qualità MGS e scalabilità temporale (strato L2)")]
[DataRow("SVCBST-19", "SVC, scalabilità spaziale e temporale (strato L1, 640×480)")]
[DataRow("SVCBCT-1", "SVC, qualità CGS e scalabilità temporale (strato L1)")]
[DataRow("MVCDS-4", "MVC, due viste")]
@@ -94,9 +156,10 @@ public sealed class H264ConformanceTests
Assert.AreEqual(declared, expected.Count, $"{name}: riferimento.md5 non ha tutti i fotogrammi dichiarati");
List<string> actual;
string? skipped;
try
{
actual = Decode(StreamFile(folder));
actual = Decode(StreamFile(folder), out skipped);
}
catch (H264Exception ex)
{
@@ -106,7 +169,12 @@ public sealed class H264ConformanceTests
if (expected.Count == 0)
{
Assert.Inconclusive($"da fare: {feature}; manca la ricostruzione ufficiale (oggi escono {actual.Count} fotogrammi della vista base)");
Assert.Inconclusive($"da verificare: {feature}; manca la ricostruzione ufficiale (oggi escono {actual.Count} fotogrammi di tutte le viste, vedi {nameof(MvcDecodesEveryView)})");
}
if (skipped is not null)
{
Assert.Inconclusive($"da fare: {feature}; non ancora scritto: {skipped} (oggi esce lo strato base, {actual.Count} fotogrammi)");
}
var same = 0;
@@ -174,14 +242,14 @@ public sealed class H264ConformanceTests
/// <paramref name="stream"/> (the conformance stream <paramref name="name"/>, possibly rewritten) must give every frame
/// of the official reconstruction.
/// </summary>
internal static void AssertStreamMatches(string name, byte[] stream, string reference = "riferimento.md5")
internal static void AssertStreamMatches(string name, byte[] stream, string reference = "riferimento.md5", bool enhancementLayers = true)
{
var folder = Folder(name);
var expected = ReadReference(Path.Combine(folder, reference), out var declared);
Assert.AreEqual(declared, expected.Count, $"{name}: {reference} non ha tutti i fotogrammi dichiarati");
var frames = new List<H264Frame>();
var decoder = new H264Decoder();
var decoder = new H264Decoder { DecodeEnhancementLayers = enhancementLayers };
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(stream);
@@ -212,18 +280,44 @@ public sealed class H264ConformanceTests
return OutputOrder(frames).Select(Md5).ToList();
}
private static List<string> Decode(string stream)
private static List<string> Decode(string stream, out string? skipped)
{
var frames = new List<H264Frame>();
var decoder = new H264Decoder();
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(File.ReadAllBytes(stream));
skipped = decoder.EnhancementLayersSkipped;
return OutputOrder(frames).Select(Md5).ToList();
}
private static List<H264Frame> OutputOrder(List<H264Frame> frames) =>
frames.OrderBy(f => f.Period).ThenBy(f => f.Poc).ThenBy(f => f.DecodeIndex).ToList();
/// <summary>The mean luma step across 8-sample block edges over the mean step inside the blocks (about 1 for a clean picture).</summary>
private static double Blockiness(H264Frame frame)
{
long edge = 0, inside = 0, edges = 0, insides = 0;
for (var y = 0; y < frame.Height; y++)
{
for (var x = 1; x < frame.Width; x++)
{
var step = Math.Abs(frame.Y[(y * frame.Width) + x] - frame.Y[(y * frame.Width) + x - 1]);
if ((x & 7) == 0)
{
edge += step;
edges++;
}
else
{
inside += step;
insides++;
}
}
}
return ((double)edge / edges) / Math.Max(0.01, (double)inside / insides);
}
private static string Md5(H264Frame frame) => Convert.ToHexStringLower(MD5.HashData(frame.ToPlanar()));
/// <summary>