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:
Alby96andClaude Opus 5.5 committed 2026-11-18 17:31:12 +01:00
1 parent 8d03ca23de
commit da84c79f7e
23 files changed
+2016 -607

No files matched your search

+110 -47
View File
@@ -14,8 +14,10 @@ public enum H264AccessPoint
}
/// <summary>
/// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Extended, Main and High
/// profiles in 4:2:0 with 8-bit samples — CAVLC and CABAC, I, P and B slices, 8×8 transform and scaling matrices, spatial
/// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Extended, Main and the High
/// profiles — 4:2:0, 4:2:2, 4:4:4 (also with the colour planes coded separately) and monochrome, 8 to 14 bits per sample,
/// lossless macroblocks (qpprime_y_zero_transform_bypass_flag) — CAVLC and CABAC, I, P and B slices, 8×8 transform and
/// scaling matrices, spatial
/// and temporal direct prediction, list modification, memory management operations and long-term references,
/// deblocking — for progressive frames and for interlaced video: field pictures, frames and fields mixed picture by
/// picture (PAFF), frames of frame and field macroblock pairs (MBAFF). Frames come out whole: the two fields of a pair are
@@ -23,8 +25,9 @@ public enum H264AccessPoint
/// SI slices (switching pictures), slice data partitioning (NAL units 2–4); redundant coded pictures are skipped, the
/// primary one is decoded. Written from the standard but not yet checked against a conformance stream: explicit and
/// implicit weighted prediction, gaps in frame_num, I_PCM, SI macroblocks and sp_for_switch_flag, data partitioning
/// (checked only on conformance streams split into partitions). Not handled (an <see cref="H264Exception"/>):
/// 4:2:2/4:4:4 and depths above 8 bits.
/// (checked only on conformance streams split into partitions), 4:4:4, separate colour planes, lossless coding and bit
/// depths above 10. Not handled (an <see cref="H264Exception"/>): CABAC in 4:4:4 with the colour planes coded together
/// (its contexts 460–1023 are not transcribed yet), SP and SI slices outside 4:2:0 at 8 bits.
/// </summary>
public sealed partial class H264Decoder
{
@@ -304,18 +307,7 @@ public sealed partial class H264Decoder
private SliceHeader ParseSliceHeader(RbspReader reader, NalUnit nal, out Sps sps, out Pps pps)
{
var header = SliceHeader.Parse(reader, nal, sequences, pictures, out sps, out pps);
if (sps.ChromaFormatIdc != 1 || sps.BitDepthLuma != 8 || sps.BitDepthChroma != 8)
{
throw new H264Exception("Solo video 4:2:0 a 8 bit.");
}
if (sps.TransformBypass)
{
throw new H264Exception("La codifica senza perdita non è gestita.");
}
return header;
return SliceHeader.Parse(reader, nal, sequences, pictures, out sps, out pps);
}
/// <summary>A slice whose header is read: the picture it belongs to, then its macroblocks.</summary>
@@ -332,6 +324,11 @@ public sealed partial class H264Decoder
return;
}
if (separatePlanes)
{
SelectColourPlane(header.ColourPlaneId);
}
if (!header.IsIntra && !HasReference())
{
// A P or B slice without any picture to predict from: decoding started away from a random access point
@@ -368,6 +365,9 @@ public sealed partial class H264Decoder
return false;
}
// Colour planes coded separately: the macroblocks of the plane of the slice.
var slices = separatePlanes ? planeStates[h.ColourPlaneId].Slice : mbSlice;
var w = sps.WidthInMbs;
int index;
if (h.FieldPic)
@@ -383,7 +383,7 @@ public sealed partial class H264Decoder
index = h.FirstMb;
}
return (uint)index < (uint)mbSlice.Length && mbSlice[index] >= 0;
return (uint)index < (uint)slices.Length && slices[index] >= 0;
}
/// <summary>Whether a picture other than the one being decoded can be predicted from.</summary>
@@ -411,7 +411,7 @@ public sealed partial class H264Decoder
{
if (activeSps is null || !ReferenceEquals(activeSps, sps))
{
if (activeSps is null || activeSps.WidthInMbs != sps.WidthInMbs || activeSps.HeightInMbs != sps.HeightInMbs)
if (activeSps is null || !SameLayout(activeSps, sps))
{
if (openField is { } waiting && activeSps is not null)
{
@@ -421,10 +421,11 @@ public sealed partial class H264Decoder
dpb.Clear();
pool.Clear();
AllocateMacroblockState(sps.WidthInMbs, sps.HeightInMbs);
AllocateMacroblockState(sps.WidthInMbs, sps.HeightInMbs, sps.SeparateColourPlane ? 3 : 1);
}
activeSps = sps;
ConfigureFormat(sps);
}
var idr = nal.Type == 5;
@@ -480,7 +481,10 @@ public sealed partial class H264Decoder
sliceFilters.Clear();
sliceSwitching.Clear();
anySwitching = false;
Array.Fill(mbSlice, -1);
foreach (var state in planeStates)
{
Array.Fill(state.Slice, -1);
}
// A picture nobody refers to and nobody wants: its header has set the state above, its slices are not decoded.
picSkipped = nal.RefIdc == 0 && Wanted is { } wanted && !wanted(picture.DecodeIndex);
@@ -495,18 +499,31 @@ public sealed partial class H264Decoder
while (pool.Count > 0)
{
var p = pool.Pop();
if (p.Fits(sps.WidthInMbs, sps.HeightInMbs) && !p.InDpb && !ReferenceEquals(p, openField))
if (p.Fits(sps.WidthInMbs, sps.HeightInMbs, sps.ChromaFormatIdc, BytesPerSample, PlaneCount(sps)) && !p.InDpb && !ReferenceEquals(p, openField))
{
p.ShortMask = p.LongMask = 0;
p.NonExisting = false;
Array.Clear(p.RefPic);
p.ClearReferences();
return p;
}
}
return new Picture(sps.WidthInMbs, sps.HeightInMbs);
return new Picture(sps.WidthInMbs, sps.HeightInMbs, sps.ChromaFormatIdc, BytesPerSample, PlaneCount(sps));
}
private int BytesPerSample => wide ? 2 : 1;
private static int PlaneCount(Sps sps) => sps.SeparateColourPlane ? 3 : 1;
/// <summary>Two sequences whose pictures and macroblock data have the same shape: size, chroma format, sample size.</summary>
private static bool SameLayout(Sps a, Sps b) =>
a.WidthInMbs == b.WidthInMbs && a.HeightInMbs == b.HeightInMbs && a.ChromaFormatIdc == b.ChromaFormatIdc
&& a.SeparateColourPlane == b.SeparateColourPlane && SampleBytes(a) == SampleBytes(b);
/// <summary>Bytes of each stored sample of a sequence: 2 when luma, or chroma if present, has more than 8 bits.</summary>
private static int SampleBytes(Sps s) =>
s.BitDepthLuma > 8 || (s.ChromaFormatIdc != 0 && !s.SeparateColourPlane && s.BitDepthChroma > 8) ? 2 : 1;
/// <summary>Picture order count (§8.2.1) of the picture starting now, into the fields of <paramref name="p"/> it codes.</summary>
private void ComputePoc(Picture p, SliceHeader h, NalUnit nal, Sps sps, bool idr, int structure)
{
@@ -669,8 +686,7 @@ public sealed partial class H264Decoder
gap.TopPoc = gap.BottomPoc = 0;
gap.Decoded = 3;
gap.CodedAsFields = false;
Array.Fill(gap.MbIntra, true);
Array.Clear(gap.MbField);
gap.MarkAsGap();
SlidingWindow(sps, n, null);
gap.ShortMask = 3;
AddToDpb(gap);
@@ -774,51 +790,98 @@ public sealed partial class H264Decoder
}
}
/// <summary>
/// The frame of a picture, cropped (§7.4.2.1.1, CropUnitX and CropUnitY). A monochrome frame gets chroma planes of
/// 4:2:0 size at the middle value, the rows of a field without its pair the middle value too, as the reference
/// decoder writes them; colour planes coded separately come out as 4:4:4 with the luma bit depth.
/// </summary>
private static H264Frame Crop(Picture p, Sps sps)
{
var cropUnitY = sps.FrameMbsOnly ? 2 : 4;
var left = sps.CropLeft * 2;
var top = sps.CropTop * cropUnitY;
var width = Math.Max(2, p.Width - left - (sps.CropRight * 2));
var height = Math.Max(2, p.Height - top - (sps.CropBottom * cropUnitY));
var y = new byte[width * height];
for (var r = 0; r < height; r++)
{
Array.Copy(p.Y, ((top + r) * p.Width) + left, y, r * width, width);
}
var bps = p.BytesPerSample;
var format = sps.ChromaFormatIdc;
var bitDepthY = sps.BitDepthLuma;
var bitDepthC = format == 0 || sps.SeparateColourPlane ? bitDepthY : sps.BitDepthChroma;
int unitX = sps.CropUnitX, unitY = sps.CropUnitY;
var left = sps.CropLeft * unitX;
var top = sps.CropTop * unitY;
var width = Math.Max(2, p.Width - left - (sps.CropRight * unitX));
var height = Math.Max(2, p.Height - top - (sps.CropBottom * unitY));
var y = CopyRect(p.Y, p.Width, left, top, width, height, bps);
int cw = (width + 1) / 2, ch = (height + 1) / 2, pcw = p.Width / 2;
var cb = new byte[cw * ch];
var cr = new byte[cw * ch];
for (var r = 0; r < ch; r++)
byte[] cb, cr;
int ch, chromaTop;
if (format == 0)
{
Array.Copy(p.Cb, (((top / 2) + r) * pcw) + (left / 2), cb, r * cw, cw);
Array.Copy(p.Cr, (((top / 2) + r) * pcw) + (left / 2), cr, r * cw, cw);
int cw = (width + 1) / 2;
ch = (height + 1) / 2;
chromaTop = 0;
cb = new byte[cw * ch * bps];
FillMiddle(cb, bps, bitDepthC);
cr = (byte[])cb.Clone();
}
else
{
int subW = sps.SubWidthC, subH = sps.SubHeightC;
var cw = (width + subW - 1) / subW;
ch = (height + subH - 1) / subH;
chromaTop = top / subH;
cb = CopyRect(p.Cb, p.ChromaWidth, left / subW, chromaTop, cw, ch, bps);
cr = CopyRect(p.Cr, p.ChromaWidth, left / subW, chromaTop, cw, ch, bps);
}
if (p.Decoded != 3)
{
// A field without its pair: the rows of the missing field are grey, as the reference decoder writes them.
var missing = p.Decoded == 1 ? 1 : 0;
var rowY = width * bps;
for (var r = 0; r < height; r++)
{
if (((top + r) & 1) == missing)
{
y.AsSpan(r * width, width).Fill(128);
FillMiddle(y.AsSpan(r * rowY, rowY), bps, bitDepthY);
}
}
for (var r = 0; r < ch; r++)
if (format != 0)
{
if ((((top / 2) + r) & 1) == missing)
var rowC = cb.Length / ch;
for (var r = 0; r < ch; r++)
{
cb.AsSpan(r * cw, cw).Fill(128);
cr.AsSpan(r * cw, cw).Fill(128);
if (((chromaTop + r) & 1) == missing)
{
FillMiddle(cb.AsSpan(r * rowC, rowC), bps, bitDepthC);
FillMiddle(cr.AsSpan(r * rowC, rowC), bps, bitDepthC);
}
}
}
}
return new H264Frame(width, height, y, cb, cr, p.Poc, p.Period, p.DecodeIndex, sps.MatrixCoefficients, sps.FullRange);
return new H264Frame(width, height, y, cb, cr, p.Poc, p.Period, p.DecodeIndex, sps.MatrixCoefficients, sps.FullRange, format, bitDepthY, bitDepthC);
}
/// <summary>A <paramref name="width"/> × <paramref name="height"/> rectangle of a plane <paramref name="stride"/> samples wide.</summary>
private static byte[] CopyRect(byte[] plane, int stride, int left, int top, int width, int height, int bps)
{
var result = new byte[width * height * bps];
for (var r = 0; r < height; r++)
{
Array.Copy(plane, (((top + r) * stride) + left) * bps, result, r * width * bps, width * bps);
}
return result;
}
/// <summary>Samples at the middle value 2^(bitDepth − 1).</summary>
private static void FillMiddle(Span<byte> samples, int bps, int bitDepth)
{
if (bps == 1)
{
samples.Fill((byte)(1 << (bitDepth - 1)));
}
else
{
System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(samples).Fill((ushort)(1 << (bitDepth - 1)));
}
}
private void AddToDpb(Picture p)