Decodificatore H.264 per i formati dei profili High: 4:2:2, 4:4:4, piani separati, 4:0:0, da 8 a 14 bit, senza perdita (#58)
Il decodificatore rifiutava tutto ciò che non era 4:2:0 a 8 bit, così i video 4:2:2, monocromatici o a 10 bit restavano senza miniatura. Ora i campioni stanno in piani di uno o due byte e i nuclei di predizione, trasformata e filtro sono generici su byte e ushort, specializzati dal JIT: a 8 bit i tempi restano quelli di prima (misurati sui flussi di conformità, 100,4%). - 4:2:2: DC della crominanza 2x4 con qP + 3, tabelle CAVLC di nC -2, contesti CABAC per NumC8x8, predizione intra 8x16, vettore verticale a piena risoluzione, bordi della crominanza alle righe 4, 8 e 12. - 4:4:4: Cb e Cr codificati come la luminanza in CAVLC, con le loro matrici e il filtro della luminanza; separate_colour_plane_flag come tre immagini monocromatiche con i propri dati di macroblocco e di moto. - 4:0:0 senza sintassi della crominanza; in uscita la crominanza 4:2:0 al valore medio, come il file ufficiale. - Profondità da 8 a 14 bit: QP da -QpBdOffset, soglie del deblocking e scarti dei pesi scalati; uscita a due byte little-endian. - Senza perdita: qpprime_y_zero_transform_bypass_flag a QP'Y 0, con la DPCM della predizione intra orizzontale e verticale. - VideoFrameDecoder converte in RGB alla profondità e al campionamento del fotogramma. I dieci flussi 4:2:2 (8 e 10 bit) e 4:0:0 della serie ITU-T coincidono con la ricostruzione ufficiale e passano fra i verificati. 4:4:4, piani separati, senza perdita e 11-14 bit si provano con flussi sintetici (H264FormatTests). Il CABAC in 4:4:4 con i piani insieme si rifiuta: mancano i contesti 460-1023. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8d03ca23de
commit
da84c79f7e
23 files changed
+2016
-607
No files matched your search
@@ -59,7 +59,7 @@ internal sealed class ElementaryStream
|
||||
/// <summary>MD5 values of frames in output order.</summary>
|
||||
public static List<string> Md5InOutputOrder(IEnumerable<H264Frame> frames) =>
|
||||
frames.OrderBy(f => f.Period).ThenBy(f => f.Poc).ThenBy(f => f.DecodeIndex)
|
||||
.Select(f => Convert.ToHexStringLower(MD5.HashData(f.ToI420())))
|
||||
.Select(f => Convert.ToHexStringLower(MD5.HashData(f.ToPlanar())))
|
||||
.ToList();
|
||||
|
||||
public static ElementaryStream Load(string name) => FromAnnexB(name, AnnexB(name));
|
||||
|
||||
@@ -104,6 +104,44 @@ public sealed class VideoFrameDecoderTests
|
||||
Assert.IsTrue(other[1] > 20, $"{other[0]} {other[1]} {other[2]}");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TenBitSamplesKeepTheirRange()
|
||||
{
|
||||
// 10 bits, two bytes each, little-endian: limited range has black at 64, white at 940, neutral chroma at 512.
|
||||
static byte[] Samples(int count, int value) => [.. Enumerable.Range(0, count).SelectMany(_ => new[] { (byte)value, (byte)(value >> 8) })];
|
||||
static H264Frame Flat(int y, int cb, int cr, bool full) =>
|
||||
new(2, 2, Samples(4, y), Samples(1, cb), Samples(1, cr), 0, 0, 0, 1, full, ChromaFormat: 1, BitDepthLuma: 10, BitDepthChroma: 10);
|
||||
|
||||
CollectionAssert.AreEqual(new byte[] { 0, 0, 0 }, VideoFrameDecoder.ToImage(Flat(64, 512, 512, false), 0, 0).Rgb[..3]);
|
||||
CollectionAssert.AreEqual(new byte[] { 255, 255, 255 }, VideoFrameDecoder.ToImage(Flat(940, 512, 512, false), 0, 0).Rgb[..3]);
|
||||
CollectionAssert.AreEqual(new byte[] { 255, 255, 255 }, VideoFrameDecoder.ToImage(Flat(1023, 512, 512, true), 0, 0).Rgb[..3]);
|
||||
|
||||
// Pure red of BT.709 at 8 bits (Y 63, Cb 102, Cr 240) is the same colour at 10 bits (× 4).
|
||||
var eight = VideoFrameDecoder.ToImage(new H264Frame(2, 2, [63, 63, 63, 63], [102], [240], 0, 0, 0, 1, false), 0, 0).Rgb[..3];
|
||||
var ten = VideoFrameDecoder.ToImage(Flat(63 * 4, 102 * 4, 240 * 4, false), 0, 0).Rgb[..3];
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
Assert.IsLessThanOrEqualTo(1, Math.Abs(eight[i] - ten[i]), $"componente {i}: {eight[i]} e {ten[i]}");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(2)]
|
||||
[DataRow(3)]
|
||||
public void EveryChromaSamplingReachesItsOwnPixels(int chromaFormat)
|
||||
{
|
||||
// A 2×2 frame of grey luma; in 4:2:2 each row has its own chroma sample, in 4:4:4 each pixel. The top row is
|
||||
// blue (Cb high), the bottom one red (Cr high).
|
||||
var cw = chromaFormat == 3 ? 2 : 1;
|
||||
byte[] cb = [.. Enumerable.Repeat((byte)200, cw), .. Enumerable.Repeat((byte)128, cw)];
|
||||
byte[] cr = [.. Enumerable.Repeat((byte)128, cw), .. Enumerable.Repeat((byte)200, cw)];
|
||||
var frame = new H264Frame(2, 2, [128, 128, 128, 128], cb, cr, 0, 0, 0, 1, true, ChromaFormat: chromaFormat);
|
||||
var rgb = VideoFrameDecoder.ToImage(frame, 0, 0).Rgb;
|
||||
Assert.IsGreaterThan(rgb[0] + 50, (int)rgb[2], "in alto prevale il blu");
|
||||
Assert.IsGreaterThan(rgb[(2 * 3) + 2] + 50, (int)rgb[2 * 3], "in basso prevale il rosso");
|
||||
CollectionAssert.AreEqual(rgb[..3], rgb[3..6], "la riga in alto è uniforme");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AVideoOfAStillPictureIsRecognised()
|
||||
{
|
||||
|
||||
@@ -40,7 +40,8 @@ del riferimento.
|
||||
|
||||
## I flussi verificati
|
||||
|
||||
`H264ConformanceTests.FramesMatchTheReference`, tutti 4:2:0 a 8 bit. A immagini intere, sulla sequenza «Foreman»:
|
||||
`H264ConformanceTests.FramesMatchTheReference`: 4:2:0 a 8 bit, poi 4:2:2 a 8 e 10 bit e 4:0:0. A immagini intere, sulla
|
||||
sequenza «Foreman»:
|
||||
|
||||
| Flusso | Profilo, formato | Che cosa prova |
|
||||
|---|---|---|
|
||||
@@ -106,17 +107,9 @@ Per gli strumenti che nessun flusso della serie usa, `H264ExtendedToolsTests` ri
|
||||
Le slice SI e `sp_for_switch_flag` a 1 non hanno flussi: le prova un flusso sintetico di
|
||||
`H264SyntheticStreamTests`, con i valori calcolati a mano dalle equazioni di §8.6.2.
|
||||
|
||||
`H264ConformanceTests.SvcBaseLayerMatchesTheReference`: lo strato base dei tre flussi SVC qui sotto, con
|
||||
`riferimento-base.md5`.
|
||||
Formati di High 4:2:2 e High, CIF; oltre gli 8 bit due byte little-endian per campione.
|
||||
|
||||
## I flussi delle parti ancora da fare
|
||||
|
||||
`H264ConformanceTests.FeaturesStillToDo`: il decodificatore oggi rifiuta queste parti con un'`H264Exception` (o, per SVC
|
||||
e MVC, 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.
|
||||
|
||||
**4:2:2, 8 e 10 bit** (High 4:2:2), CIF, 5 fotogrammi ciascuno:
|
||||
**4:2:2, 8 e 10 bit** (High 4:2:2), 5 fotogrammi ciascuno:
|
||||
|
||||
| Flusso | Che cosa prova |
|
||||
|---|---|
|
||||
@@ -129,8 +122,23 @@ ricordare di spostarla fra i flussi verificati.
|
||||
| `FREXT2_TANDBERG_A` | 8 bit, slice I e P, CAVLC, deblocking attivo |
|
||||
| `FREXT3_TANDBERG_A` | 8 bit, slice I, B e P, CAVLC |
|
||||
|
||||
**Monocromatico 4:0:0** (High), CIF, 100 fotogrammi: `HPCAMOLQ_BRCM_B` (CABAC) e `HPCVMOLQ_BRCM_B` (CAVLC), con
|
||||
slice B, diretta temporale e matrici di quantizzazione.
|
||||
**Monocromatico 4:0:0** (High), 100 fotogrammi: `HPCAMOLQ_BRCM_B` (CABAC) e `HPCVMOLQ_BRCM_B` (CAVLC), con
|
||||
slice B, diretta temporale e matrici di quantizzazione; escono con i due piani di crominanza 4:2:0 al valore medio,
|
||||
come nel file ufficiale.
|
||||
|
||||
Le parti dei profili High che la serie qui non ha con la ricostruzione (4:4:4, piani di colore separati, codifica senza
|
||||
perdita con la sua DPCM, profondità da 11 a 14 bit, 10 bit in 4:2:0) le prova `H264FormatTests` con flussi sintetici
|
||||
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`.
|
||||
|
||||
## 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.
|
||||
|
||||
**SVC** (Scalable Baseline; lo strato base è Baseline):
|
||||
|
||||
|
||||
@@ -9,12 +9,14 @@ namespace Febe.Tests.Codecs.H264;
|
||||
/// MD5 of the corresponding frame of the official reconstruction (see Conformita/LEGGIMI.md). The verified streams include
|
||||
/// interlaced video — field pictures, PAFF, MBAFF, both together — with memory management operations, long-term
|
||||
/// references and POC type 1 on fields (MR6_BT_B, MR9_BT_B), slice groups of every map type with slices in any order
|
||||
/// (FM1_BT_B, FM1_FT_E, FM2_SVA_C) and SP slices (sp1_bt_a, sp2_bt_b; sp2 with the deblocking filter on). None of them
|
||||
/// (FM1_BT_B, FM1_FT_E, FM2_SVA_C), SP slices (sp1_bt_a, sp2_bt_b; sp2 with the deblocking filter on), 4:2:2 at 8 and 10
|
||||
/// bits with CABAC and CAVLC (Hi422FR10–15_SONY_A, FREXT2/3_TANDBERG_A) and monochrome 4:0:0 (HPCAMOLQ_BRCM_B,
|
||||
/// HPCVMOLQ_BRCM_B). None of them
|
||||
/// 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 (4:2:2, more than 8 bits, 4:0:0, SVC, MVC) are in <see cref="FeaturesStillToDo"/>: they are inconclusive
|
||||
/// 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.
|
||||
/// </summary>
|
||||
@@ -56,6 +58,16 @@ public sealed class H264ConformanceTests
|
||||
[DataRow("FM1_BT_B")]
|
||||
[DataRow("sp1_bt_a")]
|
||||
[DataRow("sp2_bt_b")]
|
||||
[DataRow("Hi422FR10_SONY_A")]
|
||||
[DataRow("Hi422FR11_SONY_A")]
|
||||
[DataRow("Hi422FR12_SONY_A")]
|
||||
[DataRow("Hi422FR13_SONY_A")]
|
||||
[DataRow("Hi422FR14_SONY_A")]
|
||||
[DataRow("Hi422FR15_SONY_A")]
|
||||
[DataRow("FREXT2_TANDBERG_A")]
|
||||
[DataRow("FREXT3_TANDBERG_A")]
|
||||
[DataRow("HPCAMOLQ_BRCM_B")]
|
||||
[DataRow("HPCVMOLQ_BRCM_B")]
|
||||
public void FramesMatchTheReference(string name) => AssertMatches(name, "riferimento.md5");
|
||||
|
||||
[TestMethod]
|
||||
@@ -70,16 +82,6 @@ public sealed class H264ConformanceTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("Hi422FR10_SONY_A", "4:2:2 a 8 bit, solo slice I (CABAC)")]
|
||||
[DataRow("Hi422FR11_SONY_A", "4:2:2 a 8 bit con slice P (CABAC)")]
|
||||
[DataRow("Hi422FR12_SONY_A", "4:2:2 a 8 bit con slice B (CABAC)")]
|
||||
[DataRow("Hi422FR13_SONY_A", "4:2:2 a 10 bit, solo slice I (CABAC)")]
|
||||
[DataRow("Hi422FR14_SONY_A", "4:2:2 a 10 bit con slice P (CABAC)")]
|
||||
[DataRow("Hi422FR15_SONY_A", "4:2:2 a 10 bit con slice B (CABAC)")]
|
||||
[DataRow("FREXT2_TANDBERG_A", "4:2:2 a 8 bit con slice P (CAVLC)")]
|
||||
[DataRow("FREXT3_TANDBERG_A", "4:2:2 a 8 bit con slice B (CAVLC)")]
|
||||
[DataRow("HPCAMOLQ_BRCM_B", "monocromatico 4:0:0 (CABAC, High)")]
|
||||
[DataRow("HPCVMOLQ_BRCM_B", "monocromatico 4:0:0 (CAVLC, High)")]
|
||||
[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)")]
|
||||
@@ -154,7 +156,7 @@ public sealed class H264ConformanceTests
|
||||
{
|
||||
var expected = all.Single(f => f.DecodeIndex == frame.DecodeIndex);
|
||||
Assert.AreEqual((expected.Poc, expected.Period), (frame.Poc, frame.Period), $"{name}: ordine del fotogramma {frame.DecodeIndex}");
|
||||
CollectionAssert.AreEqual(expected.ToI420(), frame.ToI420(), $"{name}: fotogramma {frame.DecodeIndex}");
|
||||
CollectionAssert.AreEqual(expected.ToPlanar(), frame.ToPlanar(), $"{name}: fotogramma {frame.DecodeIndex}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,7 +224,7 @@ public sealed class H264ConformanceTests
|
||||
private static List<H264Frame> OutputOrder(List<H264Frame> frames) =>
|
||||
frames.OrderBy(f => f.Period).ThenBy(f => f.Poc).ThenBy(f => f.DecodeIndex).ToList();
|
||||
|
||||
private static string Md5(H264Frame frame) => Convert.ToHexStringLower(MD5.HashData(frame.ToI420()));
|
||||
private static string Md5(H264Frame frame) => Convert.ToHexStringLower(MD5.HashData(frame.ToPlanar()));
|
||||
|
||||
/// <summary>
|
||||
/// The frame MD5s of a riferimento.md5, in output order, and the number of frames its first line declares (0 when
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
using Febe.Core.Codecs.H264;
|
||||
using static Febe.Tests.Codecs.H264.SyntheticStreams;
|
||||
|
||||
namespace Febe.Tests.Codecs.H264;
|
||||
|
||||
/// <summary>
|
||||
/// The formats of the High profiles on tiny streams written by <see cref="SyntheticStreams"/>, where the conformance
|
||||
/// streams in the repository have no reference: every chroma format at every bit depth, the colour planes of 4:4:4
|
||||
/// coded separately, lossless macroblocks with their DPCM, the CABAC of 4:4:4 that is refused.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class H264FormatTests
|
||||
{
|
||||
[TestMethod]
|
||||
[DataRow(0, 8, 8)]
|
||||
[DataRow(0, 12, 9)]
|
||||
[DataRow(1, 10, 10)]
|
||||
[DataRow(1, 8, 10)]
|
||||
[DataRow(2, 12, 9)]
|
||||
[DataRow(3, 14, 14)]
|
||||
[DataRow(3, 9, 8)]
|
||||
public void PcmSamplesKeepTheirFormatAndBitDepth(int chromaFormat, int bitDepthLuma, int bitDepthChroma)
|
||||
{
|
||||
// Two I_PCM macroblocks side by side: every sample is written as it is, at its bit depth.
|
||||
var h = new HighSettings(chromaFormat, bitDepthLuma, bitDepthChroma, WidthInMbs: 2);
|
||||
int luma = (1 << bitDepthLuma) - 3, cb = (1 << (bitDepthChroma - 1)) - 7, cr = (1 << bitDepthChroma) - 2;
|
||||
var frames = Decode([.. HighSps(h), .. HighPps(h), .. HighIdr(h, b =>
|
||||
{
|
||||
Pcm(b, h, luma, cb, cr);
|
||||
Pcm(b, h, luma, cb, cr);
|
||||
})]);
|
||||
|
||||
Assert.HasCount(1, frames);
|
||||
var f = frames[0];
|
||||
Assert.AreEqual(32, f.Width);
|
||||
Assert.AreEqual(16, f.Height);
|
||||
Assert.AreEqual(chromaFormat, f.ChromaFormat);
|
||||
Assert.AreEqual(bitDepthLuma, f.BitDepthLuma);
|
||||
|
||||
// Monochrome comes out with 4:2:0 chroma at the middle value, at the luma bit depth (as the reference decoder writes it).
|
||||
var depthC = chromaFormat == 0 ? bitDepthLuma : bitDepthChroma;
|
||||
Assert.AreEqual(depthC, f.BitDepthChroma);
|
||||
var bytes = Math.Max(bitDepthLuma, depthC) > 8 ? 2 : 1;
|
||||
Assert.HasCount(32 * 16 * bytes, f.Y);
|
||||
var (cw, ch) = chromaFormat switch
|
||||
{
|
||||
3 => (32, 16),
|
||||
2 => (16, 16),
|
||||
_ => (16, 8),
|
||||
};
|
||||
Assert.AreEqual(cw, f.ChromaWidth);
|
||||
Assert.AreEqual(ch, f.ChromaHeight);
|
||||
Assert.HasCount(cw * ch * bytes, f.Cb);
|
||||
Assert.HasCount(cw * ch * bytes, f.Cr);
|
||||
for (var i = 0; i < 32 * 16; i++)
|
||||
{
|
||||
Assert.AreEqual(luma, f.LumaAt(i), $"luma {i}");
|
||||
}
|
||||
|
||||
int expectedCb = chromaFormat == 0 ? 1 << (depthC - 1) : cb, expectedCr = chromaFormat == 0 ? 1 << (depthC - 1) : cr;
|
||||
for (var i = 0; i < cw * ch; i++)
|
||||
{
|
||||
Assert.AreEqual(expectedCb, f.ChromaAt(f.Cb, i), $"Cb {i}");
|
||||
Assert.AreEqual(expectedCr, f.ChromaAt(f.Cr, i), $"Cr {i}");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(8)]
|
||||
[DataRow(10)]
|
||||
public void SeparateColourPlanesMakeOneFrame(int bitDepth)
|
||||
{
|
||||
// separate_colour_plane_flag: three slices of the same IDR picture, one per colour_plane_id, each a monochrome
|
||||
// picture of I_PCM macroblocks at the luma bit depth.
|
||||
var h = new HighSettings(3, bitDepth, bitDepth, SeparatePlanes: true, WidthInMbs: 2);
|
||||
int[] values = [11 << (bitDepth - 8), 22 << (bitDepth - 8), 33 << (bitDepth - 8)];
|
||||
var stream = new List<byte>([.. HighSps(h), .. HighPps(h)]);
|
||||
for (var plane = 0; plane < 3; plane++)
|
||||
{
|
||||
var v = values[plane];
|
||||
stream.AddRange(HighIdr(h, b =>
|
||||
{
|
||||
Pcm(b, h, v, 0, 0);
|
||||
Pcm(b, h, v, 0, 0);
|
||||
}, plane));
|
||||
}
|
||||
|
||||
var frames = Decode([.. stream]);
|
||||
Assert.HasCount(1, frames);
|
||||
var f = frames[0];
|
||||
Assert.AreEqual(3, f.ChromaFormat);
|
||||
Assert.AreEqual(bitDepth, f.BitDepthChroma);
|
||||
Assert.AreEqual(32, f.ChromaWidth);
|
||||
for (var i = 0; i < 32 * 16; i++)
|
||||
{
|
||||
Assert.AreEqual(values[0], f.LumaAt(i), $"Y {i}");
|
||||
Assert.AreEqual(values[1], f.ChromaAt(f.Cb, i), $"Cb {i}");
|
||||
Assert.AreEqual(values[2], f.ChromaAt(f.Cr, i), $"Cr {i}");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(0, 8, 1)]
|
||||
[DataRow(0, 8, 0)]
|
||||
[DataRow(0, 8, 2)]
|
||||
[DataRow(0, 10, 1)]
|
||||
[DataRow(1, 8, 0)]
|
||||
[DataRow(2, 10, 1)]
|
||||
[DataRow(3, 8, 1)]
|
||||
[DataRow(3, 8, 0)]
|
||||
[DataRow(3, 12, 2)]
|
||||
public void ALosslessMacroblockAccumulatesItsResidual(int chromaFormat, int bitDepth, int mode)
|
||||
{
|
||||
// An I_PCM macroblock, then an Intra_16x16 one predicted from it at QP′Y 0 with qpprime_y_zero_transform_bypass_flag:
|
||||
// lossless (§8.5.15). Its only residual is a DC level on the first 4×4 block of each luma-like plane, taken as
|
||||
// it is (no transform, no scaling) and accumulated along the prediction: horizontal (mode 1) adds it to the whole
|
||||
// first row, vertical (mode 0, the I_PCM macroblock above) to the whole first column, DC (mode 2) only to the
|
||||
// first sample.
|
||||
var vertical = mode == 0;
|
||||
var h = new HighSettings(chromaFormat, bitDepth, bitDepth, Lossless: true, WidthInMbs: vertical ? 1 : 2, HeightInMbs: vertical ? 2 : 1);
|
||||
var shift = bitDepth - 8;
|
||||
int[] pcm = [100 << shift, 60 << shift, 180 << shift];
|
||||
int[] dc = [1, 2, -1];
|
||||
var frames = Decode([.. HighSps(h), .. HighPps(h), .. HighIdr(h, b =>
|
||||
{
|
||||
Pcm(b, h, pcm[0], pcm[1], pcm[2]);
|
||||
Intra16x16Dc(b, h, mode, dc);
|
||||
})]);
|
||||
|
||||
Assert.HasCount(1, frames);
|
||||
var f = frames[0];
|
||||
var planes = chromaFormat == 3 ? 3 : 1;
|
||||
for (var p = 0; p < planes; p++)
|
||||
{
|
||||
var plane = p == 0 ? f.Y : p == 1 ? f.Cb : f.Cr;
|
||||
for (var y = 0; y < 16; y++)
|
||||
{
|
||||
for (var x = 0; x < 16; x++)
|
||||
{
|
||||
var touched = mode == 1 ? y == 0 : mode == 0 ? x == 0 : x == 0 && y == 0;
|
||||
var expected = pcm[p] + (touched ? dc[p] : 0);
|
||||
var index = vertical ? ((16 + y) * 16) + x : (y * 32) + 16 + x;
|
||||
var actual = p == 0 ? f.LumaAt(index) : f.ChromaAt(plane, index);
|
||||
Assert.AreEqual(expected, actual, $"piano {p}, ({x}, {y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (chromaFormat is 1 or 2)
|
||||
{
|
||||
// Chroma: DC prediction from the I_PCM chroma, no residual.
|
||||
for (var i = 0; i < f.ChromaWidth * f.ChromaHeight; i++)
|
||||
{
|
||||
Assert.AreEqual(pcm[1], f.ChromaAt(f.Cb, i), $"Cb {i}");
|
||||
Assert.AreEqual(pcm[2], f.ChromaAt(f.Cr, i), $"Cr {i}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CabacIn444IsRefusedUntilItsContextsAreWritten()
|
||||
{
|
||||
// The residual of Cb and Cr of 4:4:4 with CABAC needs the contexts 460–1023: not transcribed yet, so the slice is
|
||||
// refused rather than decoded wrong.
|
||||
var h = new HighSettings(3, Cabac: true);
|
||||
Assert.ThrowsExactly<H264Exception>(() => Decode([.. HighSps(h), .. HighPps(h), .. HighIdr(h, b => b.Bits(0, 8))]));
|
||||
}
|
||||
|
||||
private static List<H264Frame> Decode(byte[] stream)
|
||||
{
|
||||
var decoder = new H264Decoder();
|
||||
var frames = new List<H264Frame>();
|
||||
decoder.FrameDecoded += frames.Add;
|
||||
decoder.DecodeAnnexB(stream);
|
||||
decoder.Flush();
|
||||
return frames;
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,8 @@ public sealed class H264TablesTests
|
||||
{
|
||||
CollectionAssert.AreEquivalent(Enumerable.Range(0, 48).ToArray(), H264Tables.CbpIntra.Select(b => (int)b).ToArray());
|
||||
CollectionAssert.AreEquivalent(Enumerable.Range(0, 48).ToArray(), H264Tables.CbpInter.Select(b => (int)b).ToArray());
|
||||
CollectionAssert.AreEquivalent(Enumerable.Range(0, 16).ToArray(), H264Tables.CbpIntraNoChroma.Select(b => (int)b).ToArray());
|
||||
CollectionAssert.AreEquivalent(Enumerable.Range(0, 16).ToArray(), H264Tables.CbpInterNoChroma.Select(b => (int)b).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -203,6 +203,183 @@ internal static class SyntheticStreams
|
||||
return Nal(0x65, bits);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settings of a High 4:4:4 Predictive sequence (profile_idc 244): chroma format, bit depths, separate colour planes,
|
||||
/// lossless macroblocks (qpprime_y_zero_transform_bypass_flag, with the slices at QP′Y 0), CABAC.
|
||||
/// </summary>
|
||||
internal sealed record HighSettings(
|
||||
int ChromaFormat = 1,
|
||||
int BitDepthLuma = 8,
|
||||
int BitDepthChroma = 8,
|
||||
bool SeparatePlanes = false,
|
||||
bool Lossless = false,
|
||||
int WidthInMbs = 1,
|
||||
int HeightInMbs = 1,
|
||||
bool Cabac = false)
|
||||
{
|
||||
/// <summary>ChromaArrayType: no chroma syntax for monochrome and separate planes.</summary>
|
||||
internal int ChromaArrayType => SeparatePlanes ? 0 : ChromaFormat;
|
||||
|
||||
/// <summary>Chroma samples of each component in a macroblock.</summary>
|
||||
internal int ChromaSamples => ChromaArrayType switch
|
||||
{
|
||||
0 => 0,
|
||||
1 => 64,
|
||||
2 => 128,
|
||||
_ => 256,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The sequence parameter set of <paramref name="h"/> (§7.3.2.1.1), POC type 2, no VUI.</summary>
|
||||
internal static byte[] HighSps(HighSettings h)
|
||||
{
|
||||
var bits = new BitWriter();
|
||||
bits.Bits(244, 8); // profile_idc: High 4:4:4 Predictive
|
||||
bits.Bits(0, 8); // constraint flags
|
||||
bits.Bits(30, 8); // level_idc
|
||||
bits.Ue(0); // seq_parameter_set_id
|
||||
bits.Ue((uint)h.ChromaFormat);
|
||||
if (h.ChromaFormat == 3)
|
||||
{
|
||||
bits.Bits(h.SeparatePlanes ? 1u : 0u, 1);
|
||||
}
|
||||
|
||||
bits.Ue((uint)h.BitDepthLuma - 8);
|
||||
bits.Ue((uint)h.BitDepthChroma - 8);
|
||||
bits.Bits(h.Lossless ? 1u : 0u, 1); // qpprime_y_zero_transform_bypass_flag
|
||||
bits.Bits(0, 1); // seq_scaling_matrix_present_flag
|
||||
bits.Ue(0); // log2_max_frame_num_minus4
|
||||
bits.Ue(2); // pic_order_cnt_type
|
||||
bits.Ue(1); // max_num_ref_frames
|
||||
bits.Bits(0, 1); // gaps_in_frame_num_value_allowed_flag
|
||||
bits.Ue((uint)h.WidthInMbs - 1);
|
||||
bits.Ue((uint)h.HeightInMbs - 1);
|
||||
bits.Bits(1, 1); // frame_mbs_only_flag
|
||||
bits.Bits(1, 1); // direct_8x8_inference_flag
|
||||
bits.Bits(0, 1); // frame_cropping_flag
|
||||
bits.Bits(0, 1); // vui_parameters_present_flag
|
||||
return Nal(0x67, bits);
|
||||
}
|
||||
|
||||
/// <summary>The picture parameter set of <paramref name="h"/>: QP′Y 0 (QPY −QpBdOffsetY) when lossless, else 26.</summary>
|
||||
internal static byte[] HighPps(HighSettings h)
|
||||
{
|
||||
var bits = new BitWriter();
|
||||
bits.Ue(0); // pic_parameter_set_id
|
||||
bits.Ue(0); // seq_parameter_set_id
|
||||
bits.Bits(h.Cabac ? 1u : 0u, 1); // entropy_coding_mode_flag
|
||||
bits.Bits(0, 1); // bottom_field_pic_order_in_frame_present_flag
|
||||
bits.Ue(0); // num_slice_groups_minus1
|
||||
bits.Ue(0); // num_ref_idx_l0_default_active_minus1
|
||||
bits.Ue(0); // num_ref_idx_l1_default_active_minus1
|
||||
bits.Bits(0, 1); // weighted_pred_flag
|
||||
bits.Bits(0, 2); // weighted_bipred_idc
|
||||
bits.Se(h.Lossless ? -26 - (6 * (h.BitDepthLuma - 8)) : 0); // pic_init_qp_minus26
|
||||
bits.Se(0); // pic_init_qs_minus26
|
||||
bits.Se(0); // chroma_qp_index_offset
|
||||
bits.Bits(1, 1); // deblocking_filter_control_present_flag
|
||||
bits.Bits(0, 1); // constrained_intra_pred_flag
|
||||
bits.Bits(0, 1); // redundant_pic_cnt_present_flag
|
||||
return Nal(0x68, bits);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One I slice of an IDR picture of <paramref name="h"/> (for separate planes, the slice of <paramref name="colourPlane"/>),
|
||||
/// deblocking off, its macroblocks written by <paramref name="macroblocks"/>.
|
||||
/// </summary>
|
||||
internal static byte[] HighIdr(HighSettings h, Action<BitWriter> macroblocks, int colourPlane = 0)
|
||||
{
|
||||
var bits = new BitWriter();
|
||||
bits.Ue(0); // first_mb_in_slice
|
||||
bits.Ue(7); // slice_type: I (all slices of the picture)
|
||||
bits.Ue(0); // pic_parameter_set_id
|
||||
if (h.SeparatePlanes)
|
||||
{
|
||||
bits.Bits((uint)colourPlane, 2);
|
||||
}
|
||||
|
||||
bits.Bits(0, 4); // frame_num
|
||||
bits.Ue(0); // idr_pic_id
|
||||
bits.Bits(0, 1); // no_output_of_prior_pics_flag
|
||||
bits.Bits(0, 1); // long_term_reference_flag
|
||||
bits.Se(0); // slice_qp_delta
|
||||
bits.Ue(1); // disable_deblocking_filter_idc: off
|
||||
macroblocks(bits);
|
||||
return Nal(0x65, bits);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An I_PCM macroblock (CAVLC): its luma samples all <paramref name="luma"/>, then (with chroma syntax) Cb and Cr all
|
||||
/// <paramref name="cb"/> and <paramref name="cr"/>, at the bit depths of <paramref name="h"/>.
|
||||
/// </summary>
|
||||
internal static void Pcm(BitWriter bits, HighSettings h, int luma, int cb, int cr)
|
||||
{
|
||||
bits.Ue(25); // mb_type: I_PCM
|
||||
bits.Align(); // pcm_alignment_zero_bit
|
||||
for (var i = 0; i < 256; i++)
|
||||
{
|
||||
bits.Bits((uint)luma, h.BitDepthLuma);
|
||||
}
|
||||
|
||||
for (var c = 0; c < 2; c++)
|
||||
{
|
||||
for (var i = 0; i < h.ChromaSamples; i++)
|
||||
{
|
||||
bits.Bits((uint)(c == 0 ? cb : cr), h.BitDepthChroma);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An Intra_16x16 macroblock (CAVLC) without AC residual, prediction mode <paramref name="mode"/> (0 vertical,
|
||||
/// 1 horizontal, 2 DC; chroma DC if the chroma has syntax), and in each luma-like plane (Y; Cb and Cr too in 4:4:4) one
|
||||
/// DC level of <paramref name="dc"/> on the first block. The neighbour it predicts from must be I_PCM: its blocks
|
||||
/// count 16 coefficients, so nC is 16 and coeff_token the 6-bit code of §9.2.1.
|
||||
/// </summary>
|
||||
internal static void Intra16x16Dc(BitWriter bits, HighSettings h, int mode, int[] dc)
|
||||
{
|
||||
bits.Ue((uint)(1 + mode)); // mb_type: I_16x16_<mode>_0_0
|
||||
if (h.ChromaArrayType is 1 or 2)
|
||||
{
|
||||
bits.Ue(0); // intra_chroma_pred_mode: DC
|
||||
}
|
||||
|
||||
bits.Se(0); // mb_qp_delta
|
||||
var planes = h.ChromaArrayType == 3 ? 3 : 1;
|
||||
for (var p = 0; p < planes; p++)
|
||||
{
|
||||
var level = dc[p];
|
||||
if (level == 0)
|
||||
{
|
||||
bits.Bits(0b000011, 6); // coeff_token: TotalCoeff 0
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Math.Abs(level) == 1)
|
||||
{
|
||||
bits.Bits(0b000001, 6); // coeff_token: TotalCoeff 1, TrailingOnes 1
|
||||
bits.Bits(level < 0 ? 1u : 0u, 1); // trailing_ones_sign_flag
|
||||
}
|
||||
else
|
||||
{
|
||||
// coeff_token: TotalCoeff 1, TrailingOnes 0; level_prefix with suffixLength 0, the first level after
|
||||
// fewer than three trailing ones counting from 2 (levelCode = 2 |level| − 4, + 1 when negative).
|
||||
bits.Bits(0b000000, 6);
|
||||
var levelCode = (2 * Math.Abs(level)) - 4 + (level < 0 ? 1 : 0);
|
||||
if (levelCode >= 14)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(dc), "Livello troppo grande per questo flusso di prova.");
|
||||
}
|
||||
|
||||
bits.Bits(1, levelCode + 1); // level_prefix: levelCode zeros then a one
|
||||
}
|
||||
|
||||
bits.Bits(1, 1); // total_zeros: 0
|
||||
}
|
||||
|
||||
// No chroma residual: the mb_type says coded_block_pattern chroma 0.
|
||||
}
|
||||
|
||||
private static byte[] Nal(byte header, BitWriter bits)
|
||||
{
|
||||
bits.Bits(1, 1); // rbsp_stop_one_bit
|
||||
|
||||
Reference in new issue
Block a user