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
@@ -1,7 +1,8 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>
|
||||
/// The variable-length codes of CAVLC (ITU-T H.264, tables 9-5, 9-7, 9-8, 9-9 and 9-10), written as bit strings and
|
||||
/// The variable-length codes of CAVLC (ITU-T H.264, tables 9-5, 9-7, 9-8, 9-9 and 9-10, with the columns of the
|
||||
/// 4:2:2 chroma DC: nC = −2 and table 9-9 (b)), written as bit strings and
|
||||
/// turned once into lookup tables indexed by the next 16 bits of the stream.
|
||||
/// </summary>
|
||||
internal static class CavlcTables
|
||||
@@ -82,6 +83,20 @@ internal static class CavlcTables
|
||||
"000010", "00000011", "00000010", "0000000",
|
||||
];
|
||||
|
||||
/// <summary>coeff_token for the chroma DC of 4:2:2 (nC = −2, eight coefficients).</summary>
|
||||
private static readonly string?[] CoeffTokenChroma422Dc =
|
||||
[
|
||||
"1", null, null, null,
|
||||
"0001111", "01", null, null,
|
||||
"0001110", "0001101", "001", null,
|
||||
"000000111", "0001100", "0001011", "00001",
|
||||
"000000110", "000000101", "0001010", "000001",
|
||||
"0000000111", "0000000110", "000000100", "0001001",
|
||||
"00000000111", "00000000110", "0000000101", "0001000",
|
||||
"000000000111", "000000000110", "00000000101", "0000000100",
|
||||
"0000000000111", "000000000101", "000000000100", "00000000100",
|
||||
];
|
||||
|
||||
/// <summary>total_zeros of 4×4 blocks, indexed [TotalCoeff − 1][total_zeros].</summary>
|
||||
private static readonly string[][] TotalZeros4x4 =
|
||||
[
|
||||
@@ -110,6 +125,18 @@ internal static class CavlcTables
|
||||
["1", "0"],
|
||||
];
|
||||
|
||||
/// <summary>total_zeros of the 4:2:2 chroma DC (table 9-9 (b)), indexed [TotalCoeff − 1][total_zeros].</summary>
|
||||
private static readonly string[][] TotalZerosChroma422Dc =
|
||||
[
|
||||
["1", "010", "011", "0010", "0011", "0001", "00001", "00000"],
|
||||
["000", "01", "001", "100", "101", "110", "111"],
|
||||
["000", "001", "01", "10", "110", "111"],
|
||||
["110", "00", "01", "10", "111"],
|
||||
["00", "01", "10", "11"],
|
||||
["00", "01", "1"],
|
||||
["0", "1"],
|
||||
];
|
||||
|
||||
/// <summary>run_before, indexed [Min(zerosLeft, 7) − 1][run_before].</summary>
|
||||
private static readonly string[][] RunBefore =
|
||||
[
|
||||
@@ -122,13 +149,18 @@ internal static class CavlcTables
|
||||
["111", "110", "101", "100", "011", "010", "001", "0001", "00001", "000001", "0000001", "00000001", "000000001", "0000000001", "00000000001"],
|
||||
];
|
||||
|
||||
/// <summary>Lookup tables of coeff_token: [0..2] by nC class, [3] for nC ≥ 8 (fixed 6 bits), [4] for the chroma DC.</summary>
|
||||
/// <summary>
|
||||
/// Lookup tables of coeff_token: [0..2] by nC class, [3] for nC ≥ 8 (fixed 6 bits), [4] for the 4:2:0 chroma DC, [5]
|
||||
/// for the 4:2:2 one.
|
||||
/// </summary>
|
||||
internal static readonly ushort[][] CoeffTokenLookup = BuildCoeffTokenLookups();
|
||||
|
||||
internal static readonly ushort[][] TotalZerosLookup = BuildLookups(TotalZeros4x4);
|
||||
|
||||
internal static readonly ushort[][] TotalZerosChromaDcLookup = BuildLookups(TotalZerosChromaDc);
|
||||
|
||||
internal static readonly ushort[][] TotalZerosChroma422DcLookup = BuildLookups(TotalZerosChroma422Dc);
|
||||
|
||||
internal static readonly ushort[][] RunBeforeLookup = BuildLookups(RunBefore);
|
||||
|
||||
/// <summary>All the code tables, for the self-checks of the tests (prefix-free, complete where the standard is).</summary>
|
||||
@@ -138,6 +170,7 @@ internal static class CavlcTables
|
||||
yield return ("coeff_token 1", CoeffToken1);
|
||||
yield return ("coeff_token 2", CoeffToken2);
|
||||
yield return ("coeff_token -1", CoeffTokenChromaDc);
|
||||
yield return ("coeff_token -2", CoeffTokenChroma422Dc);
|
||||
for (var i = 0; i < TotalZeros4x4.Length; i++)
|
||||
{
|
||||
yield return ($"total_zeros {i + 1}", TotalZeros4x4[i]);
|
||||
@@ -148,6 +181,11 @@ internal static class CavlcTables
|
||||
yield return ($"total_zeros DC {i + 1}", TotalZerosChromaDc[i]);
|
||||
}
|
||||
|
||||
for (var i = 0; i < TotalZerosChroma422Dc.Length; i++)
|
||||
{
|
||||
yield return ($"total_zeros DC 4:2:2 {i + 1}", TotalZerosChroma422Dc[i]);
|
||||
}
|
||||
|
||||
for (var i = 0; i < RunBefore.Length; i++)
|
||||
{
|
||||
yield return ($"run_before {i + 1}", RunBefore[i]);
|
||||
@@ -212,6 +250,6 @@ internal static class CavlcTables
|
||||
}
|
||||
}
|
||||
|
||||
return [Build(CoeffToken0), Build(CoeffToken1), Build(CoeffToken2), Build(fixedLength), Build(CoeffTokenChromaDc)];
|
||||
return [Build(CoeffToken0), Build(CoeffToken1), Build(CoeffToken2), Build(fixedLength), Build(CoeffTokenChromaDc), Build(CoeffTokenChroma422Dc)];
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,16 @@
|
||||
using static Febe.Core.Codecs.H264.Samples;
|
||||
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
public sealed partial class H264Decoder
|
||||
{
|
||||
/// <summary>The luma-like plane the deblocking filter is working on: Y, or one colour plane coded separately.</summary>
|
||||
private byte[] deblockLuma = [];
|
||||
|
||||
/// <summary>
|
||||
/// Deblocking filter (§8.7) of the picture just decoded, macroblock by macroblock in address order: a frame, one
|
||||
/// field (its rows only, as a picture of its own), or an MBAFF frame (pairs, top then bottom macroblock).
|
||||
/// field (its rows only, as a picture of its own), or an MBAFF frame (pairs, top then bottom macroblock). Colour planes
|
||||
/// coded separately are filtered one by one, each as a monochrome picture with its own macroblock data.
|
||||
/// </summary>
|
||||
private void Deblock(Picture picture)
|
||||
{
|
||||
@@ -19,25 +25,59 @@ public sealed partial class H264Decoder
|
||||
return;
|
||||
}
|
||||
|
||||
if (curStructure != 0)
|
||||
if (!separatePlanes)
|
||||
{
|
||||
DeblockRows(picture, 2, curStructure - 1);
|
||||
DeblockPlane(picture, picture.Y);
|
||||
return;
|
||||
}
|
||||
else if (activeSps!.MbAdaptiveFrameField)
|
||||
|
||||
for (var k = 0; k < 3; k++)
|
||||
{
|
||||
DeblockPairs(picture);
|
||||
SelectColourPlane(k);
|
||||
picture.SelectPlane(k);
|
||||
DeblockPlane(picture, picture.Plane(k));
|
||||
}
|
||||
|
||||
SelectColourPlane(0);
|
||||
picture.SelectPlane(0);
|
||||
}
|
||||
|
||||
private void DeblockPlane(Picture picture, byte[] luma)
|
||||
{
|
||||
deblockLuma = luma;
|
||||
if (wide)
|
||||
{
|
||||
DeblockPicture<ushort>(picture);
|
||||
}
|
||||
else
|
||||
{
|
||||
DeblockRows(picture, 1, 0);
|
||||
DeblockPicture<byte>(picture);
|
||||
}
|
||||
}
|
||||
|
||||
private void DeblockPicture<T>(Picture picture)
|
||||
where T : unmanaged
|
||||
{
|
||||
if (curStructure != 0)
|
||||
{
|
||||
DeblockRows<T>(picture, 2, curStructure - 1);
|
||||
}
|
||||
else if (activeSps!.MbAdaptiveFrameField)
|
||||
{
|
||||
DeblockPairs<T>(picture);
|
||||
}
|
||||
else
|
||||
{
|
||||
DeblockRows<T>(picture, 1, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A frame (<paramref name="rowStep"/> 1) or the field of <paramref name="parity"/> (<paramref name="rowStep"/> 2).</summary>
|
||||
private void DeblockRows(Picture picture, int rowStep, int parity)
|
||||
private void DeblockRows<T>(Picture picture, int rowStep, int parity)
|
||||
where T : unmanaged
|
||||
{
|
||||
var w = widthInMbs;
|
||||
int width = picture.Width, cwidth = width / 2;
|
||||
int width = picture.Width, cwidth = picture.ChromaWidth;
|
||||
int stride = width * rowStep, cstride = cwidth * rowStep;
|
||||
Span<byte> bs = stackalloc byte[4];
|
||||
var rows = heightInMbs / rowStep;
|
||||
@@ -58,21 +98,21 @@ public sealed partial class H264Decoder
|
||||
continue;
|
||||
}
|
||||
|
||||
var lumaOrigin = ((((row * 16 * rowStep) + parity) * width)) + (mx * 16);
|
||||
var chromaOrigin = ((((row * 8 * rowStep) + parity) * cwidth)) + (mx * 8);
|
||||
var lumaOrigin = (((row * 16 * rowStep) + parity) * width) + (mx * 16);
|
||||
var chromaOrigin = (((row * mbHeightC * rowStep) + parity) * cwidth) + (mx * mbWidthC);
|
||||
if (mx > 0 && mbSlice[m - 1] >= 0 && (disable != 2 || mbSlice[m - 1] == s))
|
||||
{
|
||||
MbEdge(picture, m - 1, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
MbEdge<T>(picture, m - 1, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
}
|
||||
|
||||
InnerEdges(picture, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
InnerEdges<T>(picture, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
var up = m - (rowStep * w);
|
||||
if (row > 0 && mbSlice[up] >= 0 && (disable != 2 || mbSlice[up] == s))
|
||||
{
|
||||
MbEdge(picture, up, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
MbEdge<T>(picture, up, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
}
|
||||
|
||||
InnerEdges(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
InnerEdges<T>(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,10 +121,11 @@ public sealed partial class H264Decoder
|
||||
/// An MBAFF frame. Between a frame and a field pair the left edge is filtered row by row, each row against the
|
||||
/// macroblock that holds it; the top edge of a frame macroblock under a field pair twice, once per field (§8.7.1).
|
||||
/// </summary>
|
||||
private void DeblockPairs(Picture picture)
|
||||
private void DeblockPairs<T>(Picture picture)
|
||||
where T : unmanaged
|
||||
{
|
||||
var w = widthInMbs;
|
||||
int width = picture.Width, cwidth = width / 2;
|
||||
int width = picture.Width, cwidth = picture.ChromaWidth;
|
||||
Span<byte> bs = stackalloc byte[4];
|
||||
Span<byte> rowBs = stackalloc byte[16];
|
||||
Span<int> rowMb = stackalloc int[16];
|
||||
@@ -113,14 +154,14 @@ public sealed partial class H264Decoder
|
||||
if (isField)
|
||||
{
|
||||
lumaOrigin = (((pairY * 32) + bottom) * width) + (mx * 16);
|
||||
chromaOrigin = (((pairY * 16) + bottom) * cwidth) + (mx * 8);
|
||||
chromaOrigin = (((pairY * 2 * mbHeightC) + bottom) * cwidth) + (mx * mbWidthC);
|
||||
stride = 2 * width;
|
||||
cstride = 2 * cwidth;
|
||||
}
|
||||
else
|
||||
{
|
||||
lumaOrigin = ((((2 * pairY) + bottom) * 16) * width) + (mx * 16);
|
||||
chromaOrigin = ((((2 * pairY) + bottom) * 8) * cwidth) + (mx * 8);
|
||||
chromaOrigin = ((((2 * pairY) + bottom) * mbHeightC) * cwidth) + (mx * mbWidthC);
|
||||
stride = width;
|
||||
cstride = cwidth;
|
||||
}
|
||||
@@ -132,20 +173,20 @@ public sealed partial class H264Decoder
|
||||
var leftField = field[leftTop];
|
||||
if (leftField == isField)
|
||||
{
|
||||
MbEdge(picture, leftTop + (bottom * w), m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
MbEdge<T>(picture, leftTop + (bottom * w), m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
}
|
||||
else
|
||||
{
|
||||
MixedLeftEdge(picture, m, leftTop, isField, bottom != 0, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, rowBs, rowMb);
|
||||
MixedLeftEdge<T>(picture, m, leftTop, isField, bottom != 0, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, rowBs, rowMb);
|
||||
}
|
||||
}
|
||||
|
||||
InnerEdges(picture, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
InnerEdges<T>(picture, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
|
||||
// Top edge.
|
||||
if (!isField && bottom == 1)
|
||||
{
|
||||
MbEdge(picture, m - w, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
MbEdge<T>(picture, m - w, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
}
|
||||
else if (pairY > 0)
|
||||
{
|
||||
@@ -157,18 +198,18 @@ public sealed partial class H264Decoder
|
||||
// A frame macroblock under a field pair: each field of its top rows against that field.
|
||||
for (var j = 0; j < 2; j++)
|
||||
{
|
||||
MbEdge(picture, aboveTop + (j * w), m, false, lumaOrigin + (j * width), 2 * width, chromaOrigin + (j * cwidth), 2 * cwidth, alphaOffset, betaOffset, bs);
|
||||
MbEdge<T>(picture, aboveTop + (j * w), m, false, lumaOrigin + (j * width), 2 * width, chromaOrigin + (j * cwidth), 2 * cwidth, alphaOffset, betaOffset, bs);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var pm = isField && bottom == 0 && field[aboveTop] ? aboveTop : aboveTop + w;
|
||||
MbEdge(picture, pm, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
MbEdge<T>(picture, pm, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
InnerEdges(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
InnerEdges<T>(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -176,11 +217,13 @@ public sealed partial class H264Decoder
|
||||
|
||||
/// <summary>
|
||||
/// The left edge of an MBAFF macroblock whose left pair is of the other kind (frame and field): bS and qP row by
|
||||
/// row, from the macroblock holding each row of the left pair.
|
||||
/// row, from the macroblock holding each row of the left pair. A chroma row takes the bS of a luma row: in 4:2:0 the
|
||||
/// mapping of §8.7.2.1, in 4:2:2 and 4:4:4 (as many chroma rows as luma rows) the row itself.
|
||||
/// </summary>
|
||||
private void MixedLeftEdge(
|
||||
private void MixedLeftEdge<T>(
|
||||
Picture picture, int m, int leftTop, bool isField, bool bottom, int lumaOrigin, int stride, int chromaOrigin, int cstride,
|
||||
int alphaOffset, int betaOffset, Span<byte> rowBs, Span<int> rowMb)
|
||||
where T : unmanaged
|
||||
{
|
||||
var w = widthInMbs;
|
||||
var leftField = picture.MbField[leftTop];
|
||||
@@ -191,6 +234,7 @@ public sealed partial class H264Decoder
|
||||
rowBs[r] = (byte)BoundaryStrength(picture, pm, (((yM & 15) >> 2) * 4) + 3, m, (r >> 2) * 4, true, true);
|
||||
}
|
||||
|
||||
var luma = Plane<T>(deblockLuma);
|
||||
for (var r = 0; r < 16; r++)
|
||||
{
|
||||
if (rowBs[r] == 0)
|
||||
@@ -198,18 +242,22 @@ public sealed partial class H264Decoder
|
||||
continue;
|
||||
}
|
||||
|
||||
var qpav = (mbQp[rowMb[r]] + mbQp[m] + 1) >> 1;
|
||||
var indexA = Math.Clamp(qpav + alphaOffset, 0, 51);
|
||||
int alpha = H264Tables.Alpha[indexA], beta = H264Tables.Beta[Math.Clamp(qpav + betaOffset, 0, 51)];
|
||||
if (alpha != 0 && beta != 0)
|
||||
if (Thresholds(mbQp[rowMb[r]], mbQp[m], alphaOffset, betaOffset, bitDepthY, out var alpha, out var beta, out var indexA))
|
||||
{
|
||||
FilterLuma(picture.Y, lumaOrigin + (r * stride), 1, rowBs[r], alpha, beta, indexA);
|
||||
FilterLuma(luma, lumaOrigin + (r * stride), 1, rowBs[r], alpha, beta, indexA, bitDepthY - 8, maxY);
|
||||
}
|
||||
}
|
||||
|
||||
for (var k = 0; k < 8; k++)
|
||||
if (chromaArrayType == 0)
|
||||
{
|
||||
var lumaRow = isField && !leftField ? 2 * k : (4 * (k >> 1)) + (k & 1);
|
||||
return;
|
||||
}
|
||||
|
||||
var cb = Plane<T>(picture.Cb);
|
||||
var cr = Plane<T>(picture.Cr);
|
||||
for (var k = 0; k < mbHeightC; k++)
|
||||
{
|
||||
var lumaRow = mbHeightC == 16 ? k : isField && !leftField ? 2 * k : (4 * (k >> 1)) + (k & 1);
|
||||
var strength = rowBs[lumaRow];
|
||||
if (strength == 0)
|
||||
{
|
||||
@@ -219,20 +267,28 @@ public sealed partial class H264Decoder
|
||||
var pm = rowMb[lumaRow];
|
||||
for (var c = 0; c < 2; c++)
|
||||
{
|
||||
var qpav = (mbQpC[(pm * 2) + c] + mbQpC[(m * 2) + c] + 1) >> 1;
|
||||
var indexA = Math.Clamp(qpav + alphaOffset, 0, 51);
|
||||
int alpha = H264Tables.Alpha[indexA], beta = H264Tables.Beta[Math.Clamp(qpav + betaOffset, 0, 51)];
|
||||
if (alpha != 0 && beta != 0)
|
||||
if (!Thresholds(mbQpC[(pm * 2) + c], mbQpC[(m * 2) + c], alphaOffset, betaOffset, bitDepthC, out var alpha, out var beta, out var indexA))
|
||||
{
|
||||
FilterChroma(c == 0 ? picture.Cb : picture.Cr, chromaOrigin + (k * cstride), 1, strength, alpha, beta, indexA);
|
||||
continue;
|
||||
}
|
||||
|
||||
var plane = c == 0 ? cb : cr;
|
||||
if (chromaArrayType == 3)
|
||||
{
|
||||
FilterLuma(plane, chromaOrigin + (k * cstride), 1, strength, alpha, beta, indexA, bitDepthC - 8, maxC);
|
||||
}
|
||||
else
|
||||
{
|
||||
FilterChroma(plane, chromaOrigin + (k * cstride), 1, strength, alpha, beta, indexA, bitDepthC - 8, maxC);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A macroblock edge between <paramref name="pm"/> (left or above) and <paramref name="qm"/>, luma and chroma.</summary>
|
||||
private void MbEdge(
|
||||
private void MbEdge<T>(
|
||||
Picture picture, int pm, int qm, bool vertical, int lumaOrigin, int stride, int chromaOrigin, int cstride, int alphaOffset, int betaOffset, Span<byte> bs)
|
||||
where T : unmanaged
|
||||
{
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
@@ -246,24 +302,44 @@ public sealed partial class H264Decoder
|
||||
}
|
||||
|
||||
int along = vertical ? stride : 1, across = vertical ? 1 : stride;
|
||||
LumaEdge(picture.Y, lumaOrigin, along, across, bs, mbQp[pm], mbQp[qm], alphaOffset, betaOffset);
|
||||
Edge(Plane<T>(deblockLuma), lumaOrigin, along, across, bs, 16, mbQp[pm], mbQp[qm], alphaOffset, betaOffset, bitDepthY, chromaStyle: false);
|
||||
if (chromaArrayType == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int calong = vertical ? cstride : 1, cacross = vertical ? 1 : cstride;
|
||||
var count = vertical ? mbHeightC : mbWidthC;
|
||||
for (var c = 0; c < 2; c++)
|
||||
{
|
||||
ChromaEdge(c == 0 ? picture.Cb : picture.Cr, chromaOrigin, calong, cacross, bs, mbQpC[(pm * 2) + c], mbQpC[(qm * 2) + c], alphaOffset, betaOffset);
|
||||
Edge(Plane<T>(c == 0 ? picture.Cb : picture.Cr), chromaOrigin, calong, cacross, bs, count, mbQpC[(pm * 2) + c], mbQpC[(qm * 2) + c], alphaOffset, betaOffset, bitDepthC, chromaStyle: chromaArrayType != 3);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The internal edges of macroblock <paramref name="m"/> in one direction (luma 4, 8, 12; chroma 4).</summary>
|
||||
private void InnerEdges(
|
||||
/// <summary>
|
||||
/// The internal edges of macroblock <paramref name="m"/> in one direction: luma 4, 8, 12 (only 8 with the 8×8
|
||||
/// transform); chroma at the same luma positions where they fall on a 4×4 chroma block edge — 4 for 4:2:0, the
|
||||
/// rows 4, 8 and 12 of 4:2:2 (whatever the transform of luma), all the luma edges in 4:4:4.
|
||||
/// </summary>
|
||||
private void InnerEdges<T>(
|
||||
Picture picture, int m, bool vertical, int lumaOrigin, int stride, int chromaOrigin, int cstride, int alphaOffset, int betaOffset, Span<byte> bs)
|
||||
where T : unmanaged
|
||||
{
|
||||
var t8 = mbT8[m];
|
||||
int along = vertical ? stride : 1, across = vertical ? 1 : stride;
|
||||
int calong = vertical ? cstride : 1, cacross = vertical ? 1 : cstride;
|
||||
var chromaSize = vertical ? mbWidthC : mbHeightC;
|
||||
var count = vertical ? mbHeightC : mbWidthC;
|
||||
for (var edge = 1; edge < 4; edge++)
|
||||
{
|
||||
if (t8 && (edge & 1) != 0)
|
||||
var lumaEdge = !t8 || (edge & 1) == 0;
|
||||
var chromaEdge = chromaArrayType switch
|
||||
{
|
||||
0 => false,
|
||||
3 => lumaEdge,
|
||||
_ => chromaSize == 16 || edge == 2,
|
||||
};
|
||||
if (!lumaEdge && !chromaEdge)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -279,55 +355,67 @@ public sealed partial class H264Decoder
|
||||
continue;
|
||||
}
|
||||
|
||||
var offset = edge * 4 * (vertical ? 1 : stride);
|
||||
LumaEdge(picture.Y, lumaOrigin + offset, along, across, bs, mbQp[m], mbQp[m], alphaOffset, betaOffset);
|
||||
if (edge == 2)
|
||||
if (lumaEdge)
|
||||
{
|
||||
var coffset = 4 * (vertical ? 1 : cstride);
|
||||
var offset = edge * 4 * (vertical ? 1 : stride);
|
||||
Edge(Plane<T>(deblockLuma), lumaOrigin + offset, along, across, bs, 16, mbQp[m], mbQp[m], alphaOffset, betaOffset, bitDepthY, chromaStyle: false);
|
||||
}
|
||||
|
||||
if (chromaEdge)
|
||||
{
|
||||
var position = edge * chromaSize / 4;
|
||||
var coffset = position * (vertical ? 1 : cstride);
|
||||
for (var c = 0; c < 2; c++)
|
||||
{
|
||||
ChromaEdge(c == 0 ? picture.Cb : picture.Cr, chromaOrigin + coffset, calong, cacross, bs, mbQpC[(m * 2) + c], mbQpC[(m * 2) + c], alphaOffset, betaOffset);
|
||||
Edge(Plane<T>(c == 0 ? picture.Cb : picture.Cr), chromaOrigin + coffset, calong, cacross, bs, count, mbQpC[(m * 2) + c], mbQpC[(m * 2) + c], alphaOffset, betaOffset, bitDepthC, chromaStyle: chromaArrayType != 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void LumaEdge(byte[] plane, int origin, int along, int across, ReadOnlySpan<byte> bs, int qpP, int qpQ, int alphaOffset, int betaOffset)
|
||||
/// <summary>
|
||||
/// α, β and indexA of an edge (§8.7.2.2) from the qP of its two sides, scaled to the bit depth (equations 8-466,
|
||||
/// 8-467); false when the edge is not filtered.
|
||||
/// </summary>
|
||||
private static bool Thresholds(int qpP, int qpQ, int alphaOffset, int betaOffset, int bitDepth, out int alpha, out int beta, out int indexA)
|
||||
{
|
||||
var qpav = (qpP + qpQ + 1) >> 1;
|
||||
var indexA = Math.Clamp(qpav + alphaOffset, 0, 51);
|
||||
int alpha = H264Tables.Alpha[indexA], beta = H264Tables.Beta[Math.Clamp(qpav + betaOffset, 0, 51)];
|
||||
if (alpha == 0 || beta == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
for (var k = 0; k < 16; k++)
|
||||
{
|
||||
var strength = bs[k >> 2];
|
||||
if (strength != 0)
|
||||
{
|
||||
FilterLuma(plane, origin + (k * along), across, strength, alpha, beta, indexA);
|
||||
}
|
||||
}
|
||||
indexA = Math.Clamp(qpav + alphaOffset, 0, 51);
|
||||
alpha = H264Tables.Alpha[indexA] << (bitDepth - 8);
|
||||
beta = H264Tables.Beta[Math.Clamp(qpav + betaOffset, 0, 51)] << (bitDepth - 8);
|
||||
return alpha != 0 && beta != 0;
|
||||
}
|
||||
|
||||
private static void ChromaEdge(byte[] plane, int origin, int along, int across, ReadOnlySpan<byte> bs, int qpP, int qpQ, int alphaOffset, int betaOffset)
|
||||
/// <summary>
|
||||
/// The <paramref name="count"/> samples along one edge (16 in luma; 8 or 16 in chroma), each with the bS of its 4×4
|
||||
/// luma block; the filter of chroma (chromaStyleFilteringFlag) or that of luma, which 4:4:4 uses for Cb and Cr.
|
||||
/// </summary>
|
||||
private static void Edge<T>(Span<T> plane, int origin, int along, int across, ReadOnlySpan<byte> bs, int count, int qpP, int qpQ, int alphaOffset, int betaOffset, int bitDepth, bool chromaStyle)
|
||||
where T : unmanaged
|
||||
{
|
||||
var qpav = (qpP + qpQ + 1) >> 1;
|
||||
var indexA = Math.Clamp(qpav + alphaOffset, 0, 51);
|
||||
int alpha = H264Tables.Alpha[indexA], beta = H264Tables.Beta[Math.Clamp(qpav + betaOffset, 0, 51)];
|
||||
if (alpha == 0 || beta == 0)
|
||||
if (!Thresholds(qpP, qpQ, alphaOffset, betaOffset, bitDepth, out var alpha, out var beta, out var indexA))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
for (var k = 0; k < 8; k++)
|
||||
var shift = count == 16 ? 2 : 1;
|
||||
var bdShift = bitDepth - 8;
|
||||
var max = (1 << bitDepth) - 1;
|
||||
for (var k = 0; k < count; k++)
|
||||
{
|
||||
var strength = bs[k >> 1];
|
||||
if (strength != 0)
|
||||
var strength = bs[k >> shift];
|
||||
if (strength == 0)
|
||||
{
|
||||
FilterChroma(plane, origin + (k * along), across, strength, alpha, beta, indexA);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (chromaStyle)
|
||||
{
|
||||
FilterChroma(plane, origin + (k * along), across, strength, alpha, beta, indexA, bdShift, max);
|
||||
}
|
||||
else
|
||||
{
|
||||
FilterLuma(plane, origin + (k * along), across, strength, alpha, beta, indexA, bdShift, max);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -417,51 +505,71 @@ public sealed partial class H264Decoder
|
||||
private static bool MvFar(short[] mv, int a, int b, int verticalLimit) =>
|
||||
Math.Abs(mv[a] - mv[b]) >= 4 || Math.Abs(mv[a + 1] - mv[b + 1]) >= verticalLimit;
|
||||
|
||||
/// <summary>
|
||||
/// The transform block holding the 4×4 luma block <paramref name="blk"/> has coefficients; in 4:4:4 (not coded as
|
||||
/// separate planes) those of the Cb and Cr blocks at the same place count too.
|
||||
/// </summary>
|
||||
private bool HasCoefficients(int m, int blk)
|
||||
{
|
||||
var baseIndex = m * 24;
|
||||
if (!mbT8[m])
|
||||
var planes = chromaArrayType == 3 ? 3 : 1;
|
||||
for (var plane = 0; plane < planes; plane++)
|
||||
{
|
||||
return nz[baseIndex + blk] != 0;
|
||||
var baseIndex = (m * NzPerMb) + (plane * 16);
|
||||
if (!mbT8[m])
|
||||
{
|
||||
if (nz[baseIndex + blk] != 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// The 8×8 transform block containing the 4×4 block.
|
||||
var r0 = ((blk >> 3) * 8) + (((blk & 3) >> 1) * 2);
|
||||
if ((nz[baseIndex + r0] | nz[baseIndex + r0 + 1] | nz[baseIndex + r0 + 4] | nz[baseIndex + r0 + 5]) != 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// The 8×8 transform block containing the 4×4 block.
|
||||
var r0 = ((blk >> 3) * 8) + (((blk & 3) >> 1) * 2);
|
||||
return (nz[baseIndex + r0] | nz[baseIndex + r0 + 1] | nz[baseIndex + r0 + 4] | nz[baseIndex + r0 + 5]) != 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void FilterLuma(byte[] s, int o, int step, int bS, int alpha, int beta, int indexA)
|
||||
/// <summary>The filter of luma edges (§8.7.2.3, §8.7.2.4), also that of Cb and Cr in 4:4:4; tC0 scaled by <paramref name="bdShift"/>.</summary>
|
||||
private static void FilterLuma<T>(Span<T> s, int o, int step, int bS, int alpha, int beta, int indexA, int bdShift, int max)
|
||||
where T : unmanaged
|
||||
{
|
||||
int p0 = s[o - step], q0 = s[o];
|
||||
int p0 = Get(s[o - step]), q0 = Get(s[o]);
|
||||
if (Math.Abs(p0 - q0) >= alpha)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int p1 = s[o - (2 * step)], q1 = s[o + step];
|
||||
int p1 = Get(s[o - (2 * step)]), q1 = Get(s[o + step]);
|
||||
if (Math.Abs(p1 - p0) >= beta || Math.Abs(q1 - q0) >= beta)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int p2 = s[o - (3 * step)], q2 = s[o + (2 * step)];
|
||||
int p2 = Get(s[o - (3 * step)]), q2 = Get(s[o + (2 * step)]);
|
||||
var ap = Math.Abs(p2 - p0) < beta;
|
||||
var aq = Math.Abs(q2 - q0) < beta;
|
||||
if (bS < 4)
|
||||
{
|
||||
int tc0 = H264Tables.Tc0[(indexA * 3) + bS - 1];
|
||||
var tc0 = H264Tables.Tc0[(indexA * 3) + bS - 1] << bdShift;
|
||||
var tc = tc0 + (ap ? 1 : 0) + (aq ? 1 : 0);
|
||||
var delta = Math.Clamp((((q0 - p0) << 2) + (p1 - q1) + 4) >> 3, -tc, tc);
|
||||
s[o - step] = Clip(p0 + delta);
|
||||
s[o] = Clip(q0 - delta);
|
||||
s[o - step] = Make<T>(Clip(p0 + delta, max));
|
||||
s[o] = Make<T>(Clip(q0 - delta, max));
|
||||
if (ap)
|
||||
{
|
||||
s[o - (2 * step)] = (byte)(p1 + Math.Clamp((p2 + ((p0 + q0 + 1) >> 1) - (p1 << 1)) >> 1, -tc0, tc0));
|
||||
s[o - (2 * step)] = Make<T>(p1 + Math.Clamp((p2 + ((p0 + q0 + 1) >> 1) - (p1 << 1)) >> 1, -tc0, tc0));
|
||||
}
|
||||
|
||||
if (aq)
|
||||
{
|
||||
s[o + step] = (byte)(q1 + Math.Clamp((q2 + ((p0 + q0 + 1) >> 1) - (q1 << 1)) >> 1, -tc0, tc0));
|
||||
s[o + step] = Make<T>(q1 + Math.Clamp((q2 + ((p0 + q0 + 1) >> 1) - (q1 << 1)) >> 1, -tc0, tc0));
|
||||
}
|
||||
|
||||
return;
|
||||
@@ -470,38 +578,40 @@ public sealed partial class H264Decoder
|
||||
var strong = Math.Abs(p0 - q0) < ((alpha >> 2) + 2);
|
||||
if (ap && strong)
|
||||
{
|
||||
int p3 = s[o - (4 * step)];
|
||||
s[o - step] = (byte)((p2 + (2 * p1) + (2 * p0) + (2 * q0) + q1 + 4) >> 3);
|
||||
s[o - (2 * step)] = (byte)((p2 + p1 + p0 + q0 + 2) >> 2);
|
||||
s[o - (3 * step)] = (byte)(((2 * p3) + (3 * p2) + p1 + p0 + q0 + 4) >> 3);
|
||||
var p3 = Get(s[o - (4 * step)]);
|
||||
s[o - step] = Make<T>((p2 + (2 * p1) + (2 * p0) + (2 * q0) + q1 + 4) >> 3);
|
||||
s[o - (2 * step)] = Make<T>((p2 + p1 + p0 + q0 + 2) >> 2);
|
||||
s[o - (3 * step)] = Make<T>(((2 * p3) + (3 * p2) + p1 + p0 + q0 + 4) >> 3);
|
||||
}
|
||||
else
|
||||
{
|
||||
s[o - step] = (byte)(((2 * p1) + p0 + q1 + 2) >> 2);
|
||||
s[o - step] = Make<T>(((2 * p1) + p0 + q1 + 2) >> 2);
|
||||
}
|
||||
|
||||
if (aq && strong)
|
||||
{
|
||||
int q3 = s[o + (3 * step)];
|
||||
s[o] = (byte)((p1 + (2 * p0) + (2 * q0) + (2 * q1) + q2 + 4) >> 3);
|
||||
s[o + step] = (byte)((p0 + q0 + q1 + q2 + 2) >> 2);
|
||||
s[o + (2 * step)] = (byte)(((2 * q3) + (3 * q2) + q1 + q0 + p0 + 4) >> 3);
|
||||
var q3 = Get(s[o + (3 * step)]);
|
||||
s[o] = Make<T>((p1 + (2 * p0) + (2 * q0) + (2 * q1) + q2 + 4) >> 3);
|
||||
s[o + step] = Make<T>((p0 + q0 + q1 + q2 + 2) >> 2);
|
||||
s[o + (2 * step)] = Make<T>(((2 * q3) + (3 * q2) + q1 + q0 + p0 + 4) >> 3);
|
||||
}
|
||||
else
|
||||
{
|
||||
s[o] = (byte)(((2 * q1) + q0 + p1 + 2) >> 2);
|
||||
s[o] = Make<T>(((2 * q1) + q0 + p1 + 2) >> 2);
|
||||
}
|
||||
}
|
||||
|
||||
private static void FilterChroma(byte[] s, int o, int step, int bS, int alpha, int beta, int indexA)
|
||||
/// <summary>The filter of the chroma edges of 4:2:0 and 4:2:2 (chromaStyleFilteringFlag).</summary>
|
||||
private static void FilterChroma<T>(Span<T> s, int o, int step, int bS, int alpha, int beta, int indexA, int bdShift, int max)
|
||||
where T : unmanaged
|
||||
{
|
||||
int p0 = s[o - step], q0 = s[o];
|
||||
int p0 = Get(s[o - step]), q0 = Get(s[o]);
|
||||
if (Math.Abs(p0 - q0) >= alpha)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int p1 = s[o - (2 * step)], q1 = s[o + step];
|
||||
int p1 = Get(s[o - (2 * step)]), q1 = Get(s[o + step]);
|
||||
if (Math.Abs(p1 - p0) >= beta || Math.Abs(q1 - q0) >= beta)
|
||||
{
|
||||
return;
|
||||
@@ -509,16 +619,14 @@ public sealed partial class H264Decoder
|
||||
|
||||
if (bS < 4)
|
||||
{
|
||||
var tc = H264Tables.Tc0[(indexA * 3) + bS - 1] + 1;
|
||||
var tc = (H264Tables.Tc0[(indexA * 3) + bS - 1] << bdShift) + 1;
|
||||
var delta = Math.Clamp((((q0 - p0) << 2) + (p1 - q1) + 4) >> 3, -tc, tc);
|
||||
s[o - step] = Clip(p0 + delta);
|
||||
s[o] = Clip(q0 - delta);
|
||||
s[o - step] = Make<T>(Clip(p0 + delta, max));
|
||||
s[o] = Make<T>(Clip(q0 - delta, max));
|
||||
return;
|
||||
}
|
||||
|
||||
s[o - step] = (byte)(((2 * p1) + p0 + q1 + 2) >> 2);
|
||||
s[o] = (byte)(((2 * q1) + q0 + p1 + 2) >> 2);
|
||||
s[o - step] = Make<T>(((2 * p1) + p0 + q1 + 2) >> 2);
|
||||
s[o] = Make<T>(((2 * q1) + q0 + p1 + 2) >> 2);
|
||||
}
|
||||
|
||||
private static byte Clip(int v) => (byte)(v < 0 ? 0 : v > 255 ? 255 : v);
|
||||
}
|
||||
@@ -336,6 +336,13 @@ public sealed partial class H264Decoder
|
||||
{
|
||||
if (!cabacMode)
|
||||
{
|
||||
if (numC8x8 == 0)
|
||||
{
|
||||
// Without chroma syntax (monochrome, 4:4:4, separate planes) the code covers the luma bits only.
|
||||
var luma = rd.ReadUe(15);
|
||||
return intra ? H264Tables.CbpIntraNoChroma[luma] : H264Tables.CbpInterNoChroma[luma];
|
||||
}
|
||||
|
||||
var code = rd.ReadUe(47);
|
||||
return intra ? H264Tables.CbpIntra[code] : H264Tables.CbpInter[code];
|
||||
}
|
||||
@@ -368,7 +375,12 @@ public sealed partial class H264Decoder
|
||||
cbp |= cabac.Decision(73 + condA + (2 * condB)) << b8;
|
||||
}
|
||||
|
||||
var a = mbA >= 0 ? mbCbp[mbA] >> 4 : 0;
|
||||
if (numC8x8 == 0)
|
||||
{
|
||||
return cbp;
|
||||
}
|
||||
|
||||
var a =mbA >= 0 ? mbCbp[mbA] >> 4 : 0;
|
||||
var b = mbB >= 0 ? mbCbp[mbB] >> 4 : 0;
|
||||
var inc = (a != 0 ? 1 : 0) + (b != 0 ? 2 : 0);
|
||||
if (cabac.Decision(77 + inc) != 0)
|
||||
@@ -417,7 +429,7 @@ public sealed partial class H264Decoder
|
||||
int nC;
|
||||
if (cat == 3)
|
||||
{
|
||||
nC = -1;
|
||||
nC = numC8x8 == 2 ? -2 : -1;
|
||||
}
|
||||
else if (cat == 4)
|
||||
{
|
||||
@@ -425,11 +437,12 @@ public sealed partial class H264Decoder
|
||||
}
|
||||
else
|
||||
{
|
||||
nC = LumaNc(blk);
|
||||
nC = LumaNc(blk, comp);
|
||||
}
|
||||
|
||||
var table = nC switch
|
||||
{
|
||||
-2 => CavlcTables.CoeffTokenLookup[5],
|
||||
-1 => CavlcTables.CoeffTokenLookup[4],
|
||||
< 2 => CavlcTables.CoeffTokenLookup[0],
|
||||
< 4 => CavlcTables.CoeffTokenLookup[1],
|
||||
@@ -515,7 +528,8 @@ public sealed partial class H264Decoder
|
||||
var zerosLeft = 0;
|
||||
if (total < maxNum)
|
||||
{
|
||||
var tz = cat == 3 ? CavlcTables.TotalZerosChromaDcLookup[total - 1] : CavlcTables.TotalZerosLookup[total - 1];
|
||||
var tz = cat != 3 ? CavlcTables.TotalZerosLookup[total - 1]
|
||||
: numC8x8 == 2 ? CavlcTables.TotalZerosChroma422DcLookup[total - 1] : CavlcTables.TotalZerosChromaDcLookup[total - 1];
|
||||
var e = tz[rd.Peek(16)];
|
||||
if (e == 0)
|
||||
{
|
||||
@@ -575,18 +589,18 @@ public sealed partial class H264Decoder
|
||||
private bool HiddenByPartitioning(int n) => partitioned && pps.ConstrainedIntraPred && !IsIntra(n) && IsIntra(mb);
|
||||
|
||||
/// <summary>nC of a luma 4×4 block (raster index) from the blocks to its left and above (§9.2.1).</summary>
|
||||
private int LumaNc(int raster)
|
||||
private int LumaNc(int raster, int plane)
|
||||
{
|
||||
int bx = raster & 3, by = raster >> 2;
|
||||
bool hasA = true, hasB = true;
|
||||
int nA = 0, nB = 0;
|
||||
if (bx > 0)
|
||||
{
|
||||
nA = nz[(mb * 24) + raster - 1];
|
||||
nA = nz[(mb * NzPerMb) + (plane * 16) + raster - 1];
|
||||
}
|
||||
else if (Locate(-1, by * 4, 16, out var yM) is var a and >= 0)
|
||||
{
|
||||
nA = HiddenByPartitioning(a) ? 0 : nz[(a * 24) + (((yM & 15) >> 2) * 4) + 3];
|
||||
nA = HiddenByPartitioning(a) ? 0 : nz[(a * NzPerMb) + (plane * 16) + (((yM & 15) >> 2) * 4) + 3];
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -595,11 +609,11 @@ public sealed partial class H264Decoder
|
||||
|
||||
if (by > 0)
|
||||
{
|
||||
nB = nz[(mb * 24) + raster - 4];
|
||||
nB = nz[(mb * NzPerMb) + (plane * 16) + raster - 4];
|
||||
}
|
||||
else if (Locate(bx * 4, -1, 16, out _) is var b and >= 0)
|
||||
{
|
||||
nB = HiddenByPartitioning(b) ? 0 : nz[(b * 24) + 12 + bx];
|
||||
nB = HiddenByPartitioning(b) ? 0 : nz[(b * NzPerMb) + (plane * 16) + 12 + bx];
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -609,19 +623,20 @@ public sealed partial class H264Decoder
|
||||
return hasA && hasB ? (nA + nB + 1) >> 1 : hasA ? nA : hasB ? nB : 0;
|
||||
}
|
||||
|
||||
/// <summary>nC of a chroma AC block of 4:2:0 or 4:2:2 (blocks in raster order, two per row).</summary>
|
||||
private int ChromaNc(int b, int comp)
|
||||
{
|
||||
int bx = b & 1, by = b >> 1;
|
||||
var baseIndex = 16 + (comp * 4);
|
||||
var baseIndex = 16 + (comp * 16);
|
||||
bool hasA = true, hasB = true;
|
||||
int nA = 0, nB = 0;
|
||||
if (bx > 0)
|
||||
{
|
||||
nA = nz[(mb * 24) + baseIndex + b - 1];
|
||||
nA = nz[(mb * NzPerMb) + baseIndex + b - 1];
|
||||
}
|
||||
else if (Locate(-1, by * 4, 8, out var yM) is var a and >= 0)
|
||||
else if (Locate(-1, by * 4, mbHeightC, out var yM) is var a and >= 0)
|
||||
{
|
||||
nA = HiddenByPartitioning(a) ? 0 : nz[(a * 24) + baseIndex + (((yM & 7) >> 2) * 2) + 1];
|
||||
nA = HiddenByPartitioning(a) ? 0 : nz[(a * NzPerMb) + baseIndex + (((yM & (mbHeightC - 1)) >> 2) * 2) + 1];
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -630,11 +645,11 @@ public sealed partial class H264Decoder
|
||||
|
||||
if (by > 0)
|
||||
{
|
||||
nB = nz[(mb * 24) + baseIndex + b - 2];
|
||||
nB = nz[(mb * NzPerMb) + baseIndex + b - 2];
|
||||
}
|
||||
else if (Locate(bx * 4, -1, 8, out _) is var n and >= 0)
|
||||
else if (Locate(bx * 4, -1, mbHeightC, out _) is var n and >= 0)
|
||||
{
|
||||
nB = HiddenByPartitioning(n) ? 0 : nz[(n * 24) + baseIndex + 2 + bx];
|
||||
nB = HiddenByPartitioning(n) ? 0 : nz[(n * NzPerMb) + baseIndex + (mbHeightC / 2) - 2 + bx];
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -683,14 +698,14 @@ public sealed partial class H264Decoder
|
||||
var last = -1;
|
||||
for (var i = 0; i < maxNum - 1; i++)
|
||||
{
|
||||
var ctx = cat == 5 ? sig8x8[i] : cat == 3 ? Math.Min(i, 2) : i;
|
||||
var ctx = cat == 5 ? sig8x8[i] : cat == 3 ? Math.Min(i / numC8x8, 2) : i;
|
||||
if (cabac.Decision(sigBase + ctx) == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
significant[i] = true;
|
||||
var lastCtx = cat == 5 ? H264Tables.LastContext8x8[i] : cat == 3 ? Math.Min(i, 2) : i;
|
||||
var lastCtx = cat == 5 ? H264Tables.LastContext8x8[i] : cat == 3 ? Math.Min(i / numC8x8, 2) : i;
|
||||
if (cabac.Decision(lastBase + lastCtx) != 0)
|
||||
{
|
||||
last = i;
|
||||
@@ -808,13 +823,13 @@ public sealed partial class H264Decoder
|
||||
}
|
||||
else
|
||||
{
|
||||
n = left ? Locate(-1, by * 4, 8, out var yM) : Locate(bx * 4, -1, 8, out yM);
|
||||
n = left ? Locate(-1, by * 4, mbHeightC, out var yM) : Locate(bx * 4, -1, mbHeightC, out yM);
|
||||
if (n < 0)
|
||||
{
|
||||
return currentIntra ? 1 : 0;
|
||||
}
|
||||
|
||||
index = left ? ((((yM & 7) >> 2) * 2) + 1) : 2 + bx;
|
||||
index = left ? ((((yM & (mbHeightC - 1)) >> 2) * 2) + 1) : (mbHeightC / 2) - 2 + bx;
|
||||
}
|
||||
|
||||
if (mbKind[n] == MbKind.IPcm)
|
||||
@@ -822,7 +837,7 @@ public sealed partial class H264Decoder
|
||||
return 1;
|
||||
}
|
||||
|
||||
return nz[(n * 24) + 16 + (comp * 4) + index] != 0 ? 1 : 0;
|
||||
return nz[(n * NzPerMb) + 16 + (comp * 16) + index] != 0 ? 1 : 0;
|
||||
}
|
||||
|
||||
default:
|
||||
@@ -849,7 +864,7 @@ public sealed partial class H264Decoder
|
||||
return 1;
|
||||
}
|
||||
|
||||
return nz[(n * 24) + index] != 0 ? 1 : 0;
|
||||
return nz[(n * NzPerMb) + index] != 0 ? 1 : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -555,11 +555,28 @@ public sealed partial class H264Decoder
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inter prediction of one partition with its motion (§8.4.2), written into the current picture. A field macroblock
|
||||
/// predicts from fields: rows of one parity of a frame store, in field coordinates.
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Inter prediction of one partition with its motion (§8.4.2), written into the current picture. A field macroblock
|
||||
/// predicts from fields: rows of one parity of a frame store, in field coordinates.
|
||||
/// </summary>
|
||||
private void MotionCompensate(int px, int py, int w, int h)
|
||||
{
|
||||
if (wide)
|
||||
{
|
||||
MotionCompensate<ushort>(px, py, w, h);
|
||||
}
|
||||
else
|
||||
{
|
||||
MotionCompensate<byte>(px, py, w, h);
|
||||
}
|
||||
}
|
||||
|
||||
private void MotionCompensate<T>(int px, int py, int w, int h)
|
||||
where T : unmanaged
|
||||
{
|
||||
var picture = cur!;
|
||||
var b8 = ((py >> 3) * 2) + (px >> 3);
|
||||
@@ -571,8 +588,8 @@ public sealed partial class H264Decoder
|
||||
var x = (mbX * 16) + px;
|
||||
var y = ((mbField ? mbY >> 1 : mbY) * 16) + py;
|
||||
|
||||
Span<byte> a = stackalloc byte[256];
|
||||
Span<byte> b = stackalloc byte[256];
|
||||
Span<T> a = stackalloc T[256];
|
||||
Span<T> b = stackalloc T[256];
|
||||
var size = w * h;
|
||||
var pa = a[..size];
|
||||
var pb = b[..size];
|
||||
@@ -589,74 +606,98 @@ public sealed partial class H264Decoder
|
||||
int mv0x = picture.Mv[i0], mv0y = picture.Mv[i0 + 1], mv1x = picture.Mv[i1], mv1y = picture.Mv[i1 + 1];
|
||||
int width = picture.Width, height = picture.Height;
|
||||
|
||||
// Luma.
|
||||
if (use0)
|
||||
{
|
||||
var field = e0.Parity >= 0;
|
||||
InterPrediction.Luma(e0.Pic!.Y, field ? e0.Parity * width : 0, field ? 2 * width : width, width, field ? height / 2 : height, (x * 4) + mv0x, (y * 4) + mv0y, w, h, pa);
|
||||
}
|
||||
|
||||
if (use1)
|
||||
{
|
||||
var field = e1.Parity >= 0;
|
||||
InterPrediction.Luma(e1.Pic!.Y, field ? e1.Parity * width : 0, field ? 2 * width : width, width, field ? height / 2 : height, (x * 4) + mv1x, (y * 4) + mv1y, w, h, use0 ? pb : pa);
|
||||
}
|
||||
|
||||
Combine(pa, pb, use0, use1, r0, r1, 0);
|
||||
for (var row = 0; row < h; row++)
|
||||
{
|
||||
pa.Slice(row * w, w).CopyTo(picture.Y.AsSpan(lumaO + ((py + row) * lumaStride) + px, w));
|
||||
}
|
||||
|
||||
// Chroma; between fields of opposite parity the vertical vector moves by a quarter of a chroma row (Table 8-9).
|
||||
int cw = w / 2, ch = h / 2, cwidth = width / 2, cheight = height / 2;
|
||||
var csize = cw * ch;
|
||||
var ca = a[..csize];
|
||||
var cb = b[..csize];
|
||||
var parity = mbY & 1;
|
||||
var adjust0 = e0.Parity < 0 || e0.Parity == parity ? 0 : parity == 0 ? -2 : 2;
|
||||
var adjust1 = e1.Parity < 0 || e1.Parity == parity ? 0 : parity == 0 ? -2 : 2;
|
||||
for (var comp = 1; comp <= 2; comp++)
|
||||
// Luma, or the colour plane of the slice; in 4:4:4 Cb and Cr too, with the same interpolation (§8.4.2.2).
|
||||
for (var plane = 0; plane < LumaLikePlanes; plane++)
|
||||
{
|
||||
var source = plane == 0 ? colourPlane : plane;
|
||||
var max = plane == 0 ? maxY : maxC;
|
||||
if (use0)
|
||||
{
|
||||
var field = e0.Parity >= 0;
|
||||
InterPrediction.Chroma(comp == 1 ? e0.Pic!.Cb : e0.Pic!.Cr, field ? e0.Parity * cwidth : 0, field ? 2 * cwidth : cwidth, cwidth, field ? cheight / 2 : cheight, (x * 4) + mv0x, (y * 4) + mv0y + adjust0, cw, ch, ca);
|
||||
InterPrediction.Luma<T>(Samples.Plane<T>(e0.Pic!.Plane(source)), field ? e0.Parity * width : 0, field ? 2 * width : width, width, field ? height / 2 : height, (x * 4) + mv0x, (y * 4) + mv0y, w, h, pa, max);
|
||||
}
|
||||
|
||||
if (use1)
|
||||
{
|
||||
var field = e1.Parity >= 0;
|
||||
InterPrediction.Chroma(comp == 1 ? e1.Pic!.Cb : e1.Pic!.Cr, field ? e1.Parity * cwidth : 0, field ? 2 * cwidth : cwidth, cwidth, field ? cheight / 2 : cheight, (x * 4) + mv1x, (y * 4) + mv1y + adjust1, cw, ch, use0 ? cb : ca);
|
||||
InterPrediction.Luma<T>(Samples.Plane<T>(e1.Pic!.Plane(source)), field ? e1.Parity * width : 0, field ? 2 * width : width, width, field ? height / 2 : height, (x * 4) + mv1x, (y * 4) + mv1y, w, h, use0 ? pb : pa, max);
|
||||
}
|
||||
|
||||
Combine(ca, cb, use0, use1, r0, r1, comp);
|
||||
var plane = comp == 1 ? picture.Cb : picture.Cr;
|
||||
Combine(pa, pb, use0, use1, r0, r1, plane, plane == 0 ? bitDepthY : bitDepthC);
|
||||
var target = Samples.Plane<T>(picture.Plane(source));
|
||||
for (var row = 0; row < h; row++)
|
||||
{
|
||||
pa.Slice(row * w, w).CopyTo(target.Slice(lumaO + ((py + row) * lumaStride) + px, w));
|
||||
}
|
||||
}
|
||||
|
||||
if (numC8x8 == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Chroma of 4:2:0 and 4:2:2 in eighths of a chroma sample: 4:2:2 has full vertical resolution, so its vertical
|
||||
// vector is in eighths already doubled (§8.4.1.4, §8.4.2.2.2); between fields of opposite parity the vertical
|
||||
// vector of 4:2:0 moves by a quarter of a chroma row (Table 8-9).
|
||||
var full = chromaArrayType == 2;
|
||||
int cw = w / 2, ch = full ? h : h / 2, cwidth = picture.ChromaWidth, cheight = picture.ChromaHeight;
|
||||
var csize = cw * ch;
|
||||
var ca = a[..csize];
|
||||
var cb = b[..csize];
|
||||
var parity = mbY & 1;
|
||||
var adjust0 = full || e0.Parity < 0 || e0.Parity == parity ? 0 : parity == 0 ? -2 : 2;
|
||||
var adjust1 = full || e1.Parity < 0 || e1.Parity == parity ? 0 : parity == 0 ? -2 : 2;
|
||||
var ey0 = full ? ((y * 4) + mv0y) * 2 : (y * 4) + mv0y + adjust0;
|
||||
var ey1 = full ? ((y * 4) + mv1y) * 2 : (y * 4) + mv1y + adjust1;
|
||||
var cy = full ? py : py / 2;
|
||||
for (var comp = 1; comp <= 2; comp++)
|
||||
{
|
||||
if (use0)
|
||||
{
|
||||
var field = e0.Parity >= 0;
|
||||
InterPrediction.Chroma<T>(Samples.Plane<T>(comp == 1 ? e0.Pic!.Cb : e0.Pic!.Cr), field ? e0.Parity * cwidth : 0, field ? 2 * cwidth : cwidth, cwidth, field ? cheight / 2 : cheight, (x * 4) + mv0x, ey0, cw, ch, ca);
|
||||
}
|
||||
|
||||
if (use1)
|
||||
{
|
||||
var field = e1.Parity >= 0;
|
||||
InterPrediction.Chroma<T>(Samples.Plane<T>(comp == 1 ? e1.Pic!.Cb : e1.Pic!.Cr), field ? e1.Parity * cwidth : 0, field ? 2 * cwidth : cwidth, cwidth, field ? cheight / 2 : cheight, (x * 4) + mv1x, ey1, cw, ch, use0 ? cb : ca);
|
||||
}
|
||||
|
||||
Combine(ca, cb, use0, use1, r0, r1, comp, bitDepthC);
|
||||
var plane = Samples.Plane<T>(comp == 1 ? picture.Cb : picture.Cr);
|
||||
for (var row = 0; row < ch; row++)
|
||||
{
|
||||
ca.Slice(row * cw, cw).CopyTo(plane.AsSpan(chromaO + (((py / 2) + row) * chromaStride) + (px / 2), cw));
|
||||
ca.Slice(row * cw, cw).CopyTo(plane.Slice(chromaO + ((cy + row) * chromaStride) + (px / 2), cw));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Combine(Span<byte> a, ReadOnlySpan<byte> b, bool use0, bool use1, int r0, int r1, int comp)
|
||||
/// <summary>
|
||||
/// The weighted sample prediction (§8.4.2.3) of component <paramref name="comp"/> (0 luma, 1 Cb, 2 Cr): the offsets
|
||||
/// are in units of 8-bit samples, scaled to <paramref name="bitDepth"/>.
|
||||
/// </summary>
|
||||
private void Combine<T>(Span<T> a, ReadOnlySpan<T> b, bool use0, bool use1, int r0, int r1, int comp, int bitDepth)
|
||||
where T : unmanaged
|
||||
{
|
||||
// Explicit weights are by frame for the field macroblocks of an MBAFF frame (refIdxWP = refIdx >> 1).
|
||||
var fieldMb = mbaff && mbField;
|
||||
int w0Index = fieldMb ? r0 >> 1 : r0, w1Index = fieldMb ? r1 >> 1 : r1;
|
||||
var shift = bitDepth - 8;
|
||||
var max = (1 << bitDepth) - 1;
|
||||
if (use0 && use1)
|
||||
{
|
||||
if (weightMode == 1 && sh.Weights is { } weights && sh.Offsets is { } offsets)
|
||||
{
|
||||
var logWd = comp == 0 ? sh.LumaLog2WeightDenom : sh.ChromaLog2WeightDenom;
|
||||
InterPrediction.WeightTwo(a, b, logWd, weights[0][(w0Index * 3) + comp], weights[1][(w1Index * 3) + comp], offsets[0][(w0Index * 3) + comp], offsets[1][(w1Index * 3) + comp]);
|
||||
InterPrediction.WeightTwo(a, b, logWd, weights[0][(w0Index * 3) + comp], weights[1][(w1Index * 3) + comp], offsets[0][(w0Index * 3) + comp] << shift, offsets[1][(w1Index * 3) + comp] << shift, max);
|
||||
}
|
||||
else if (weightMode == 2)
|
||||
{
|
||||
var w0 = fieldMb
|
||||
? implicitField[mbY & 1][(r0 * 2 * sh.NumRefIdxActiveL1) + r1]
|
||||
: implicitW0[(r0 * sh.NumRefIdxActiveL1) + r1];
|
||||
InterPrediction.WeightTwo(a, b, 5, w0, 64 - w0, 0, 0);
|
||||
InterPrediction.WeightTwo(a, b, 5, w0, 64 - w0, 0, 0, max);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -671,7 +712,7 @@ public sealed partial class H264Decoder
|
||||
var list = use0 ? 0 : 1;
|
||||
var r = use0 ? w0Index : w1Index;
|
||||
var logWd = comp == 0 ? sh.LumaLog2WeightDenom : sh.ChromaLog2WeightDenom;
|
||||
InterPrediction.WeightOne(a, logWd, w[list][(r * 3) + comp], o[list][(r * 3) + comp]);
|
||||
InterPrediction.WeightOne(a, logWd, w[list][(r * 3) + comp], o[list][(r * 3) + comp] << shift, max);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
|
||||
@@ -39,6 +39,12 @@ internal static class H264Tables
|
||||
17, 18, 20, 24, 19, 21, 26, 28, 23, 27, 29, 30, 22, 25, 38, 41,
|
||||
];
|
||||
|
||||
/// <summary>coded_block_pattern of Intra_4x4 and Intra_8x8 macroblocks from codeNum without chroma syntax (table 9-4, ChromaArrayType 0 and 3).</summary>
|
||||
internal static readonly byte[] CbpIntraNoChroma = [15, 0, 7, 11, 13, 14, 3, 5, 10, 12, 1, 2, 4, 8, 6, 9];
|
||||
|
||||
/// <summary>coded_block_pattern of inter macroblocks from codeNum without chroma syntax (table 9-4, ChromaArrayType 0 and 3).</summary>
|
||||
internal static readonly byte[] CbpInterNoChroma = [0, 1, 2, 4, 8, 3, 5, 10, 12, 15, 7, 11, 13, 14, 6, 9];
|
||||
|
||||
/// <summary>normAdjust4x4 values v[m][0..2] (equation 8-315).</summary>
|
||||
internal static readonly byte[,] NormAdjust4x4 =
|
||||
{
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
using static Febe.Core.Codecs.H264.Samples;
|
||||
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>Fractional sample interpolation (§8.4.2.2) and weighted sample prediction (§8.4.2.3).</summary>
|
||||
/// <summary>
|
||||
/// Fractional sample interpolation (§8.4.2.2) and weighted sample prediction (§8.4.2.3), at any bit depth (<c>max</c> is
|
||||
/// 2^BitDepth − 1). The luma interpolation serves also the Cb and Cr planes of 4:4:4.
|
||||
/// </summary>
|
||||
internal static class InterPrediction
|
||||
{
|
||||
/// <summary>
|
||||
@@ -9,7 +14,8 @@ internal static class InterPrediction
|
||||
/// picture whose row y starts at <paramref name="origin"/> + y × <paramref name="stride"/> (a frame, or one field of a
|
||||
/// frame store). Samples outside the picture repeat the edge.
|
||||
/// </summary>
|
||||
internal static void Luma(byte[] plane, int origin, int stride, int pw, int ph, int qx, int qy, int w, int h, Span<byte> dst)
|
||||
internal static void Luma<T>(ReadOnlySpan<T> plane, int origin, int stride, int pw, int ph, int qx, int qy, int w, int h, Span<T> dst, int max)
|
||||
where T : unmanaged
|
||||
{
|
||||
int xInt = qx >> 2, yInt = qy >> 2, xFrac = qx & 3, yFrac = qy & 3;
|
||||
|
||||
@@ -27,15 +33,23 @@ internal static class InterPrediction
|
||||
}
|
||||
|
||||
var rowBase = origin + (sy * stride);
|
||||
var target = win.Slice(r * ww, ww);
|
||||
if (inside)
|
||||
{
|
||||
var source = plane.Slice(rowBase + xInt - 2, ww);
|
||||
for (var c = 0; c < ww; c++)
|
||||
{
|
||||
target[c] = Get(source[c]);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
for (var c = 0; c < ww; c++)
|
||||
{
|
||||
var sx = xInt - 2 + c;
|
||||
if (!inside)
|
||||
{
|
||||
sx = sx < 0 ? 0 : sx >= pw ? pw - 1 : sx;
|
||||
}
|
||||
|
||||
win[(r * ww) + c] = plane[rowBase + sx];
|
||||
sx = sx < 0 ? 0 : sx >= pw ? pw - 1 : sx;
|
||||
target[c] = Get(plane[rowBase + sx]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +59,7 @@ internal static class InterPrediction
|
||||
{
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
dst[(y * w) + x] = (byte)win[((y + 2) * ww) + x + 2];
|
||||
dst[(y * w) + x] = Make<T>(win[((y + 2) * ww) + x + 2]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,7 +79,7 @@ internal static class InterPrediction
|
||||
{
|
||||
var b = ((y + 2) * ww) + x;
|
||||
var v = win[b] - (5 * win[b + 1]) + (20 * win[b + 2]) + (20 * win[b + 3]) - (5 * win[b + 4]) + win[b + 5];
|
||||
bh[(y * w) + x] = Clip((v + 16) >> 5);
|
||||
bh[(y * w) + x] = Clip((v + 16) >> 5, max);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -78,7 +92,7 @@ internal static class InterPrediction
|
||||
{
|
||||
var b = (y * ww) + x + 2;
|
||||
var v = win[b] - (5 * win[b + ww]) + (20 * win[b + (2 * ww)]) + (20 * win[b + (3 * ww)]) - (5 * win[b + (4 * ww)]) + win[b + (5 * ww)];
|
||||
vh[(y * (w + 1)) + x] = Clip((v + 16) >> 5);
|
||||
vh[(y * (w + 1)) + x] = Clip((v + 16) >> 5, max);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -103,7 +117,7 @@ internal static class InterPrediction
|
||||
{
|
||||
var b = (y * w) + x;
|
||||
var v = b1[b] - (5 * b1[b + w]) + (20 * b1[b + (2 * w)]) + (20 * b1[b + (3 * w)]) - (5 * b1[b + (4 * w)]) + b1[b + (5 * w)];
|
||||
jc[b] = Clip((v + 512) >> 10);
|
||||
jc[b] = Clip((v + 512) >> 10, max);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -163,16 +177,17 @@ internal static class InterPrediction
|
||||
break;
|
||||
}
|
||||
|
||||
dst[(y * w) + x] = (byte)value;
|
||||
dst[(y * w) + x] = Make<T>(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Chroma prediction (4:2:0) of a <paramref name="w"/> × <paramref name="h"/> block whose corner, in eighths of a
|
||||
/// chroma sample, is (<paramref name="ex"/>, <paramref name="ey"/>), from a plane view as for <see cref="Luma"/>.
|
||||
/// Chroma prediction (4:2:0 and 4:2:2) of a <paramref name="w"/> × <paramref name="h"/> block whose corner, in eighths
|
||||
/// of a chroma sample, is (<paramref name="ex"/>, <paramref name="ey"/>), from a plane view as for <see cref="Luma"/>.
|
||||
/// </summary>
|
||||
internal static void Chroma(byte[] plane, int origin, int stride, int pw, int ph, int ex, int ey, int w, int h, Span<byte> dst)
|
||||
internal static void Chroma<T>(ReadOnlySpan<T> plane, int origin, int stride, int pw, int ph, int ex, int ey, int w, int h, Span<T> dst)
|
||||
where T : unmanaged
|
||||
{
|
||||
int xInt = ex >> 3, yInt = ey >> 3, xFrac = ex & 7, yFrac = ey & 7;
|
||||
int wA = (8 - xFrac) * (8 - yFrac), wB = xFrac * (8 - yFrac), wC = (8 - xFrac) * yFrac, wD = xFrac * yFrac;
|
||||
@@ -184,40 +199,42 @@ internal static class InterPrediction
|
||||
{
|
||||
var x0 = Math.Clamp(xInt + x, 0, pw - 1);
|
||||
var x1 = Math.Clamp(xInt + x + 1, 0, pw - 1);
|
||||
dst[(y * w) + x] = (byte)(((wA * plane[y0 + x0]) + (wB * plane[y0 + x1]) + (wC * plane[y1 + x0]) + (wD * plane[y1 + x1]) + 32) >> 6);
|
||||
dst[(y * w) + x] = Make<T>(((wA * Get(plane[y0 + x0])) + (wB * Get(plane[y0 + x1])) + (wC * Get(plane[y1 + x0])) + (wD * Get(plane[y1 + x1])) + 32) >> 6);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Default bi-prediction average (equation 8-273), into <paramref name="a"/>.</summary>
|
||||
internal static void Average(Span<byte> a, ReadOnlySpan<byte> b)
|
||||
internal static void Average<T>(Span<T> a, ReadOnlySpan<T> b)
|
||||
where T : unmanaged
|
||||
{
|
||||
for (var i = 0; i < a.Length; i++)
|
||||
{
|
||||
a[i] = (byte)((a[i] + b[i] + 1) >> 1);
|
||||
a[i] = Make<T>((Get(a[i]) + Get(b[i]) + 1) >> 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Weighted prediction from one list (equation 8-270).</summary>
|
||||
internal static void WeightOne(Span<byte> a, int logWd, int weight, int offset)
|
||||
/// <summary>Weighted prediction from one list (equation 8-270); <paramref name="offset"/> is already scaled to the bit depth.</summary>
|
||||
internal static void WeightOne<T>(Span<T> a, int logWd, int weight, int offset, int max)
|
||||
where T : unmanaged
|
||||
{
|
||||
for (var i = 0; i < a.Length; i++)
|
||||
{
|
||||
var v = logWd >= 1 ? ((a[i] * weight) + (1 << (logWd - 1))) >> logWd : a[i] * weight;
|
||||
a[i] = (byte)Clip(v + offset);
|
||||
var s = Get(a[i]);
|
||||
var v = logWd >= 1 ? ((s * weight) + (1 << (logWd - 1))) >> logWd : s * weight;
|
||||
a[i] = Make<T>(Clip(v + offset, max));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Weighted bi-prediction (equation 8-272), into <paramref name="a"/>.</summary>
|
||||
internal static void WeightTwo(Span<byte> a, ReadOnlySpan<byte> b, int logWd, int w0, int w1, int o0, int o1)
|
||||
/// <summary>Weighted bi-prediction (equation 8-272), into <paramref name="a"/>; the offsets are already scaled to the bit depth.</summary>
|
||||
internal static void WeightTwo<T>(Span<T> a, ReadOnlySpan<T> b, int logWd, int w0, int w1, int o0, int o1, int max)
|
||||
where T : unmanaged
|
||||
{
|
||||
var offset = (o0 + o1 + 1) >> 1;
|
||||
for (var i = 0; i < a.Length; i++)
|
||||
{
|
||||
var v = (((a[i] * w0) + (b[i] * w1) + (1 << logWd)) >> (logWd + 1)) + offset;
|
||||
a[i] = (byte)Clip(v);
|
||||
var v = (((Get(a[i]) * w0) + (Get(b[i]) * w1) + (1 << logWd)) >> (logWd + 1)) + offset;
|
||||
a[i] = Make<T>(Clip(v, max));
|
||||
}
|
||||
}
|
||||
|
||||
private static int Clip(int v) => v < 0 ? 0 : v > 255 ? 255 : v;
|
||||
}
|
||||
@@ -1,25 +1,33 @@
|
||||
using static Febe.Core.Codecs.H264.Samples;
|
||||
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>Intra prediction of luma 4×4, 8×8 and 16×16 blocks and of 4:2:0 chroma (§8.3), written into the plane.</summary>
|
||||
/// <summary>
|
||||
/// Intra prediction (§8.3) written into the plane: luma 4×4, 8×8 and 16×16 blocks (also the Cb and Cr planes of 4:4:4,
|
||||
/// predicted like luma, and the colour planes coded separately) and the chroma of 4:2:0 and 4:2:2, at any bit depth: a
|
||||
/// missing neighbour counts as 1 << (BitDepth − 1).
|
||||
/// </summary>
|
||||
internal static class IntraPrediction
|
||||
{
|
||||
/// <summary>Intra_4x4 (§8.3.1.2) of the block at <paramref name="o"/>.</summary>
|
||||
internal static void Predict4x4(byte[] p, int o, int stride, int mode, bool left, bool top, bool topRight, bool topLeft)
|
||||
internal static void Predict4x4<T>(Span<T> p, int o, int stride, int mode, bool left, bool top, bool topRight, bool topLeft, int bitDepth)
|
||||
where T : unmanaged
|
||||
{
|
||||
var mid = 1 << (bitDepth - 1);
|
||||
Span<int> t = stackalloc int[8];
|
||||
Span<int> l = stackalloc int[4];
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
t[i] = top ? p[o - stride + i] : 128;
|
||||
l[i] = left ? p[o + (i * stride) - 1] : 128;
|
||||
t[i] = top ? Get(p[o - stride + i]) : mid;
|
||||
l[i] = left ? Get(p[o + (i * stride) - 1]) : mid;
|
||||
}
|
||||
|
||||
for (var i = 4; i < 8; i++)
|
||||
{
|
||||
t[i] = topRight ? p[o - stride + i] : t[3];
|
||||
t[i] = topRight ? Get(p[o - stride + i]) : t[3];
|
||||
}
|
||||
|
||||
var tl = topLeft ? p[o - stride - 1] : 128;
|
||||
var tl = topLeft ? Get(p[o - stride - 1]) : mid;
|
||||
switch (mode)
|
||||
{
|
||||
case 0: // Vertical
|
||||
@@ -27,7 +35,7 @@ internal static class IntraPrediction
|
||||
{
|
||||
for (var x = 0; x < 4; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)t[x];
|
||||
p[o + (y * stride) + x] = Make<T>(t[x]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,10 +43,7 @@ internal static class IntraPrediction
|
||||
case 1: // Horizontal
|
||||
for (var y = 0; y < 4; y++)
|
||||
{
|
||||
for (var x = 0; x < 4; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)l[y];
|
||||
}
|
||||
p.Slice(o + (y * stride), 4).Fill(Make<T>(l[y]));
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -59,7 +64,7 @@ internal static class IntraPrediction
|
||||
}
|
||||
else
|
||||
{
|
||||
dc = 128;
|
||||
dc = mid;
|
||||
}
|
||||
|
||||
Fill(p, o, stride, 4, 4, dc);
|
||||
@@ -71,7 +76,7 @@ internal static class IntraPrediction
|
||||
{
|
||||
for (var x = 0; x < 4; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)(x == 3 && y == 3
|
||||
p[o + (y * stride) + x] = Make<T>(x == 3 && y == 3
|
||||
? (t[6] + (3 * t[7]) + 2) >> 2
|
||||
: (t[x + y] + (2 * t[x + y + 1]) + t[x + y + 2] + 2) >> 2);
|
||||
}
|
||||
@@ -98,7 +103,7 @@ internal static class IntraPrediction
|
||||
{
|
||||
for (var x = 0; x < 4; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)Directional(e, 4, mode, x, y, 4);
|
||||
p[o + (y * stride) + x] = Make<T>(Directional(e, 4, mode, x, y, 4));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,22 +212,24 @@ internal static class IntraPrediction
|
||||
private static int L(ReadOnlySpan<int> e, int c, int i) => e[c - 1 - i];
|
||||
|
||||
/// <summary>Intra_8x8 with the reference sample filtering of §8.3.2.2.1.</summary>
|
||||
internal static void Predict8x8(byte[] p, int o, int stride, int mode, bool left, bool top, bool topRight, bool topLeft)
|
||||
internal static void Predict8x8<T>(Span<T> p, int o, int stride, int mode, bool left, bool top, bool topRight, bool topLeft, int bitDepth)
|
||||
where T : unmanaged
|
||||
{
|
||||
var mid = 1 << (bitDepth - 1);
|
||||
Span<int> t = stackalloc int[16];
|
||||
Span<int> l = stackalloc int[8];
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
t[i] = top ? p[o - stride + i] : 128;
|
||||
l[i] = left ? p[o + (i * stride) - 1] : 128;
|
||||
t[i] = top ? Get(p[o - stride + i]) : mid;
|
||||
l[i] = left ? Get(p[o + (i * stride) - 1]) : mid;
|
||||
}
|
||||
|
||||
for (var i = 8; i < 16; i++)
|
||||
{
|
||||
t[i] = topRight ? p[o - stride + i] : t[7];
|
||||
t[i] = topRight ? Get(p[o - stride + i]) : t[7];
|
||||
}
|
||||
|
||||
var tl = topLeft ? p[o - stride - 1] : 128;
|
||||
var tl = topLeft ? Get(p[o - stride - 1]) : mid;
|
||||
|
||||
// Filtered references p′.
|
||||
Span<int> ft = stackalloc int[16];
|
||||
@@ -273,7 +280,7 @@ internal static class IntraPrediction
|
||||
{
|
||||
for (var x = 0; x < 8; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)ft[x];
|
||||
p[o + (y * stride) + x] = Make<T>(ft[x]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,10 +288,7 @@ internal static class IntraPrediction
|
||||
case 1:
|
||||
for (var y = 0; y < 8; y++)
|
||||
{
|
||||
for (var x = 0; x < 8; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)fl[y];
|
||||
}
|
||||
p.Slice(o + (y * stride), 8).Fill(Make<T>(fl[y]));
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -297,7 +301,7 @@ internal static class IntraPrediction
|
||||
sumL += fl[i];
|
||||
}
|
||||
|
||||
var dc = top && left ? (sumT + sumL + 8) >> 4 : left ? (sumL + 4) >> 3 : top ? (sumT + 4) >> 3 : 128;
|
||||
var dc = top && left ? (sumT + sumL + 8) >> 4 : left ? (sumL + 4) >> 3 : top ? (sumT + 4) >> 3 : mid;
|
||||
Fill(p, o, stride, 8, 8, dc);
|
||||
break;
|
||||
}
|
||||
@@ -307,7 +311,7 @@ internal static class IntraPrediction
|
||||
{
|
||||
for (var x = 0; x < 8; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)(x == 7 && y == 7
|
||||
p[o + (y * stride) + x] = Make<T>(x == 7 && y == 7
|
||||
? (ft[14] + (3 * ft[15]) + 2) >> 2
|
||||
: (ft[x + y] + (2 * ft[x + y + 1]) + ft[x + y + 2] + 2) >> 2);
|
||||
}
|
||||
@@ -332,7 +336,7 @@ internal static class IntraPrediction
|
||||
{
|
||||
for (var x = 0; x < 8; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)Directional(e, 8, mode, x, y, 8);
|
||||
p[o + (y * stride) + x] = Make<T>(Directional(e, 8, mode, x, y, 8));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,22 +346,22 @@ internal static class IntraPrediction
|
||||
}
|
||||
|
||||
/// <summary>Intra_16x16 (§8.3.3).</summary>
|
||||
internal static void Predict16x16(byte[] p, int o, int stride, int mode, bool left, bool top, bool topLeft)
|
||||
internal static void Predict16x16<T>(Span<T> p, int o, int stride, int mode, bool left, bool top, bool topLeft, int bitDepth)
|
||||
where T : unmanaged
|
||||
{
|
||||
switch (mode)
|
||||
{
|
||||
case 0:
|
||||
for (var y = 0; y < 16; y++)
|
||||
{
|
||||
Array.Copy(p, o - stride, p, o + (y * stride), 16);
|
||||
p.Slice(o - stride, 16).CopyTo(p.Slice(o + (y * stride), 16));
|
||||
}
|
||||
|
||||
break;
|
||||
case 1:
|
||||
for (var y = 0; y < 16; y++)
|
||||
{
|
||||
var v = p[o + (y * stride) - 1];
|
||||
p.AsSpan(o + (y * stride), 16).Fill(v);
|
||||
p.Slice(o + (y * stride), 16).Fill(p[o + (y * stride) - 1]);
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -368,68 +372,73 @@ internal static class IntraPrediction
|
||||
{
|
||||
if (top)
|
||||
{
|
||||
sumT += p[o - stride + i];
|
||||
sumT += Get(p[o - stride + i]);
|
||||
}
|
||||
|
||||
if (left)
|
||||
{
|
||||
sumL += p[o + (i * stride) - 1];
|
||||
sumL += Get(p[o + (i * stride) - 1]);
|
||||
}
|
||||
}
|
||||
|
||||
var dc = top && left ? (sumT + sumL + 16) >> 5 : left ? (sumL + 8) >> 4 : top ? (sumT + 8) >> 4 : 128;
|
||||
var dc = top && left ? (sumT + sumL + 16) >> 5 : left ? (sumL + 8) >> 4 : top ? (sumT + 8) >> 4 : 1 << (bitDepth - 1);
|
||||
Fill(p, o, stride, 16, 16, dc);
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
Plane(p, o, stride, 16, 16, topLeft);
|
||||
Plane(p, o, stride, 16, 16, topLeft, (1 << bitDepth) - 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Chroma prediction of one 8×8 4:2:0 component (§8.3.4): 0 DC, 1 horizontal, 2 vertical, 3 plane. The left
|
||||
/// samples of the upper and of the lower four rows may differ in availability (an MBAFF frame with constrained intra
|
||||
/// prediction, where they come from two macroblocks): the DC prediction of each 4×4 block uses its own.
|
||||
/// Chroma prediction of one component of 4:2:0 (8×8) or 4:2:2 (8×16) (§8.3.4): 0 DC, 1 horizontal, 2 vertical, 3
|
||||
/// plane. Bit g of <paramref name="leftRows"/> says whether the left samples of rows 4g to 4g + 3 are available: they
|
||||
/// may differ (an MBAFF frame with constrained intra prediction, where they come from two macroblocks), and the DC
|
||||
/// prediction of each 4×4 block uses its own.
|
||||
/// </summary>
|
||||
internal static void PredictChroma(byte[] p, int o, int stride, int mode, bool leftUpper, bool leftLower, bool top, bool topLeft)
|
||||
internal static void PredictChroma<T>(Span<T> p, int o, int stride, int mode, int height, int leftRows, bool top, bool topLeft, int bitDepth)
|
||||
where T : unmanaged
|
||||
{
|
||||
var mid = 1 << (bitDepth - 1);
|
||||
switch (mode)
|
||||
{
|
||||
case 0:
|
||||
for (var by = 0; by < 2; by++)
|
||||
for (var by = 0; by < height / 4; by++)
|
||||
{
|
||||
var left = ((leftRows >> by) & 1) != 0;
|
||||
for (var bx = 0; bx < 2; bx++)
|
||||
{
|
||||
var b = o + (by * 4 * stride) + (bx * 4);
|
||||
var left = by == 0 ? leftUpper : leftLower;
|
||||
int sumT = 0, sumL = 0;
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
if (top)
|
||||
{
|
||||
sumT += p[o - stride + (bx * 4) + i];
|
||||
sumT += Get(p[o - stride + (bx * 4) + i]);
|
||||
}
|
||||
|
||||
if (left)
|
||||
{
|
||||
sumL += p[o + (((by * 4) + i) * stride) - 1];
|
||||
sumL += Get(p[o + (((by * 4) + i) * stride) - 1]);
|
||||
}
|
||||
}
|
||||
|
||||
// §8.3.4.1–8.3.4.3: the blocks at (0, 0) and those off the first row and column use both edges,
|
||||
// the others of the first row prefer the top one, those of the first column the left one.
|
||||
int dc;
|
||||
if ((bx == 0 && by == 0) || (bx == 1 && by == 1))
|
||||
if ((bx == 0 && by == 0) || (bx > 0 && by > 0))
|
||||
{
|
||||
dc = top && left ? (sumT + sumL + 4) >> 3 : left ? (sumL + 2) >> 2 : top ? (sumT + 2) >> 2 : 128;
|
||||
dc = top && left ? (sumT + sumL + 4) >> 3 : left ? (sumL + 2) >> 2 : top ? (sumT + 2) >> 2 : mid;
|
||||
}
|
||||
else if (bx == 1)
|
||||
else if (bx > 0)
|
||||
{
|
||||
dc = top ? (sumT + 2) >> 2 : left ? (sumL + 2) >> 2 : 128;
|
||||
dc = top ? (sumT + 2) >> 2 : left ? (sumL + 2) >> 2 : mid;
|
||||
}
|
||||
else
|
||||
{
|
||||
dc = left ? (sumL + 2) >> 2 : top ? (sumT + 2) >> 2 : 128;
|
||||
dc = left ? (sumL + 2) >> 2 : top ? (sumT + 2) >> 2 : mid;
|
||||
}
|
||||
|
||||
Fill(p, b, stride, 4, 4, dc);
|
||||
@@ -438,28 +447,31 @@ internal static class IntraPrediction
|
||||
|
||||
break;
|
||||
case 1:
|
||||
for (var y = 0; y < 8; y++)
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var v = p[o + (y * stride) - 1];
|
||||
p.AsSpan(o + (y * stride), 8).Fill(v);
|
||||
p.Slice(o + (y * stride), 8).Fill(p[o + (y * stride) - 1]);
|
||||
}
|
||||
|
||||
break;
|
||||
case 2:
|
||||
for (var y = 0; y < 8; y++)
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
Array.Copy(p, o - stride, p, o + (y * stride), 8);
|
||||
p.Slice(o - stride, 8).CopyTo(p.Slice(o + (y * stride), 8));
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
Plane(p, o, stride, 8, 8, topLeft);
|
||||
Plane(p, o, stride, 8, height, topLeft, (1 << bitDepth) - 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Plane prediction of a 16×16 luma or 8×8 chroma block.</summary>
|
||||
private static void Plane(byte[] p, int o, int stride, int w, int h, bool topLeft)
|
||||
/// <summary>
|
||||
/// Plane prediction of a 16×16 luma block or of an 8×8 or 8×16 chroma one (equations 8-125 to 8-131 and 8-138 to
|
||||
/// 8-145): the gradient of a 16-sample side is weighed by 5, of an 8-sample side by 34.
|
||||
/// </summary>
|
||||
private static void Plane<T>(Span<T> p, int o, int stride, int w, int h, bool topLeft, int max)
|
||||
where T : unmanaged
|
||||
{
|
||||
_ = topLeft; // the plane mode is only used when all three neighbours are available
|
||||
var hw = w / 2;
|
||||
@@ -467,48 +479,41 @@ internal static class IntraPrediction
|
||||
int sumH = 0, sumV = 0;
|
||||
for (var i = 0; i < hw; i++)
|
||||
{
|
||||
var right = p[o - stride + hw + i];
|
||||
var right = Get(p[o - stride + hw + i]);
|
||||
var leftIndex = hw - 2 - i;
|
||||
var leftSample = leftIndex >= 0 ? p[o - stride + leftIndex] : p[o - stride - 1];
|
||||
var leftSample = Get(leftIndex >= 0 ? p[o - stride + leftIndex] : p[o - stride - 1]);
|
||||
sumH += (i + 1) * (right - leftSample);
|
||||
}
|
||||
|
||||
for (var i = 0; i < hh; i++)
|
||||
{
|
||||
var below = p[o + ((hh + i) * stride) - 1];
|
||||
var below = Get(p[o + ((hh + i) * stride) - 1]);
|
||||
var aboveIndex = hh - 2 - i;
|
||||
var aboveSample = aboveIndex >= 0 ? p[o + (aboveIndex * stride) - 1] : p[o - stride - 1];
|
||||
var aboveSample = Get(aboveIndex >= 0 ? p[o + (aboveIndex * stride) - 1] : p[o - stride - 1]);
|
||||
sumV += (i + 1) * (below - aboveSample);
|
||||
}
|
||||
|
||||
var a = 16 * (p[o + ((h - 1) * stride) - 1] + p[o - stride + w - 1]);
|
||||
int b, c;
|
||||
if (w == 16)
|
||||
{
|
||||
b = ((5 * sumH) + 32) >> 6;
|
||||
c = ((5 * sumV) + 32) >> 6;
|
||||
}
|
||||
else
|
||||
{
|
||||
b = ((34 * sumH) + 32) >> 6;
|
||||
c = ((34 * sumV) + 32) >> 6;
|
||||
}
|
||||
|
||||
var a = 16 * (Get(p[o + ((h - 1) * stride) - 1]) + Get(p[o - stride + w - 1]));
|
||||
var b = (((w == 16 ? 5 : 34) * sumH) + 32) >> 6;
|
||||
var c = (((h == 16 ? 5 : 34) * sumV) + 32) >> 6;
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
for (var x = 0; x < w; x++)
|
||||
var row = p.Slice(o + (y * stride), w);
|
||||
var v = a + (c * (y - (hh - 1))) - (b * (hw - 1)) + 16;
|
||||
for (var x = 0; x < w; x++, v += b)
|
||||
{
|
||||
var v = (a + (b * (x - (hw - 1))) + (c * (y - (hh - 1))) + 16) >> 5;
|
||||
p[o + (y * stride) + x] = (byte)Math.Clamp(v, 0, 255);
|
||||
row[x] = Make<T>(Clip(v >> 5, max));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void Fill(byte[] p, int o, int stride, int w, int h, int value)
|
||||
private static void Fill<T>(Span<T> p, int o, int stride, int w, int h, int value)
|
||||
where T : unmanaged
|
||||
{
|
||||
var sample = Make<T>(value);
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
p.AsSpan(o + (y * stride), w).Fill((byte)value);
|
||||
p.Slice(o + (y * stride), w).Fill(sample);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,10 +13,31 @@ internal sealed class Sps
|
||||
internal int LevelIdc;
|
||||
internal int Id;
|
||||
internal int ChromaFormatIdc = 1;
|
||||
|
||||
/// <summary>separate_colour_plane_flag: the three colour planes of 4:4:4 are coded as three monochrome pictures.</summary>
|
||||
internal bool SeparateColourPlane;
|
||||
|
||||
internal int BitDepthLuma = 8;
|
||||
internal int BitDepthChroma = 8;
|
||||
|
||||
/// <summary>qpprime_y_zero_transform_bypass_flag: macroblocks with QP′Y 0 are lossless (§8.5.15).</summary>
|
||||
internal bool TransformBypass;
|
||||
|
||||
/// <summary>ChromaArrayType (§7.4.2.1.1): chroma_format_idc, or 0 when the colour planes are separate.</summary>
|
||||
internal int ChromaArrayType => SeparateColourPlane ? 0 : ChromaFormatIdc;
|
||||
|
||||
/// <summary>SubWidthC (Table 6-1): 2 for 4:2:0 and 4:2:2, 1 for 4:4:4.</summary>
|
||||
internal int SubWidthC => ChromaFormatIdc == 3 ? 1 : 2;
|
||||
|
||||
/// <summary>SubHeightC (Table 6-1): 2 for 4:2:0, 1 for 4:2:2 and 4:4:4.</summary>
|
||||
internal int SubHeightC => ChromaFormatIdc == 1 ? 2 : 1;
|
||||
|
||||
/// <summary>QpBdOffsetY = 6 × bit_depth_luma_minus8.</summary>
|
||||
internal int QpBdOffsetY => 6 * (BitDepthLuma - 8);
|
||||
|
||||
/// <summary>QpBdOffsetC = 6 × bit_depth_chroma_minus8.</summary>
|
||||
internal int QpBdOffsetC => 6 * (BitDepthChroma - 8);
|
||||
|
||||
/// <summary>Scaling lists 0–5 (4×4) and 6–11 (8×8) in zig-zag order, after the fall-back rule A.</summary>
|
||||
internal byte[][] ScalingLists = ScalingMatrix.Flat();
|
||||
|
||||
@@ -46,6 +67,12 @@ internal sealed class Sps
|
||||
|
||||
internal int MaxFrameNum => 1 << Log2MaxFrameNum;
|
||||
|
||||
/// <summary>CropUnitX of §7.4.2.1.1: 1 without chroma (or in 4:4:4), else SubWidthC.</summary>
|
||||
internal int CropUnitX => ChromaArrayType == 0 ? 1 : SubWidthC;
|
||||
|
||||
/// <summary>CropUnitY of §7.4.2.1.1, doubled when the frames may be coded as fields.</summary>
|
||||
internal int CropUnitY => (ChromaArrayType == 0 ? 1 : SubHeightC) * (FrameMbsOnly ? 1 : 2);
|
||||
|
||||
internal int HeightInMbs => (2 - (FrameMbsOnly ? 1 : 0)) * HeightInMapUnits;
|
||||
|
||||
internal static Sps Parse(RbspReader r)
|
||||
@@ -59,7 +86,7 @@ internal sealed class Sps
|
||||
s.ChromaFormatIdc = r.ReadUe(3);
|
||||
if (s.ChromaFormatIdc == 3)
|
||||
{
|
||||
r.Skip(1); // separate_colour_plane_flag
|
||||
s.SeparateColourPlane = r.ReadFlag();
|
||||
}
|
||||
|
||||
s.BitDepthLuma = r.ReadUe(6) + 8;
|
||||
@@ -123,9 +150,8 @@ internal sealed class Sps
|
||||
s.CropTop = r.ReadUe(8192);
|
||||
s.CropBottom = r.ReadUe(8192);
|
||||
|
||||
// §7.4.2.1.1: the cropped frame keeps at least one sample (CropUnitX = 2, CropUnitY = 2 for frames in 4:2:0).
|
||||
var cropUnitY = 2 * (s.FrameMbsOnly ? 1 : 2);
|
||||
if (2 * (s.CropLeft + s.CropRight) >= s.WidthInMbs * 16 || cropUnitY * (s.CropTop + s.CropBottom) >= s.HeightInMbs * 16)
|
||||
// §7.4.2.1.1: the cropped frame keeps at least one sample.
|
||||
if (s.CropUnitX * (s.CropLeft + s.CropRight) >= s.WidthInMbs * 16 || s.CropUnitY * (s.CropTop + s.CropBottom) >= s.HeightInMbs * 16)
|
||||
{
|
||||
throw new H264Exception("Ritaglio dell'immagine non valido.");
|
||||
}
|
||||
|
||||
@@ -2,34 +2,49 @@ namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>
|
||||
/// A frame store of the decoded picture buffer: a decoded frame, or the two fields of a complementary field pair (its
|
||||
/// even rows are the top field, its odd rows the bottom one), with what later pictures need from it: samples (4:2:0,
|
||||
/// 8 bits, the full macroblock area), motion vectors and references of every block (for direct prediction and the
|
||||
/// deblocking of the pictures that follow), and its marking.
|
||||
/// even rows are the top field, its odd rows the bottom one), with what later pictures need from it: samples (the full
|
||||
/// macroblock area, one or two bytes per sample), motion vectors and references of every block (for direct prediction
|
||||
/// and the deblocking of the pictures that follow), and its marking.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The data of the macroblocks is kept on the grid of the frame, whatever the coding: a frame macroblock at its row; a
|
||||
/// macroblock pair of an MBAFF frame at rows 2k (top) and 2k + 1 (bottom), field pairs included; the macroblock of row
|
||||
/// k of a field picture at row 2k + parity. Field macroblocks (<see cref="MbField"/>) keep their motion vectors in
|
||||
/// field units and refer to fields (<see cref="RefPar"/>).
|
||||
/// field units and refer to fields (<see cref="RefPar"/>). When the three colour planes of 4:4:4 are coded separately
|
||||
/// (separate_colour_plane_flag) each has macroblocks of its own: the motion data is kept per plane, and
|
||||
/// <see cref="SelectPlane"/> chooses the one the properties show.
|
||||
/// </remarks>
|
||||
internal sealed class Picture
|
||||
{
|
||||
internal Picture(int widthInMbs, int heightInMbs)
|
||||
private readonly MotionPlane[] motion;
|
||||
private MotionPlane selected;
|
||||
|
||||
/// <param name="widthInMbs">Width in macroblocks.</param>
|
||||
/// <param name="heightInMbs">Height in macroblocks.</param>
|
||||
/// <param name="chromaFormat">chroma_format_idc: 0 monochrome (no chroma planes), 1 4:2:0, 2 4:2:2, 3 4:4:4.</param>
|
||||
/// <param name="bytesPerSample">1 up to 8 bits, 2 above.</param>
|
||||
/// <param name="colourPlanes">3 when the colour planes are coded separately, else 1.</param>
|
||||
internal Picture(int widthInMbs, int heightInMbs, int chromaFormat = 1, int bytesPerSample = 1, int colourPlanes = 1)
|
||||
{
|
||||
WidthInMbs = widthInMbs;
|
||||
HeightInMbs = heightInMbs;
|
||||
Width = widthInMbs * 16;
|
||||
Height = heightInMbs * 16;
|
||||
ChromaFormat = chromaFormat;
|
||||
BytesPerSample = bytesPerSample;
|
||||
ChromaWidth = chromaFormat == 0 ? 0 : chromaFormat == 3 ? Width : Width / 2;
|
||||
ChromaHeight = chromaFormat == 0 ? 0 : chromaFormat == 1 ? Height / 2 : Height;
|
||||
var mbs = widthInMbs * heightInMbs;
|
||||
Y = new byte[Width * Height];
|
||||
Cb = new byte[Width * Height / 4];
|
||||
Cr = new byte[Width * Height / 4];
|
||||
Mv = new short[2 * mbs * 16 * 2];
|
||||
RefIdx = new sbyte[2 * mbs * 4];
|
||||
RefPic = new Picture?[2 * mbs * 4];
|
||||
RefPar = new sbyte[2 * mbs * 4];
|
||||
MbIntra = new bool[mbs];
|
||||
MbField = new bool[mbs];
|
||||
Y = new byte[Width * Height * bytesPerSample];
|
||||
Cb = new byte[ChromaWidth * ChromaHeight * bytesPerSample];
|
||||
Cr = new byte[ChromaWidth * ChromaHeight * bytesPerSample];
|
||||
motion = new MotionPlane[colourPlanes];
|
||||
for (var i = 0; i < colourPlanes; i++)
|
||||
{
|
||||
motion[i] = new MotionPlane(mbs);
|
||||
}
|
||||
|
||||
selected = motion[0];
|
||||
}
|
||||
|
||||
internal int WidthInMbs { get; }
|
||||
@@ -40,6 +55,17 @@ internal sealed class Picture
|
||||
|
||||
internal int Height { get; }
|
||||
|
||||
/// <summary>chroma_format_idc of the samples (3 also for separate colour planes).</summary>
|
||||
internal int ChromaFormat { get; }
|
||||
|
||||
internal int BytesPerSample { get; }
|
||||
|
||||
/// <summary>Width of the Cb and Cr planes in samples (0 for monochrome).</summary>
|
||||
internal int ChromaWidth { get; }
|
||||
|
||||
/// <summary>Height of the Cb and Cr planes in samples (0 for monochrome).</summary>
|
||||
internal int ChromaHeight { get; }
|
||||
|
||||
internal byte[] Y { get; }
|
||||
|
||||
internal byte[] Cb { get; }
|
||||
@@ -47,21 +73,46 @@ internal sealed class Picture
|
||||
internal byte[] Cr { get; }
|
||||
|
||||
/// <summary>Motion vectors: [((list * mbs + mb) * 16 + raster 4×4 block) * 2 + component], quarter samples.</summary>
|
||||
internal short[] Mv { get; }
|
||||
internal short[] Mv => selected.Mv;
|
||||
|
||||
/// <summary>Reference indices: [(list * mbs + mb) * 4 + 8×8 block]; −1 when the list is not used.</summary>
|
||||
internal sbyte[] RefIdx { get; }
|
||||
internal sbyte[] RefIdx => selected.RefIdx;
|
||||
|
||||
/// <summary>The frame store each 8×8 block refers to, by list (same index as <see cref="RefIdx"/>).</summary>
|
||||
internal Picture?[] RefPic { get; }
|
||||
internal Picture?[] RefPic => selected.RefPic;
|
||||
|
||||
/// <summary>The field of <see cref="RefPic"/> referred to: 0 top, 1 bottom, −1 the frame (same index as <see cref="RefIdx"/>).</summary>
|
||||
internal sbyte[] RefPar { get; }
|
||||
internal sbyte[] RefPar => selected.RefPar;
|
||||
|
||||
internal bool[] MbIntra { get; }
|
||||
internal bool[] MbIntra => selected.MbIntra;
|
||||
|
||||
/// <summary>Field macroblocks: those of field pictures and the field pairs of MBAFF frames.</summary>
|
||||
internal bool[] MbField { get; }
|
||||
internal bool[] MbField => selected.MbField;
|
||||
|
||||
/// <summary>The plane of colour component <paramref name="k"/> (0 Y, 1 Cb, 2 Cr).</summary>
|
||||
internal byte[] Plane(int k) => k == 0 ? Y : k == 1 ? Cb : Cr;
|
||||
|
||||
/// <summary>Shows the motion data of colour plane <paramref name="k"/> (only one exists unless the planes are separate).</summary>
|
||||
internal void SelectPlane(int k) => selected = motion[Math.Min(k, motion.Length - 1)];
|
||||
|
||||
/// <summary>A store taken from the pool: no block refers to any picture yet.</summary>
|
||||
internal void ClearReferences()
|
||||
{
|
||||
foreach (var m in motion)
|
||||
{
|
||||
Array.Clear(m.RefPic);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A frame inferred for a gap in frame_num: all its macroblocks count as intra frame macroblocks.</summary>
|
||||
internal void MarkAsGap()
|
||||
{
|
||||
foreach (var m in motion)
|
||||
{
|
||||
Array.Fill(m.MbIntra, true);
|
||||
Array.Clear(m.MbField);
|
||||
}
|
||||
}
|
||||
|
||||
internal int MbCount => WidthInMbs * HeightInMbs;
|
||||
|
||||
@@ -127,7 +178,20 @@ internal sealed class Picture
|
||||
/// <summary>Whether the field (0 top, 1 bottom) or the frame (−1) is a long-term reference.</summary>
|
||||
internal bool IsLongTerm(int parity) => parity < 0 ? LongMask == 3 : (LongMask & (1 << parity)) != 0;
|
||||
|
||||
internal bool Fits(int widthInMbs, int heightInMbs) => WidthInMbs == widthInMbs && HeightInMbs == heightInMbs;
|
||||
internal bool Fits(int widthInMbs, int heightInMbs, int chromaFormat, int bytesPerSample, int colourPlanes) =>
|
||||
WidthInMbs == widthInMbs && HeightInMbs == heightInMbs && ChromaFormat == chromaFormat && BytesPerSample == bytesPerSample
|
||||
&& motion.Length == colourPlanes;
|
||||
|
||||
/// <summary>The motion data of the macroblocks of one colour plane.</summary>
|
||||
private sealed class MotionPlane(int mbs)
|
||||
{
|
||||
internal readonly short[] Mv = new short[2 * mbs * 16 * 2];
|
||||
internal readonly sbyte[] RefIdx = new sbyte[2 * mbs * 4];
|
||||
internal readonly Picture?[] RefPic = new Picture?[2 * mbs * 4];
|
||||
internal readonly sbyte[] RefPar = new sbyte[2 * mbs * 4];
|
||||
internal readonly bool[] MbIntra = new bool[mbs];
|
||||
internal readonly bool[] MbField = new bool[mbs];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A reference picture of a list: a frame (<see cref="Parity"/> −1) or one field of a frame store.</summary>
|
||||
@@ -138,22 +202,45 @@ internal readonly record struct RefEntry(Picture? Pic, int Parity)
|
||||
internal bool IsLongTerm => Pic!.IsLongTerm(Parity);
|
||||
}
|
||||
|
||||
/// <summary>A decoded frame, cropped, in planar YUV 4:2:0.</summary>
|
||||
/// <summary>
|
||||
/// A decoded frame, cropped, in planar YUV. Up to 8 bits each sample is a byte; above, two bytes, little-endian (as the
|
||||
/// reference decoders write their files). A monochrome frame (4:0:0) comes with Cb and Cr planes of 4:2:0 size at the
|
||||
/// middle value 2^(BitDepthChroma − 1), as reference decoders write it too.
|
||||
/// </summary>
|
||||
/// <param name="Width">Luma width after cropping.</param>
|
||||
/// <param name="Height">Luma height after cropping.</param>
|
||||
/// <param name="Y">Luma, <paramref name="Width"/> × <paramref name="Height"/>.</param>
|
||||
/// <param name="Cb">Blue-difference chroma, (Width + 1) / 2 × (Height + 1) / 2.</param>
|
||||
/// <param name="Y">Luma, <paramref name="Width"/> × <paramref name="Height"/> samples.</param>
|
||||
/// <param name="Cb">Blue-difference chroma, <see cref="ChromaWidth"/> × <see cref="ChromaHeight"/> samples.</param>
|
||||
/// <param name="Cr">Red-difference chroma, same size as <paramref name="Cb"/>.</param>
|
||||
/// <param name="Poc">Picture order count: frames are shown by increasing value within a <paramref name="Period"/>.</param>
|
||||
/// <param name="Period">Increases at each IDR picture.</param>
|
||||
/// <param name="DecodeIndex">Position of the frame in decoding order (0 for the first).</param>
|
||||
/// <param name="MatrixCoefficients">matrix_coefficients of the VUI (1 = BT.709, 5 and 6 = BT.601, 2 = unspecified).</param>
|
||||
/// <param name="FullRange">video_full_range_flag of the VUI.</param>
|
||||
/// <param name="ChromaFormat">chroma_format_idc: 0 monochrome, 1 4:2:0, 2 4:2:2, 3 4:4:4.</param>
|
||||
/// <param name="BitDepthLuma">Bits of each luma sample, 8 to 14.</param>
|
||||
/// <param name="BitDepthChroma">Bits of each chroma sample, 8 to 14.</param>
|
||||
public sealed record H264Frame(
|
||||
int Width, int Height, byte[] Y, byte[] Cb, byte[] Cr, int Poc, int Period, long DecodeIndex, int MatrixCoefficients, bool FullRange)
|
||||
int Width, int Height, byte[] Y, byte[] Cb, byte[] Cr, int Poc, int Period, long DecodeIndex, int MatrixCoefficients, bool FullRange,
|
||||
int ChromaFormat = 1, int BitDepthLuma = 8, int BitDepthChroma = 8)
|
||||
{
|
||||
/// <summary>The frame as one I420 buffer (Y, then Cb, then Cr), as reference decoders write it.</summary>
|
||||
public byte[] ToI420()
|
||||
/// <summary>Width of <see cref="Cb"/> and <see cref="Cr"/> in samples.</summary>
|
||||
public int ChromaWidth => ChromaFormat == 3 ? Width : (Width + 1) / 2;
|
||||
|
||||
/// <summary>Height of <see cref="Cb"/> and <see cref="Cr"/> in samples.</summary>
|
||||
public int ChromaHeight => ChromaFormat is 2 or 3 ? Height : (Height + 1) / 2;
|
||||
|
||||
/// <summary>Bytes of every sample of the three planes: 2 when either bit depth is above 8, else 1.</summary>
|
||||
public int BytesPerSample => BitDepthLuma > 8 || BitDepthChroma > 8 ? 2 : 1;
|
||||
|
||||
/// <summary>Luma sample <paramref name="index"/> (row × Width + column), whatever the bit depth.</summary>
|
||||
public int LumaAt(int index) => BytesPerSample == 2 ? Y[2 * index] | (Y[(2 * index) + 1] << 8) : Y[index];
|
||||
|
||||
/// <summary>Sample <paramref name="index"/> of a chroma plane (row × ChromaWidth + column), whatever the bit depth.</summary>
|
||||
public int ChromaAt(byte[] plane, int index) => BytesPerSample == 2 ? plane[2 * index] | (plane[(2 * index) + 1] << 8) : plane[index];
|
||||
|
||||
/// <summary>The frame as one planar buffer (Y, then Cb, then Cr), as reference decoders write it.</summary>
|
||||
public byte[] ToPlanar()
|
||||
{
|
||||
var buffer = new byte[Y.Length + Cb.Length + Cr.Length];
|
||||
Y.CopyTo(buffer, 0);
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>
|
||||
/// The two sample types of the decoder: <see cref="byte"/> for 8-bit video, <see cref="ushort"/> above 8 bits (up to 14,
|
||||
/// High 4:4:4). The planes of a picture are byte arrays of one or two bytes per sample (little-endian, as the official
|
||||
/// reconstructions store them); the prediction, transform and filter code is generic over the sample type, and the JIT
|
||||
/// compiles it once for each, so 8-bit video pays nothing for the wider one.
|
||||
/// </summary>
|
||||
internal static class Samples
|
||||
{
|
||||
/// <summary>The value of a sample.</summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static int Get<T>(T sample)
|
||||
where T : unmanaged =>
|
||||
typeof(T) == typeof(byte) ? Unsafe.As<T, byte>(ref sample) : Unsafe.As<T, ushort>(ref sample);
|
||||
|
||||
/// <summary>A sample of value <paramref name="value"/>, already within the range of the bit depth.</summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static T Make<T>(int value)
|
||||
where T : unmanaged
|
||||
{
|
||||
if (typeof(T) == typeof(byte))
|
||||
{
|
||||
var b = (byte)value;
|
||||
return Unsafe.As<byte, T>(ref b);
|
||||
}
|
||||
|
||||
var u = (ushort)value;
|
||||
return Unsafe.As<ushort, T>(ref u);
|
||||
}
|
||||
|
||||
/// <summary>A plane stored as bytes, seen as samples of type <typeparamref name="T"/>.</summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static Span<T> Plane<T>(byte[] plane)
|
||||
where T : unmanaged => MemoryMarshal.Cast<byte, T>(plane.AsSpan());
|
||||
|
||||
/// <summary>Clip1 of §5.7: <paramref name="value"/> within 0..<paramref name="max"/>.</summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static int Clip(int value, int max) => value < 0 ? 0 : value > max ? max : value;
|
||||
}
|
||||
@@ -16,6 +16,10 @@ internal sealed class SliceHeader
|
||||
internal int FirstMb;
|
||||
internal SliceType Type;
|
||||
internal int PpsId;
|
||||
|
||||
/// <summary>colour_plane_id: the colour plane (0 Y, 1 Cb, 2 Cr) of a slice when the planes are coded separately.</summary>
|
||||
internal int ColourPlaneId;
|
||||
|
||||
internal int FrameNum;
|
||||
internal bool FieldPic;
|
||||
internal bool BottomField;
|
||||
@@ -89,6 +93,15 @@ internal sealed class SliceHeader
|
||||
throw new H264Exception("Slice senza i suoi insiemi di parametri.");
|
||||
}
|
||||
|
||||
if (sps.SeparateColourPlane)
|
||||
{
|
||||
h.ColourPlaneId = (int)r.Read(2);
|
||||
if (h.ColourPlaneId > 2)
|
||||
{
|
||||
throw new H264Exception("colour_plane_id non valido.");
|
||||
}
|
||||
}
|
||||
|
||||
h.FrameNum = (int)r.Read(sps.Log2MaxFrameNum);
|
||||
if (!sps.FrameMbsOnly)
|
||||
{
|
||||
@@ -280,7 +293,8 @@ internal sealed class SliceHeader
|
||||
private static void ParseWeights(RbspReader r, SliceHeader h, Sps sps)
|
||||
{
|
||||
h.LumaLog2WeightDenom = r.ReadUe(7);
|
||||
var chroma = sps.ChromaFormatIdc != 0;
|
||||
// No chroma weights without chroma: monochrome, or each colour plane coded separately (ChromaArrayType 0).
|
||||
var chroma = sps.ChromaArrayType != 0;
|
||||
if (chroma)
|
||||
{
|
||||
h.ChromaLog2WeightDenom = r.ReadUe(7);
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
using static Febe.Core.Codecs.H264.Samples;
|
||||
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>Inverse transforms of §8.5.12 and §8.5.13, adding the residual to the prediction already in the plane.</summary>
|
||||
/// <summary>
|
||||
/// Inverse transforms of §8.5.12 and §8.5.13, adding the residual to the prediction already in the plane, and the
|
||||
/// transform bypass of lossless macroblocks (§8.5.15), at any bit depth (<c>max</c> is 2^BitDepth − 1).
|
||||
/// </summary>
|
||||
internal static class Transform
|
||||
{
|
||||
/// <summary>Inverse 4×4 transform of scaled coefficients (raster order), added to the 4×4 block at <paramref name="o"/>.</summary>
|
||||
internal static void Add4x4(Span<int> d, byte[] plane, int o, int stride)
|
||||
internal static void Add4x4<T>(Span<int> d, Span<T> plane, int o, int stride, int max)
|
||||
where T : unmanaged
|
||||
{
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
@@ -20,15 +26,16 @@ internal static class Transform
|
||||
{
|
||||
int f0 = d[j], f1 = d[4 + j], f2 = d[8 + j], f3 = d[12 + j];
|
||||
int g0 = f0 + f2, g1 = f0 - f2, g2 = (f1 >> 1) - f3, g3 = f1 + (f3 >> 1);
|
||||
AddSample(plane, o + j, g0 + g3);
|
||||
AddSample(plane, o + stride + j, g1 + g2);
|
||||
AddSample(plane, o + (2 * stride) + j, g1 - g2);
|
||||
AddSample(plane, o + (3 * stride) + j, g0 - g3);
|
||||
AddSample(plane, o + j, g0 + g3, max);
|
||||
AddSample(plane, o + stride + j, g1 + g2, max);
|
||||
AddSample(plane, o + (2 * stride) + j, g1 - g2, max);
|
||||
AddSample(plane, o + (3 * stride) + j, g0 - g3, max);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Inverse 8×8 transform (§8.5.13), added to the 8×8 block at <paramref name="o"/>.</summary>
|
||||
internal static void Add8x8(Span<int> d, byte[] plane, int o, int stride)
|
||||
internal static void Add8x8<T>(Span<int> d, Span<T> plane, int o, int stride, int max)
|
||||
where T : unmanaged
|
||||
{
|
||||
Span<int> tmp = stackalloc int[8];
|
||||
for (var i = 0; i < 8; i++)
|
||||
@@ -48,7 +55,47 @@ internal static class Transform
|
||||
Butterfly8(column, tmp);
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
AddSample(plane, o + (i * stride) + j, tmp[i]);
|
||||
AddSample(plane, o + (i * stride) + j, tmp[i], max);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The residual of a lossless block (TransformBypassModeFlag, §8.5.15): <paramref name="r"/> holds the
|
||||
/// <paramref name="w"/> × <paramref name="h"/> coefficients in raster order, which are the residual itself; under an
|
||||
/// intra prediction that is horizontal (<paramref name="dpcm"/> 1) or vertical (2) each sample adds those before it
|
||||
/// along the direction of the prediction. The result is added to the prediction in the plane.
|
||||
/// </summary>
|
||||
internal static void AddBypass<T>(Span<int> r, int w, int h, int dpcm, Span<T> plane, int o, int stride, int max)
|
||||
where T : unmanaged
|
||||
{
|
||||
if (dpcm == 1)
|
||||
{
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
for (var x = 1; x < w; x++)
|
||||
{
|
||||
r[(y * w) + x] += r[(y * w) + x - 1];
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (dpcm == 2)
|
||||
{
|
||||
for (var y = 1; y < h; y++)
|
||||
{
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
r[(y * w) + x] += r[((y - 1) * w) + x];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
var row = plane.Slice(o + (y * stride), w);
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
row[x] = Make<T>(Clip(Get(row[x]) + r[(y * w) + x], max));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,9 +144,35 @@ internal static class Transform
|
||||
}
|
||||
}
|
||||
|
||||
private static void AddSample(byte[] plane, int index, int residual)
|
||||
/// <summary>
|
||||
/// The inverse transform of the eight chroma DC coefficients of 4:2:2 (equation 8-329): f = A · c · B, with c of four
|
||||
/// rows and two columns in raster order, A the 4×4 matrix of <see cref="Hadamard4x4"/> and B = [1 1; 1 −1]; in place.
|
||||
/// </summary>
|
||||
internal static void ChromaDc422(Span<int> c)
|
||||
{
|
||||
var v = plane[index] + ((residual + 32) >> 6);
|
||||
plane[index] = (byte)(v < 0 ? 0 : v > 255 ? 255 : v);
|
||||
// c · B on each row.
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
int a = c[2 * i], b = c[(2 * i) + 1];
|
||||
c[2 * i] = a + b;
|
||||
c[(2 * i) + 1] = a - b;
|
||||
}
|
||||
|
||||
// A · (c · B) on each column.
|
||||
for (var j = 0; j < 2; j++)
|
||||
{
|
||||
int f0 = c[j], f1 = c[2 + j], f2 = c[4 + j], f3 = c[6 + j];
|
||||
int e0 = f0 + f1, e1 = f0 - f1, e2 = f2 + f3, e3 = f2 - f3;
|
||||
c[j] = e0 + e2;
|
||||
c[2 + j] = e0 - e2;
|
||||
c[4 + j] = e1 - e3;
|
||||
c[6 + j] = e1 + e3;
|
||||
}
|
||||
}
|
||||
|
||||
private static void AddSample<T>(Span<T> plane, int index, int residual, int max)
|
||||
where T : unmanaged
|
||||
{
|
||||
plane[index] = Make<T>(Clip(Get(plane[index]) + ((residual + 32) >> 6), max));
|
||||
}
|
||||
}
|
||||
@@ -469,25 +469,35 @@ public sealed class VideoFrameDecoder
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A coarse grid of mean luma and chroma values, to compare frames without their compression noise.</summary>
|
||||
/// <summary>
|
||||
/// A coarse grid of mean luma and chroma values, to compare frames without their compression noise; values on the
|
||||
/// 8-bit scale whatever the bit depth, the chroma at any sampling (its own grid over its own plane).
|
||||
/// </summary>
|
||||
private static double[] Grid(H264Frame frame)
|
||||
{
|
||||
var grid = new double[GridSize * GridSize * 2];
|
||||
var counts = new int[GridSize * GridSize];
|
||||
var wide = frame.BytesPerSample == 2;
|
||||
ReadOnlySpan<ushort> y16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Y) : default;
|
||||
var lumaShift = frame.BitDepthLuma - 8;
|
||||
for (var y = 0; y < frame.Height; y++)
|
||||
{
|
||||
var gy = y * GridSize / frame.Height;
|
||||
var row = frame.Y.AsSpan(y * frame.Width, frame.Width);
|
||||
for (var x = 0; x < row.Length; x++)
|
||||
var start = y * frame.Width;
|
||||
for (var x = 0; x < frame.Width; x++)
|
||||
{
|
||||
var cell = (gy * GridSize) + (x * GridSize / frame.Width);
|
||||
grid[cell] += row[x];
|
||||
grid[cell] += wide ? y16[start + x] >> lumaShift : frame.Y[start + x];
|
||||
counts[cell]++;
|
||||
}
|
||||
}
|
||||
|
||||
var cw = (frame.Width + 1) / 2;
|
||||
var ch = (frame.Height + 1) / 2;
|
||||
var cw = frame.ChromaWidth;
|
||||
var ch = frame.ChromaHeight;
|
||||
ReadOnlySpan<ushort> cb16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Cb) : default;
|
||||
ReadOnlySpan<ushort> cr16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Cr) : default;
|
||||
var chromaShift = frame.BitDepthChroma - 8;
|
||||
var middle = 1 << (frame.BitDepthChroma - 1);
|
||||
var chromaCounts = new int[GridSize * GridSize];
|
||||
for (var y = 0; y < ch; y++)
|
||||
{
|
||||
@@ -496,7 +506,19 @@ public sealed class VideoFrameDecoder
|
||||
{
|
||||
var cell = (gy * GridSize) + (x * GridSize / cw);
|
||||
var i = (y * cw) + x;
|
||||
grid[(GridSize * GridSize) + cell] += (Math.Abs(frame.Cb[i] - 128) + Math.Abs(frame.Cr[i] - 128)) / 2.0;
|
||||
int u, v;
|
||||
if (wide)
|
||||
{
|
||||
u = Math.Abs(cb16[i] - middle) >> chromaShift;
|
||||
v = Math.Abs(cr16[i] - middle) >> chromaShift;
|
||||
}
|
||||
else
|
||||
{
|
||||
u = Math.Abs(frame.Cb[i] - 128);
|
||||
v = Math.Abs(frame.Cr[i] - 128);
|
||||
}
|
||||
|
||||
grid[(GridSize * GridSize) + cell] += (u + v) / 2.0;
|
||||
chromaCounts[cell]++;
|
||||
}
|
||||
}
|
||||
@@ -512,8 +534,10 @@ public sealed class VideoFrameDecoder
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The frame in RGB: BT.709 or BT.601 coefficients as the stream says (unspecified: BT.709 from 720 lines up), limited
|
||||
/// or full range, reduced by an integer factor to fit <paramref name="maxLongSide"/>, then rotated clockwise.
|
||||
/// The frame in RGB: BT.709, BT.601 or BT.2020 coefficients as the stream says (unspecified: BT.709 from 720 lines
|
||||
/// up), limited or full range at the bit depth of the frame (limited: black at 16 · 2^(n − 8), luma span 219 · 2^(n − 8),
|
||||
/// chroma 224 · 2^(n − 8) around 2^(n − 1)), any chroma sampling (4:2:0, 4:2:2, 4:4:4; monochrome comes with grey
|
||||
/// chroma), reduced by an integer factor to fit <paramref name="maxLongSide"/>, then rotated clockwise.
|
||||
/// </summary>
|
||||
internal static VideoImage ToImage(H264Frame frame, int rotation, int maxLongSide)
|
||||
{
|
||||
@@ -527,9 +551,11 @@ public sealed class VideoFrameDecoder
|
||||
_ => frame.Height >= 720 ? (0.2126, 0.0722) : (0.299, 0.114),
|
||||
};
|
||||
var kg = 1 - kr - kb;
|
||||
var yScale = frame.FullRange ? 1.0 : 255.0 / 219.0;
|
||||
var cScale = frame.FullRange ? 1.0 : 255.0 / 224.0;
|
||||
var yOffset = frame.FullRange ? 0 : 16;
|
||||
int lumaBits = frame.BitDepthLuma - 8, chromaBits = frame.BitDepthChroma - 8;
|
||||
var yScale = frame.FullRange ? 255.0 / ((1 << frame.BitDepthLuma) - 1) : 255.0 / (219 << lumaBits);
|
||||
var cScale = frame.FullRange ? 255.0 / ((1 << frame.BitDepthChroma) - 1) : 255.0 / (224 << chromaBits);
|
||||
var yOffset = frame.FullRange ? 0 : 16 << lumaBits;
|
||||
var middle = 1 << (frame.BitDepthChroma - 1);
|
||||
const int Shift = 16;
|
||||
const double One = 1 << Shift;
|
||||
var cy = (int)Math.Round(yScale * One);
|
||||
@@ -549,7 +575,13 @@ public sealed class VideoFrameDecoder
|
||||
var width = Math.Max(1, frame.Width / factor);
|
||||
var height = Math.Max(1, frame.Height / factor);
|
||||
var rgb = new byte[width * height * 3];
|
||||
var cw = (frame.Width + 1) / 2;
|
||||
var cw = frame.ChromaWidth;
|
||||
var shiftX = frame.ChromaFormat == 3 ? 0 : 1;
|
||||
var shiftY = frame.ChromaFormat is 2 or 3 ? 0 : 1;
|
||||
var wide = frame.BytesPerSample == 2;
|
||||
ReadOnlySpan<ushort> y16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Y) : default;
|
||||
ReadOnlySpan<ushort> cb16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Cb) : default;
|
||||
ReadOnlySpan<ushort> cr16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Cr) : default;
|
||||
var area = factor * factor;
|
||||
for (var oy = 0; oy < height; oy++)
|
||||
{
|
||||
@@ -560,13 +592,25 @@ public sealed class VideoFrameDecoder
|
||||
{
|
||||
var y = (oy * factor) + dy;
|
||||
var lumaRow = y * frame.Width;
|
||||
var chromaRow = (y >> 1) * cw;
|
||||
var chromaRow = (y >> shiftY) * cw;
|
||||
for (var dx = 0; dx < factor; dx++)
|
||||
{
|
||||
var x = (ox * factor) + dx;
|
||||
var l = (frame.Y[lumaRow + x] - yOffset) * cy;
|
||||
var u = frame.Cb[chromaRow + (x >> 1)] - 128;
|
||||
var v = frame.Cr[chromaRow + (x >> 1)] - 128;
|
||||
var ci = chromaRow + (x >> shiftX);
|
||||
int l, u, v;
|
||||
if (wide)
|
||||
{
|
||||
l = (y16[lumaRow + x] - yOffset) * cy;
|
||||
u = cb16[ci] - middle;
|
||||
v = cr16[ci] - middle;
|
||||
}
|
||||
else
|
||||
{
|
||||
l = (frame.Y[lumaRow + x] - yOffset) * cy;
|
||||
u = frame.Cb[ci] - middle;
|
||||
v = frame.Cr[ci] - middle;
|
||||
}
|
||||
|
||||
r += Clip((l + (crR * v) + Half) >> Shift);
|
||||
g += Clip((l - (cbG * u) - (crG * v) + Half) >> Shift);
|
||||
b += Clip((l + (cbB * u) + Half) >> Shift);
|
||||
|
||||
Reference in new issue
Block a user