Decodificatore H.264 per le immagini interlacciate: campi, PAFF e MBAFF (#58)

I video interlacciati (telecamere, registrazioni televisive) davano un'H264Exception e restavano
senza miniatura. Ora il decodificatore li gestisce tutti, scritto in casa sulla specifica:

- campi e coppie di campi (PAFF) e macroblocchi adattivi (MBAFF) su una sola griglia di
  fotogramma, con origine e passo per macroblocco, senza copie in piani separati;
- POC, liste dei riferimenti, riordino e marcatura (MMCO, lungo termine) per campi;
- vicini MBAFF della tabella 6-4, vettori di moto e riferimenti scalati fra campo e
  fotogramma, diretta spaziale e temporale con il colocato di campo, pesi impliciti per parità;
- contesti CABAC e CAVLC di campo, scansioni di campo 4x4 e 8x8;
- deblocking per campi e per coppie MBAFF;
- uscita con i due campi intercalati; un campo rimasto solo esce con l'altro a 128.

I 17 flussi interlacciati della serie ITU-T H.264.1 passano da «da fare» ai flussi verificati e
coincidono fotogramma per fotogramma con la ricostruzione ufficiale; i 12 a immagini intere e lo
strato base SVC coincidono ancora e non sono più lenti. Prove di robustezza e di immagini saltate
anche sui flussi interlacciati; LEGGIMI.md e una riga in decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 16:05:41 +01:00
1 parent 25a6d9ce1d
commit 9c626f67ec
15 files changed
+1909 -613

No files matched your search

+1
View File
@@ -428,3 +428,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-18 | Lettori di contenitori più tolleranti: un blocco Matroska danneggiato o troncato, o oltre il limite dei campioni, ferma la lettura e i blocchi letti restano; una traccia MP4 con `tkhd`, `elst`, `mdhd`, `hdlr` o `esds` danneggiati si scarta e le altre restano; la durata AVI oltre 10⁹ secondi è ignota senza perdere la data; i tempi Matroska usano come unità il massimo comun divisore fra TimecodeScale e un secondo, così la scala dei tempi è esatta per ogni TimecodeScale; la sonda dei metadati legge su un thread del pool e controlla l'annullamento fra i frammenti, e senza campioni non copia le tabelle né conserva i campioni dei frammenti | Come per il lettore ISO già prima: un file con un solo punto rovinato dopo il primo secondo non deve restare senza miniatura né perdere la data. La divisione intera 10⁹ / TimecodeScale spostava i tempi dello 0,1% con 3 ms e sbagliava fotogramma oltre il secondo | | 2026-11-18 | Lettori di contenitori più tolleranti: un blocco Matroska danneggiato o troncato, o oltre il limite dei campioni, ferma la lettura e i blocchi letti restano; una traccia MP4 con `tkhd`, `elst`, `mdhd`, `hdlr` o `esds` danneggiati si scarta e le altre restano; la durata AVI oltre 10⁹ secondi è ignota senza perdere la data; i tempi Matroska usano come unità il massimo comun divisore fra TimecodeScale e un secondo, così la scala dei tempi è esatta per ogni TimecodeScale; la sonda dei metadati legge su un thread del pool e controlla l'annullamento fra i frammenti, e senza campioni non copia le tabelle né conserva i campioni dei frammenti | Come per il lettore ISO già prima: un file con un solo punto rovinato dopo il primo secondo non deve restare senza miniatura né perdere la data. La divisione intera 10⁹ / TimecodeScale spostava i tempi dello 0,1% con 3 ms e sbagliava fotogramma oltre il secondo |
| 2026-11-18 | Ciò che il decodificatore dei fotogrammi offre ma la produzione non usa ancora: `AnalyseStillnessAsync` (video di un'immagine ferma) e `Mp4Writer` (rimpacchettare con moov in testa) sono pronti per una tappa successiva e oggi servono solo alle prove; la miniatura di un video passa ancora da un BMP decodificato da SkiaSharp (tappa C1: dare `VideoImage` direttamente al ridimensionamento e al codificatore JPEG scritti in casa, senza BMP) | La riga del 18 novembre sui video li descriveva come se fossero già usati. Il passaggio per BMP resta finché SkiaSharp è nel programma | | 2026-11-18 | Ciò che il decodificatore dei fotogrammi offre ma la produzione non usa ancora: `AnalyseStillnessAsync` (video di un'immagine ferma) e `Mp4Writer` (rimpacchettare con moov in testa) sono pronti per una tappa successiva e oggi servono solo alle prove; la miniatura di un video passa ancora da un BMP decodificato da SkiaSharp (tappa C1: dare `VideoImage` direttamente al ridimensionamento e al codificatore JPEG scritti in casa, senza BMP) | La riga del 18 novembre sui video li descriveva come se fossero già usati. Il passaggio per BMP resta finché SkiaSharp è nel programma |
| 2026-11-18 | Flussi di conformità ITU-T H.264.1 anche per le parti che il decodificatore non gestisce ancora (campi, PAFF, MBAFF, FMO e ASO, slice SP, 4:2:2 a 8 e 10 bit, 4:0:0, SVC, MVC), 37 in tutto e 8,3 MB, in `tests/Febe.Tests/Media/H264/Conformita` con il loro `riferimento.md5`: la prova è inconclusiva («da fare: …») finché la parte manca e fallisce apposta quando un flusso coincide senza essere passato fra i verificati. L'MD5 è quello dei campioni come stanno nel file YUV ufficiale (due byte little-endian oltre gli 8 bit, 4:2:2 com'è, il 4:0:0 con i piani a 128 del file); per SVC uno per lo strato più alto e uno per lo strato base, che si prova già; per MVC la serie non ha ricostruzioni e il file lo dice. Restano fuori partizionamento dei dati, slice ridondanti e SI (nessun flusso della serie li usa), High 10 in 4:2:0, 4:2:2 Intra e 4:4:4 con piani separati e senza perdita (i flussi non hanno la ricostruzione e pesano da 2 a 113 MB) | Alberto ha permesso il 18 novembre di scaricare i flussi ufficiali di conformità: il vuoto del decodificatore deve vedersi nella serie di prove senza farla diventare rossa, e chi scrive una parte ha già pronto il riferimento ufficiale. Le ricostruzioni restano fuori dal repository (sono decine di MB); i flussi sono stati scelti piccoli, uno o due per parte. Il dettaglio di che cosa copre ciascun flusso e di che cosa manca è in `LEGGIMI.md` della cartella. Il riepilogo delle prove della CI (`riepilogo-prove.sh`) conta e elenca a parte le inconclusive «da fare: …» e non le somma alle saltate, che restano a zero ammesse: senza, la verifica sarebbe rossa per 37 prove che segnano parti mancanti, non un ambiente rotto | | 2026-11-18 | Flussi di conformità ITU-T H.264.1 anche per le parti che il decodificatore non gestisce ancora (campi, PAFF, MBAFF, FMO e ASO, slice SP, 4:2:2 a 8 e 10 bit, 4:0:0, SVC, MVC), 37 in tutto e 8,3 MB, in `tests/Febe.Tests/Media/H264/Conformita` con il loro `riferimento.md5`: la prova è inconclusiva («da fare: …») finché la parte manca e fallisce apposta quando un flusso coincide senza essere passato fra i verificati. L'MD5 è quello dei campioni come stanno nel file YUV ufficiale (due byte little-endian oltre gli 8 bit, 4:2:2 com'è, il 4:0:0 con i piani a 128 del file); per SVC uno per lo strato più alto e uno per lo strato base, che si prova già; per MVC la serie non ha ricostruzioni e il file lo dice. Restano fuori partizionamento dei dati, slice ridondanti e SI (nessun flusso della serie li usa), High 10 in 4:2:0, 4:2:2 Intra e 4:4:4 con piani separati e senza perdita (i flussi non hanno la ricostruzione e pesano da 2 a 113 MB) | Alberto ha permesso il 18 novembre di scaricare i flussi ufficiali di conformità: il vuoto del decodificatore deve vedersi nella serie di prove senza farla diventare rossa, e chi scrive una parte ha già pronto il riferimento ufficiale. Le ricostruzioni restano fuori dal repository (sono decine di MB); i flussi sono stati scelti piccoli, uno o due per parte. Il dettaglio di che cosa copre ciascun flusso e di che cosa manca è in `LEGGIMI.md` della cartella. Il riepilogo delle prove della CI (`riepilogo-prove.sh`) conta e elenca a parte le inconclusive «da fare: …» e non le somma alle saltate, che restano a zero ammesse: senza, la verifica sarebbe rossa per 37 prove che segnano parti mancanti, non un ambiente rotto |
| 2026-11-18 | Il decodificatore H.264 gestisce le immagini interlacciate (campi, PAFF, MBAFF) su una sola griglia di fotogramma: un campo è l'insieme delle sue righe pari o dispari, e ogni macroblocco ricostruisce con un'origine e un passo (doppio per i macroblocchi di campo) invece di copiare i campi in piani separati; liste dei riferimenti e marcatura per campi secondo §8.2.4 e §8.2.5, vicini MBAFF secondo la tabella 6-4, filtro di deblocking per i campi e per le coppie MBAFF come lo fa il decodificatore di riferimento dell'ITU-T (il bordo superiore di un macroblocco di fotogramma sotto una coppia di campi filtrato due volte, il bordo sinistro misto riga per riga). Due campi fanno un fotogramma se hanno parità opposte, lo stesso `frame_num` e sono entrambi di riferimento o entrambi no; un campo rimasto solo esce come fotogramma con le righe dell'altro campo a 128 | I 17 flussi interlacciati della serie di conformità coincidono così con la ricostruzione ufficiale fotogramma per fotogramma, e i flussi a immagini intere non rallentano (la griglia unica evita copie e doppi percorsi). Il grigio per il campo mancante non inventa righe che il flusso non ha |
+317 -128
View File
@@ -2,7 +2,10 @@ namespace Febe.Core.Codecs.H264;
public sealed partial class H264Decoder public sealed partial class H264Decoder
{ {
/// <summary>Deblocking filter (§8.7) over the whole decoded picture, macroblock by macroblock in raster order.</summary> /// <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).
/// </summary>
private void Deblock(Picture picture) private void Deblock(Picture picture)
{ {
var any = false; var any = false;
@@ -16,156 +19,331 @@ public sealed partial class H264Decoder
return; return;
} }
var stride = picture.Width; if (curStructure != 0)
var cstride = stride / 2;
Span<byte> bs = stackalloc byte[16];
for (var m = 0; m < mbCount; m++)
{ {
var s = mbSlice[m]; DeblockRows(picture, 2, curStructure - 1);
if (s < 0) }
{ else if (activeSps!.MbAdaptiveFrameField)
continue; {
} DeblockPairs(picture);
}
else
{
DeblockRows(picture, 1, 0);
}
}
var (disable, alphaOffset, betaOffset) = sliceFilters[s]; /// <summary>A frame (<paramref name="rowStep"/> 1) or the field of <paramref name="parity"/> (<paramref name="rowStep"/> 2).</summary>
if (disable == 1) private void DeblockRows(Picture picture, int rowStep, int parity)
{
var w = widthInMbs;
int width = picture.Width, cwidth = width / 2;
int stride = width * rowStep, cstride = cwidth * rowStep;
Span<byte> bs = stackalloc byte[4];
var rows = heightInMbs / rowStep;
for (var row = 0; row < rows; row++)
{
for (var mx = 0; mx < w; mx++)
{ {
continue; var m = (((row * rowStep) + parity) * w) + mx;
} var s = mbSlice[m];
if (s < 0)
int mx = m % widthInMbs, my = m / widthInMbs;
var leftOk = mx > 0 && mbSlice[m - 1] >= 0 && (disable != 2 || mbSlice[m - 1] == s);
var topOk = my > 0 && mbSlice[m - widthInMbs] >= 0 && (disable != 2 || mbSlice[m - widthInMbs] == s);
var t8 = mbT8[m];
for (var dir = 0; dir < 2; dir++)
{
var edgeOk = dir == 0 ? leftOk : topOk;
var neighbour = dir == 0 ? m - 1 : m - widthInMbs;
for (var edge = 0; edge < 4; edge++)
{ {
for (var i = 0; i < 4; i++) continue;
{
var value = 0;
if ((edge != 0 || edgeOk) && !(t8 && (edge & 1) != 0))
{
var qb = dir == 0 ? (i * 4) + edge : (edge * 4) + i;
int pm, pb;
if (edge == 0)
{
pm = neighbour;
pb = dir == 0 ? (i * 4) + 3 : 12 + i;
}
else
{
pm = m;
pb = qb - (dir == 0 ? 1 : 4);
}
value = BoundaryStrength(picture, pm, pb, m, qb, edge == 0);
}
bs[(edge * 4) + i] = (byte)value;
}
} }
// Luma. var (disable, alphaOffset, betaOffset) = sliceFilters[s];
for (var edge = 0; edge < 4; edge++) if (disable == 1)
{ {
if ((bs[edge * 4] | bs[(edge * 4) + 1] | bs[(edge * 4) + 2] | bs[(edge * 4) + 3]) == 0) continue;
}
var lumaOrigin = ((((row * 16 * rowStep) + parity) * width)) + (mx * 16);
var chromaOrigin = ((((row * 8 * rowStep) + parity) * cwidth)) + (mx * 8);
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);
}
InnerEdges(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);
}
InnerEdges(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
}
}
}
/// <summary>
/// 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)
{
var w = widthInMbs;
int width = picture.Width, cwidth = width / 2;
Span<byte> bs = stackalloc byte[4];
Span<byte> rowBs = stackalloc byte[16];
Span<int> rowMb = stackalloc int[16];
var field = picture.MbField;
for (var pairY = 0; pairY < heightInMbs / 2; pairY++)
{
for (var mx = 0; mx < w; mx++)
{
for (var bottom = 0; bottom < 2; bottom++)
{
var m = (((2 * pairY) + bottom) * w) + mx;
var s = mbSlice[m];
if (s < 0)
{ {
continue; continue;
} }
var pm = edge == 0 ? neighbour : m; var (disable, alphaOffset, betaOffset) = sliceFilters[s];
var qpav = (mbQp[pm] + mbQp[m] + 1) >> 1; if (disable == 1)
var indexA = Math.Clamp(qpav + alphaOffset, 0, 51);
var indexB = Math.Clamp(qpav + betaOffset, 0, 51);
int alpha = H264Tables.Alpha[indexA], beta = H264Tables.Beta[indexB];
if (alpha == 0 || beta == 0)
{ {
continue; continue;
} }
for (var k = 0; k < 16; k++) var isField = field[m];
int lumaOrigin, stride, chromaOrigin, cstride;
if (isField)
{ {
var strength = bs[(edge * 4) + (k >> 2)]; lumaOrigin = (((pairY * 32) + bottom) * width) + (mx * 16);
if (strength == 0) chromaOrigin = (((pairY * 16) + bottom) * cwidth) + (mx * 8);
{ stride = 2 * width;
continue; cstride = 2 * cwidth;
} }
else
{
lumaOrigin = ((((2 * pairY) + bottom) * 16) * width) + (mx * 16);
chromaOrigin = ((((2 * pairY) + bottom) * 8) * cwidth) + (mx * 8);
stride = width;
cstride = cwidth;
}
int o, step; // Left edge.
if (dir == 0) var leftTop = (2 * pairY * w) + mx - 1;
if (mx > 0 && mbSlice[leftTop] >= 0 && (disable != 2 || mbSlice[leftTop] == s))
{
var leftField = field[leftTop];
if (leftField == isField)
{ {
o = (((my * 16) + k) * stride) + (mx * 16) + (edge * 4); MbEdge(picture, leftTop + (bottom * w), m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
step = 1;
} }
else else
{ {
o = (((my * 16) + (edge * 4)) * stride) + (mx * 16) + k; MixedLeftEdge(picture, m, leftTop, isField, bottom != 0, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, rowBs, rowMb);
step = stride;
} }
FilterLuma(picture.Y, o, step, strength, alpha, beta, indexA);
}
}
// Chroma (4:2:0): the edges at 0 and 4 chroma samples, with the strength of luma edges 0 and 2.
for (var ce = 0; ce < 2; ce++)
{
var edge = ce * 2;
if ((bs[edge * 4] | bs[(edge * 4) + 1] | bs[(edge * 4) + 2] | bs[(edge * 4) + 3]) == 0)
{
continue;
} }
var pm = edge == 0 ? neighbour : m; InnerEdges(picture, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
for (var c = 0; c < 2; c++)
// Top edge.
if (!isField && bottom == 1)
{ {
var plane = c == 0 ? picture.Cb : picture.Cr; MbEdge(picture, m - w, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
var qpav = (mbQpC[(pm * 2) + c] + mbQpC[(m * 2) + c] + 1) >> 1; }
var indexA = Math.Clamp(qpav + alphaOffset, 0, 51); else if (pairY > 0)
var indexB = Math.Clamp(qpav + betaOffset, 0, 51); {
int alpha = H264Tables.Alpha[indexA], beta = H264Tables.Beta[indexB]; var aboveTop = (((2 * pairY) - 2) * w) + mx;
if (alpha == 0 || beta == 0) if (mbSlice[aboveTop] >= 0 && (disable != 2 || mbSlice[aboveTop] == s))
{ {
continue; if (!isField && field[aboveTop])
}
for (var k = 0; k < 8; k++)
{
var strength = bs[(edge * 4) + (k >> 1)];
if (strength == 0)
{ {
continue; // A frame macroblock under a field pair: each field of its top rows against that field.
} for (var j = 0; j < 2; j++)
{
int o, step; MbEdge(picture, aboveTop + (j * w), m, false, lumaOrigin + (j * width), 2 * width, chromaOrigin + (j * cwidth), 2 * cwidth, alphaOffset, betaOffset, bs);
if (dir == 0) }
{
o = (((my * 8) + k) * cstride) + (mx * 8) + (ce * 4);
step = 1;
} }
else else
{ {
o = (((my * 8) + (ce * 4)) * cstride) + (mx * 8) + k; var pm = isField && bottom == 0 && field[aboveTop] ? aboveTop : aboveTop + w;
step = cstride; MbEdge(picture, pm, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
} }
FilterChroma(plane, o, step, strength, alpha, beta, indexA);
} }
} }
InnerEdges(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
} }
} }
} }
} }
/// <summary>bS of the edge between 4×4 luma blocks <paramref name="pb"/> of <paramref name="pm"/> and <paramref name="qb"/> of <paramref name="qm"/> (§8.7.2.1).</summary> /// <summary>
private int BoundaryStrength(Picture picture, int pm, int pb, int qm, int qb, bool mbEdge) /// 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.
/// </summary>
private void MixedLeftEdge(
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)
{ {
var w = widthInMbs;
var leftField = picture.MbField[leftTop];
for (var r = 0; r < 16; r++)
{
var pm = LeftOfPair(leftTop, w, leftField, isField, bottom, r, 16, out var yM);
rowMb[r] = pm;
rowBs[r] = (byte)BoundaryStrength(picture, pm, (((yM & 15) >> 2) * 4) + 3, m, (r >> 2) * 4, true, true);
}
for (var r = 0; r < 16; r++)
{
if (rowBs[r] == 0)
{
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)
{
FilterLuma(picture.Y, lumaOrigin + (r * stride), 1, rowBs[r], alpha, beta, indexA);
}
}
for (var k = 0; k < 8; k++)
{
var lumaRow = isField && !leftField ? 2 * k : (4 * (k >> 1)) + (k & 1);
var strength = rowBs[lumaRow];
if (strength == 0)
{
continue;
}
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)
{
FilterChroma(c == 0 ? picture.Cb : picture.Cr, chromaOrigin + (k * cstride), 1, strength, alpha, beta, indexA);
}
}
}
}
/// <summary>A macroblock edge between <paramref name="pm"/> (left or above) and <paramref name="qm"/>, luma and chroma.</summary>
private void MbEdge(
Picture picture, int pm, int qm, bool vertical, int lumaOrigin, int stride, int chromaOrigin, int cstride, int alphaOffset, int betaOffset, Span<byte> bs)
{
for (var i = 0; i < 4; i++)
{
int qb = vertical ? i * 4 : i, pb = vertical ? (i * 4) + 3 : 12 + i;
bs[i] = (byte)BoundaryStrength(picture, pm, pb, qm, qb, true, vertical);
}
if ((bs[0] | bs[1] | bs[2] | bs[3]) == 0)
{
return;
}
int along = vertical ? stride : 1, across = vertical ? 1 : stride;
LumaEdge(picture.Y, lumaOrigin, along, across, bs, mbQp[pm], mbQp[qm], alphaOffset, betaOffset);
int calong = vertical ? cstride : 1, cacross = vertical ? 1 : cstride;
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);
}
}
/// <summary>The internal edges of macroblock <paramref name="m"/> in one direction (luma 4, 8, 12; chroma 4).</summary>
private void InnerEdges(
Picture picture, int m, bool vertical, int lumaOrigin, int stride, int chromaOrigin, int cstride, int alphaOffset, int betaOffset, Span<byte> bs)
{
var t8 = mbT8[m];
int along = vertical ? stride : 1, across = vertical ? 1 : stride;
int calong = vertical ? cstride : 1, cacross = vertical ? 1 : cstride;
for (var edge = 1; edge < 4; edge++)
{
if (t8 && (edge & 1) != 0)
{
continue;
}
for (var i = 0; i < 4; i++)
{
var qb = vertical ? (i * 4) + edge : (edge * 4) + i;
bs[i] = (byte)BoundaryStrength(picture, m, qb - (vertical ? 1 : 4), m, qb, false, vertical);
}
if ((bs[0] | bs[1] | bs[2] | bs[3]) == 0)
{
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)
{
var coffset = 4 * (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);
}
}
}
}
private static void LumaEdge(byte[] plane, int origin, int along, int across, ReadOnlySpan<byte> bs, int qpP, int qpQ, int alphaOffset, int betaOffset)
{
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);
}
}
}
private static void ChromaEdge(byte[] plane, int origin, int along, int across, ReadOnlySpan<byte> bs, int qpP, int qpQ, int alphaOffset, int betaOffset)
{
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 < 8; k++)
{
var strength = bs[k >> 1];
if (strength != 0)
{
FilterChroma(plane, origin + (k * along), across, strength, alpha, beta, indexA);
}
}
}
/// <summary>
/// bS of the edge between 4×4 luma blocks <paramref name="pb"/> of <paramref name="pm"/> and <paramref name="qb"/> of
/// <paramref name="qm"/> (§8.7.2.1). Field macroblocks (all those of a field picture) take 4 only across vertical
/// edges and compare vertical vectors in field units; between a frame and a field macroblock (mixed edges of MBAFF
/// frames) it is at least 1.
/// </summary>
private int BoundaryStrength(Picture picture, int pm, int pb, int qm, int qb, bool mbEdge, bool vertical)
{
bool fieldP = picture.MbField[pm], fieldQ = picture.MbField[qm];
if (picture.MbIntra[pm] || picture.MbIntra[qm]) if (picture.MbIntra[pm] || picture.MbIntra[qm])
{ {
return mbEdge ? 4 : 3; return mbEdge && (vertical || (!fieldP && !fieldQ)) ? 4 : 3;
} }
if (HasCoefficients(pm, pb) || HasCoefficients(qm, qb)) if (HasCoefficients(pm, pb) || HasCoefficients(qm, qb))
@@ -173,14 +351,20 @@ public sealed partial class H264Decoder
return 2; return 2;
} }
if (fieldP != fieldQ)
{
return 1;
}
var limit = fieldQ ? 2 : 4;
int pi = (pm * 4) + B8OfRaster(pb), qi = (qm * 4) + B8OfRaster(qb); int pi = (pm * 4) + B8OfRaster(pb), qi = (qm * 4) + B8OfRaster(qb);
var l1 = mbCount * 4; var l1 = mbCount * 4;
var p0 = picture.RefIdx[pi] >= 0 ? picture.RefPic[pi] ?? picture : null; var p0 = UsedReference(picture, pi);
var p1 = picture.RefIdx[l1 + pi] >= 0 ? picture.RefPic[l1 + pi] ?? picture : null; var p1 = UsedReference(picture, l1 + pi);
var q0 = picture.RefIdx[qi] >= 0 ? picture.RefPic[qi] ?? picture : null; var q0 = UsedReference(picture, qi);
var q1 = picture.RefIdx[l1 + qi] >= 0 ? picture.RefPic[l1 + qi] ?? picture : null; var q1 = UsedReference(picture, l1 + qi);
var countP = (p0 is null ? 0 : 1) + (p1 is null ? 0 : 1); var countP = (p0.Pic is null ? 0 : 1) + (p1.Pic is null ? 0 : 1);
var countQ = (q0 is null ? 0 : 1) + (q1 is null ? 0 : 1); var countQ = (q0.Pic is null ? 0 : 1) + (q1.Pic is null ? 0 : 1);
if (countP != countQ) if (countP != countQ)
{ {
return 1; return 1;
@@ -192,14 +376,14 @@ public sealed partial class H264Decoder
int pv1 = l1Mv + pv0, qv1 = l1Mv + qv0; int pv1 = l1Mv + pv0, qv1 = l1Mv + qv0;
if (countP == 1) if (countP == 1)
{ {
var refP = p0 ?? p1; var refP = p0.Pic is not null ? p0 : p1;
var refQ = q0 ?? q1; var refQ = q0.Pic is not null ? q0 : q1;
if (!ReferenceEquals(refP, refQ)) if (refP != refQ)
{ {
return 1; return 1;
} }
return MvFar(mv, p0 is not null ? pv0 : pv1, q0 is not null ? qv0 : qv1) ? 1 : 0; return MvFar(mv, p0.Pic is not null ? pv0 : pv1, q0.Pic is not null ? qv0 : qv1, limit) ? 1 : 0;
} }
if (countP == 0) if (countP == 0)
@@ -207,26 +391,31 @@ public sealed partial class H264Decoder
return 0; return 0;
} }
var sameSet = (ReferenceEquals(p0, q0) && ReferenceEquals(p1, q1)) || (ReferenceEquals(p0, q1) && ReferenceEquals(p1, q0)); var sameSet = (p0 == q0 && p1 == q1) || (p0 == q1 && p1 == q0);
if (!sameSet) if (!sameSet)
{ {
return 1; return 1;
} }
if (!ReferenceEquals(p0, p1)) if (p0 != p1)
{ {
return ReferenceEquals(p0, q0) return p0 == q0
? (MvFar(mv, pv0, qv0) || MvFar(mv, pv1, qv1) ? 1 : 0) ? (MvFar(mv, pv0, qv0, limit) || MvFar(mv, pv1, qv1, limit) ? 1 : 0)
: (MvFar(mv, pv0, qv1) || MvFar(mv, pv1, qv0) ? 1 : 0); : (MvFar(mv, pv0, qv1, limit) || MvFar(mv, pv1, qv0, limit) ? 1 : 0);
} }
// Both motion vectors of both blocks refer to the same picture. // Both motion vectors of both blocks refer to the same picture.
var straight = MvFar(mv, pv0, qv0) || MvFar(mv, pv1, qv1); var straight = MvFar(mv, pv0, qv0, limit) || MvFar(mv, pv1, qv1, limit);
var crossed = MvFar(mv, pv0, qv1) || MvFar(mv, pv1, qv0); var crossed = MvFar(mv, pv0, qv1, limit) || MvFar(mv, pv1, qv0, limit);
return straight && crossed ? 1 : 0; return straight && crossed ? 1 : 0;
} }
private static bool MvFar(short[] mv, int a, int b) => Math.Abs(mv[a] - mv[b]) >= 4 || Math.Abs(mv[a + 1] - mv[b + 1]) >= 4; /// <summary>The picture (frame, or field of a frame store) a block refers to in a list; empty when the list is not used.</summary>
private static RefEntry UsedReference(Picture picture, int index) =>
picture.RefIdx[index] < 0 ? default : new RefEntry(picture.RefPic[index] ?? picture, picture.RefPar[index]);
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;
private bool HasCoefficients(int m, int blk) private bool HasCoefficients(int m, int blk)
{ {
@@ -10,7 +10,7 @@ public sealed partial class H264Decoder
private int ReadMbSkip() private int ReadMbSkip()
{ {
var inc = (availA && !IsSkip(mb - 1) ? 1 : 0) + (availB && !IsSkip(mb - widthInMbs) ? 1 : 0); var inc = (mbA >= 0 && !IsSkip(mbA) ? 1 : 0) + (mbB >= 0 && !IsSkip(mbB) ? 1 : 0);
return cabac.Decision((sh.IsB ? 24 : 11) + inc); return cabac.Decision((sh.IsB ? 24 : 11) + inc);
} }
@@ -25,8 +25,8 @@ public sealed partial class H264Decoder
{ {
case SliceType.I: case SliceType.I:
{ {
var inc = (availA && mbKind[mb - 1] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0) var inc = (mbA >= 0 && mbKind[mbA] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0)
+ (availB && mbKind[mb - widthInMbs] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0); + (mbB >= 0 && mbKind[mbB] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0);
if (cabac.Decision(3 + inc) == 0) if (cabac.Decision(3 + inc) == 0)
{ {
return 0; return 0;
@@ -49,8 +49,8 @@ public sealed partial class H264Decoder
return 5 + (cabac.Decision(17) == 0 ? 0 : IntraMbTypeSuffix(17, intraSlice: false)); return 5 + (cabac.Decision(17) == 0 ? 0 : IntraMbTypeSuffix(17, intraSlice: false));
default: default:
{ {
var inc = (availA && mbKind[mb - 1] is not (MbKind.BSkip or MbKind.BDirect) ? 1 : 0) var inc = (mbA >= 0 && mbKind[mbA] is not (MbKind.BSkip or MbKind.BDirect) ? 1 : 0)
+ (availB && mbKind[mb - widthInMbs] is not (MbKind.BSkip or MbKind.BDirect) ? 1 : 0); + (mbB >= 0 && mbKind[mbB] is not (MbKind.BSkip or MbKind.BDirect) ? 1 : 0);
if (cabac.Decision(27 + inc) == 0) if (cabac.Decision(27 + inc) == 0)
{ {
return 0; return 0;
@@ -202,7 +202,9 @@ public sealed partial class H264Decoder
return 0; return 0;
} }
return cur!.RefIdx[(((list * mbCount) + n) * 4) + b8] > 0 ? 1 : 0; // A field neighbour of a frame macroblock counts in fields: index 1 is still the first frame (§9.3.3.1.1.6).
var zero = mbaff && !mbField && cur!.MbField[n] ? 1 : 0;
return cur!.RefIdx[(((list * mbCount) + n) * 4) + b8] > zero ? 1 : 0;
} }
private int ReadMvd(int list, int comp, int px, int py) private int ReadMvd(int list, int comp, int px, int py)
@@ -256,7 +258,14 @@ public sealed partial class H264Decoder
return 0; return 0;
} }
return mvdAbs[(((((list * mbCount) + n) * 16) + blk) * 2) + comp]; int value = mvdAbs[(((((list * mbCount) + n) * 16) + blk) * 2) + comp];
if (comp == 1 && mbaff && cur!.MbField[n] != mbField)
{
// Vertical differences in the units of the current macroblock (§9.3.3.1.1.7).
value = mbField ? value / 2 : value * 2;
}
return value;
} }
private bool ReadTransform8x8() private bool ReadTransform8x8()
@@ -266,7 +275,7 @@ public sealed partial class H264Decoder
return rd.ReadFlag(); return rd.ReadFlag();
} }
var inc = (availA && mbT8[mb - 1] ? 1 : 0) + (availB && mbT8[mb - widthInMbs] ? 1 : 0); var inc = (mbA >= 0 && mbT8[mbA] ? 1 : 0) + (mbB >= 0 && mbT8[mbB] ? 1 : 0);
return cabac.Decision(399 + inc) != 0; return cabac.Decision(399 + inc) != 0;
} }
@@ -295,7 +304,7 @@ public sealed partial class H264Decoder
return rd.ReadUe(3); return rd.ReadUe(3);
} }
var inc = ChromaModeCond(availA, mb - 1) + ChromaModeCond(availB, mb - widthInMbs); var inc = ChromaModeCond(mbA) + ChromaModeCond(mbB);
if (cabac.Decision(64 + inc) == 0) if (cabac.Decision(64 + inc) == 0)
{ {
return 0; return 0;
@@ -309,8 +318,8 @@ public sealed partial class H264Decoder
return cabac.Decision(67) == 0 ? 2 : 3; return cabac.Decision(67) == 0 ? 2 : 3;
} }
private int ChromaModeCond(bool available, int n) => private int ChromaModeCond(int n) =>
available && IsIntra(n) && mbKind[n] != MbKind.IPcm && chromaModes[n] != 0 ? 1 : 0; n >= 0 && IsIntra(n) && mbKind[n] != MbKind.IPcm && chromaModes[n] != 0 ? 1 : 0;
private int ReadCbp(bool intra) private int ReadCbp(bool intra)
{ {
@@ -331,7 +340,8 @@ public sealed partial class H264Decoder
} }
else else
{ {
condA = availA && ((mbCbp[mb - 1] >> (b8 + 1)) & 1) == 0 ? 1 : 0; var n = Locate(-1, by * 8, 16, out var yM);
condA = n >= 0 && ((mbCbp[n] >> ((((yM & 15) >> 3) * 2) + 1)) & 1) == 0 ? 1 : 0;
} }
if (by == 1) if (by == 1)
@@ -340,14 +350,15 @@ public sealed partial class H264Decoder
} }
else else
{ {
condB = availB && ((mbCbp[mb - widthInMbs] >> (b8 + 2)) & 1) == 0 ? 1 : 0; var n = Locate(bx * 8, -1, 16, out _);
condB = n >= 0 && ((mbCbp[n] >> (b8 + 2)) & 1) == 0 ? 1 : 0;
} }
cbp |= cabac.Decision(73 + condA + (2 * condB)) << b8; cbp |= cabac.Decision(73 + condA + (2 * condB)) << b8;
} }
var a = availA ? mbCbp[mb - 1] >> 4 : 0; var a = mbA >= 0 ? mbCbp[mbA] >> 4 : 0;
var b = availB ? mbCbp[mb - widthInMbs] >> 4 : 0; var b = mbB >= 0 ? mbCbp[mbB] >> 4 : 0;
var inc = (a != 0 ? 1 : 0) + (b != 0 ? 2 : 0); var inc = (a != 0 ? 1 : 0) + (b != 0 ? 2 : 0);
if (cabac.Decision(77 + inc) != 0) if (cabac.Decision(77 + inc) != 0)
{ {
@@ -556,9 +567,9 @@ public sealed partial class H264Decoder
{ {
nA = nz[(mb * 24) + raster - 1]; nA = nz[(mb * 24) + raster - 1];
} }
else if (availA) else if (Locate(-1, by * 4, 16, out var yM) is var a and >= 0)
{ {
nA = nz[((mb - 1) * 24) + raster + 3]; nA = nz[(a * 24) + (((yM & 15) >> 2) * 4) + 3];
} }
else else
{ {
@@ -569,9 +580,9 @@ public sealed partial class H264Decoder
{ {
nB = nz[(mb * 24) + raster - 4]; nB = nz[(mb * 24) + raster - 4];
} }
else if (availB) else if (Locate(bx * 4, -1, 16, out _) is var b and >= 0)
{ {
nB = nz[((mb - widthInMbs) * 24) + raster + 12]; nB = nz[(b * 24) + 12 + bx];
} }
else else
{ {
@@ -591,9 +602,9 @@ public sealed partial class H264Decoder
{ {
nA = nz[(mb * 24) + baseIndex + b - 1]; nA = nz[(mb * 24) + baseIndex + b - 1];
} }
else if (availA) else if (Locate(-1, by * 4, 8, out var yM) is var a and >= 0)
{ {
nA = nz[((mb - 1) * 24) + baseIndex + b + 1]; nA = nz[(a * 24) + baseIndex + (((yM & 7) >> 2) * 2) + 1];
} }
else else
{ {
@@ -604,9 +615,9 @@ public sealed partial class H264Decoder
{ {
nB = nz[(mb * 24) + baseIndex + b - 2]; nB = nz[(mb * 24) + baseIndex + b - 2];
} }
else if (availB) else if (Locate(bx * 4, -1, 8, out _) is var n and >= 0)
{ {
nB = nz[((mb - widthInMbs) * 24) + baseIndex + b + 2]; nB = nz[(n * 24) + baseIndex + 2 + bx];
} }
else else
{ {
@@ -636,24 +647,26 @@ public sealed partial class H264Decoder
} }
} }
// Blocks of field macroblocks have their own significance contexts (Table 9-34).
int sigBase, lastBase, absBase; int sigBase, lastBase, absBase;
if (cat == 5) if (cat == 5)
{ {
(sigBase, lastBase, absBase) = (402, 417, 426); (sigBase, lastBase, absBase) = mbField ? (436, 451, 426) : (402, 417, 426);
} }
else else
{ {
sigBase = 105 + SigCatOffset[cat]; sigBase = (mbField ? 277 : 105) + SigCatOffset[cat];
lastBase = 166 + SigCatOffset[cat]; lastBase = (mbField ? 338 : 166) + SigCatOffset[cat];
absBase = 227 + AbsCatOffset[cat]; absBase = 227 + AbsCatOffset[cat];
} }
var sig8x8 = mbField ? H264Tables.SignificantContext8x8Field : H264Tables.SignificantContext8x8;
Span<bool> significant = stackalloc bool[64]; Span<bool> significant = stackalloc bool[64];
significant.Clear(); significant.Clear();
var last = -1; var last = -1;
for (var i = 0; i < maxNum - 1; i++) for (var i = 0; i < maxNum - 1; i++)
{ {
var ctx = cat == 5 ? H264Tables.SignificantContext8x8[i] : cat == 3 ? Math.Min(i, 2) : i; var ctx = cat == 5 ? sig8x8[i] : cat == 3 ? Math.Min(i, 2) : i;
if (cabac.Decision(sigBase + ctx) == 0) if (cabac.Decision(sigBase + ctx) == 0)
{ {
continue; continue;
@@ -743,12 +756,12 @@ public sealed partial class H264Decoder
switch (cat) switch (cat)
{ {
case 0: case 0:
if (!(left ? availA : availB)) n = left ? mbA : mbB;
if (n < 0)
{ {
return currentIntra ? 1 : 0; return currentIntra ? 1 : 0;
} }
n = left ? mb - 1 : mb - widthInMbs;
if (mbKind[n] == MbKind.IPcm) if (mbKind[n] == MbKind.IPcm)
{ {
return 1; return 1;
@@ -756,12 +769,12 @@ public sealed partial class H264Decoder
return mbKind[n] == MbKind.I16x16 ? cbfDc[n] & 1 : 0; return mbKind[n] == MbKind.I16x16 ? cbfDc[n] & 1 : 0;
case 3: case 3:
if (!(left ? availA : availB)) n = left ? mbA : mbB;
if (n < 0)
{ {
return currentIntra ? 1 : 0; return currentIntra ? 1 : 0;
} }
n = left ? mb - 1 : mb - widthInMbs;
if (mbKind[n] == MbKind.IPcm) if (mbKind[n] == MbKind.IPcm)
{ {
return 1; return 1;
@@ -778,13 +791,13 @@ public sealed partial class H264Decoder
} }
else else
{ {
if (!(left ? availA : availB)) n = left ? Locate(-1, by * 4, 8, out var yM) : Locate(bx * 4, -1, 8, out yM);
if (n < 0)
{ {
return currentIntra ? 1 : 0; return currentIntra ? 1 : 0;
} }
n = left ? mb - 1 : mb - widthInMbs; index = left ? ((((yM & 7) >> 2) * 2) + 1) : 2 + bx;
index = left ? blk + 1 : blk + 2;
} }
if (mbKind[n] == MbKind.IPcm) if (mbKind[n] == MbKind.IPcm)
@@ -805,13 +818,13 @@ public sealed partial class H264Decoder
} }
else else
{ {
if (!(left ? availA : availB)) n = left ? Locate(-1, by * 4, 16, out var yM) : Locate(bx * 4, -1, 16, out yM);
if (n < 0)
{ {
return currentIntra ? 1 : 0; return currentIntra ? 1 : 0;
} }
n = left ? mb - 1 : mb - widthInMbs; index = left ? ((((yM & 15) >> 2) * 4) + 3) : 12 + bx;
index = left ? blk + 3 : blk + 12;
} }
if (mbKind[n] == MbKind.IPcm) if (mbKind[n] == MbKind.IPcm)
+257 -118
View File
@@ -3,8 +3,13 @@ namespace Febe.Core.Codecs.H264;
public sealed partial class H264Decoder public sealed partial class H264Decoder
{ {
private int weightMode; private int weightMode;
/// <summary>Implicit weights w0 of the slice by (refIdxL0, refIdxL1): frames, or the fields of a field picture.</summary>
private int[] implicitW0 = []; private int[] implicitW0 = [];
/// <summary>MBAFF: implicit weights of the field macroblocks, by parity of the macroblock.</summary>
private int[][] implicitField = [[], []];
/// <summary> /// <summary>
/// The neighbouring 4×4 luma block covering (<paramref name="xN"/>, <paramref name="yN"/>) relative to the current /// The neighbouring 4×4 luma block covering (<paramref name="xN"/>, <paramref name="yN"/>) relative to the current
/// macroblock (§6.4.12): 0 not available, 1 in another macroblock, 2 in the current one (its availability then /// macroblock (§6.4.12): 0 not available, 1 in another macroblock, 2 in the current one (its availability then
@@ -12,66 +17,29 @@ public sealed partial class H264Decoder
/// </summary> /// </summary>
private int Neighbor(int xN, int yN, out int n, out int blk) private int Neighbor(int xN, int yN, out int n, out int blk)
{ {
blk = (((yN & 15) >> 2) * 4) + ((xN & 15) >> 2); if ((uint)xN < 16 && (uint)yN < 16)
n = -1;
if (yN < 0)
{ {
if (xN < 0) n = mb;
{ blk = ((yN >> 2) * 4) + (xN >> 2);
if (!availD) return 2;
{
return 0;
}
n = mb - widthInMbs - 1;
}
else if (xN < 16)
{
if (!availB)
{
return 0;
}
n = mb - widthInMbs;
}
else
{
if (!availC)
{
return 0;
}
n = mb - widthInMbs + 1;
}
return 1;
} }
if (yN >= 16) n = Locate(xN, yN, 16, out var yM);
if (n < 0)
{ {
blk = 0;
return 0; return 0;
} }
if (xN < 0) blk = (((yM & 15) >> 2) * 4) + ((xN & 15) >> 2);
{ return 1;
if (!availA)
{
return 0;
}
n = mb - 1;
return 1;
}
if (xN >= 16)
{
return 0;
}
n = mb;
return 2;
} }
/// <summary>
/// Motion of a neighbouring block (§8.4.1.3.2); in an MBAFF frame brought to the units of the current macroblock:
/// a frame neighbour of a field macroblock has its vertical vector halved and its index doubled, a field neighbour
/// of a frame macroblock the reverse.
/// </summary>
private (bool Available, int RefIdx, int X, int Y) MotionNeighbor(int list, int xN, int yN) private (bool Available, int RefIdx, int X, int Y) MotionNeighbor(int list, int xN, int yN)
{ {
var where = Neighbor(xN, yN, out var n, out var blk); var where = Neighbor(xN, yN, out var n, out var blk);
@@ -81,14 +49,29 @@ public sealed partial class H264Decoder
} }
var picture = cur!; var picture = cur!;
var refIdx = picture.RefIdx[(((list * mbCount) + n) * 4) + B8OfRaster(blk)]; int refIdx = picture.RefIdx[(((list * mbCount) + n) * 4) + B8OfRaster(blk)];
if (refIdx < 0 || picture.MbIntra[n]) if (refIdx < 0 || picture.MbIntra[n])
{ {
return (true, -1, 0, 0); return (true, -1, 0, 0);
} }
var i = ((((list * mbCount) + n) * 16) + blk) * 2; var i = ((((list * mbCount) + n) * 16) + blk) * 2;
return (true, refIdx, picture.Mv[i], picture.Mv[i + 1]); int x = picture.Mv[i], y = picture.Mv[i + 1];
if (mbaff && picture.MbField[n] != mbField)
{
if (mbField)
{
y /= 2;
refIdx *= 2;
}
else
{
y *= 2;
refIdx >>= 1;
}
}
return (true, refIdx, x, y);
} }
/// <summary> /// <summary>
@@ -185,7 +168,8 @@ public sealed partial class H264Decoder
private void PredictDirect(int first, int end) private void PredictDirect(int first, int end)
{ {
var picture = cur!; var picture = cur!;
var col = Reference(1, 0); var colEntry = Reference(1, 0);
var col = colEntry.Pic!;
var inference = sps.Direct8x8Inference; var inference = sps.Direct8x8Inference;
int ref0 = -1, ref1 = -1; int ref0 = -1, ref1 = -1;
@@ -233,21 +217,84 @@ public sealed partial class H264Decoder
} }
} }
// The co-located macroblock (§8.4.1.2.1, Tables 8-6 and 8-8), on the frame grid of RefPicList1[0]: a field
// macroblock of a frame macroblock takes the field of the pair closer in order (Fld_To_Frm), a field one of a
// frame macroblock the frame macroblock covering its rows (Frm_To_Fld).
var w = widthInMbs;
var colInterlaced = col.MbField[(mbY * w) + mbX];
int colParity = 0;
if (colInterlaced)
{
if (!mbField)
{
var poc = picture.Poc;
colParity = Math.Abs(col.TopPoc - poc) < Math.Abs(col.BottomPoc - poc) ? 0 : 1;
}
else
{
colParity = fieldPic && col.CodedAsFields ? colEntry.Parity : mbY & 1;
}
}
var colShort = !colEntry.IsLongTerm;
for (var sub = first; sub < end; sub++) for (var sub = first; sub < end; sub++)
{ {
for (var k = 0; k < 4; k++) for (var k = 0; k < 4; k++)
{ {
var blk = ((((sub >> 1) * 2) + (k >> 1)) * 4) + ((sub & 1) * 2) + (k & 1); var blk = ((((sub >> 1) * 2) + (k >> 1)) * 4) + ((sub & 1) * 2) + (k & 1);
var colBlk = inference ? sub switch { 0 => 0, 1 => 3, 2 => 12, _ => 15 } : blk; int xCol, yCol;
int colX = 0, colY = 0, colRef = -1; if (inference)
{
xCol = (sub & 1) * 12;
yCol = (sub >> 1) * 12;
}
else
{
xCol = (blk & 3) * 4;
yCol = (blk >> 2) * 4;
}
int colRow, yM, vertical;
if (colInterlaced)
{
colRow = (mbY & ~1) + colParity;
if (!mbField)
{
yM = (8 * (mbY & 1)) + (4 * (yCol / 8));
vertical = 2; // Fld_To_Frm
}
else
{
yM = yCol;
vertical = 0;
}
}
else if (mbField)
{
colRow = (mbY & ~1) + (yCol / 8);
yM = (2 * yCol) % 16;
vertical = 1; // Frm_To_Fld
}
else
{
colRow = mbY;
yM = yCol;
vertical = 0;
}
var colMb = (colRow * w) + mbX;
var colBlk = ((yM >> 2) * 4) + (xCol >> 2);
int colX = 0, colY = 0, colRef = -1, colRefPar = -1;
Picture? colRefPic = null; Picture? colRefPic = null;
if (!col.MbIntra[mb]) if (!col.MbIntra[colMb])
{ {
var colB8 = B8OfRaster(colBlk); var colB8 = B8OfRaster(colBlk);
var list = col.RefIdx[(mb * 4) + colB8] >= 0 ? 0 : 1; var list = col.RefIdx[(colMb * 4) + colB8] >= 0 ? 0 : 1;
colRef = col.RefIdx[(((list * mbCount) + mb) * 4) + colB8]; var index = (((list * mbCount) + colMb) * 4) + colB8;
colRefPic = col.RefPic[(((list * mbCount) + mb) * 4) + colB8]; colRef = col.RefIdx[index];
var i = ((((list * mbCount) + mb) * 16) + colBlk) * 2; colRefPic = col.RefPic[index];
colRefPar = col.RefPar[index];
var i = ((((list * mbCount) + colMb) * 16) + colBlk) * 2;
colX = col.Mv[i]; colX = col.Mv[i];
colY = col.Mv[i + 1]; colY = col.Mv[i + 1];
} }
@@ -255,7 +302,7 @@ public sealed partial class H264Decoder
int r0, r1, m0x, m0y, m1x, m1y; int r0, r1, m0x, m0y, m1x, m1y;
if (sh.DirectSpatialMvPred) if (sh.DirectSpatialMvPred)
{ {
var colZero = !col.LongTerm && colRef == 0 && colX is >= -1 and <= 1 && colY is >= -1 and <= 1; var colZero = colShort && colRef == 0 && colX is >= -1 and <= 1 && colY is >= -1 and <= 1;
r0 = ref0; r0 = ref0;
r1 = ref1; r1 = ref1;
if (directZero || (r0 == 0 && colZero)) if (directZero || (r0 == 0 && colZero))
@@ -278,18 +325,29 @@ public sealed partial class H264Decoder
} }
else else
{ {
r0 = colRef < 0 ? 0 : MapColToList0(colRefPic); if (vertical == 1)
{
colY /= 2;
}
else if (vertical == 2)
{
colY *= 2;
}
r0 = colRef < 0 ? 0 : MapColToList0(colRefPic, colRefPar);
r1 = 0; r1 = 0;
var pic0 = Reference(0, r0); var pic0 = Reference(0, r0);
var td = Math.Clamp(col.Poc - pic0.Poc, -128, 127); var pic1 = Reference(1, 0);
if (pic0.LongTerm || td == 0) var td = Math.Clamp(pic1.Poc - pic0.Poc, -128, 127);
if (pic0.IsLongTerm || td == 0)
{ {
(m0x, m0y) = (colX, colY); (m0x, m0y) = (colX, colY);
(m1x, m1y) = (0, 0); (m1x, m1y) = (0, 0);
} }
else else
{ {
var tb = Math.Clamp(picture.Poc - pic0.Poc, -128, 127); var curPoc = mbField ? picture.PocOf(mbY & 1) : picture.Poc;
var tb = Math.Clamp(curPoc - pic0.Poc, -128, 127);
var tx = (16384 + Math.Abs(td / 2)) / td; var tx = (16384 + Math.Abs(td / 2)) / td;
var scale = Math.Clamp(((tb * tx) + 32) >> 6, -1024, 1023); var scale = Math.Clamp(((tb * tx) + 32) >> 6, -1024, 1023);
m0x = ((scale * colX) + 128) >> 8; m0x = ((scale * colX) + 128) >> 8;
@@ -320,24 +378,39 @@ public sealed partial class H264Decoder
private void SetDirectRef(int list, int b8, int refIdx) private void SetDirectRef(int list, int b8, int refIdx)
{ {
var index = (((list * mbCount) + mb) * 4) + b8; var index = (((list * mbCount) + mb) * 4) + b8;
var active = list == 0 ? sh.NumRefIdxActiveL0 : sh.NumRefIdxActiveL1; if (refIdx < 0 || refIdx >= RefIdxRange(list))
if (refIdx < 0 || refIdx >= active)
{ {
cur!.RefIdx[index] = -1; cur!.RefIdx[index] = -1;
cur.RefPic[index] = null; cur.RefPic[index] = null;
cur.RefPar[index] = -1;
return; return;
} }
var entry = Reference(list, refIdx);
cur!.RefIdx[index] = (sbyte)refIdx; cur!.RefIdx[index] = (sbyte)refIdx;
cur.RefPic[index] = Reference(list, refIdx); cur.RefPic[index] = entry.Pic;
cur.RefPar[index] = (sbyte)entry.Parity;
} }
private int MapColToList0(Picture? picture) /// <summary>
/// The lowest index of list 0 referring to the picture the co-located block referred to (§8.4.1.2.3): for a field
/// macroblock that field, or the field of that frame with the parity of the macroblock; for a frame macroblock the
/// frame (or the frame containing that field).
/// </summary>
private int MapColToList0(Picture? picture, int parity)
{ {
var list = refList[0]; if (picture is null)
for (var i = 0; i < list.Length; i++)
{ {
if (ReferenceEquals(list[i], picture)) return 0;
}
var fieldOf = MbFieldOf;
var target = mbField ? (parity >= 0 ? parity : mbY & 1) : -1;
var count = RefIdxRange(0);
for (var i = 0; i < count; i++)
{
var e = ListEntry(0, i, fieldOf);
if (ReferenceEquals(e.Pic, picture) && e.Parity == target)
{ {
return i; return i;
} }
@@ -346,20 +419,46 @@ public sealed partial class H264Decoder
return 0; return 0;
} }
/// <summary>A reference picture of the slice; a substitute when the stream refers to a missing one.</summary> /// <summary>For a field macroblock of an MBAFF frame its parity (its references are fields of the frame lists), else −1.</summary>
private Picture Reference(int list, int refIdx) private int MbFieldOf => mbaff && mbField ? mbY & 1 : -1;
/// <summary>
/// The entry of a list for a reference index: as built, or (<paramref name="fieldOf"/> ≥ 0) for a field macroblock
/// of that parity in an MBAFF frame, the field of frame refIdx / 2 with the same parity for even indices, the
/// opposite for odd ones (§8.4.2.1). Empty when missing.
/// </summary>
private RefEntry ListEntry(int list, int refIdx, int fieldOf)
{ {
var l = refList[list]; var l = refList[list];
if ((uint)refIdx < (uint)l.Length && l[refIdx] is { } p) if (fieldOf < 0)
{ {
return p; return (uint)refIdx < (uint)l.Length ? l[refIdx] : default;
} }
foreach (var q in l) var i = refIdx >> 1;
if ((uint)i >= (uint)l.Length || l[i].Pic is null)
{ {
if (q is not null) return default;
}
return new RefEntry(l[i].Pic, (refIdx & 1) == 0 ? fieldOf : 1 - fieldOf);
}
/// <summary>A reference picture of the current macroblock; a substitute when the stream refers to a missing one.</summary>
private RefEntry Reference(int list, int refIdx)
{
var fieldOf = MbFieldOf;
var entry = ListEntry(list, refIdx, fieldOf);
if (entry.Pic is not null)
{
return entry;
}
foreach (var q in refList[list])
{
if (q.Pic is not null)
{ {
return q; return fieldOf < 0 ? q : new RefEntry(q.Pic, fieldOf);
} }
} }
@@ -367,10 +466,17 @@ public sealed partial class H264Decoder
{ {
if (q.IsReference && !ReferenceEquals(q, cur)) if (q.IsReference && !ReferenceEquals(q, cur))
{ {
return q; var parity = fieldOf >= 0 ? fieldOf : fieldPic ? (((q.ShortMask | q.LongMask) & 1) != 0 ? 0 : 1) : -1;
return new RefEntry(q, parity);
} }
} }
// The first field of the frame, for its second field.
if (fieldPic && cur is { } picture && ((picture.ShortMask | picture.LongMask) & (1 << (1 - curParity))) != 0)
{
return new RefEntry(picture, 1 - curParity);
}
// Never the picture itself: a frame predicted from its own unfinished samples is corrupt, not damaged. // Never the picture itself: a frame predicted from its own unfinished samples is corrupt, not damaged.
throw new H264Exception("Slice P o B senza immagini di riferimento."); throw new H264Exception("Slice P o B senza immagini di riferimento.");
} }
@@ -384,32 +490,48 @@ public sealed partial class H264Decoder
} }
int n0 = sh.NumRefIdxActiveL0, n1 = sh.NumRefIdxActiveL1; int n0 = sh.NumRefIdxActiveL0, n1 = sh.NumRefIdxActiveL1;
if (implicitW0.Length < n0 * n1) var picture = cur!;
FillImplicit(ref implicitW0, n0, n1, fieldPic ? picture.PocOf(curParity) : picture.Poc, -1);
if (mbaff)
{ {
implicitW0 = new int[Math.Max(n0 * n1, 1)]; for (var parity = 0; parity < 2; parity++)
{
FillImplicit(ref implicitField[parity], 2 * n0, 2 * n1, picture.PocOf(parity), parity);
}
}
}
/// <summary>Implicit weights (§8.4.2.3.1) for every pair of indices, with the order counts of frames or of fields.</summary>
private void FillImplicit(ref int[] table, int n0, int n1, int poc, int fieldOf)
{
if (table.Length < n0 * n1)
{
table = new int[Math.Max(n0 * n1, 1)];
} }
var poc = cur!.Poc;
for (var i = 0; i < n0; i++) for (var i = 0; i < n0; i++)
{ {
var p0 = ListEntry(0, i, fieldOf);
for (var j = 0; j < n1; j++) for (var j = 0; j < n1; j++)
{ {
var p0 = Reference(0, i); var p1 = ListEntry(1, j, fieldOf);
var p1 = Reference(1, j);
var w0 = 32; var w0 = 32;
var td = Math.Clamp(p1.Poc - p0.Poc, -128, 127); if (p0.Pic is not null && p1.Pic is not null)
if (td != 0 && !p0.LongTerm && !p1.LongTerm)
{ {
var tb = Math.Clamp(poc - p0.Poc, -128, 127); var td = Math.Clamp(p1.Poc - p0.Poc, -128, 127);
var tx = (16384 + Math.Abs(td / 2)) / td; if (td != 0 && !p0.IsLongTerm && !p1.IsLongTerm)
var scale = Math.Clamp(((tb * tx) + 32) >> 6, -1024, 1023);
if ((scale >> 2) is >= -64 and <= 128)
{ {
w0 = 64 - (scale >> 2); var tb = Math.Clamp(poc - p0.Poc, -128, 127);
var tx = (16384 + Math.Abs(td / 2)) / td;
var scale = Math.Clamp(((tb * tx) + 32) >> 6, -1024, 1023);
if ((scale >> 2) is >= -64 and <= 128)
{
w0 = 64 - (scale >> 2);
}
} }
} }
implicitW0[(i * n1) + j] = w0; table[(i * n1) + j] = w0;
} }
} }
} }
@@ -433,7 +555,10 @@ public sealed partial class H264Decoder
} }
} }
/// <summary>Inter prediction of one partition with its motion (§8.4.2), written into the current picture.</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) private void MotionCompensate(int px, int py, int w, int h)
{ {
var picture = cur!; var picture = cur!;
@@ -444,79 +569,93 @@ public sealed partial class H264Decoder
var i0 = ((mb * 16) + blk) * 2; var i0 = ((mb * 16) + blk) * 2;
var i1 = (((mbCount + mb) * 16) + blk) * 2; var i1 = (((mbCount + mb) * 16) + blk) * 2;
var x = (mbX * 16) + px; var x = (mbX * 16) + px;
var y = (mbY * 16) + py; var y = ((mbField ? mbY >> 1 : mbY) * 16) + py;
Span<byte> a = stackalloc byte[256]; Span<byte> a = stackalloc byte[256];
Span<byte> b = stackalloc byte[256]; Span<byte> b = stackalloc byte[256];
var size = w * h; var size = w * h;
var pa = a[..size]; var pa = a[..size];
var pb = b[..size]; var pb = b[..size];
Picture? p0 = r0 >= 0 ? Reference(0, r0) : null; var use0 = r0 >= 0;
Picture? p1 = r1 >= 0 ? Reference(1, r1) : null; var use1 = r1 >= 0;
if (p0 is null && p1 is null) if (!use0 && !use1)
{ {
p0 = Reference(0, 0); use0 = true;
r0 = 0; r0 = 0;
} }
var e0 = use0 ? Reference(0, r0) : default;
var e1 = use1 ? Reference(1, r1) : default;
int mv0x = picture.Mv[i0], mv0y = picture.Mv[i0 + 1], mv1x = picture.Mv[i1], mv1y = picture.Mv[i1 + 1]; 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. // Luma.
if (p0 is not null) if (use0)
{ {
InterPrediction.Luma(p0, (x * 4) + mv0x, (y * 4) + mv0y, w, h, pa); 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 (p1 is not null) if (use1)
{ {
InterPrediction.Luma(p1, (x * 4) + mv1x, (y * 4) + mv1y, w, h, p0 is null ? pa : pb); 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, p0 is not null, p1 is not null, r0, r1, 0); Combine(pa, pb, use0, use1, r0, r1, 0);
var stride = picture.Width;
for (var row = 0; row < h; row++) for (var row = 0; row < h; row++)
{ {
pa.Slice(row * w, w).CopyTo(picture.Y.AsSpan(((y + row) * stride) + x, w)); pa.Slice(row * w, w).CopyTo(picture.Y.AsSpan(lumaO + ((py + row) * lumaStride) + px, w));
} }
// Chroma. // 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, cstride = stride / 2, cheight = picture.Height / 2; int cw = w / 2, ch = h / 2, cwidth = width / 2, cheight = height / 2;
var csize = cw * ch; var csize = cw * ch;
var ca = a[..csize]; var ca = a[..csize];
var cb = b[..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++) for (var comp = 1; comp <= 2; comp++)
{ {
if (p0 is not null) if (use0)
{ {
InterPrediction.Chroma(comp == 1 ? p0.Cb : p0.Cr, cstride, cheight, (x * 4) + mv0x, (y * 4) + mv0y, cw, ch, ca); 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);
} }
if (p1 is not null) if (use1)
{ {
InterPrediction.Chroma(comp == 1 ? p1.Cb : p1.Cr, cstride, cheight, (x * 4) + mv1x, (y * 4) + mv1y, cw, ch, p0 is null ? ca : cb); 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);
} }
Combine(ca, cb, p0 is not null, p1 is not null, r0, r1, comp); Combine(ca, cb, use0, use1, r0, r1, comp);
var plane = comp == 1 ? picture.Cb : picture.Cr; var plane = comp == 1 ? picture.Cb : picture.Cr;
for (var row = 0; row < ch; row++) for (var row = 0; row < ch; row++)
{ {
ca.Slice(row * cw, cw).CopyTo(plane.AsSpan((((y / 2) + row) * cstride) + (x / 2), cw)); ca.Slice(row * cw, cw).CopyTo(plane.AsSpan(chromaO + (((py / 2) + row) * chromaStride) + (px / 2), cw));
} }
} }
} }
private void Combine(Span<byte> a, ReadOnlySpan<byte> b, bool use0, bool use1, int r0, int r1, int comp) private void Combine(Span<byte> a, ReadOnlySpan<byte> b, bool use0, bool use1, int r0, int r1, int comp)
{ {
// 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;
if (use0 && use1) if (use0 && use1)
{ {
if (weightMode == 1 && sh.Weights is { } weights && sh.Offsets is { } offsets) if (weightMode == 1 && sh.Weights is { } weights && sh.Offsets is { } offsets)
{ {
var logWd = comp == 0 ? sh.LumaLog2WeightDenom : sh.ChromaLog2WeightDenom; var logWd = comp == 0 ? sh.LumaLog2WeightDenom : sh.ChromaLog2WeightDenom;
InterPrediction.WeightTwo(a, b, logWd, weights[0][(r0 * 3) + comp], weights[1][(r1 * 3) + comp], offsets[0][(r0 * 3) + comp], offsets[1][(r1 * 3) + comp]); 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]);
} }
else if (weightMode == 2) else if (weightMode == 2)
{ {
var w0 = implicitW0[(r0 * sh.NumRefIdxActiveL1) + r1]; 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);
} }
else else
@@ -530,7 +669,7 @@ public sealed partial class H264Decoder
if (weightMode == 1 && sh.Weights is { } w && sh.Offsets is { } o) if (weightMode == 1 && sh.Weights is { } w && sh.Offsets is { } o)
{ {
var list = use0 ? 0 : 1; var list = use0 ? 0 : 1;
var r = use0 ? r0 : r1; var r = use0 ? w0Index : w1Index;
var logWd = comp == 0 ? sh.LumaLog2WeightDenom : sh.ChromaLog2WeightDenom; 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]);
} }
+500 -76
View File
@@ -35,7 +35,7 @@ public sealed partial class H264Decoder
private static readonly byte[] BSubShape = [0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3]; private static readonly byte[] BSubShape = [0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3];
private readonly List<(int Disable, int Alpha, int Beta)> sliceFilters = []; private readonly List<(int Disable, int Alpha, int Beta)> sliceFilters = [];
private readonly Picture?[][] refList = [[], []]; private readonly RefEntry[][] refList = [[], []];
private readonly CabacEngine cabac = new(); private readonly CabacEngine cabac = new();
private int widthInMbs; private int widthInMbs;
@@ -67,14 +67,41 @@ public sealed partial class H264Decoder
private int[][] ls4 = []; private int[][] ls4 = [];
private int[][] ls8 = []; private int[][] ls8 = [];
// Macroblock state. /// <summary>The picture is an MBAFF frame: macroblock pairs, each of two frame or two field macroblocks.</summary>
private bool mbaff;
/// <summary>The picture is a field: its macroblocks are on every other row of the frame grid.</summary>
private bool fieldPic;
/// <summary>The parity of the field being decoded (0 top, 1 bottom).</summary>
private int curParity;
// Macroblock state: mb is the index on the frame grid (see Picture), mbY its row there.
private int mb; private int mb;
private int mbX; private int mbX;
private int mbY; private int mbY;
private bool availA;
private bool availB; /// <summary>The current macroblock is a field macroblock (of a field picture or a field pair).</summary>
private bool availC; private bool mbField;
private bool availD;
private int lumaO;
private int lumaStride;
private int chromaO;
private int chromaStride;
// Neighbouring macroblocks A (left), B (above), C (above right), D (above left) on the frame grid, −1 when not
// available; in an MBAFF frame A and B are those of the luma locations (−1, 0) and (0, −1), C and D are not used.
private int mbA;
private int mbB;
private int mbC;
private int mbD;
// MBAFF: the top macroblocks of the pairs to the left, above, above right and above left, −1 when not available.
private int pairA;
private int pairB;
private int pairC;
private int pairD;
private readonly bool[] blkDone = new bool[16]; private readonly bool[] blkDone = new bool[16];
private readonly int[] lumaCoef = new int[256]; private readonly int[] lumaCoef = new int[256];
private readonly bool[] lumaHas = new bool[16]; private readonly bool[] lumaHas = new bool[16];
@@ -118,6 +145,9 @@ public sealed partial class H264Decoder
pps = p; pps = p;
rd = reader; rd = reader;
cabacMode = p.Cabac; cabacMode = p.Cabac;
fieldPic = header.FieldPic;
curParity = header.BottomField ? 1 : 0;
mbaff = s.MbAdaptiveFrameField && !header.FieldPic;
sliceNum = sliceCounter++; sliceNum = sliceCounter++;
sliceFilters.Add((header.DisableDeblocking, header.AlphaOffset, header.BetaOffset)); sliceFilters.Add((header.DisableDeblocking, header.AlphaOffset, header.BetaOffset));
qp = p.PicInitQp + header.QpDelta; qp = p.PicInitQp + header.QpDelta;
@@ -157,37 +187,54 @@ public sealed partial class H264Decoder
cabac.Start(rd); cabac.Start(rd);
} }
mb = header.FirstMb; // Macroblock addresses of the slice: those of the field, or of the pairs (two per pair) in an MBAFF frame.
if (mb >= mbCount) var total = fieldPic ? mbCount / 2 : mbCount;
var addr = header.FirstMb * (mbaff ? 2 : 1);
if (addr >= total)
{ {
throw new H264Exception("Primo macroblocco fuori dall'immagine."); throw new H264Exception("Primo macroblocco fuori dall'immagine.");
} }
var isIntraSlice = header.IsIntra; if (!mbaff)
while (mb < mbCount) {
DecodeMacroblocks(addr, total);
}
else if (cabacMode)
{
DecodePairsCabac(addr, total);
}
else
{
DecodePairsCavlc(addr, total);
}
}
private void DecodeMacroblocks(int addr, int total)
{
var isIntraSlice = sh.IsIntra;
while (addr < total)
{ {
if (!isIntraSlice && !cabacMode) if (!isIntraSlice && !cabacMode)
{ {
var run = rd.ReadUe(); var run = rd.ReadUe();
if (run > (uint)(mbCount - mb)) if (run > (uint)(total - addr))
{ {
throw new H264Exception("mb_skip_run fuori dall'immagine."); throw new H264Exception("mb_skip_run fuori dall'immagine.");
} }
for (var i = 0; i < (int)run; i++) for (var i = 0; i < (int)run; i++)
{ {
BeginMacroblock(); BeginMacroblock(addr++);
DecodeSkip(); DecodeSkip();
mb++;
} }
if ((run > 0 && !rd.MoreRbspData) || mb >= mbCount) if ((run > 0 && !rd.MoreRbspData) || addr >= total)
{ {
break; break;
} }
} }
BeginMacroblock(); BeginMacroblock(addr++);
if (!isIntraSlice && cabacMode && ReadMbSkip() != 0) if (!isIntraSlice && cabacMode && ReadMbSkip() != 0)
{ {
DecodeSkip(); DecodeSkip();
@@ -197,7 +244,6 @@ public sealed partial class H264Decoder
DecodeMacroblock(); DecodeMacroblock();
} }
mb++;
var more = cabacMode ? cabac.Terminate() == 0 : rd.MoreRbspData; var more = cabacMode ? cabac.Terminate() == 0 : rd.MoreRbspData;
if (!more) if (!more)
{ {
@@ -206,16 +252,336 @@ public sealed partial class H264Decoder
} }
} }
/// <summary>Position and neighbour availability of macroblock <see cref="mb"/>.</summary> /// <summary>
private void BeginMacroblock() /// The macroblock pairs of an MBAFF slice with CAVLC (§7.3.4): mb_field_decoding_flag comes with the top macroblock,
/// or with the bottom one when the top one is skipped — right after the mb_skip_run that skips it, so it is read
/// there, before the skipped top macroblock is predicted.
/// </summary>
private void DecodePairsCavlc(int addr, int total)
{ {
mbX = mb % widthInMbs; var isIntraSlice = sh.IsIntra;
mbY = mb / widthInMbs; while (addr < total)
mbSlice[mb] = sliceNum; {
availA = mbX > 0 && mbSlice[mb - 1] == sliceNum; if (!isIntraSlice)
availB = mbY > 0 && mbSlice[mb - widthInMbs] == sliceNum; {
availC = mbY > 0 && mbX < widthInMbs - 1 && mbSlice[mb - widthInMbs + 1] == sliceNum; var run = rd.ReadUe();
availD = mbY > 0 && mbX > 0 && mbSlice[mb - widthInMbs - 1] == sliceNum; if (run > (uint)(total - addr))
{
throw new H264Exception("mb_skip_run fuori dall'immagine.");
}
for (var i = 0; i < (int)run; i++)
{
if ((addr & 1) == 0)
{
SetPairField(addr, InferPairField(addr));
if (i == run - 1 && rd.MoreRbspData)
{
SetPairField(addr, rd.ReadFlag());
}
}
BeginMacroblock(addr++);
DecodeSkip();
}
if ((run > 0 && !rd.MoreRbspData) || addr >= total)
{
break;
}
}
if ((addr & 1) == 0)
{
SetPairField(addr, rd.ReadFlag());
}
BeginMacroblock(addr++);
DecodeMacroblock();
if (!rd.MoreRbspData)
{
break;
}
}
}
/// <summary>
/// The macroblock pairs of an MBAFF slice with CABAC (§7.3.4). When the top macroblock is skipped, the skip flag of
/// the bottom one follows, and then (if that one is not skipped) mb_field_decoding_flag: both are read before the
/// skipped top macroblock is predicted, the first with the inferred flag (§7.4.4). end_of_slice_flag follows the
/// bottom macroblock only.
/// </summary>
private void DecodePairsCabac(int addr, int total)
{
var isIntraSlice = sh.IsIntra;
var bottomSkipKnown = false;
var bottomSkip = false;
while (addr < total)
{
var top = (addr & 1) == 0;
bool skip;
if (top)
{
SetPairField(addr, InferPairField(addr));
PlaceMacroblock(addr);
skip = !isIntraSlice && ReadMbSkip() != 0;
if (skip)
{
mbKind[mb] = sh.IsB ? MbKind.BSkip : MbKind.PSkip;
PlaceMacroblock(addr + 1);
bottomSkip = ReadMbSkip() != 0;
bottomSkipKnown = true;
if (!bottomSkip)
{
SetPairField(addr, ReadFieldFlag());
}
}
else
{
SetPairField(addr, ReadFieldFlag());
}
}
else
{
PlaceMacroblock(addr);
skip = bottomSkipKnown ? bottomSkip : !isIntraSlice && ReadMbSkip() != 0;
bottomSkipKnown = false;
}
BeginMacroblock(addr++);
if (skip)
{
DecodeSkip();
}
else
{
DecodeMacroblock();
}
if (!top && cabac.Terminate() != 0)
{
break;
}
}
}
/// <summary>The flag of a pair whose mb_field_decoding_flag is not (yet) read (§7.4.4): the left pair's, else the one above.</summary>
private bool InferPairField(int addr)
{
var pair = addr >> 1;
int x = pair % widthInMbs, top = (2 * (pair / widthInMbs) * widthInMbs) + x;
if (x > 0 && mbSlice[top - 1] == sliceNum)
{
return cur!.MbField[top - 1];
}
return top >= 2 * widthInMbs && mbSlice[top - (2 * widthInMbs)] == sliceNum && cur!.MbField[top - (2 * widthInMbs)];
}
private void SetPairField(int addr, bool field)
{
var pair = addr >> 1;
var top = (2 * (pair / widthInMbs) * widthInMbs) + (pair % widthInMbs);
cur!.MbField[top] = field;
cur.MbField[top + widthInMbs] = field;
}
private bool ReadFieldFlag()
{
if (!cabacMode)
{
return rd.ReadFlag();
}
var inc = (pairA >= 0 && cur!.MbField[pairA] ? 1 : 0) + (pairB >= 0 && cur!.MbField[pairB] ? 1 : 0);
return cabac.Decision(70 + inc) != 0;
}
/// <summary>
/// Position of the macroblock of address <paramref name="addr"/> in the slice: its place on the frame grid, its
/// samples, its neighbours (§6.4.9, §6.4.10). In an MBAFF frame the flag of its pair must be set.
/// </summary>
private void PlaceMacroblock(int addr)
{
var w = widthInMbs;
if (mbaff)
{
var pair = addr >> 1;
mbX = pair % w;
var pairRow = 2 * (pair / w);
mbY = pairRow + (addr & 1);
mb = (mbY * w) + mbX;
mbSlice[mb] = sliceNum;
var top = (pairRow * w) + mbX;
mbField = cur!.MbField[top];
pairA = mbX > 0 && mbSlice[top - 1] == sliceNum ? top - 1 : -1;
var above = top - (2 * w);
var hasAbove = pairRow > 0;
pairB = hasAbove && mbSlice[above] == sliceNum ? above : -1;
pairC = hasAbove && mbX < w - 1 && mbSlice[above + 1] == sliceNum ? above + 1 : -1;
pairD = hasAbove && mbX > 0 && mbSlice[above - 1] == sliceNum ? above - 1 : -1;
mbC = mbD = -1;
mbA = Locate(-1, 0, 16, out _);
mbB = Locate(0, -1, 16, out _);
}
else
{
var rowStep = fieldPic ? 2 : 1;
mbX = addr % w;
var row = addr / w;
mbY = (row * rowStep) + (fieldPic ? curParity : 0);
mb = (mbY * w) + mbX;
mbField = fieldPic;
mbSlice[mb] = sliceNum;
var up = rowStep * w;
mbA = mbX > 0 && mbSlice[mb - 1] == sliceNum ? mb - 1 : -1;
mbB = row > 0 && mbSlice[mb - up] == sliceNum ? mb - up : -1;
mbC = row > 0 && mbX < w - 1 && mbSlice[mb - up + 1] == sliceNum ? mb - up + 1 : -1;
mbD = row > 0 && mbX > 0 && mbSlice[mb - up - 1] == sliceNum ? mb - up - 1 : -1;
}
var width = cur!.Width;
var cwidth = width / 2;
if (mbField)
{
int pairY = mbY >> 1, parity = mbY & 1;
lumaO = (((pairY * 32) + parity) * width) + (mbX * 16);
lumaStride = 2 * width;
chromaO = (((pairY * 16) + parity) * cwidth) + (mbX * 8);
chromaStride = 2 * cwidth;
}
else
{
lumaO = (mbY * 16 * width) + (mbX * 16);
lumaStride = width;
chromaO = (mbY * 8 * cwidth) + (mbX * 8);
chromaStride = cwidth;
}
}
/// <summary>
/// The macroblock covering the luma (<paramref name="maxH"/> 16) or chroma (8) location (xN, yN) relative to the
/// current macroblock (§6.4.12), −1 when not available; <paramref name="yM"/> is its row there (negative counts
/// from the bottom). In an MBAFF frame, Table 6-4.
/// </summary>
private int Locate(int xN, int yN, int maxH, out int yM)
{
yM = yN;
var maxW = maxH;
if (yN >= maxH || (xN >= maxW && yN >= 0))
{
return -1;
}
if (!mbaff)
{
if (yN < 0)
{
return xN < 0 ? mbD : xN < maxW ? mbB : mbC;
}
return xN < 0 ? mbA : mb;
}
if (xN >= 0 && yN >= 0)
{
return mb;
}
var w = widthInMbs;
var bottom = (mbY & 1) != 0;
var field = cur!.MbField;
if (yN < 0)
{
var x = xN < 0 ? (mbField || !bottom ? pairD : pairA) : xN < maxW ? pairB : pairC;
if (!mbField)
{
if (!bottom)
{
return x < 0 ? -1 : x + w;
}
if (xN >= maxW)
{
return -1;
}
if (xN >= 0)
{
return mb - w;
}
// The left pair, from the bottom macroblock of a frame pair.
if (x < 0)
{
return -1;
}
if (!field[x])
{
return x;
}
yM = (yN + maxH) >> 1;
return x + w;
}
if (x < 0)
{
return -1;
}
if (bottom || field[x])
{
return bottom ? x + w : x;
}
yM = 2 * yN;
return x + w;
}
// xN < 0, 0 <= yN < maxH: the pair to the left.
return pairA < 0 ? -1 : LeftOfPair(pairA, w, field[pairA], mbField, bottom, yN, maxH, out yM);
}
/// <summary>
/// MBAFF: the macroblock of the pair to the left (whose top macroblock is <paramref name="leftTop"/>) holding row
/// <paramref name="yN"/> of the current macroblock, and its row <paramref name="yM"/> there (Table 6-4, xN &lt; 0).
/// </summary>
private static int LeftOfPair(int leftTop, int w, bool leftField, bool curField, bool bottom, int yN, int maxH, out int yM)
{
yM = yN;
if (!curField)
{
if (!leftField)
{
return bottom ? leftTop + w : leftTop;
}
yM = (bottom ? yN + maxH : yN) >> 1;
return leftTop + ((yN & 1) * w);
}
if (leftField)
{
return bottom ? leftTop + w : leftTop;
}
var frameRow = (yN << 1) + (bottom ? 1 : 0);
if (frameRow < maxH)
{
yM = frameRow;
return leftTop;
}
yM = frameRow - maxH;
return leftTop + w;
}
/// <summary>Starts the macroblock of address <paramref name="addr"/>: its position, and its data cleared.</summary>
private void BeginMacroblock(int addr)
{
PlaceMacroblock(addr);
Array.Clear(blkDone); Array.Clear(blkDone);
Array.Clear(nz, mb * 24, 24); Array.Clear(nz, mb * 24, 24);
cbfDc[mb] = 0; cbfDc[mb] = 0;
@@ -223,16 +589,19 @@ public sealed partial class H264Decoder
mbT8[mb] = false; mbT8[mb] = false;
chromaModes[mb] = 0; chromaModes[mb] = 0;
intraModes.AsSpan(mb * 16, 16).Fill(2); intraModes.AsSpan(mb * 16, 16).Fill(2);
var picture = cur!;
for (var list = 0; list < 2; list++) for (var list = 0; list < 2; list++)
{ {
mvdAbs.AsSpan(((list * mbCount) + mb) * 32, 32).Clear(); mvdAbs.AsSpan(((list * mbCount) + mb) * 32, 32).Clear();
cur!.Mv.AsSpan(((list * mbCount) + mb) * 32, 32).Clear(); picture.Mv.AsSpan(((list * mbCount) + mb) * 32, 32).Clear();
cur.RefIdx.AsSpan(((list * mbCount) + mb) * 4, 4).Fill(-1); picture.RefIdx.AsSpan(((list * mbCount) + mb) * 4, 4).Fill(-1);
cur.RefPic.AsSpan(((list * mbCount) + mb) * 4, 4).Clear(); picture.RefPic.AsSpan(((list * mbCount) + mb) * 4, 4).Clear();
picture.RefPar.AsSpan(((list * mbCount) + mb) * 4, 4).Fill(-1);
} }
subDirect.AsSpan(mb * 4, 4).Clear(); subDirect.AsSpan(mb * 4, 4).Clear();
cur!.MbIntra[mb] = false; picture.MbIntra[mb] = false;
picture.MbField[mb] = mbField;
} }
private void DecodeMacroblock() private void DecodeMacroblock()
@@ -399,27 +768,29 @@ public sealed partial class H264Decoder
{ {
modeA = intraModes[(mb * 16) + (by * 4) + bx - 1]; modeA = intraModes[(mb * 16) + (by * 4) + bx - 1];
} }
else if (!availA || (pps.ConstrainedIntraPred && !IsIntra(mb - 1)))
{
return 2;
}
else else
{ {
var a = mb - 1; var a = Locate(-1, by * 4, 16, out var yM);
modeA = mbKind[a] is MbKind.I4x4 or MbKind.I8x8 ? intraModes[(a * 16) + (by * 4) + 3] : 2; if (a < 0 || (pps.ConstrainedIntraPred && !IsIntra(a)))
{
return 2;
}
modeA = mbKind[a] is MbKind.I4x4 or MbKind.I8x8 ? intraModes[(a * 16) + (((yM & 15) >> 2) * 4) + 3] : 2;
} }
if (by > 0) if (by > 0)
{ {
modeB = intraModes[(mb * 16) + ((by - 1) * 4) + bx]; modeB = intraModes[(mb * 16) + ((by - 1) * 4) + bx];
} }
else if (!availB || (pps.ConstrainedIntraPred && !IsIntra(mb - widthInMbs)))
{
return 2;
}
else else
{ {
var b = mb - widthInMbs; var b = Locate(bx * 4, -1, 16, out _);
if (b < 0 || (pps.ConstrainedIntraPred && !IsIntra(b)))
{
return 2;
}
modeB = mbKind[b] is MbKind.I4x4 or MbKind.I8x8 ? intraModes[(b * 16) + 12 + bx] : 2; modeB = mbKind[b] is MbKind.I4x4 or MbKind.I8x8 ? intraModes[(b * 16) + 12 + bx] : 2;
} }
@@ -437,23 +808,22 @@ public sealed partial class H264Decoder
} }
var picture = cur!; var picture = cur!;
var w = picture.Width;
for (var y = 0; y < 16; y++) for (var y = 0; y < 16; y++)
{ {
for (var x = 0; x < 16; x++) for (var x = 0; x < 16; x++)
{ {
picture.Y[(((mbY * 16) + y) * w) + (mbX * 16) + x] = (byte)rd.Read(8); picture.Y[lumaO + (y * lumaStride) + x] = (byte)rd.Read(8);
} }
} }
var cw = w / 2; for (var c = 0; c < 2; c++)
foreach (var plane in new[] { picture.Cb, picture.Cr })
{ {
var plane = c == 0 ? picture.Cb : picture.Cr;
for (var y = 0; y < 8; y++) for (var y = 0; y < 8; y++)
{ {
for (var x = 0; x < 8; x++) for (var x = 0; x < 8; x++)
{ {
plane[(((mbY * 8) + y) * cw) + (mbX * 8) + x] = (byte)rd.Read(8); plane[chromaO + (y * chromaStride) + x] = (byte)rd.Read(8);
} }
} }
} }
@@ -515,7 +885,7 @@ public sealed partial class H264Decoder
var ref0 = !isB && type == 4; var ref0 = !isB && type == 4;
for (var list = 0; list < 2; list++) for (var list = 0; list < 2; list++)
{ {
var active = list == 0 ? sh.NumRefIdxActiveL0 : sh.NumRefIdxActiveL1; var active = RefIdxRange(list);
for (var i = 0; i < 4; i++) for (var i = 0; i < 4; i++)
{ {
if ((partPred[i] & (1 << list)) == 0) if ((partPred[i] & (1 << list)) == 0)
@@ -572,7 +942,7 @@ public sealed partial class H264Decoder
count = shape == Shape16x16 ? 1 : 2; count = shape == Shape16x16 ? 1 : 2;
for (var list = 0; list < 2; list++) for (var list = 0; list < 2; list++)
{ {
var active = list == 0 ? sh.NumRefIdxActiveL0 : sh.NumRefIdxActiveL1; var active = RefIdxRange(list);
for (var part = 0; part < count; part++) for (var part = 0; part < count; part++)
{ {
if ((partPred[part] & (1 << list)) == 0) if ((partPred[part] & (1 << list)) == 0)
@@ -738,17 +1108,28 @@ public sealed partial class H264Decoder
} }
} }
private void SetRefIdx(int list, int b8, int refIdx) /// <summary>
/// The number of reference indices of a list for the current macroblock: twice the active ones for a field
/// macroblock of an MBAFF frame, which refers to fields (§8.4.2.1).
/// </summary>
private int RefIdxRange(int list)
{ {
var active = list == 0 ? sh.NumRefIdxActiveL0 : sh.NumRefIdxActiveL1; var active = list == 0 ? sh.NumRefIdxActiveL0 : sh.NumRefIdxActiveL1;
if (refIdx >= active) return mbaff && mbField ? 2 * active : active;
}
private void SetRefIdx(int list, int b8, int refIdx)
{
if (refIdx >= RefIdxRange(list))
{ {
throw new H264Exception("ref_idx fuori dalla lista."); throw new H264Exception("ref_idx fuori dalla lista.");
} }
var index = (((list * mbCount) + mb) * 4) + b8; var index = (((list * mbCount) + mb) * 4) + b8;
var entry = Reference(list, refIdx);
cur!.RefIdx[index] = (sbyte)refIdx; cur!.RefIdx[index] = (sbyte)refIdx;
cur.RefPic[index] = Reference(list, refIdx); cur.RefPic[index] = entry.Pic;
cur.RefPar[index] = (sbyte)entry.Parity;
} }
private void SetPartitionRefIdx(int list, int part, int refIdx) private void SetPartitionRefIdx(int list, int part, int refIdx)
@@ -819,6 +1200,9 @@ public sealed partial class H264Decoder
var qpMod = qp % 6; var qpMod = qp % 6;
var scale4 = ls4[listY]; var scale4 = ls4[listY];
// Field macroblocks are scanned in field order (§8.5.6).
var scan4 = mbField ? H264Tables.FieldScan4x4 : H264Tables.ZigZag4x4;
if (intra16) if (intra16)
{ {
var count = ReadBlock(0, 0, 0, levels, 16); var count = ReadBlock(0, 0, 0, levels, 16);
@@ -826,7 +1210,7 @@ public sealed partial class H264Decoder
c.Clear(); c.Clear();
for (var k = 0; k < 16; k++) for (var k = 0; k < 16; k++)
{ {
c[H264Tables.ZigZag4x4[k]] = levels[k]; c[scan4[k]] = levels[k];
} }
if (count > 0) if (count > 0)
@@ -885,7 +1269,7 @@ public sealed partial class H264Decoder
var level = levels[k]; var level = levels[k];
if (level != 0) if (level != 0)
{ {
var pos = H264Tables.ZigZag4x4[k + 1]; var pos = scan4[k + 1];
lumaCoef[(raster * 16) + pos] = Scale4(level, scale4[(qpMod * 16) + pos], qpDiv); lumaCoef[(raster * 16) + pos] = Scale4(level, scale4[(qpMod * 16) + pos], qpDiv);
lumaHas[raster] = true; lumaHas[raster] = true;
} }
@@ -910,7 +1294,7 @@ public sealed partial class H264Decoder
var level = levels[k]; var level = levels[k];
if (level != 0) if (level != 0)
{ {
var pos = H264Tables.ZigZag4x4[k]; var pos = scan4[k];
lumaCoef[(raster * 16) + pos] = Scale4(level, scale4[(qpMod * 16) + pos], qpDiv); lumaCoef[(raster * 16) + pos] = Scale4(level, scale4[(qpMod * 16) + pos], qpDiv);
lumaHas[raster] = true; lumaHas[raster] = true;
} }
@@ -970,7 +1354,7 @@ public sealed partial class H264Decoder
var level = levels[k]; var level = levels[k];
if (level != 0) if (level != 0)
{ {
var pos = H264Tables.ZigZag4x4[k + 1]; var pos = scan4[k + 1];
chromaCoef[(((c * 4) + b) * 16) + pos] = Scale4(level, scale[((qpc % 6) * 16) + pos], qpc / 6); chromaCoef[(((c * 4) + b) * 16) + pos] = Scale4(level, scale[((qpc % 6) * 16) + pos], qpc / 6);
chromaHas[(c * 4) + b] = true; chromaHas[(c * 4) + b] = true;
} }
@@ -989,6 +1373,7 @@ public sealed partial class H264Decoder
var qpDiv = qp / 6; var qpDiv = qp / 6;
var qpMod = qp % 6; var qpMod = qp % 6;
var any = false; var any = false;
var scan8 = mbField ? H264Tables.FieldScan8x8 : H264Tables.ZigZag8x8;
for (var k = 0; k < 64; k++) for (var k = 0; k < 64; k++)
{ {
var level = source[k]; var level = source[k];
@@ -997,7 +1382,7 @@ public sealed partial class H264Decoder
continue; continue;
} }
var pos = H264Tables.ZigZag8x8[k]; var pos = scan8[k];
var ls = scale[(qpMod * 64) + pos]; var ls = scale[(qpMod * 64) + pos];
lumaCoef[(b8 * 64) + pos] = qp >= 36 ? (level * ls) << (qpDiv - 6) : ((level * ls) + (1 << (5 - qpDiv))) >> (6 - qpDiv); lumaCoef[(b8 * 64) + pos] = qp >= 36 ? (level * ls) << (qpDiv - 6) : ((level * ls) + (1 << (5 - qpDiv))) >> (6 - qpDiv);
any = true; any = true;
@@ -1009,17 +1394,57 @@ public sealed partial class H264Decoder
} }
} }
private int LumaOffset(int bx, int by) => (((mbY * 16) + by) * cur!.Width) + (mbX * 16) + bx; private int LumaOffset(int bx, int by) => lumaO + (by * lumaStride) + bx;
/// <summary>
/// The rows of the left neighbour usable for intra prediction, one bit per row (16 luma or 8 chroma): in an MBAFF
/// frame they may belong to the two macroblocks of the pair, one intra and one not (constrained intra prediction).
/// </summary>
private int LeftRows(int maxH, bool constrained)
{
var all = (1 << maxH) - 1;
if (!mbaff)
{
return mbA >= 0 && (!constrained || IsIntra(mbA)) ? all : 0;
}
if (pairA < 0)
{
return 0;
}
if (!constrained)
{
return all;
}
var mask = 0;
for (var r = 0; r < maxH; r++)
{
var n = Locate(-1, r, maxH, out _);
if (n >= 0 && IsIntra(n))
{
mask |= 1 << r;
}
}
return mask;
}
private static bool Rows(int mask, int first, int count) => ((mask >> first) & ((1 << count) - 1)) == (1 << count) - 1;
private void ReconstructIntra(int predMode16) private void ReconstructIntra(int predMode16)
{ {
var picture = cur!; var picture = cur!;
var stride = picture.Width; var stride = lumaStride;
var constrained = pps.ConstrainedIntraPred; var constrained = pps.ConstrainedIntraPred;
var a = availA && (!constrained || IsIntra(mb - 1)); var nB = Locate(0, -1, 16, out _);
var b = availB && (!constrained || IsIntra(mb - widthInMbs)); var nC = Locate(16, -1, 16, out _);
var c = availC && (!constrained || IsIntra(mb - widthInMbs + 1)); var nD = Locate(-1, -1, 16, out _);
var d = availD && (!constrained || IsIntra(mb - widthInMbs - 1)); var b = nB >= 0 && (!constrained || IsIntra(nB));
var c = nC >= 0 && (!constrained || IsIntra(nC));
var d = nD >= 0 && (!constrained || IsIntra(nD));
var left = LeftRows(16, constrained);
Span<int> block = stackalloc int[64]; Span<int> block = stackalloc int[64];
switch (mbKind[mb]) switch (mbKind[mb])
{ {
@@ -1028,9 +1453,9 @@ public sealed partial class H264Decoder
{ {
var raster = H264Tables.BlockToRaster[i]; var raster = H264Tables.BlockToRaster[i];
int bx = raster & 3, by = raster >> 2; int bx = raster & 3, by = raster >> 2;
var left = bx > 0 || a; var hasLeft = bx > 0 || Rows(left, by * 4, 4);
var top = by > 0 || b; var top = by > 0 || b;
var topLeft = bx > 0 && by > 0 || (bx == 0 && by > 0 ? a : bx > 0 && by == 0 ? b : d); var topLeft = (bx > 0 && by > 0) || (bx == 0 && by > 0 ? Rows(left, (by * 4) - 1, 1) : bx > 0 && by == 0 ? b : d);
bool topRight; bool topRight;
if (by == 0) if (by == 0)
{ {
@@ -1042,7 +1467,7 @@ public sealed partial class H264Decoder
} }
var o = LumaOffset(bx * 4, by * 4); var o = LumaOffset(bx * 4, by * 4);
IntraPrediction.Predict4x4(picture.Y, o, stride, intraModes[(mb * 16) + raster], left, top, topRight, topLeft); IntraPrediction.Predict4x4(picture.Y, o, stride, intraModes[(mb * 16) + raster], hasLeft, top, topRight, topLeft);
if (lumaHas[raster]) if (lumaHas[raster])
{ {
lumaCoef.AsSpan(raster * 16, 16).CopyTo(block); lumaCoef.AsSpan(raster * 16, 16).CopyTo(block);
@@ -1057,12 +1482,12 @@ public sealed partial class H264Decoder
for (var i = 0; i < 4; i++) for (var i = 0; i < 4; i++)
{ {
int bx = i & 1, by = i >> 1; int bx = i & 1, by = i >> 1;
var left = bx > 0 || a; var hasLeft = bx > 0 || Rows(left, by * 8, 8);
var top = by > 0 || b; var top = by > 0 || b;
var topLeft = bx > 0 && by > 0 || (bx == 0 && by > 0 ? a : bx > 0 && by == 0 ? b : d); var topLeft = (bx > 0 && by > 0) || (bx == 0 && by > 0 ? Rows(left, 7, 1) : bx > 0 && by == 0 ? b : d);
var topRight = by == 0 ? (bx == 0 ? b : c) : bx == 0; var topRight = by == 0 ? (bx == 0 ? b : c) : bx == 0;
var o = LumaOffset(bx * 8, by * 8); var o = LumaOffset(bx * 8, by * 8);
IntraPrediction.Predict8x8(picture.Y, o, stride, intraModes[(mb * 16) + (by * 8) + (bx * 2)], left, top, topRight, topLeft); IntraPrediction.Predict8x8(picture.Y, o, stride, intraModes[(mb * 16) + (by * 8) + (bx * 2)], hasLeft, top, topRight, topLeft);
if (lumaHas[i]) if (lumaHas[i])
{ {
lumaCoef.AsSpan(i * 64, 64).CopyTo(block); lumaCoef.AsSpan(i * 64, 64).CopyTo(block);
@@ -1073,7 +1498,7 @@ public sealed partial class H264Decoder
break; break;
default: default:
{ {
IntraPrediction.Predict16x16(picture.Y, LumaOffset(0, 0), stride, predMode16, a, b, d); IntraPrediction.Predict16x16(picture.Y, LumaOffset(0, 0), stride, predMode16, Rows(left, 0, 16), b, d);
for (var raster = 0; raster < 16; raster++) for (var raster = 0; raster < 16; raster++)
{ {
if (lumaHas[raster]) if (lumaHas[raster])
@@ -1087,17 +1512,17 @@ public sealed partial class H264Decoder
} }
} }
var cstride = stride / 2; var chromaLeft = LeftRows(8, constrained);
var co = (mbY * 8 * cstride) + (mbX * 8); bool upper = Rows(chromaLeft, 0, 4), lower = Rows(chromaLeft, 4, 4);
IntraPrediction.PredictChroma(picture.Cb, co, cstride, chromaModes[mb], a, b, d); IntraPrediction.PredictChroma(picture.Cb, chromaO, chromaStride, chromaModes[mb], upper, lower, b, d);
IntraPrediction.PredictChroma(picture.Cr, co, cstride, chromaModes[mb], a, b, d); IntraPrediction.PredictChroma(picture.Cr, chromaO, chromaStride, chromaModes[mb], upper, lower, b, d);
AddChromaResidual(); AddChromaResidual();
} }
private void AddInterResidual() private void AddInterResidual()
{ {
var picture = cur!; var picture = cur!;
var stride = picture.Width; var stride = lumaStride;
Span<int> block = stackalloc int[64]; Span<int> block = stackalloc int[64];
if (mbT8[mb]) if (mbT8[mb])
{ {
@@ -1128,7 +1553,6 @@ public sealed partial class H264Decoder
private void AddChromaResidual() private void AddChromaResidual()
{ {
var picture = cur!; var picture = cur!;
var cstride = picture.Width / 2;
Span<int> block = stackalloc int[16]; Span<int> block = stackalloc int[16];
for (var c = 0; c < 2; c++) for (var c = 0; c < 2; c++)
{ {
@@ -1141,8 +1565,8 @@ public sealed partial class H264Decoder
} }
chromaCoef.AsSpan(((c * 4) + b) * 16, 16).CopyTo(block); chromaCoef.AsSpan(((c * 4) + b) * 16, 16).CopyTo(block);
var o = (((mbY * 8) + ((b >> 1) * 4)) * cstride) + (mbX * 8) + ((b & 1) * 4); var o = chromaO + ((b >> 1) * 4 * chromaStride) + ((b & 1) * 4);
Transform.Add4x4(block, plane, o, cstride); Transform.Add4x4(block, plane, o, chromaStride);
} }
} }
} }
File diff suppressed because it is too large. Load diff
+17
View File
@@ -9,6 +9,16 @@ internal static class H264Tables
/// <summary>Zig-zag scan of 8×8 frame blocks: scan index → raster position (row * 8 + column).</summary> /// <summary>Zig-zag scan of 8×8 frame blocks: scan index → raster position (row * 8 + column).</summary>
internal static readonly byte[] ZigZag8x8 = BuildZigZag(8); internal static readonly byte[] ZigZag8x8 = BuildZigZag(8);
/// <summary>Field scan of 4×4 blocks (table 8-13): scan index → raster position (row * 4 + column).</summary>
internal static readonly byte[] FieldScan4x4 = [0, 4, 1, 8, 12, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15];
/// <summary>Field scan of 8×8 blocks (table 8-14): scan index → raster position (row * 8 + column).</summary>
internal static readonly byte[] FieldScan8x8 =
[
0, 8, 16, 1, 9, 24, 32, 17, 2, 25, 40, 48, 56, 33, 10, 3, 18, 41, 49, 57, 26, 11, 4, 19, 34, 42, 50, 58, 27, 12, 5, 20,
35, 43, 51, 59, 28, 13, 6, 21, 36, 44, 52, 60, 29, 14, 22, 37, 45, 53, 61, 30, 7, 15, 38, 46, 54, 62, 23, 31, 39, 47, 55, 63,
];
/// <summary>luma4x4BlkIdx → raster index of the 4×4 block in the macroblock ((y / 4) * 4 + x / 4).</summary> /// <summary>luma4x4BlkIdx → raster index of the 4×4 block in the macroblock ((y / 4) * 4 + x / 4).</summary>
internal static readonly byte[] BlockToRaster = [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15]; internal static readonly byte[] BlockToRaster = [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15];
@@ -100,6 +110,13 @@ internal static class H264Tables
7, 6, 11, 12, 13, 11, 6, 7, 8, 9, 14, 10, 9, 8, 6, 11, 12, 13, 11, 6, 9, 14, 10, 9, 11, 12, 13, 11, 14, 10, 12, 7, 6, 11, 12, 13, 11, 6, 7, 8, 9, 14, 10, 9, 8, 6, 11, 12, 13, 11, 6, 9, 14, 10, 9, 11, 12, 13, 11, 14, 10, 12,
]; ];
/// <summary>ctxIdxInc of significant_coeff_flag for 8×8 field blocks (table 9-43), by levelListIdx.</summary>
internal static readonly byte[] SignificantContext8x8Field =
[
0, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 7, 7, 8, 4, 5, 6, 9, 10, 10, 8, 11, 12, 11, 9, 9, 10, 10, 8, 11, 12, 11,
9, 9, 10, 10, 8, 11, 12, 11, 9, 9, 10, 10, 8, 13, 13, 9, 9, 10, 10, 8, 13, 13, 9, 9, 10, 10, 14, 14, 14, 14, 14,
];
/// <summary>ctxIdxInc of last_significant_coeff_flag for 8×8 blocks (table 9-43), by levelListIdx.</summary> /// <summary>ctxIdxInc of last_significant_coeff_flag for 8×8 blocks (table 9-43), by levelListIdx.</summary>
internal static readonly byte[] LastContext8x8 = internal static readonly byte[] LastContext8x8 =
[ [
+9 -9
View File
@@ -5,12 +5,12 @@ internal static class InterPrediction
{ {
/// <summary> /// <summary>
/// Luma prediction of a <paramref name="w"/> × <paramref name="h"/> block whose top-left corner, in quarter /// Luma prediction of a <paramref name="w"/> × <paramref name="h"/> block whose top-left corner, in quarter
/// samples, is (<paramref name="qx"/>, <paramref name="qy"/>). Samples outside the picture repeat the edge. /// samples, is (<paramref name="qx"/>, <paramref name="qy"/>), from the <paramref name="pw"/> × <paramref name="ph"/>
/// 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> /// </summary>
internal static void Luma(Picture reference, int qx, int qy, int w, int h, Span<byte> dst) 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)
{ {
var plane = reference.Y;
int pw = reference.Width, ph = reference.Height;
int xInt = qx >> 2, yInt = qy >> 2, xFrac = qx & 3, yFrac = qy & 3; int xInt = qx >> 2, yInt = qy >> 2, xFrac = qx & 3, yFrac = qy & 3;
// Window with two samples before and three after in each direction. // Window with two samples before and three after in each direction.
@@ -26,7 +26,7 @@ internal static class InterPrediction
sy = sy < 0 ? 0 : sy >= ph ? ph - 1 : sy; sy = sy < 0 ? 0 : sy >= ph ? ph - 1 : sy;
} }
var rowBase = sy * pw; var rowBase = origin + (sy * stride);
for (var c = 0; c < ww; c++) for (var c = 0; c < ww; c++)
{ {
var sx = xInt - 2 + c; var sx = xInt - 2 + c;
@@ -170,16 +170,16 @@ internal static class InterPrediction
/// <summary> /// <summary>
/// Chroma prediction (4:2:0) of a <paramref name="w"/> × <paramref name="h"/> block whose corner, in eighths of a /// 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"/>). /// chroma sample, is (<paramref name="ex"/>, <paramref name="ey"/>), from a plane view as for <see cref="Luma"/>.
/// </summary> /// </summary>
internal static void Chroma(byte[] plane, int pw, int ph, int ex, int ey, int w, int h, Span<byte> dst) 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)
{ {
int xInt = ex >> 3, yInt = ey >> 3, xFrac = ex & 7, yFrac = ey & 7; 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; int wA = (8 - xFrac) * (8 - yFrac), wB = xFrac * (8 - yFrac), wC = (8 - xFrac) * yFrac, wD = xFrac * yFrac;
for (var y = 0; y < h; y++) for (var y = 0; y < h; y++)
{ {
var y0 = Math.Clamp(yInt + y, 0, ph - 1) * pw; var y0 = origin + (Math.Clamp(yInt + y, 0, ph - 1) * stride);
var y1 = Math.Clamp(yInt + y + 1, 0, ph - 1) * pw; var y1 = origin + (Math.Clamp(yInt + y + 1, 0, ph - 1) * stride);
for (var x = 0; x < w; x++) for (var x = 0; x < w; x++)
{ {
var x0 = Math.Clamp(xInt + x, 0, pw - 1); var x0 = Math.Clamp(xInt + x, 0, pw - 1);
+7 -2
View File
@@ -388,8 +388,12 @@ internal static class IntraPrediction
} }
} }
/// <summary>Chroma prediction of one 8×8 4:2:0 component (§8.3.4): 0 DC, 1 horizontal, 2 vertical, 3 plane.</summary> /// <summary>
internal static void PredictChroma(byte[] p, int o, int stride, int mode, bool left, bool top, bool topLeft) /// 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.
/// </summary>
internal static void PredictChroma(byte[] p, int o, int stride, int mode, bool leftUpper, bool leftLower, bool top, bool topLeft)
{ {
switch (mode) switch (mode)
{ {
@@ -399,6 +403,7 @@ internal static class IntraPrediction
for (var bx = 0; bx < 2; bx++) for (var bx = 0; bx < 2; bx++)
{ {
var b = o + (by * 4 * stride) + (bx * 4); var b = o + (by * 4 * stride) + (bx * 4);
var left = by == 0 ? leftUpper : leftLower;
int sumT = 0, sumL = 0; int sumT = 0, sumL = 0;
for (var i = 0; i < 4; i++) for (var i = 0; i < 4; i++)
{ {
+72 -9
View File
@@ -1,10 +1,17 @@
namespace Febe.Core.Codecs.H264; namespace Febe.Core.Codecs.H264;
/// <summary> /// <summary>
/// A decoded frame with what later pictures need from it: samples (4:2:0, 8 bits, the full macroblock area), motion /// A frame store of the decoded picture buffer: a decoded frame, or the two fields of a complementary field pair (its
/// vectors and references of every block (for direct prediction and the deblocking of the pictures that follow), and /// even rows are the top field, its odd rows the bottom one), with what later pictures need from it: samples (4:2:0,
/// its state in the decoded picture buffer. /// 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.
/// </summary> /// </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"/>).
/// </remarks>
internal sealed class Picture internal sealed class Picture
{ {
internal Picture(int widthInMbs, int heightInMbs) internal Picture(int widthInMbs, int heightInMbs)
@@ -20,7 +27,9 @@ internal sealed class Picture
Mv = new short[2 * mbs * 16 * 2]; Mv = new short[2 * mbs * 16 * 2];
RefIdx = new sbyte[2 * mbs * 4]; RefIdx = new sbyte[2 * mbs * 4];
RefPic = new Picture?[2 * mbs * 4]; RefPic = new Picture?[2 * mbs * 4];
RefPar = new sbyte[2 * mbs * 4];
MbIntra = new bool[mbs]; MbIntra = new bool[mbs];
MbField = new bool[mbs];
} }
internal int WidthInMbs { get; } internal int WidthInMbs { get; }
@@ -43,38 +52,92 @@ internal sealed class Picture
/// <summary>Reference indices: [(list * mbs + mb) * 4 + 8×8 block]; −1 when the list is not used.</summary> /// <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 { get; }
/// <summary>The picture each 8×8 block refers to, by list (same index as <see cref="RefIdx"/>).</summary> /// <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 { get; }
/// <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 bool[] MbIntra { get; } internal bool[] MbIntra { get; }
/// <summary>Field macroblocks: those of field pictures and the field pairs of MBAFF frames.</summary>
internal bool[] MbField { get; }
internal int MbCount => WidthInMbs * HeightInMbs; internal int MbCount => WidthInMbs * HeightInMbs;
internal int Poc; /// <summary>TopFieldOrderCnt and BottomFieldOrderCnt (§8.2.1) of the fields decoded so far.</summary>
internal int TopPoc;
internal int BottomPoc;
/// <summary>The fields decoded so far: 1 top, 2 bottom, 3 both (a frame or a field pair).</summary>
internal int Decoded;
/// <summary>Coded as two field pictures (else as a frame, progressive or MBAFF).</summary>
internal bool CodedAsFields;
internal int FrameNum; internal int FrameNum;
internal int FrameNumWrap; internal int FrameNumWrap;
internal int LongTermFrameIdx; internal int LongTermFrameIdx;
internal bool ShortTerm;
internal bool LongTerm; /// <summary>Fields used for short-term reference: 1 top, 2 bottom, 3 both (the frame).</summary>
internal int ShortMask;
/// <summary>Fields used for long-term reference, as <see cref="ShortMask"/>.</summary>
internal int LongMask;
/// <summary>A frame inferred for a gap in frame_num (§8.2.5.2): never output, its samples are not meaningful.</summary> /// <summary>A frame inferred for a gap in frame_num (§8.2.5.2): never output, its samples are not meaningful.</summary>
internal bool NonExisting; internal bool NonExisting;
/// <summary>Decoding order of the picture in the stream.</summary> /// <summary>Some field of the frame was not reconstructed (nobody refers to it, nobody wants it): it is not handed out.</summary>
internal bool Skipped;
/// <summary>In the decoded picture buffer.</summary>
internal bool InDpb;
/// <summary>Decoding order of the frame in the stream.</summary>
internal long DecodeIndex; internal long DecodeIndex;
/// <summary>Counts IDR pictures (and memory_management_control_operation 5): output order restarts with each.</summary> /// <summary>Counts IDR pictures (and memory_management_control_operation 5): output order restarts with each.</summary>
internal int Period; internal int Period;
internal bool IsReference => ShortTerm || LongTerm; internal bool IsReference => (ShortMask | LongMask) != 0;
/// <summary>A short-term reference frame: both fields marked (§8.2.4.1, frames and complementary pairs).</summary>
internal bool ShortTerm => ShortMask == 3;
/// <summary>A long-term reference frame.</summary>
internal bool LongTerm => LongMask == 3;
internal int PicNum => FrameNumWrap; internal int PicNum => FrameNumWrap;
internal int LongTermPicNum => LongTermFrameIdx; internal int LongTermPicNum => LongTermFrameIdx;
/// <summary>PicOrderCnt of the frame (§8.2.1): the smaller of the fields decoded.</summary>
internal int Poc => Decoded switch
{
1 => TopPoc,
2 => BottomPoc,
_ => Math.Min(TopPoc, BottomPoc),
};
/// <summary>PicOrderCnt of a field (0 top, 1 bottom) or of the frame (−1).</summary>
internal int PocOf(int parity) => parity < 0 ? Poc : parity == 0 ? TopPoc : BottomPoc;
/// <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) => WidthInMbs == widthInMbs && HeightInMbs == heightInMbs;
} }
/// <summary>A reference picture of a list: a frame (<see cref="Parity"/> −1) or one field of a frame store.</summary>
internal readonly record struct RefEntry(Picture? Pic, int Parity)
{
internal int Poc => Pic!.PocOf(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 4:2:0.</summary>
/// <param name="Width">Luma width after cropping.</param> /// <param name="Width">Luma width after cropping.</param>
/// <param name="Height">Luma height after cropping.</param> /// <param name="Height">Luma height after cropping.</param>
+5 -1
View File
@@ -18,6 +18,7 @@ internal sealed class SliceHeader
internal int PpsId; internal int PpsId;
internal int FrameNum; internal int FrameNum;
internal bool FieldPic; internal bool FieldPic;
internal bool BottomField;
internal int IdrPicId; internal int IdrPicId;
internal int PocLsb; internal int PocLsb;
internal int DeltaPocBottom; internal int DeltaPocBottom;
@@ -59,6 +60,9 @@ internal sealed class SliceHeader
internal bool IsB => Type == SliceType.B; internal bool IsB => Type == SliceType.B;
/// <summary>0 frame, 1 top field, 2 bottom field.</summary>
internal int Structure => !FieldPic ? 0 : BottomField ? 2 : 1;
internal static SliceHeader Parse(RbspReader r, NalUnit nal, IReadOnlyDictionary<int, Sps> sequences, IReadOnlyDictionary<int, Pps> pictures, out Sps sps, out Pps pps) internal static SliceHeader Parse(RbspReader r, NalUnit nal, IReadOnlyDictionary<int, Sps> sequences, IReadOnlyDictionary<int, Pps> pictures, out Sps sps, out Pps pps)
{ {
var h = new SliceHeader { FirstMb = (int)r.ReadUe() }; var h = new SliceHeader { FirstMb = (int)r.ReadUe() };
@@ -81,7 +85,7 @@ internal sealed class SliceHeader
h.FieldPic = r.ReadFlag(); h.FieldPic = r.ReadFlag();
if (h.FieldPic) if (h.FieldPic)
{ {
throw new H264Exception("I video interlacciati non sono gestiti."); h.BottomField = r.ReadFlag();
} }
} }
@@ -40,7 +40,7 @@ del riferimento.
## I flussi verificati ## I flussi verificati
`H264ConformanceTests.FramesMatchTheReference`: a immagini intere, 4:2:0 a 8 bit, sulla sequenza «Foreman». `H264ConformanceTests.FramesMatchTheReference`, tutti 4:2:0 a 8 bit. A immagini intere, sulla sequenza «Foreman»:
| Flusso | Profilo, formato | Che cosa prova | | Flusso | Profilo, formato | Che cosa prova |
|---|---|---| |---|---|---|
@@ -57,17 +57,8 @@ del riferimento.
| `FRExt3_Panasonic_E` | High, CIF, 11 | CABAC, trasformata 8×8 e 4×4 adattiva, matrici di quantizzazione, slice B con diretta temporale | | `FRExt3_Panasonic_E` | High, CIF, 11 | CABAC, trasformata 8×8 e 4×4 adattiva, matrici di quantizzazione, slice B con diretta temporale |
| `HCAFR1_HHI_C` | High, CIF, 10 | CABAC con inizializzazione adattiva (`cabac_init_idc` 0, 1, 2), trasformata 8×8, matrici predefinite, slice B | | `HCAFR1_HHI_C` | High, CIF, 10 | CABAC con inizializzazione adattiva (`cabac_init_idc` 0, 1, 2), trasformata 8×8, matrici predefinite, slice B |
`H264ConformanceTests.SvcBaseLayerMatchesTheReference`: lo strato base dei tre flussi SVC qui sotto, con Immagini interlacciate (campi, PAFF, MBAFF). Ogni fotogramma esce con i due campi intercalati riga per riga; un campo
`riferimento-base.md5`. rimasto senza il suo compagno esce da solo, con le righe dell'altro campo grigie (128).
## I flussi delle parti ancora da fare
`H264ConformanceTests.FeaturesStillToDo`: il decodificatore oggi rifiuta queste parti con un'`H264Exception` (o, per SVC
e MVC, dà solo lo strato o la vista base), e la prova è **inconclusiva** con il messaggio «da fare: …», così la serie
resta verde e il vuoto si vede. Quando una di queste coincide con il riferimento la prova **fallisce** apposta, per
ricordare di spostarla fra i flussi verificati.
**Immagini interlacciate** (campi, PAFF, MBAFF), 4:2:0 a 8 bit:
| Flusso | Profilo, formato | Che cosa prova | | Flusso | Profilo, formato | Che cosa prova |
|---|---|---| |---|---|---|
@@ -89,6 +80,19 @@ ricordare di spostarla fra i flussi verificati.
| `MR6_BT_B` | Extended, 192×128, 60 | campi, CAVLC, POC di tipo 1, MMCO, riordino, numero di slice variabile | | `MR6_BT_B` | Extended, 192×128, 60 | campi, CAVLC, POC di tipo 1, MMCO, riordino, numero di slice variabile |
| `MR9_BT_B` | Main, 192×128, 58 | MBAFF e PAFF, CABAC, slice B, POC di tipo 1, MMCO, riordino | | `MR9_BT_B` | Main, 192×128, 58 | MBAFF e PAFF, CABAC, slice B, POC di tipo 1, MMCO, riordino |
Nessuno di questi flussi usa la predizione pesata, i salti di `frame_num` o gli I_PCM: quelle parti del decodificatore
non hanno qui un riferimento ufficiale.
`H264ConformanceTests.SvcBaseLayerMatchesTheReference`: lo strato base dei tre flussi SVC qui sotto, con
`riferimento-base.md5`.
## I flussi delle parti ancora da fare
`H264ConformanceTests.FeaturesStillToDo`: il decodificatore oggi rifiuta queste parti con un'`H264Exception` (o, per SVC
e MVC, dà solo lo strato o la vista base), e la prova è **inconclusiva** con il messaggio «da fare: …», così la serie
resta verde e il vuoto si vede. Quando una di queste coincide con il riferimento la prova **fallisce** apposta, per
ricordare di spostarla fra i flussi verificati.
**Strumenti di Baseline ed Extended**, QCIF 4:2:0 a 8 bit: **Strumenti di Baseline ed Extended**, QCIF 4:2:0 a 8 bit:
| Flusso | Profilo, formato | Che cosa prova | | Flusso | Profilo, formato | Che cosa prova |
@@ -6,11 +6,12 @@ namespace Febe.Tests.Codecs.H264;
/// <summary> /// <summary>
/// The decoder against streams of the ITU-T H.264.1 conformance suite: every output frame, in output order, must have the /// The decoder against streams of the ITU-T H.264.1 conformance suite: every output frame, in output order, must have the
/// MD5 of the corresponding frame of the official reconstruction (see Conformita/LEGGIMI.md). None of the verified streams /// MD5 of the corresponding frame of the official reconstruction (see Conformita/LEGGIMI.md). The verified streams include
/// uses weighted prediction, memory management operations, long-term references, gaps in frame_num, POC type 1, I_PCM or /// interlaced video — field pictures, PAFF, MBAFF, both together — with memory management operations, long-term
/// CABAC pictures of several slices: those parts of the decoder have no reference MD5 here (some are reached by /// references and POC type 1 on fields (MR6_BT_B, MR9_BT_B). None of them uses weighted prediction, gaps in frame_num or
/// <see cref="H264SyntheticStreamTests"/>, without an official reference). The streams of the parts the decoder does not /// I_PCM: those parts of the decoder have no reference MD5 here (some are reached by <see cref="H264SyntheticStreamTests"/>,
/// handle yet (interlaced pictures, FMO and ASO, SP slices, 4:2:2, more than 8 bits, 4:0:0, SVC, MVC) are in /// without an official reference). The streams of the parts the decoder does not handle yet (FMO and ASO, SP slices,
/// 4:2:2, more than 8 bits, 4:0:0, SVC, MVC) are in
/// <see cref="FeaturesStillToDo"/>: they are inconclusive until the feature is written, and fail as soon as one of them /// <see cref="FeaturesStillToDo"/>: they are inconclusive until the feature is written, and fail as soon as one of them
/// matches its reference without having been moved among the verified ones. /// matches its reference without having been moved among the verified ones.
/// </summary> /// </summary>
@@ -30,6 +31,23 @@ public sealed class H264ConformanceTests
[DataRow("FRExt1_Panasonic_D")] [DataRow("FRExt1_Panasonic_D")]
[DataRow("FRExt3_Panasonic_E")] [DataRow("FRExt3_Panasonic_E")]
[DataRow("HCAFR1_HHI_C")] [DataRow("HCAFR1_HHI_C")]
[DataRow("CVFI1_SVA_C")]
[DataRow("FI1_Sony_E")]
[DataRow("CAFI1_SVA_C")]
[DataRow("Sharp_MP_PAFF_1r2")]
[DataRow("HCAFF1_HHI_B")]
[DataRow("CVMAQP3_Sony_D")]
[DataRow("FREXT02_JVC_C")]
[DataRow("CAMACI3_Sony_C")]
[DataRow("CAMASL3_Sony_B")]
[DataRow("HCAMFF1_HHI_B")]
[DataRow("FREXT01_JVC_D")]
[DataRow("CAPAMA3_Sand_F")]
[DataRow("cama1_vtc_c")]
[DataRow("FRExt2_Panasonic_C")]
[DataRow("FRExt4_Panasonic_B")]
[DataRow("MR6_BT_B")]
[DataRow("MR9_BT_B")]
public void FramesMatchTheReference(string name) => AssertMatches(name, "riferimento.md5"); public void FramesMatchTheReference(string name) => AssertMatches(name, "riferimento.md5");
[TestMethod] [TestMethod]
@@ -44,23 +62,6 @@ public sealed class H264ConformanceTests
} }
[TestMethod] [TestMethod]
[DataRow("CVFI1_SVA_C", "immagini a campi (CAVLC)")]
[DataRow("FI1_Sony_E", "immagini a campi, solo slice I (CAVLC)")]
[DataRow("CAFI1_SVA_C", "immagini a campi (CABAC)")]
[DataRow("Sharp_MP_PAFF_1r2", "PAFF, fotogrammi e coppie di campi (CAVLC, POC di tipo 1)")]
[DataRow("HCAFF1_HHI_B", "PAFF (CABAC, High)")]
[DataRow("CVMAQP3_Sony_D", "MBAFF (CAVLC)")]
[DataRow("FREXT02_JVC_C", "MBAFF (CAVLC, High)")]
[DataRow("CAMACI3_Sony_C", "MBAFF con predizione intra vincolata (CABAC)")]
[DataRow("CAMASL3_Sony_B", "MBAFF con quattro slice per immagine (CABAC)")]
[DataRow("HCAMFF1_HHI_B", "MBAFF (CABAC, High)")]
[DataRow("FREXT01_JVC_D", "MBAFF (CABAC, High)")]
[DataRow("CAPAMA3_Sand_F", "PAFF e MBAFF insieme (CABAC)")]
[DataRow("cama1_vtc_c", "campi con il campo inferiore per primo e MBAFF (CABAC)")]
[DataRow("FRExt2_Panasonic_C", "campi e MBAFF con MMCO e matrici di quantizzazione (CAVLC, High)")]
[DataRow("FRExt4_Panasonic_B", "campi e MBAFF con matrici di quantizzazione (CABAC, High)")]
[DataRow("MR6_BT_B", "campi con MMCO e riordino dei riferimenti (Extended, POC di tipo 1)")]
[DataRow("MR9_BT_B", "campi e MBAFF con MMCO e riordino dei riferimenti (CABAC, POC di tipo 1)")]
[DataRow("FM2_SVA_C", "FMO (gruppi di slice di tipo 0) e ASO")] [DataRow("FM2_SVA_C", "FMO (gruppi di slice di tipo 0) e ASO")]
[DataRow("FM1_FT_E", "FMO (gruppi di slice di tipo 1, 2, 3 e 4)")] [DataRow("FM1_FT_E", "FMO (gruppi di slice di tipo 1, 2, 3 e 4)")]
[DataRow("FM1_BT_B", "FMO (gruppi di slice di tipo 0-6) e ASO")] [DataRow("FM1_BT_B", "FMO (gruppi di slice di tipo 0-6) e ASO")]
@@ -123,6 +124,12 @@ public sealed class H264ConformanceTests
[DataRow("FRExt1_Panasonic_D")] [DataRow("FRExt1_Panasonic_D")]
[DataRow("FRExt3_Panasonic_E")] [DataRow("FRExt3_Panasonic_E")]
[DataRow("HCAFR1_HHI_C")] [DataRow("HCAFR1_HHI_C")]
[DataRow("CAFI1_SVA_C")]
[DataRow("Sharp_MP_PAFF_1r2")]
[DataRow("CAPAMA3_Sand_F")]
[DataRow("cama1_vtc_c")]
[DataRow("HCAMFF1_HHI_B")]
[DataRow("MR9_BT_B")]
public void PicturesLeftOutDoNotChangeTheOthers(string name) public void PicturesLeftOutDoNotChangeTheOthers(string name)
{ {
// Pictures nobody refers to and nobody wants are not reconstructed (only their headers count): every frame // Pictures nobody refers to and nobody wants are not reconstructed (only their headers count): every frame
@@ -22,10 +22,16 @@ public sealed class H264RobustnessTests
[DataRow("FRExt1_Panasonic_D", 2650)] [DataRow("FRExt1_Panasonic_D", 2650)]
[DataRow("FRExt3_Panasonic_E", 2651)] [DataRow("FRExt3_Panasonic_E", 2651)]
[DataRow("HCAFR1_HHI_C", 2652)] [DataRow("HCAFR1_HHI_C", 2652)]
[DataRow("FI1_Sony_E", 2653)]
[DataRow("CVMAQP3_Sony_D", 2654)]
[DataRow("CAMACI3_Sony_C", 2655)]
[DataRow("CAMASL3_Sony_B", 2656)]
[DataRow("MR6_BT_B", 2657)]
[DataRow("MR9_BT_B", 2658)]
[DataRow("CAPAMA3_Sand_F", 2659)]
public void DamagedStreamsGiveFramesOrAnH264Exception(string name, int seed) public void DamagedStreamsGiveFramesOrAnH264Exception(string name, int seed)
{ {
var folder = Path.Combine(AppContext.BaseDirectory, "Media", "H264", "Conformita", name); var data = File.ReadAllBytes(H264ConformanceTests.StreamFile(H264ConformanceTests.Folder(name)));
var data = File.ReadAllBytes(Directory.EnumerateFiles(folder).Single(f => Path.GetExtension(f) is ".264" or ".jsv" or ".avc"));
var random = new Random(seed); var random = new Random(seed);
for (var trial = 0; trial < 60; trial++) for (var trial = 0; trial < 60; trial++)
{ {
@@ -48,6 +48,30 @@ public sealed class H264TablesTests
{ {
CollectionAssert.AreEquivalent(Enumerable.Range(0, 16).ToArray(), H264Tables.ZigZag4x4.Select(b => (int)b).ToArray()); CollectionAssert.AreEquivalent(Enumerable.Range(0, 16).ToArray(), H264Tables.ZigZag4x4.Select(b => (int)b).ToArray());
CollectionAssert.AreEquivalent(Enumerable.Range(0, 64).ToArray(), H264Tables.ZigZag8x8.Select(b => (int)b).ToArray()); CollectionAssert.AreEquivalent(Enumerable.Range(0, 64).ToArray(), H264Tables.ZigZag8x8.Select(b => (int)b).ToArray());
CollectionAssert.AreEquivalent(Enumerable.Range(0, 16).ToArray(), H264Tables.FieldScan4x4.Select(b => (int)b).ToArray());
CollectionAssert.AreEquivalent(Enumerable.Range(0, 64).ToArray(), H264Tables.FieldScan8x8.Select(b => (int)b).ToArray());
}
[TestMethod]
public void FieldScansGoDownBeforeAcross()
{
// Field scans (Tables 8-13 and 8-14) favour vertical frequencies: the first coefficients after DC are the ones
// below it.
CollectionAssert.AreEqual(new byte[] { 0, 4, 1, 8, 12, 5 }, H264Tables.FieldScan4x4[..6]);
CollectionAssert.AreEqual(new byte[] { 0, 8, 16, 1, 9, 24, 32, 17 }, H264Tables.FieldScan8x8[..8]);
Assert.AreEqual(63, H264Tables.FieldScan8x8[63]);
}
[TestMethod]
public void FieldSignificanceContextsOf8x8BlocksMatchTheStandard()
{
// Table 9-43, ctxIdxInc of significant_coeff_flag for field coded 8×8 blocks: 63 values from 0 to 14.
var table = H264Tables.SignificantContext8x8Field;
Assert.AreEqual(63, table.Length);
Assert.AreEqual(0, table[0]);
Assert.AreEqual(14, table.Max());
Assert.AreEqual(14, table[62]);
Assert.AreEqual(H264Tables.SignificantContext8x8.Length, table.Length);
} }
[TestMethod] [TestMethod]