From 9c626f67ec2d84baf130b78e6a8f2fcd9530aa05 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 18 Nov 2026 16:05:41 +0100 Subject: [PATCH] Decodificatore H.264 per le immagini interlacciate: campi, PAFF e MBAFF (#58) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/decisioni.md | 1 + .../Codecs/H264/H264Decoder.Deblock.cs | 445 +++++++--- .../Codecs/H264/H264Decoder.Entropy.cs | 87 +- .../Codecs/H264/H264Decoder.Motion.cs | 375 ++++++--- .../Codecs/H264/H264Decoder.Slice.cs | 576 +++++++++++-- src/Febe.Core/Codecs/H264/H264Decoder.cs | 794 +++++++++++++----- src/Febe.Core/Codecs/H264/H264Tables.cs | 17 + src/Febe.Core/Codecs/H264/InterPrediction.cs | 18 +- src/Febe.Core/Codecs/H264/IntraPrediction.cs | 9 +- src/Febe.Core/Codecs/H264/Picture.cs | 81 +- src/Febe.Core/Codecs/H264/SliceHeader.cs | 6 +- .../Media/H264/Conformita/LEGGIMI.md | 28 +- .../Media/H264/H264ConformanceTests.cs | 51 +- .../Media/H264/H264RobustnessTests.cs | 10 +- .../Febe.Tests/Media/H264/H264TablesTests.cs | 24 + 15 files changed, 1909 insertions(+), 613 deletions(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index e093acd..8c17cc3 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -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 | 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 | 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 | diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Deblock.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Deblock.cs index bd20f8e..f1963e2 100644 --- a/src/Febe.Core/Codecs/H264/H264Decoder.Deblock.cs +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Deblock.cs @@ -2,7 +2,10 @@ namespace Febe.Core.Codecs.H264; public sealed partial class H264Decoder { - /// Deblocking filter (§8.7) over the whole decoded picture, macroblock by macroblock in raster order. + /// + /// 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). + /// private void Deblock(Picture picture) { var any = false; @@ -16,156 +19,331 @@ public sealed partial class H264Decoder return; } - var stride = picture.Width; - var cstride = stride / 2; - Span bs = stackalloc byte[16]; - for (var m = 0; m < mbCount; m++) + if (curStructure != 0) { - var s = mbSlice[m]; - if (s < 0) - { - continue; - } + DeblockRows(picture, 2, curStructure - 1); + } + else if (activeSps!.MbAdaptiveFrameField) + { + DeblockPairs(picture); + } + else + { + DeblockRows(picture, 1, 0); + } + } - var (disable, alphaOffset, betaOffset) = sliceFilters[s]; - if (disable == 1) + /// A frame ( 1) or the field of ( 2). + 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 bs = stackalloc byte[4]; + var rows = heightInMbs / rowStep; + for (var row = 0; row < rows; row++) + { + for (var mx = 0; mx < w; mx++) { - continue; - } - - 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++) + var m = (((row * rowStep) + parity) * w) + mx; + var s = mbSlice[m]; + if (s < 0) { - for (var i = 0; i < 4; i++) - { - 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; - } + continue; } - // Luma. - for (var edge = 0; edge < 4; edge++) + var (disable, alphaOffset, betaOffset) = sliceFilters[s]; + 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); + } + } + } + + /// + /// 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). + /// + private void DeblockPairs(Picture picture) + { + var w = widthInMbs; + int width = picture.Width, cwidth = width / 2; + Span bs = stackalloc byte[4]; + Span rowBs = stackalloc byte[16]; + Span 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; } - var pm = edge == 0 ? neighbour : m; - var qpav = (mbQp[pm] + mbQp[m] + 1) >> 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) + var (disable, alphaOffset, betaOffset) = sliceFilters[s]; + if (disable == 1) { 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)]; - if (strength == 0) - { - continue; - } + lumaOrigin = (((pairY * 32) + bottom) * width) + (mx * 16); + chromaOrigin = (((pairY * 16) + bottom) * cwidth) + (mx * 8); + stride = 2 * width; + 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; - if (dir == 0) + // Left edge. + 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); - step = 1; + MbEdge(picture, leftTop + (bottom * w), m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); } else { - o = (((my * 16) + (edge * 4)) * stride) + (mx * 16) + k; - step = stride; + MixedLeftEdge(picture, m, leftTop, isField, bottom != 0, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, rowBs, rowMb); } - - 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; - for (var c = 0; c < 2; c++) + InnerEdges(picture, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + + // Top edge. + if (!isField && bottom == 1) { - var plane = c == 0 ? picture.Cb : picture.Cr; - var qpav = (mbQpC[(pm * 2) + c] + mbQpC[(m * 2) + c] + 1) >> 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) + MbEdge(picture, m - w, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + } + else if (pairY > 0) + { + var aboveTop = (((2 * pairY) - 2) * w) + mx; + if (mbSlice[aboveTop] >= 0 && (disable != 2 || mbSlice[aboveTop] == s)) { - continue; - } - - for (var k = 0; k < 8; k++) - { - var strength = bs[(edge * 4) + (k >> 1)]; - if (strength == 0) + if (!isField && field[aboveTop]) { - continue; - } - - int o, step; - if (dir == 0) - { - o = (((my * 8) + k) * cstride) + (mx * 8) + (ce * 4); - step = 1; + // A frame macroblock under a field pair: each field of its top rows against that field. + for (var j = 0; j < 2; j++) + { + MbEdge(picture, aboveTop + (j * w), m, false, lumaOrigin + (j * width), 2 * width, chromaOrigin + (j * cwidth), 2 * cwidth, alphaOffset, betaOffset, bs); + } } else { - o = (((my * 8) + (ce * 4)) * cstride) + (mx * 8) + k; - step = cstride; + var pm = isField && bottom == 0 && field[aboveTop] ? aboveTop : aboveTop + w; + 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); } } } } - /// bS of the edge between 4×4 luma blocks of and of (§8.7.2.1). - 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. + /// + 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 rowBs, Span 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); + } + } + } + } + + /// A macroblock edge between (left or above) and , luma and chroma. + private void MbEdge( + Picture picture, int pm, int qm, bool vertical, int lumaOrigin, int stride, int chromaOrigin, int cstride, int alphaOffset, int betaOffset, Span 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); + } + } + + /// The internal edges of macroblock in one direction (luma 4, 8, 12; chroma 4). + private void InnerEdges( + Picture picture, int m, bool vertical, int lumaOrigin, int stride, int chromaOrigin, int cstride, int alphaOffset, int betaOffset, Span 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 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 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); + } + } + } + + /// + /// bS of the edge between 4×4 luma blocks of and of + /// (§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. + /// + 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]) { - return mbEdge ? 4 : 3; + return mbEdge && (vertical || (!fieldP && !fieldQ)) ? 4 : 3; } if (HasCoefficients(pm, pb) || HasCoefficients(qm, qb)) @@ -173,14 +351,20 @@ public sealed partial class H264Decoder return 2; } + if (fieldP != fieldQ) + { + return 1; + } + + var limit = fieldQ ? 2 : 4; int pi = (pm * 4) + B8OfRaster(pb), qi = (qm * 4) + B8OfRaster(qb); var l1 = mbCount * 4; - var p0 = picture.RefIdx[pi] >= 0 ? picture.RefPic[pi] ?? picture : null; - var p1 = picture.RefIdx[l1 + pi] >= 0 ? picture.RefPic[l1 + pi] ?? picture : null; - var q0 = picture.RefIdx[qi] >= 0 ? picture.RefPic[qi] ?? picture : null; - var q1 = picture.RefIdx[l1 + qi] >= 0 ? picture.RefPic[l1 + qi] ?? picture : null; - var countP = (p0 is null ? 0 : 1) + (p1 is null ? 0 : 1); - var countQ = (q0 is null ? 0 : 1) + (q1 is null ? 0 : 1); + var p0 = UsedReference(picture, pi); + var p1 = UsedReference(picture, l1 + pi); + var q0 = UsedReference(picture, qi); + var q1 = UsedReference(picture, l1 + qi); + var countP = (p0.Pic is null ? 0 : 1) + (p1.Pic is null ? 0 : 1); + var countQ = (q0.Pic is null ? 0 : 1) + (q1.Pic is null ? 0 : 1); if (countP != countQ) { return 1; @@ -192,14 +376,14 @@ public sealed partial class H264Decoder int pv1 = l1Mv + pv0, qv1 = l1Mv + qv0; if (countP == 1) { - var refP = p0 ?? p1; - var refQ = q0 ?? q1; - if (!ReferenceEquals(refP, refQ)) + var refP = p0.Pic is not null ? p0 : p1; + var refQ = q0.Pic is not null ? q0 : q1; + if (refP != refQ) { 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) @@ -207,26 +391,31 @@ public sealed partial class H264Decoder 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) { return 1; } - if (!ReferenceEquals(p0, p1)) + if (p0 != p1) { - return ReferenceEquals(p0, q0) - ? (MvFar(mv, pv0, qv0) || MvFar(mv, pv1, qv1) ? 1 : 0) - : (MvFar(mv, pv0, qv1) || MvFar(mv, pv1, qv0) ? 1 : 0); + return p0 == q0 + ? (MvFar(mv, pv0, qv0, limit) || MvFar(mv, pv1, qv1, limit) ? 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. - var straight = MvFar(mv, pv0, qv0) || MvFar(mv, pv1, qv1); - var crossed = MvFar(mv, pv0, qv1) || MvFar(mv, pv1, qv0); + var straight = MvFar(mv, pv0, qv0, limit) || MvFar(mv, pv1, qv1, limit); + var crossed = MvFar(mv, pv0, qv1, limit) || MvFar(mv, pv1, qv0, limit); 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; + /// The picture (frame, or field of a frame store) a block refers to in a list; empty when the list is not used. + 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) { diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Entropy.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Entropy.cs index 415d4c1..52c7c74 100644 --- a/src/Febe.Core/Codecs/H264/H264Decoder.Entropy.cs +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Entropy.cs @@ -10,7 +10,7 @@ public sealed partial class H264Decoder 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); } @@ -25,8 +25,8 @@ public sealed partial class H264Decoder { case SliceType.I: { - var inc = (availA && mbKind[mb - 1] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0) - + (availB && mbKind[mb - widthInMbs] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0); + var inc = (mbA >= 0 && mbKind[mbA] 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) { return 0; @@ -49,8 +49,8 @@ public sealed partial class H264Decoder return 5 + (cabac.Decision(17) == 0 ? 0 : IntraMbTypeSuffix(17, intraSlice: false)); default: { - var inc = (availA && mbKind[mb - 1] is not (MbKind.BSkip or MbKind.BDirect) ? 1 : 0) - + (availB && mbKind[mb - widthInMbs] is not (MbKind.BSkip or MbKind.BDirect) ? 1 : 0); + var inc = (mbA >= 0 && mbKind[mbA] 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) { return 0; @@ -202,7 +202,9 @@ public sealed partial class H264Decoder 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) @@ -256,7 +258,14 @@ public sealed partial class H264Decoder 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() @@ -266,7 +275,7 @@ public sealed partial class H264Decoder 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; } @@ -295,7 +304,7 @@ public sealed partial class H264Decoder 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) { return 0; @@ -309,8 +318,8 @@ public sealed partial class H264Decoder return cabac.Decision(67) == 0 ? 2 : 3; } - private int ChromaModeCond(bool available, int n) => - available && IsIntra(n) && mbKind[n] != MbKind.IPcm && chromaModes[n] != 0 ? 1 : 0; + private int ChromaModeCond(int n) => + n >= 0 && IsIntra(n) && mbKind[n] != MbKind.IPcm && chromaModes[n] != 0 ? 1 : 0; private int ReadCbp(bool intra) { @@ -331,7 +340,8 @@ public sealed partial class H264Decoder } 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) @@ -340,14 +350,15 @@ public sealed partial class H264Decoder } 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; } - var a = availA ? mbCbp[mb - 1] >> 4 : 0; - var b = availB ? mbCbp[mb - widthInMbs] >> 4 : 0; + var a = mbA >= 0 ? mbCbp[mbA] >> 4 : 0; + var b = mbB >= 0 ? mbCbp[mbB] >> 4 : 0; var inc = (a != 0 ? 1 : 0) + (b != 0 ? 2 : 0); if (cabac.Decision(77 + inc) != 0) { @@ -556,9 +567,9 @@ public sealed partial class H264Decoder { 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 { @@ -569,9 +580,9 @@ public sealed partial class H264Decoder { 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 { @@ -591,9 +602,9 @@ public sealed partial class H264Decoder { 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 { @@ -604,9 +615,9 @@ public sealed partial class H264Decoder { 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 { @@ -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; if (cat == 5) { - (sigBase, lastBase, absBase) = (402, 417, 426); + (sigBase, lastBase, absBase) = mbField ? (436, 451, 426) : (402, 417, 426); } else { - sigBase = 105 + SigCatOffset[cat]; - lastBase = 166 + SigCatOffset[cat]; + sigBase = (mbField ? 277 : 105) + SigCatOffset[cat]; + lastBase = (mbField ? 338 : 166) + SigCatOffset[cat]; absBase = 227 + AbsCatOffset[cat]; } + var sig8x8 = mbField ? H264Tables.SignificantContext8x8Field : H264Tables.SignificantContext8x8; Span significant = stackalloc bool[64]; significant.Clear(); var last = -1; 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) { continue; @@ -743,12 +756,12 @@ public sealed partial class H264Decoder switch (cat) { case 0: - if (!(left ? availA : availB)) + n = left ? mbA : mbB; + if (n < 0) { return currentIntra ? 1 : 0; } - n = left ? mb - 1 : mb - widthInMbs; if (mbKind[n] == MbKind.IPcm) { return 1; @@ -756,12 +769,12 @@ public sealed partial class H264Decoder return mbKind[n] == MbKind.I16x16 ? cbfDc[n] & 1 : 0; case 3: - if (!(left ? availA : availB)) + n = left ? mbA : mbB; + if (n < 0) { return currentIntra ? 1 : 0; } - n = left ? mb - 1 : mb - widthInMbs; if (mbKind[n] == MbKind.IPcm) { return 1; @@ -778,13 +791,13 @@ public sealed partial class H264Decoder } 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; } - n = left ? mb - 1 : mb - widthInMbs; - index = left ? blk + 1 : blk + 2; + index = left ? ((((yM & 7) >> 2) * 2) + 1) : 2 + bx; } if (mbKind[n] == MbKind.IPcm) @@ -805,13 +818,13 @@ public sealed partial class H264Decoder } 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; } - n = left ? mb - 1 : mb - widthInMbs; - index = left ? blk + 3 : blk + 12; + index = left ? ((((yM & 15) >> 2) * 4) + 3) : 12 + bx; } if (mbKind[n] == MbKind.IPcm) diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs index aaf05c2..d786f6e 100644 --- a/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs @@ -3,8 +3,13 @@ namespace Febe.Core.Codecs.H264; public sealed partial class H264Decoder { private int weightMode; + + /// Implicit weights w0 of the slice by (refIdxL0, refIdxL1): frames, or the fields of a field picture. private int[] implicitW0 = []; + /// MBAFF: implicit weights of the field macroblocks, by parity of the macroblock. + private int[][] implicitField = [[], []]; + /// /// The neighbouring 4×4 luma block covering (, ) relative to the current /// 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 /// private int Neighbor(int xN, int yN, out int n, out int blk) { - blk = (((yN & 15) >> 2) * 4) + ((xN & 15) >> 2); - n = -1; - if (yN < 0) + if ((uint)xN < 16 && (uint)yN < 16) { - if (xN < 0) - { - if (!availD) - { - 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; + n = mb; + blk = ((yN >> 2) * 4) + (xN >> 2); + return 2; } - if (yN >= 16) + n = Locate(xN, yN, 16, out var yM); + if (n < 0) { + blk = 0; return 0; } - if (xN < 0) - { - if (!availA) - { - return 0; - } - - n = mb - 1; - return 1; - } - - if (xN >= 16) - { - return 0; - } - - n = mb; - return 2; + blk = (((yM & 15) >> 2) * 4) + ((xN & 15) >> 2); + return 1; } + /// + /// 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. + /// 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); @@ -81,14 +49,29 @@ public sealed partial class H264Decoder } 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]) { return (true, -1, 0, 0); } 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); } /// @@ -185,7 +168,8 @@ public sealed partial class H264Decoder private void PredictDirect(int first, int end) { var picture = cur!; - var col = Reference(1, 0); + var colEntry = Reference(1, 0); + var col = colEntry.Pic!; var inference = sps.Direct8x8Inference; 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 k = 0; k < 4; k++) { 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 colX = 0, colY = 0, colRef = -1; + int xCol, yCol; + 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; - if (!col.MbIntra[mb]) + if (!col.MbIntra[colMb]) { var colB8 = B8OfRaster(colBlk); - var list = col.RefIdx[(mb * 4) + colB8] >= 0 ? 0 : 1; - colRef = col.RefIdx[(((list * mbCount) + mb) * 4) + colB8]; - colRefPic = col.RefPic[(((list * mbCount) + mb) * 4) + colB8]; - var i = ((((list * mbCount) + mb) * 16) + colBlk) * 2; + var list = col.RefIdx[(colMb * 4) + colB8] >= 0 ? 0 : 1; + var index = (((list * mbCount) + colMb) * 4) + colB8; + colRef = col.RefIdx[index]; + colRefPic = col.RefPic[index]; + colRefPar = col.RefPar[index]; + var i = ((((list * mbCount) + colMb) * 16) + colBlk) * 2; colX = col.Mv[i]; colY = col.Mv[i + 1]; } @@ -255,7 +302,7 @@ public sealed partial class H264Decoder int r0, r1, m0x, m0y, m1x, m1y; 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; r1 = ref1; if (directZero || (r0 == 0 && colZero)) @@ -278,18 +325,29 @@ public sealed partial class H264Decoder } 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; var pic0 = Reference(0, r0); - var td = Math.Clamp(col.Poc - pic0.Poc, -128, 127); - if (pic0.LongTerm || td == 0) + var pic1 = Reference(1, 0); + var td = Math.Clamp(pic1.Poc - pic0.Poc, -128, 127); + if (pic0.IsLongTerm || td == 0) { (m0x, m0y) = (colX, colY); (m1x, m1y) = (0, 0); } 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 scale = Math.Clamp(((tb * tx) + 32) >> 6, -1024, 1023); m0x = ((scale * colX) + 128) >> 8; @@ -320,24 +378,39 @@ public sealed partial class H264Decoder private void SetDirectRef(int list, int b8, int refIdx) { var index = (((list * mbCount) + mb) * 4) + b8; - var active = list == 0 ? sh.NumRefIdxActiveL0 : sh.NumRefIdxActiveL1; - if (refIdx < 0 || refIdx >= active) + if (refIdx < 0 || refIdx >= RefIdxRange(list)) { cur!.RefIdx[index] = -1; cur.RefPic[index] = null; + cur.RefPar[index] = -1; return; } + var entry = Reference(list, 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) + /// + /// 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). + /// + private int MapColToList0(Picture? picture, int parity) { - var list = refList[0]; - for (var i = 0; i < list.Length; i++) + if (picture is null) { - 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; } @@ -346,20 +419,46 @@ public sealed partial class H264Decoder return 0; } - /// A reference picture of the slice; a substitute when the stream refers to a missing one. - private Picture Reference(int list, int refIdx) + /// For a field macroblock of an MBAFF frame its parity (its references are fields of the frame lists), else −1. + private int MbFieldOf => mbaff && mbField ? mbY & 1 : -1; + + /// + /// The entry of a list for a reference index: as built, or ( ≥ 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. + /// + private RefEntry ListEntry(int list, int refIdx, int fieldOf) { 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); + } + + /// A reference picture of the current macroblock; a substitute when the stream refers to a missing one. + 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)) { - 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. 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; - 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); + } + } + } + + /// Implicit weights (§8.4.2.3.1) for every pair of indices, with the order counts of frames or of fields. + 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++) { + var p0 = ListEntry(0, i, fieldOf); for (var j = 0; j < n1; j++) { - var p0 = Reference(0, i); - var p1 = Reference(1, j); + var p1 = ListEntry(1, j, fieldOf); var w0 = 32; - var td = Math.Clamp(p1.Poc - p0.Poc, -128, 127); - if (td != 0 && !p0.LongTerm && !p1.LongTerm) + if (p0.Pic is not null && p1.Pic is not null) { - 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) + var td = Math.Clamp(p1.Poc - p0.Poc, -128, 127); + if (td != 0 && !p0.IsLongTerm && !p1.IsLongTerm) { - 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 } } - /// Inter prediction of one partition with its motion (§8.4.2), written into the current picture. + /// + /// 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. + /// private void MotionCompensate(int px, int py, int w, int h) { var picture = cur!; @@ -444,79 +569,93 @@ public sealed partial class H264Decoder var i0 = ((mb * 16) + blk) * 2; var i1 = (((mbCount + mb) * 16) + blk) * 2; var x = (mbX * 16) + px; - var y = (mbY * 16) + py; + var y = ((mbField ? mbY >> 1 : mbY) * 16) + py; Span a = stackalloc byte[256]; Span b = stackalloc byte[256]; var size = w * h; var pa = a[..size]; var pb = b[..size]; - Picture? p0 = r0 >= 0 ? Reference(0, r0) : null; - Picture? p1 = r1 >= 0 ? Reference(1, r1) : null; - if (p0 is null && p1 is null) + var use0 = r0 >= 0; + var use1 = r1 >= 0; + if (!use0 && !use1) { - p0 = Reference(0, 0); + use0 = true; 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 width = picture.Width, height = picture.Height; // 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); - var stride = picture.Width; + Combine(pa, pb, use0, use1, r0, r1, 0); 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. - int cw = w / 2, ch = h / 2, cstride = stride / 2, cheight = picture.Height / 2; + // Chroma; between fields of opposite parity the vertical vector moves by a quarter of a chroma row (Table 8-9). + int cw = w / 2, ch = h / 2, cwidth = width / 2, cheight = height / 2; var csize = cw * ch; var ca = a[..csize]; var cb = b[..csize]; + var parity = mbY & 1; + var adjust0 = e0.Parity < 0 || e0.Parity == parity ? 0 : parity == 0 ? -2 : 2; + var adjust1 = e1.Parity < 0 || e1.Parity == parity ? 0 : parity == 0 ? -2 : 2; for (var comp = 1; comp <= 2; comp++) { - 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; 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 a, ReadOnlySpan 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 (weightMode == 1 && sh.Weights is { } weights && sh.Offsets is { } offsets) { var logWd = comp == 0 ? sh.LumaLog2WeightDenom : sh.ChromaLog2WeightDenom; - InterPrediction.WeightTwo(a, b, logWd, weights[0][(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) { - 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); } else @@ -530,7 +669,7 @@ public sealed partial class H264Decoder if (weightMode == 1 && sh.Weights is { } w && sh.Offsets is { } o) { var list = use0 ? 0 : 1; - var r = use0 ? r0 : r1; + var r = use0 ? w0Index : w1Index; var logWd = comp == 0 ? sh.LumaLog2WeightDenom : sh.ChromaLog2WeightDenom; InterPrediction.WeightOne(a, logWd, w[list][(r * 3) + comp], o[list][(r * 3) + comp]); } diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Slice.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Slice.cs index 50d5f44..db15d7d 100644 --- a/src/Febe.Core/Codecs/H264/H264Decoder.Slice.cs +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Slice.cs @@ -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 readonly List<(int Disable, int Alpha, int Beta)> sliceFilters = []; - private readonly Picture?[][] refList = [[], []]; + private readonly RefEntry[][] refList = [[], []]; private readonly CabacEngine cabac = new(); private int widthInMbs; @@ -67,14 +67,41 @@ public sealed partial class H264Decoder private int[][] ls4 = []; private int[][] ls8 = []; - // Macroblock state. + /// The picture is an MBAFF frame: macroblock pairs, each of two frame or two field macroblocks. + private bool mbaff; + + /// The picture is a field: its macroblocks are on every other row of the frame grid. + private bool fieldPic; + + /// The parity of the field being decoded (0 top, 1 bottom). + private int curParity; + + // Macroblock state: mb is the index on the frame grid (see Picture), mbY its row there. private int mb; private int mbX; private int mbY; - private bool availA; - private bool availB; - private bool availC; - private bool availD; + + /// The current macroblock is a field macroblock (of a field picture or a field pair). + private bool mbField; + + 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 int[] lumaCoef = new int[256]; private readonly bool[] lumaHas = new bool[16]; @@ -118,6 +145,9 @@ public sealed partial class H264Decoder pps = p; rd = reader; cabacMode = p.Cabac; + fieldPic = header.FieldPic; + curParity = header.BottomField ? 1 : 0; + mbaff = s.MbAdaptiveFrameField && !header.FieldPic; sliceNum = sliceCounter++; sliceFilters.Add((header.DisableDeblocking, header.AlphaOffset, header.BetaOffset)); qp = p.PicInitQp + header.QpDelta; @@ -157,37 +187,54 @@ public sealed partial class H264Decoder cabac.Start(rd); } - mb = header.FirstMb; - if (mb >= mbCount) + // Macroblock addresses of the slice: those of the field, or of the pairs (two per pair) in an MBAFF frame. + var total = fieldPic ? mbCount / 2 : mbCount; + var addr = header.FirstMb * (mbaff ? 2 : 1); + if (addr >= total) { throw new H264Exception("Primo macroblocco fuori dall'immagine."); } - var isIntraSlice = header.IsIntra; - while (mb < mbCount) + if (!mbaff) + { + 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) { var run = rd.ReadUe(); - if (run > (uint)(mbCount - mb)) + if (run > (uint)(total - addr)) { throw new H264Exception("mb_skip_run fuori dall'immagine."); } for (var i = 0; i < (int)run; i++) { - BeginMacroblock(); + BeginMacroblock(addr++); DecodeSkip(); - mb++; } - if ((run > 0 && !rd.MoreRbspData) || mb >= mbCount) + if ((run > 0 && !rd.MoreRbspData) || addr >= total) { break; } } - BeginMacroblock(); + BeginMacroblock(addr++); if (!isIntraSlice && cabacMode && ReadMbSkip() != 0) { DecodeSkip(); @@ -197,7 +244,6 @@ public sealed partial class H264Decoder DecodeMacroblock(); } - mb++; var more = cabacMode ? cabac.Terminate() == 0 : rd.MoreRbspData; if (!more) { @@ -206,16 +252,336 @@ public sealed partial class H264Decoder } } - /// Position and neighbour availability of macroblock . - 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. + /// + private void DecodePairsCavlc(int addr, int total) { - mbX = mb % widthInMbs; - mbY = mb / widthInMbs; - mbSlice[mb] = sliceNum; - availA = mbX > 0 && mbSlice[mb - 1] == sliceNum; - availB = mbY > 0 && mbSlice[mb - widthInMbs] == sliceNum; - availC = mbY > 0 && mbX < widthInMbs - 1 && mbSlice[mb - widthInMbs + 1] == sliceNum; - availD = mbY > 0 && mbX > 0 && mbSlice[mb - widthInMbs - 1] == sliceNum; + var isIntraSlice = sh.IsIntra; + while (addr < total) + { + if (!isIntraSlice) + { + var run = rd.ReadUe(); + 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; + } + } + } + + /// + /// 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. + /// + 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; + } + } + } + + /// 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. + 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; + } + + /// + /// Position of the macroblock of address 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. + /// + 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; + } + } + + /// + /// The macroblock covering the luma ( 16) or chroma (8) location (xN, yN) relative to the + /// current macroblock (§6.4.12), −1 when not available; is its row there (negative counts + /// from the bottom). In an MBAFF frame, Table 6-4. + /// + 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); + } + + /// + /// MBAFF: the macroblock of the pair to the left (whose top macroblock is ) holding row + /// of the current macroblock, and its row there (Table 6-4, xN < 0). + /// + 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; + } + + /// Starts the macroblock of address : its position, and its data cleared. + private void BeginMacroblock(int addr) + { + PlaceMacroblock(addr); Array.Clear(blkDone); Array.Clear(nz, mb * 24, 24); cbfDc[mb] = 0; @@ -223,16 +589,19 @@ public sealed partial class H264Decoder mbT8[mb] = false; chromaModes[mb] = 0; intraModes.AsSpan(mb * 16, 16).Fill(2); + var picture = cur!; for (var list = 0; list < 2; list++) { mvdAbs.AsSpan(((list * mbCount) + mb) * 32, 32).Clear(); - cur!.Mv.AsSpan(((list * mbCount) + mb) * 32, 32).Clear(); - cur.RefIdx.AsSpan(((list * mbCount) + mb) * 4, 4).Fill(-1); - cur.RefPic.AsSpan(((list * mbCount) + mb) * 4, 4).Clear(); + picture.Mv.AsSpan(((list * mbCount) + mb) * 32, 32).Clear(); + picture.RefIdx.AsSpan(((list * mbCount) + mb) * 4, 4).Fill(-1); + 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(); - cur!.MbIntra[mb] = false; + picture.MbIntra[mb] = false; + picture.MbField[mb] = mbField; } private void DecodeMacroblock() @@ -399,27 +768,29 @@ public sealed partial class H264Decoder { modeA = intraModes[(mb * 16) + (by * 4) + bx - 1]; } - else if (!availA || (pps.ConstrainedIntraPred && !IsIntra(mb - 1))) - { - return 2; - } else { - var a = mb - 1; - modeA = mbKind[a] is MbKind.I4x4 or MbKind.I8x8 ? intraModes[(a * 16) + (by * 4) + 3] : 2; + var a = Locate(-1, by * 4, 16, out var yM); + 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) { modeB = intraModes[(mb * 16) + ((by - 1) * 4) + bx]; } - else if (!availB || (pps.ConstrainedIntraPred && !IsIntra(mb - widthInMbs))) - { - return 2; - } 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; } @@ -437,23 +808,22 @@ public sealed partial class H264Decoder } var picture = cur!; - var w = picture.Width; for (var y = 0; y < 16; y++) { 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; - foreach (var plane in new[] { picture.Cb, picture.Cr }) + for (var c = 0; c < 2; c++) { + var plane = c == 0 ? picture.Cb : picture.Cr; for (var y = 0; y < 8; y++) { 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; 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++) { if ((partPred[i] & (1 << list)) == 0) @@ -572,7 +942,7 @@ public sealed partial class H264Decoder count = shape == Shape16x16 ? 1 : 2; 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++) { if ((partPred[part] & (1 << list)) == 0) @@ -738,17 +1108,28 @@ public sealed partial class H264Decoder } } - private void SetRefIdx(int list, int b8, int refIdx) + /// + /// 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). + /// + private int RefIdxRange(int list) { 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."); } var index = (((list * mbCount) + mb) * 4) + b8; + var entry = Reference(list, 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) @@ -819,6 +1200,9 @@ public sealed partial class H264Decoder var qpMod = qp % 6; var scale4 = ls4[listY]; + // Field macroblocks are scanned in field order (§8.5.6). + var scan4 = mbField ? H264Tables.FieldScan4x4 : H264Tables.ZigZag4x4; + if (intra16) { var count = ReadBlock(0, 0, 0, levels, 16); @@ -826,7 +1210,7 @@ public sealed partial class H264Decoder c.Clear(); for (var k = 0; k < 16; k++) { - c[H264Tables.ZigZag4x4[k]] = levels[k]; + c[scan4[k]] = levels[k]; } if (count > 0) @@ -885,7 +1269,7 @@ public sealed partial class H264Decoder var level = levels[k]; 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); lumaHas[raster] = true; } @@ -910,7 +1294,7 @@ public sealed partial class H264Decoder var level = levels[k]; if (level != 0) { - var pos = H264Tables.ZigZag4x4[k]; + var pos = scan4[k]; lumaCoef[(raster * 16) + pos] = Scale4(level, scale4[(qpMod * 16) + pos], qpDiv); lumaHas[raster] = true; } @@ -970,7 +1354,7 @@ public sealed partial class H264Decoder var level = levels[k]; 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); chromaHas[(c * 4) + b] = true; } @@ -989,6 +1373,7 @@ public sealed partial class H264Decoder var qpDiv = qp / 6; var qpMod = qp % 6; var any = false; + var scan8 = mbField ? H264Tables.FieldScan8x8 : H264Tables.ZigZag8x8; for (var k = 0; k < 64; k++) { var level = source[k]; @@ -997,7 +1382,7 @@ public sealed partial class H264Decoder continue; } - var pos = H264Tables.ZigZag8x8[k]; + var pos = scan8[k]; var ls = scale[(qpMod * 64) + pos]; lumaCoef[(b8 * 64) + pos] = qp >= 36 ? (level * ls) << (qpDiv - 6) : ((level * ls) + (1 << (5 - qpDiv))) >> (6 - qpDiv); 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; + + /// + /// 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). + /// + 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) { var picture = cur!; - var stride = picture.Width; + var stride = lumaStride; var constrained = pps.ConstrainedIntraPred; - var a = availA && (!constrained || IsIntra(mb - 1)); - var b = availB && (!constrained || IsIntra(mb - widthInMbs)); - var c = availC && (!constrained || IsIntra(mb - widthInMbs + 1)); - var d = availD && (!constrained || IsIntra(mb - widthInMbs - 1)); + var nB = Locate(0, -1, 16, out _); + var nC = Locate(16, -1, 16, out _); + var nD = Locate(-1, -1, 16, out _); + 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 block = stackalloc int[64]; switch (mbKind[mb]) { @@ -1028,9 +1453,9 @@ public sealed partial class H264Decoder { var raster = H264Tables.BlockToRaster[i]; 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 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; if (by == 0) { @@ -1042,7 +1467,7 @@ public sealed partial class H264Decoder } 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]) { lumaCoef.AsSpan(raster * 16, 16).CopyTo(block); @@ -1057,12 +1482,12 @@ public sealed partial class H264Decoder for (var i = 0; i < 4; i++) { 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 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 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]) { lumaCoef.AsSpan(i * 64, 64).CopyTo(block); @@ -1073,7 +1498,7 @@ public sealed partial class H264Decoder break; 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++) { if (lumaHas[raster]) @@ -1087,17 +1512,17 @@ public sealed partial class H264Decoder } } - var cstride = stride / 2; - var co = (mbY * 8 * cstride) + (mbX * 8); - IntraPrediction.PredictChroma(picture.Cb, co, cstride, chromaModes[mb], a, b, d); - IntraPrediction.PredictChroma(picture.Cr, co, cstride, chromaModes[mb], a, b, d); + var chromaLeft = LeftRows(8, constrained); + bool upper = Rows(chromaLeft, 0, 4), lower = Rows(chromaLeft, 4, 4); + IntraPrediction.PredictChroma(picture.Cb, chromaO, chromaStride, chromaModes[mb], upper, lower, b, d); + IntraPrediction.PredictChroma(picture.Cr, chromaO, chromaStride, chromaModes[mb], upper, lower, b, d); AddChromaResidual(); } private void AddInterResidual() { var picture = cur!; - var stride = picture.Width; + var stride = lumaStride; Span block = stackalloc int[64]; if (mbT8[mb]) { @@ -1128,7 +1553,6 @@ public sealed partial class H264Decoder private void AddChromaResidual() { var picture = cur!; - var cstride = picture.Width / 2; Span block = stackalloc int[16]; 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); - var o = (((mbY * 8) + ((b >> 1) * 4)) * cstride) + (mbX * 8) + ((b & 1) * 4); - Transform.Add4x4(block, plane, o, cstride); + var o = chromaO + ((b >> 1) * 4 * chromaStride) + ((b & 1) * 4); + Transform.Add4x4(block, plane, o, chromaStride); } } } diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.cs b/src/Febe.Core/Codecs/H264/H264Decoder.cs index 963f428..d414e86 100644 --- a/src/Febe.Core/Codecs/H264/H264Decoder.cs +++ b/src/Febe.Core/Codecs/H264/H264Decoder.cs @@ -14,13 +14,14 @@ public enum H264AccessPoint } /// -/// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Main and High profiles for -/// progressive frames in 4:2:0 with 8-bit samples — CAVLC and CABAC, I, P and B slices, 8×8 transform and scaling -/// matrices, spatial and temporal direct prediction, list modification, deblocking. Written from the standard but not -/// yet checked against a conformance stream: explicit and implicit weighted prediction, memory management operations -/// and long-term references, gaps in frame_num, picture order count type 1, I_PCM and CABAC pictures of several -/// slices. Not handled (an ): interlaced pictures (fields and MBAFF), slice groups, SP/SI -/// slices, data partitioning, 4:2:2/4:4:4 and depths above 8 bits. Redundant coded pictures are skipped. +/// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Main and High profiles in +/// 4:2:0 with 8-bit samples — CAVLC and CABAC, I, P and B slices, 8×8 transform and scaling matrices, spatial and +/// temporal direct prediction, list modification, memory management operations and long-term references, deblocking — +/// for progressive frames and for interlaced video: field pictures, frames and fields mixed picture by picture (PAFF), +/// frames of frame and field macroblock pairs (MBAFF). Frames come out whole: the two fields of a pair are interleaved. +/// Written from the standard but not yet checked against a conformance stream: explicit and implicit weighted +/// prediction, gaps in frame_num, I_PCM. Not handled (an ): slice groups, SP/SI slices, data +/// partitioning, 4:2:2/4:4:4 and depths above 8 bits. Redundant coded pictures are skipped. /// public sealed partial class H264Decoder { @@ -30,7 +31,22 @@ public sealed partial class H264Decoder private readonly Stack pool = new(); private Sps? activeSps; + + /// The frame store being decoded into (a frame, or one field of it). private Picture? cur; + + /// The structure of the picture being decoded: 0 frame, 1 top field, 2 bottom field. + private int curStructure; + + /// The picture being decoded is the second field of . + private bool curSecondField; + + /// A first field already decoded, waiting for the second field of its frame. + private Picture? openField; + + private int openStructure; + private int openRefIdc; + private SliceHeader? picHeader; private int picNalType; private int picRefIdc; @@ -111,7 +127,10 @@ public sealed partial class H264Decoder return lengthSize; } - /// Decodes one access unit stored with length prefixes (an MP4 or Matroska sample) and finishes its picture. + /// + /// Decodes one access unit stored with length prefixes (an MP4 or Matroska sample) and finishes its picture. A + /// sample holding only the first field of a frame leaves it waiting for the second one, in the next sample. + /// public void DecodeSample(ReadOnlySpan sample, int lengthSize) { var position = 0; @@ -123,7 +142,7 @@ public sealed partial class H264Decoder FinishPicture(); } - /// Decodes one access unit in Annex B form and finishes its picture. + /// Decodes one access unit in Annex B form and finishes its picture (as ). public void DecodeAccessUnitAnnexB(ReadOnlySpan accessUnit) { DecodeUnitsAnnexB(accessUnit); @@ -179,8 +198,16 @@ public sealed partial class H264Decoder } } - /// Finishes the picture being decoded, if any. - public void Flush() => FinishPicture(); + /// Finishes the picture being decoded, if any, and hands out a first field still waiting for its pair. + public void Flush() + { + FinishPicture(); + if (openField is { } field) + { + openField = null; + HandOut(field, activeSps!); + } + } /// /// Finishes the picture being decoded; a damaged picture whose deblocking or cropping fails raises an @@ -192,10 +219,11 @@ public sealed partial class H264Decoder { CompletePicture(); } - catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException) + catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException or NullReferenceException) { cur = null; picHeader = null; + openField = null; throw new H264Exception("Flusso H.264 troncato o danneggiato."); } } @@ -229,11 +257,11 @@ public sealed partial class H264Decoder } case 11: // end of stream - FinishPicture(); + Flush(); break; } } - catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException) + catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException or NullReferenceException) { throw new H264Exception("Flusso H.264 troncato o danneggiato."); } @@ -248,11 +276,6 @@ public sealed partial class H264Decoder throw new H264Exception("Solo video 4:2:0 a 8 bit."); } - if (!sps.FrameMbsOnly) - { - throw new H264Exception("I video interlacciati non sono gestiti."); - } - if (sps.TransformBypass) { throw new H264Exception("La codifica senza perdita non è gestita."); @@ -264,7 +287,7 @@ public sealed partial class H264Decoder return; } - if (cur is null || picHeader is null || StartsNewPicture(header, nal) || (header.FirstMb == 0 && mbSlice[0] >= 0)) + if (cur is null || picHeader is null || StartsNewPicture(header, nal) || FirstMacroblockDone(header, sps)) { FinishPicture(); StartPicture(nal, header, sps); @@ -289,8 +312,8 @@ public sealed partial class H264Decoder private bool StartsNewPicture(SliceHeader h, NalUnit nal) { var p = picHeader!; - if (h.FrameNum != p.FrameNum || h.PpsId != p.PpsId || (nal.RefIdc == 0) != (picRefIdc == 0) - || (nal.Type == 5) != (picNalType == 5) || (nal.Type == 5 && h.IdrPicId != p.IdrPicId)) + if (h.FrameNum != p.FrameNum || h.PpsId != p.PpsId || h.FieldPic != p.FieldPic || h.BottomField != p.BottomField + || (nal.RefIdc == 0) != (picRefIdc == 0) || (nal.Type == 5) != (picNalType == 5) || (nal.Type == 5 && h.IdrPicId != p.IdrPicId)) { return true; } @@ -303,13 +326,47 @@ public sealed partial class H264Decoder }; } + /// A slice starting on a macroblock already decoded: the previous picture lost its end, this is a new one. + private bool FirstMacroblockDone(SliceHeader h, Sps sps) + { + if (!ReferenceEquals(sps, activeSps) || mbSlice.Length != sps.WidthInMbs * sps.HeightInMbs) + { + return false; + } + + var w = sps.WidthInMbs; + int index; + if (h.FieldPic) + { + index = (((2 * (h.FirstMb / w)) + (h.BottomField ? 1 : 0)) * w) + (h.FirstMb % w); + } + else if (sps.MbAdaptiveFrameField) + { + index = (2 * (h.FirstMb / w) * w) + (h.FirstMb % w); + } + else + { + index = h.FirstMb; + } + + return (uint)index < (uint)mbSlice.Length && mbSlice[index] >= 0; + } + + /// Whether a picture other than the one being decoded can be predicted from. private bool HasReference() { foreach (var p in dpb) { - if (p.IsReference && !ReferenceEquals(p, cur)) + if (!ReferenceEquals(p, cur)) { - return true; + if (p.IsReference) + { + return true; + } + } + else if (curStructure != 0 && ((p.ShortMask | p.LongMask) & (3 - curStructure)) != 0) + { + return true; // the first field of the frame } } @@ -322,6 +379,12 @@ public sealed partial class H264Decoder { if (activeSps is null || activeSps.WidthInMbs != sps.WidthInMbs || activeSps.HeightInMbs != sps.HeightInMbs) { + if (openField is { } waiting && activeSps is not null) + { + openField = null; + HandOut(waiting, activeSps); + } + dpb.Clear(); pool.Clear(); AllocateMacroblockState(sps.WidthInMbs, sps.HeightInMbs); @@ -331,30 +394,64 @@ public sealed partial class H264Decoder } var idr = nal.Type == 5; - if (idr) + var structure = header.Structure; + + // The second field of a frame (§3.30, §3.31): the field after a first field of the opposite parity, with the same + // frame_num, both reference fields or both not, and not an IDR picture (which would release the first one). + curSecondField = false; + if (openField is { } first) { - period++; - } - else if (haveReference && header.FrameNum != prevRefFrameNum && header.FrameNum != (prevRefFrameNum + 1) % sps.MaxFrameNum) - { - FillFrameNumGap(header.FrameNum, sps); + openField = null; + if (structure != 0 && structure != openStructure && header.FrameNum == first.FrameNum && !idr + && (nal.RefIdc != 0) == (openRefIdc != 0)) + { + cur = first; + curSecondField = true; + } + else + { + HandOut(first, sps); + } } - cur = NewPicture(sps); - cur.FrameNum = header.FrameNum; - cur.Period = period; - cur.DecodeIndex = decodeCounter; + if (!curSecondField) + { + if (idr) + { + period++; + } + else if (haveReference && header.FrameNum != prevRefFrameNum && header.FrameNum != (prevRefFrameNum + 1) % sps.MaxFrameNum) + { + FillFrameNumGap(header.FrameNum, sps); + } + + cur = NewPicture(sps); + cur.FrameNum = header.FrameNum; + cur.Period = period; + cur.DecodeIndex = decodeCounter; + cur.CodedAsFields = structure != 0; + cur.Decoded = 0; + cur.Skipped = false; + } + + var picture = cur!; + curStructure = structure; picHeader = header; picNalType = nal.Type; picRefIdc = nal.RefIdc; picMmco5 = header.Mmco.Exists(m => m.Op == 5); - cur.Poc = ComputePoc(header, nal, sps, idr); + ComputePoc(picture, header, nal, sps, idr, structure); + picture.Decoded |= structure == 0 ? 3 : structure; sliceCounter = 0; sliceFilters.Clear(); Array.Fill(mbSlice, -1); // A picture nobody refers to and nobody wants: its header has set the state above, its slices are not decoded. - picSkipped = nal.RefIdc == 0 && Wanted is { } wanted && !wanted(cur.DecodeIndex); + picSkipped = nal.RefIdc == 0 && Wanted is { } wanted && !wanted(picture.DecodeIndex); + if (picSkipped) + { + picture.Skipped = true; + } } private Picture NewPicture(Sps sps) @@ -362,9 +459,10 @@ public sealed partial class H264Decoder while (pool.Count > 0) { var p = pool.Pop(); - if (p.Fits(sps.WidthInMbs, sps.HeightInMbs)) + if (p.Fits(sps.WidthInMbs, sps.HeightInMbs) && !p.InDpb && !ReferenceEquals(p, openField)) { - p.ShortTerm = p.LongTerm = p.NonExisting = false; + p.ShortMask = p.LongMask = 0; + p.NonExisting = false; Array.Clear(p.RefPic); return p; } @@ -373,8 +471,8 @@ public sealed partial class H264Decoder return new Picture(sps.WidthInMbs, sps.HeightInMbs); } - /// Picture order count (§8.2.1) of the picture starting now. - private int ComputePoc(SliceHeader h, NalUnit nal, Sps sps, bool idr) + /// Picture order count (§8.2.1) of the picture starting now, into the fields of it codes. + private void ComputePoc(Picture p, SliceHeader h, NalUnit nal, Sps sps, bool idr, int structure) { int top, bottom; switch (sps.PocType) @@ -401,8 +499,12 @@ public sealed partial class H264Decoder pocMsb = prevPocMsb; } - top = pocMsb + h.PocLsb; - bottom = top + h.DeltaPocBottom; + top = bottom = pocMsb + h.PocLsb; + if (structure == 0) + { + bottom = top + h.DeltaPocBottom; + } + break; } @@ -439,8 +541,17 @@ public sealed partial class H264Decoder expected += sps.OffsetForNonRefPic; } - top = expected + h.DeltaPoc0; - bottom = top + sps.OffsetForTopToBottomField + h.DeltaPoc1; + if (structure == 0) + { + top = expected + h.DeltaPoc0; + bottom = top + sps.OffsetForTopToBottomField + h.DeltaPoc1; + } + else + { + top = expected + h.DeltaPoc0; + bottom = expected + sps.OffsetForTopToBottomField + h.DeltaPoc0; + } + break; } @@ -452,7 +563,15 @@ public sealed partial class H264Decoder } } - return Math.Min(top, bottom); + if (structure != 2) + { + p.TopPoc = top; + } + + if (structure != 1) + { + p.BottomPoc = bottom; + } } private void UpdateFrameNumOffset(SliceHeader h, Sps sps, bool idr) @@ -485,7 +604,7 @@ public sealed partial class H264Decoder { foreach (var p in dpb) { - p.ShortTerm = false; + p.ShortMask = 0; } } @@ -511,11 +630,14 @@ public sealed partial class H264Decoder gap.FrameNum = n; gap.NonExisting = true; gap.Period = period; - gap.Poc = 0; + gap.TopPoc = gap.BottomPoc = 0; + gap.Decoded = 3; + gap.CodedAsFields = false; Array.Fill(gap.MbIntra, true); - SlidingWindow(sps, n); - gap.ShortTerm = true; - dpb.Add(gap); + Array.Clear(gap.MbField); + SlidingWindow(sps, n, null); + gap.ShortMask = 3; + AddToDpb(gap); } PruneDpb(); @@ -530,6 +652,7 @@ public sealed partial class H264Decoder var sps = activeSps; var picture = cur; + var structure = curStructure; var skipped = picSkipped; picSkipped = false; if (!skipped) @@ -545,10 +668,21 @@ public sealed partial class H264Decoder // State for the next picture. if (picMmco5) { - var temp = picture.Poc; + // After a memory_management_control_operation 5 the picture counts as frame_num 0 with its order count + // brought to 0 (tempPicOrderCnt of §8.2.1). + var temp = structure == 1 ? picture.TopPoc : structure == 2 ? picture.BottomPoc : Math.Min(picture.TopPoc, picture.BottomPoc); + if (structure != 2) + { + picture.TopPoc -= temp; + } + + if (structure != 1) + { + picture.BottomPoc -= temp; + } + prevPocMsb = 0; - prevPocLsb = 0; - picture.Poc -= temp; + prevPocLsb = structure == 2 ? 0 : picture.TopPoc; prevFrameNum = 0; prevFrameNumOffset = 0; picture.FrameNum = 0; @@ -571,28 +705,46 @@ public sealed partial class H264Decoder haveReference = true; } - if (!skipped && (Wanted?.Invoke(picture.DecodeIndex) ?? true)) + cur = null; + picHeader = null; + if (structure != 0 && !curSecondField) + { + // A first field: the frame comes out with its second field. + openField = picture; + openStructure = structure; + openRefIdc = picRefIdc; + } + else + { + HandOut(picture, sps); + } + + curSecondField = false; + PruneDpb(); + } + + /// Hands out a finished frame (or a field left without its pair) and counts it. + private void HandOut(Picture picture, Sps sps) + { + if (!picture.Skipped && (Wanted?.Invoke(picture.DecodeIndex) ?? true)) { FrameDecoded?.Invoke(Crop(picture, sps)); } decodeCounter++; - if (!picture.IsReference) + if (!picture.IsReference && !picture.InDpb) { pool.Push(picture); } - - cur = null; - picHeader = null; - PruneDpb(); } private static H264Frame Crop(Picture p, Sps sps) { + var cropUnitY = sps.FrameMbsOnly ? 2 : 4; var left = sps.CropLeft * 2; - var top = sps.CropTop * 2; + var top = sps.CropTop * cropUnitY; var width = Math.Max(2, p.Width - left - (sps.CropRight * 2)); - var height = Math.Max(2, p.Height - top - (sps.CropBottom * 2)); + var height = Math.Max(2, p.Height - top - (sps.CropBottom * cropUnitY)); var y = new byte[width * height]; for (var r = 0; r < height; r++) { @@ -608,148 +760,266 @@ public sealed partial class H264Decoder Array.Copy(p.Cr, (((top / 2) + r) * pcw) + (left / 2), cr, r * cw, cw); } + if (p.Decoded != 3) + { + // A field without its pair: the rows of the missing field are grey, as the reference decoder writes them. + var missing = p.Decoded == 1 ? 1 : 0; + for (var r = 0; r < height; r++) + { + if (((top + r) & 1) == missing) + { + y.AsSpan(r * width, width).Fill(128); + } + } + + for (var r = 0; r < ch; r++) + { + if ((((top / 2) + r) & 1) == missing) + { + cb.AsSpan(r * cw, cw).Fill(128); + cr.AsSpan(r * cw, cw).Fill(128); + } + } + } + return new H264Frame(width, height, y, cb, cr, p.Poc, p.Period, p.DecodeIndex, sps.MatrixCoefficients, sps.FullRange); } - /// Decoded reference picture marking (§8.2.5) of the picture just decoded. + private void AddToDpb(Picture p) + { + if (!p.InDpb) + { + p.InDpb = true; + dpb.Add(p); + } + } + + /// The bit of a field in the masks of : 1 top, 2 bottom, 3 the frame. + private static int FieldBit(int structure) => structure == 0 ? 3 : structure; + + /// Decoded reference picture marking (§8.2.5) of the picture (frame or field) just decoded. private void MarkReferences(Picture picture, Sps sps) { var h = picHeader!; + var bit = FieldBit(curStructure); if (picNalType == 5) { foreach (var p in dpb) { - p.ShortTerm = p.LongTerm = false; + if (!ReferenceEquals(p, picture)) + { + p.ShortMask = p.LongMask = 0; + } } if (h.LongTermReference) { - picture.LongTerm = true; + picture.LongMask |= bit; picture.LongTermFrameIdx = 0; maxLongTermFrameIdx = 0; } else { - picture.ShortTerm = true; + picture.ShortMask |= bit; maxLongTermFrameIdx = -1; } - dpb.Add(picture); + AddToDpb(picture); return; } var becameLongTerm = false; if (h.AdaptiveMarking) { - var currPicNum = picture.FrameNum; - UpdateFrameNumWrap(picture.FrameNum, sps); - foreach (var (op, a, b) in h.Mmco) - { - switch (op) - { - case 1: - { - var picNumX = currPicNum - (a + 1); - foreach (var p in dpb) - { - if (p.ShortTerm && p.PicNum == picNumX) - { - p.ShortTerm = false; - } - } - - break; - } - - case 2: - foreach (var p in dpb) - { - if (p.LongTerm && p.LongTermPicNum == a) - { - p.LongTerm = false; - } - } - - break; - case 3: - { - var picNumX = currPicNum - (a + 1); - foreach (var p in dpb) - { - if (p.LongTerm && p.LongTermFrameIdx == b) - { - p.LongTerm = false; - } - } - - foreach (var p in dpb) - { - if (p.ShortTerm && p.PicNum == picNumX) - { - p.ShortTerm = false; - p.LongTerm = true; - p.LongTermFrameIdx = b; - } - } - - break; - } - - case 4: - maxLongTermFrameIdx = a - 1; - foreach (var p in dpb) - { - if (p.LongTerm && p.LongTermFrameIdx > maxLongTermFrameIdx) - { - p.LongTerm = false; - } - } - - break; - case 5: - foreach (var p in dpb) - { - p.ShortTerm = p.LongTerm = false; - } - - maxLongTermFrameIdx = -1; - break; - case 6: - foreach (var p in dpb) - { - if (p.LongTerm && p.LongTermFrameIdx == b) - { - p.LongTerm = false; - } - } - - picture.LongTerm = true; - picture.LongTermFrameIdx = b; - becameLongTerm = true; - break; - } - } - + becameLongTerm = ApplyMmco(picture, h, sps, bit); if (picMmco5) { period++; picture.Period = period; } } - else + else if (!(curSecondField && (picture.ShortMask & (3 - bit)) != 0)) { - SlidingWindow(sps, picture.FrameNum); + // The second field of a pair whose first field is a short-term reference joins it without the sliding window. + SlidingWindow(sps, picture.FrameNum, picture); } if (!becameLongTerm) { - picture.ShortTerm = true; + picture.ShortMask |= bit; } - dpb.Add(picture); + AddToDpb(picture); LimitReferences(picture, sps); } + /// The memory management control operations of the picture (§8.2.5.4); true when it became long-term. + private bool ApplyMmco(Picture picture, SliceHeader h, Sps sps, int bit) + { + var field = curStructure != 0; + var parity = curStructure == 2 ? 1 : 0; + var currPicNum = field ? (2 * h.FrameNum) + 1 : h.FrameNum; + var becameLongTerm = false; + UpdateFrameNumWrap(h.FrameNum, sps); + foreach (var (op, a, b) in h.Mmco) + { + switch (op) + { + case 1: + { + var picNumX = currPicNum - (a + 1); + if (FindShortTerm(picNumX, field, parity, out var p, out var q)) + { + p.ShortMask &= ~q; + } + + break; + } + + case 2: + if (FindLongTerm(a, field, parity, out var lp, out var lq)) + { + lp.LongMask &= ~lq; + } + + break; + case 3: + { + var picNumX = currPicNum - (a + 1); + if (!FindShortTerm(picNumX, field, parity, out var p, out var q)) + { + break; + } + + // LongTermFrameIdx b goes to this picture: any other frame or field holding it is released, unless + // it is the other field of the same frame. + foreach (var other in dpb) + { + if (other.LongMask != 0 && other.LongTermFrameIdx == b && !ReferenceEquals(other, p)) + { + other.LongMask = 0; + } + } + + if (p.LongMask != 0 && p.LongTermFrameIdx != b) + { + p.LongMask = 0; + } + + p.ShortMask &= ~q; + p.LongMask |= q; + p.LongTermFrameIdx = b; + break; + } + + case 4: + maxLongTermFrameIdx = a - 1; + foreach (var p in dpb) + { + if (p.LongMask != 0 && p.LongTermFrameIdx > maxLongTermFrameIdx) + { + p.LongMask = 0; + } + } + + break; + case 5: + foreach (var p in dpb) + { + if (!ReferenceEquals(p, picture)) + { + p.ShortMask = p.LongMask = 0; + } + } + + // The first field of the frame, too: after this operation nothing before the picture is a reference. + picture.ShortMask = picture.LongMask = 0; + maxLongTermFrameIdx = -1; + break; + case 6: + foreach (var p in dpb) + { + if (p.LongMask != 0 && p.LongTermFrameIdx == b && !ReferenceEquals(p, picture)) + { + p.LongMask = 0; + } + } + + if (picture.LongMask != 0 && picture.LongTermFrameIdx != b) + { + picture.LongMask = 0; + } + + picture.LongMask |= bit; + picture.LongTermFrameIdx = b; + becameLongTerm = true; + break; + } + } + + return becameLongTerm; + } + + /// The short-term frame (or field) whose PicNum is (§8.2.4.1); q is its mask bit. + private bool FindShortTerm(int picNum, bool field, int parity, out Picture p, out int q) + { + foreach (var candidate in dpb) + { + if (!field) + { + if (candidate.ShortMask == 3 && candidate.FrameNumWrap == picNum) + { + (p, q) = (candidate, 3); + return true; + } + + continue; + } + + for (var f = 0; f < 2; f++) + { + if ((candidate.ShortMask & (1 << f)) != 0 && (2 * candidate.FrameNumWrap) + (f == parity ? 1 : 0) == picNum) + { + (p, q) = (candidate, 1 << f); + return true; + } + } + } + + (p, q) = (null!, 0); + return false; + } + + /// The long-term frame (or field) whose LongTermPicNum is . + private bool FindLongTerm(int longTermPicNum, bool field, int parity, out Picture p, out int q) + { + foreach (var candidate in dpb) + { + if (!field) + { + if (candidate.LongMask == 3 && candidate.LongTermFrameIdx == longTermPicNum) + { + (p, q) = (candidate, 3); + return true; + } + + continue; + } + + for (var f = 0; f < 2; f++) + { + if ((candidate.LongMask & (1 << f)) != 0 && (2 * candidate.LongTermFrameIdx) + (f == parity ? 1 : 0) == longTermPicNum) + { + (p, q) = (candidate, 1 << f); + return true; + } + } + } + + (p, q) = (null!, 0); + return false; + } + /// /// A stream may never keep more than Max(max_num_ref_frames, 1) reference frames (§8.2.5.4 and §7.4.2.1.1); a damaged /// one whose marking operations never release any would make the buffer grow with every picture. Here the oldest @@ -775,11 +1045,11 @@ public sealed partial class H264Decoder continue; } - if (p.ShortTerm && (oldestShort is null || p.FrameNumWrap < oldestShort.FrameNumWrap)) + if (p.ShortMask != 0 && (oldestShort is null || p.FrameNumWrap < oldestShort.FrameNumWrap)) { oldestShort = p; } - else if (p.LongTerm && (oldestLong is null || p.LongTermFrameIdx < oldestLong.LongTermFrameIdx)) + else if (p.ShortMask == 0 && (oldestLong is null || p.LongTermFrameIdx < oldestLong.LongTermFrameIdx)) { oldestLong = p; } @@ -790,12 +1060,15 @@ public sealed partial class H264Decoder return; } - victim.ShortTerm = victim.LongTerm = false; + victim.ShortMask = victim.LongMask = 0; } } - /// Sliding window marking (§8.2.5.3) before a new short-term frame is added. - private void SlidingWindow(Sps sps, int frameNum) + /// + /// Sliding window marking (§8.2.5.3) before a new short-term picture is added: frames, field pairs and single fields + /// count as one each; the frame store of the current picture () is not removed. + /// + private void SlidingWindow(Sps sps, int frameNum, Picture? current) { UpdateFrameNumWrap(frameNum, sps); var limit = Math.Max(1, sps.MaxNumRefFrames); @@ -805,15 +1078,15 @@ public sealed partial class H264Decoder Picture? oldest = null; foreach (var p in dpb) { - if (p.ShortTerm) + if (p.ShortMask != 0) { shortCount++; - if (oldest is null || p.FrameNumWrap < oldest.FrameNumWrap) + if (!ReferenceEquals(p, current) && (oldest is null || p.FrameNumWrap < oldest.FrameNumWrap)) { oldest = p; } } - else if (p.LongTerm) + else if (p.LongMask != 0) { longCount++; } @@ -824,7 +1097,7 @@ public sealed partial class H264Decoder return; } - oldest.ShortTerm = false; + oldest.ShortMask = 0; } } @@ -832,7 +1105,7 @@ public sealed partial class H264Decoder { foreach (var p in dpb) { - if (p.ShortTerm) + if (p.ShortMask != 0) { p.FrameNumWrap = p.FrameNum > frameNum ? p.FrameNum - sps.MaxFrameNum : p.FrameNum; } @@ -845,9 +1118,10 @@ public sealed partial class H264Decoder for (var i = dpb.Count - 1; i >= 0; i--) { var p = dpb[i]; - if (!p.IsReference && !ReferenceEquals(p, cur)) + if (!p.IsReference && !ReferenceEquals(p, cur) && !ReferenceEquals(p, openField)) { dpb.RemoveAt(i); + p.InDpb = false; pool.Push(p); } } @@ -856,8 +1130,20 @@ public sealed partial class H264Decoder /// Reference picture lists of the slice (§8.2.4): initialisation, then modification. private void BuildReferenceLists(SliceHeader h, Sps sps) { - var picture = cur!; UpdateFrameNumWrap(h.FrameNum, sps); + if (curStructure == 0) + { + BuildFrameLists(h, sps); + } + else + { + BuildFieldLists(h, sps); + } + } + + private void BuildFrameLists(SliceHeader h, Sps sps) + { + var picture = cur!; var shortTerm = new List(); var longTerm = new List(); foreach (var p in dpb) @@ -878,49 +1164,160 @@ public sealed partial class H264Decoder } longTerm.Sort((a, b) => a.LongTermPicNum.CompareTo(b.LongTermPicNum)); - List init0, init1 = []; + List init0 = [], init1 = []; if (h.Type == SliceType.P) { shortTerm.Sort((a, b) => b.PicNum.CompareTo(a.PicNum)); - init0 = [.. shortTerm, .. longTerm]; + foreach (var p in shortTerm) + { + init0.Add(new RefEntry(p, -1)); + } + + foreach (var p in longTerm) + { + init0.Add(new RefEntry(p, -1)); + } } else { - var before = shortTerm.FindAll(p => p.Poc < picture.Poc); - var after = shortTerm.FindAll(p => p.Poc > picture.Poc); + var poc = picture.Poc; + var before = shortTerm.FindAll(p => p.Poc < poc); + var after = shortTerm.FindAll(p => p.Poc > poc); before.Sort((a, b) => b.Poc.CompareTo(a.Poc)); after.Sort((a, b) => a.Poc.CompareTo(b.Poc)); - init0 = [.. before, .. after, .. longTerm]; - init1 = [.. after, .. before, .. longTerm]; - if (init1.Count > 1 && init0.Count == init1.Count) + foreach (var p in (List)[.. before, .. after, .. longTerm]) { - var same = true; - for (var i = 0; i < init0.Count && same; i++) - { - same = ReferenceEquals(init0[i], init1[i]); - } - - if (same) - { - (init1[0], init1[1]) = (init1[1], init1[0]); - } + init0.Add(new RefEntry(p, -1)); } + + foreach (var p in (List)[.. after, .. before, .. longTerm]) + { + init1.Add(new RefEntry(p, -1)); + } + + SwapIfSame(init0, init1); } refList[0] = Modify(init0, h.NumRefIdxActiveL0, h.Modifications[0], h, sps); refList[1] = h.IsB ? Modify(init1, h.NumRefIdxActiveL1, h.Modifications[1], h, sps) : []; } - private Picture?[] Modify(List initial, int count, List<(int Idc, int Value)> modifications, SliceHeader h, Sps sps) + /// Lists of a field picture (§8.2.4.2.2, §8.2.4.2.4 and §8.2.4.2.5): frames ordered, then their fields alternated. + private void BuildFieldLists(SliceHeader h, Sps sps) { - var list = new Picture?[count + 1]; + var parity = curStructure == 2 ? 1 : 0; + var picture = cur!; + var shortTerm = new List(); + var longTerm = new List(); + foreach (var p in dpb) + { + if (p.ShortMask != 0) + { + shortTerm.Add(p); + } + else if (p.LongMask != 0) + { + longTerm.Add(p); + } + } + + longTerm.Sort((a, b) => a.LongTermFrameIdx.CompareTo(b.LongTermFrameIdx)); + List init0 = [], init1 = []; + if (h.Type == SliceType.P) + { + shortTerm.Sort((a, b) => b.FrameNumWrap.CompareTo(a.FrameNumWrap)); + Alternate(shortTerm, parity, longTerm: false, init0); + Alternate(longTerm, parity, longTerm: true, init0); + } + else + { + var poc = picture.PocOf(parity); + var before = shortTerm.FindAll(p => ShortTermPoc(p) <= poc); + var after = shortTerm.FindAll(p => ShortTermPoc(p) > poc); + before.Sort((a, b) => ShortTermPoc(b).CompareTo(ShortTermPoc(a))); + after.Sort((a, b) => ShortTermPoc(a).CompareTo(ShortTermPoc(b))); + Alternate([.. before, .. after], parity, longTerm: false, init0); + Alternate(longTerm, parity, longTerm: true, init0); + Alternate([.. after, .. before], parity, longTerm: false, init1); + Alternate(longTerm, parity, longTerm: true, init1); + SwapIfSame(init0, init1); + } + + refList[0] = Modify(init0, h.NumRefIdxActiveL0, h.Modifications[0], h, sps); + refList[1] = h.IsB ? Modify(init1, h.NumRefIdxActiveL1, h.Modifications[1], h, sps) : []; + } + + /// PicOrderCnt of a frame entry for the field lists: the smaller of its fields marked short-term. + private static int ShortTermPoc(Picture p) => p.ShortMask switch + { + 1 => p.TopPoc, + 2 => p.BottomPoc, + _ => Math.Min(p.TopPoc, p.BottomPoc), + }; + + /// + /// §8.2.4.2.5: fields taken from the ordered frames alternately, starting with the parity of the current field; the + /// fields not marked (short-term or long-term, as the list) are skipped, and when one parity runs out the rest of + /// the other follows in order. + /// + private static void Alternate(List frames, int parity, bool longTerm, List output) + { + int same = 0, opposite = 0, n = frames.Count; + int sameBit = 1 << parity, oppositeBit = 1 << (1 - parity); + while (same < n || opposite < n) + { + while (same < n && ((longTerm ? frames[same].LongMask : frames[same].ShortMask) & sameBit) == 0) + { + same++; + } + + while (opposite < n && ((longTerm ? frames[opposite].LongMask : frames[opposite].ShortMask) & oppositeBit) == 0) + { + opposite++; + } + + if (same < n) + { + output.Add(new RefEntry(frames[same++], parity)); + } + + if (opposite < n) + { + output.Add(new RefEntry(frames[opposite++], 1 - parity)); + } + } + } + + /// When list 1 has more than one entry and equals list 0, its first two entries are switched (§8.2.4.2.3). + private static void SwapIfSame(List init0, List init1) + { + if (init1.Count > 1 && init0.Count == init1.Count) + { + for (var i = 0; i < init0.Count; i++) + { + if (!ReferenceEquals(init0[i].Pic, init1[i].Pic) || init0[i].Parity != init1[i].Parity) + { + return; + } + } + + (init1[0], init1[1]) = (init1[1], init1[0]); + } + } + + /// The modification of a list (§8.2.4.3), for frames or fields. + private RefEntry[] Modify(List initial, int count, List<(int Idc, int Value)> modifications, SliceHeader h, Sps sps) + { + var list = new RefEntry[count + 1]; for (var i = 0; i < count && i < initial.Count; i++) { list[i] = initial[i]; } - var maxPicNum = sps.MaxFrameNum; - var currPicNum = h.FrameNum; + var field = curStructure != 0; + var parity = curStructure == 2 ? 1 : 0; + var maxPicNum = field ? 2 * sps.MaxFrameNum : sps.MaxFrameNum; + var currPicNum = field ? (2 * h.FrameNum) + 1 : h.FrameNum; var pred = currPicNum; var refIdx = 0; foreach (var (idc, value) in modifications) @@ -930,7 +1327,7 @@ public sealed partial class H264Decoder break; } - Picture? found = null; + RefEntry found = default; if (idc is 0 or 1) { var abs = value + 1; @@ -946,11 +1343,14 @@ public sealed partial class H264Decoder pred = noWrap; var picNum = noWrap > currPicNum ? noWrap - maxPicNum : noWrap; - found = dpb.Find(p => p.ShortTerm && p.PicNum == picNum && !ReferenceEquals(p, cur)); + if (FindShortTerm(picNum, field, parity, out var p, out var q) && !(ReferenceEquals(p, cur) && q == FieldBit(curStructure))) + { + found = new RefEntry(p, field ? q - 1 : -1); + } } - else + else if (FindLongTerm(value, field, parity, out var p, out var q) && !(ReferenceEquals(p, cur) && q == FieldBit(curStructure))) { - found = dpb.Find(p => p.LongTerm && p.LongTermPicNum == value && !ReferenceEquals(p, cur)); + found = new RefEntry(p, field ? q - 1 : -1); } for (var c = count; c > refIdx; c--) @@ -962,7 +1362,7 @@ public sealed partial class H264Decoder var n = refIdx; for (var c = refIdx; c <= count; c++) { - if (!ReferenceEquals(list[c], found) || found is null) + if (found.Pic is null || !ReferenceEquals(list[c].Pic, found.Pic) || list[c].Parity != found.Parity) { list[n++] = list[c]; } diff --git a/src/Febe.Core/Codecs/H264/H264Tables.cs b/src/Febe.Core/Codecs/H264/H264Tables.cs index 2187b9c..80a43eb 100644 --- a/src/Febe.Core/Codecs/H264/H264Tables.cs +++ b/src/Febe.Core/Codecs/H264/H264Tables.cs @@ -9,6 +9,16 @@ internal static class H264Tables /// Zig-zag scan of 8×8 frame blocks: scan index → raster position (row * 8 + column). internal static readonly byte[] ZigZag8x8 = BuildZigZag(8); + /// Field scan of 4×4 blocks (table 8-13): scan index → raster position (row * 4 + column). + internal static readonly byte[] FieldScan4x4 = [0, 4, 1, 8, 12, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15]; + + /// Field scan of 8×8 blocks (table 8-14): scan index → raster position (row * 8 + column). + 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, + ]; + /// luma4x4BlkIdx → raster index of the 4×4 block in the macroblock ((y / 4) * 4 + x / 4). 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, ]; + /// ctxIdxInc of significant_coeff_flag for 8×8 field blocks (table 9-43), by levelListIdx. + 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, + ]; + /// ctxIdxInc of last_significant_coeff_flag for 8×8 blocks (table 9-43), by levelListIdx. internal static readonly byte[] LastContext8x8 = [ diff --git a/src/Febe.Core/Codecs/H264/InterPrediction.cs b/src/Febe.Core/Codecs/H264/InterPrediction.cs index 7703c42..179f3f9 100644 --- a/src/Febe.Core/Codecs/H264/InterPrediction.cs +++ b/src/Febe.Core/Codecs/H264/InterPrediction.cs @@ -5,12 +5,12 @@ internal static class InterPrediction { /// /// Luma prediction of a × block whose top-left corner, in quarter - /// samples, is (, ). Samples outside the picture repeat the edge. + /// samples, is (, ), from the × + /// picture whose row y starts at + y × (a frame, or one field of a + /// frame store). Samples outside the picture repeat the edge. /// - internal static void Luma(Picture reference, int qx, int qy, int w, int h, Span dst) + internal static void Luma(byte[] plane, int origin, int stride, int pw, int ph, int qx, int qy, int w, int h, Span 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; // 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; } - var rowBase = sy * pw; + var rowBase = origin + (sy * stride); for (var c = 0; c < ww; c++) { var sx = xInt - 2 + c; @@ -170,16 +170,16 @@ internal static class InterPrediction /// /// Chroma prediction (4:2:0) of a × block whose corner, in eighths of a - /// chroma sample, is (, ). + /// chroma sample, is (, ), from a plane view as for . /// - internal static void Chroma(byte[] plane, int pw, int ph, int ex, int ey, int w, int h, Span dst) + internal static void Chroma(byte[] plane, int origin, int stride, int pw, int ph, int ex, int ey, int w, int h, Span dst) { 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; for (var y = 0; y < h; y++) { - var y0 = Math.Clamp(yInt + y, 0, ph - 1) * pw; - var y1 = Math.Clamp(yInt + y + 1, 0, ph - 1) * pw; + var y0 = origin + (Math.Clamp(yInt + y, 0, ph - 1) * stride); + var y1 = origin + (Math.Clamp(yInt + y + 1, 0, ph - 1) * stride); for (var x = 0; x < w; x++) { var x0 = Math.Clamp(xInt + x, 0, pw - 1); diff --git a/src/Febe.Core/Codecs/H264/IntraPrediction.cs b/src/Febe.Core/Codecs/H264/IntraPrediction.cs index b8aca3e..39c77f0 100644 --- a/src/Febe.Core/Codecs/H264/IntraPrediction.cs +++ b/src/Febe.Core/Codecs/H264/IntraPrediction.cs @@ -388,8 +388,12 @@ internal static class IntraPrediction } } - /// Chroma prediction of one 8×8 4:2:0 component (§8.3.4): 0 DC, 1 horizontal, 2 vertical, 3 plane. - 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. + /// + internal static void PredictChroma(byte[] p, int o, int stride, int mode, bool leftUpper, bool leftLower, bool top, bool topLeft) { switch (mode) { @@ -399,6 +403,7 @@ internal static class IntraPrediction for (var bx = 0; bx < 2; bx++) { var b = o + (by * 4 * stride) + (bx * 4); + var left = by == 0 ? leftUpper : leftLower; int sumT = 0, sumL = 0; for (var i = 0; i < 4; i++) { diff --git a/src/Febe.Core/Codecs/H264/Picture.cs b/src/Febe.Core/Codecs/H264/Picture.cs index 0c9c384..5643055 100644 --- a/src/Febe.Core/Codecs/H264/Picture.cs +++ b/src/Febe.Core/Codecs/H264/Picture.cs @@ -1,10 +1,17 @@ namespace Febe.Core.Codecs.H264; /// -/// A decoded frame with what later pictures need from it: samples (4:2:0, 8 bits, the full macroblock area), motion -/// vectors and references of every block (for direct prediction and the deblocking of the pictures that follow), and -/// its state in the decoded picture buffer. +/// A frame store of the decoded picture buffer: a decoded frame, or the two fields of a complementary field pair (its +/// even rows are the top field, its odd rows the bottom one), with what later pictures need from it: samples (4:2:0, +/// 8 bits, the full macroblock area), motion vectors and references of every block (for direct prediction and the +/// deblocking of the pictures that follow), and its marking. /// +/// +/// 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 () keep their motion vectors in +/// field units and refer to fields (). +/// internal sealed class Picture { internal Picture(int widthInMbs, int heightInMbs) @@ -20,7 +27,9 @@ internal sealed class Picture Mv = new short[2 * mbs * 16 * 2]; RefIdx = new sbyte[2 * mbs * 4]; RefPic = new Picture?[2 * mbs * 4]; + RefPar = new sbyte[2 * mbs * 4]; MbIntra = new bool[mbs]; + MbField = new bool[mbs]; } internal int WidthInMbs { get; } @@ -43,38 +52,92 @@ internal sealed class Picture /// Reference indices: [(list * mbs + mb) * 4 + 8×8 block]; −1 when the list is not used. internal sbyte[] RefIdx { get; } - /// The picture each 8×8 block refers to, by list (same index as ). + /// The frame store each 8×8 block refers to, by list (same index as ). internal Picture?[] RefPic { get; } + /// The field of referred to: 0 top, 1 bottom, −1 the frame (same index as ). + internal sbyte[] RefPar { get; } + internal bool[] MbIntra { get; } + /// Field macroblocks: those of field pictures and the field pairs of MBAFF frames. + internal bool[] MbField { get; } + internal int MbCount => WidthInMbs * HeightInMbs; - internal int Poc; + /// TopFieldOrderCnt and BottomFieldOrderCnt (§8.2.1) of the fields decoded so far. + internal int TopPoc; + + internal int BottomPoc; + + /// The fields decoded so far: 1 top, 2 bottom, 3 both (a frame or a field pair). + internal int Decoded; + + /// Coded as two field pictures (else as a frame, progressive or MBAFF). + internal bool CodedAsFields; + internal int FrameNum; internal int FrameNumWrap; internal int LongTermFrameIdx; - internal bool ShortTerm; - internal bool LongTerm; + + /// Fields used for short-term reference: 1 top, 2 bottom, 3 both (the frame). + internal int ShortMask; + + /// Fields used for long-term reference, as . + internal int LongMask; /// A frame inferred for a gap in frame_num (§8.2.5.2): never output, its samples are not meaningful. internal bool NonExisting; - /// Decoding order of the picture in the stream. + /// Some field of the frame was not reconstructed (nobody refers to it, nobody wants it): it is not handed out. + internal bool Skipped; + + /// In the decoded picture buffer. + internal bool InDpb; + + /// Decoding order of the frame in the stream. internal long DecodeIndex; /// Counts IDR pictures (and memory_management_control_operation 5): output order restarts with each. internal int Period; - internal bool IsReference => ShortTerm || LongTerm; + internal bool IsReference => (ShortMask | LongMask) != 0; + + /// A short-term reference frame: both fields marked (§8.2.4.1, frames and complementary pairs). + internal bool ShortTerm => ShortMask == 3; + + /// A long-term reference frame. + internal bool LongTerm => LongMask == 3; internal int PicNum => FrameNumWrap; internal int LongTermPicNum => LongTermFrameIdx; + /// PicOrderCnt of the frame (§8.2.1): the smaller of the fields decoded. + internal int Poc => Decoded switch + { + 1 => TopPoc, + 2 => BottomPoc, + _ => Math.Min(TopPoc, BottomPoc), + }; + + /// PicOrderCnt of a field (0 top, 1 bottom) or of the frame (−1). + internal int PocOf(int parity) => parity < 0 ? Poc : parity == 0 ? TopPoc : BottomPoc; + + /// Whether the field (0 top, 1 bottom) or the frame (−1) is a long-term reference. + internal bool IsLongTerm(int parity) => parity < 0 ? LongMask == 3 : (LongMask & (1 << parity)) != 0; + internal bool Fits(int widthInMbs, int heightInMbs) => WidthInMbs == widthInMbs && HeightInMbs == heightInMbs; } +/// A reference picture of a list: a frame ( −1) or one field of a frame store. +internal readonly record struct RefEntry(Picture? Pic, int Parity) +{ + internal int Poc => Pic!.PocOf(Parity); + + internal bool IsLongTerm => Pic!.IsLongTerm(Parity); +} + /// A decoded frame, cropped, in planar YUV 4:2:0. /// Luma width after cropping. /// Luma height after cropping. diff --git a/src/Febe.Core/Codecs/H264/SliceHeader.cs b/src/Febe.Core/Codecs/H264/SliceHeader.cs index 9301d85..dfbd044 100644 --- a/src/Febe.Core/Codecs/H264/SliceHeader.cs +++ b/src/Febe.Core/Codecs/H264/SliceHeader.cs @@ -18,6 +18,7 @@ internal sealed class SliceHeader internal int PpsId; internal int FrameNum; internal bool FieldPic; + internal bool BottomField; internal int IdrPicId; internal int PocLsb; internal int DeltaPocBottom; @@ -59,6 +60,9 @@ internal sealed class SliceHeader internal bool IsB => Type == SliceType.B; + /// 0 frame, 1 top field, 2 bottom field. + internal int Structure => !FieldPic ? 0 : BottomField ? 2 : 1; + internal static SliceHeader Parse(RbspReader r, NalUnit nal, IReadOnlyDictionary sequences, IReadOnlyDictionary pictures, out Sps sps, out Pps pps) { var h = new SliceHeader { FirstMb = (int)r.ReadUe() }; @@ -81,7 +85,7 @@ internal sealed class SliceHeader h.FieldPic = r.ReadFlag(); if (h.FieldPic) { - throw new H264Exception("I video interlacciati non sono gestiti."); + h.BottomField = r.ReadFlag(); } } diff --git a/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md b/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md index f618691..673b818 100644 --- a/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md +++ b/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md @@ -40,7 +40,7 @@ del riferimento. ## 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 | |---|---|---| @@ -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 | | `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 -`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. - -**Immagini interlacciate** (campi, PAFF, MBAFF), 4:2:0 a 8 bit: +Immagini interlacciate (campi, PAFF, MBAFF). Ogni fotogramma esce con i due campi intercalati riga per riga; un campo +rimasto senza il suo compagno esce da solo, con le righe dell'altro campo grigie (128). | 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 | | `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: | Flusso | Profilo, formato | Che cosa prova | diff --git a/tests/Febe.Tests/Media/H264/H264ConformanceTests.cs b/tests/Febe.Tests/Media/H264/H264ConformanceTests.cs index a597985..1d98b0f 100644 --- a/tests/Febe.Tests/Media/H264/H264ConformanceTests.cs +++ b/tests/Febe.Tests/Media/H264/H264ConformanceTests.cs @@ -6,11 +6,12 @@ namespace Febe.Tests.Codecs.H264; /// /// 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 -/// uses weighted prediction, memory management operations, long-term references, gaps in frame_num, POC type 1, I_PCM or -/// CABAC pictures of several slices: those parts of the decoder have no reference MD5 here (some are reached by -/// , without an official reference). The streams of the parts the decoder does not -/// handle yet (interlaced pictures, FMO and ASO, SP slices, 4:2:2, more than 8 bits, 4:0:0, SVC, MVC) are in +/// MD5 of the corresponding frame of the official reconstruction (see Conformita/LEGGIMI.md). The verified streams include +/// interlaced video — field pictures, PAFF, MBAFF, both together — with memory management operations, long-term +/// references and POC type 1 on fields (MR6_BT_B, MR9_BT_B). None of them uses weighted prediction, gaps in frame_num or +/// I_PCM: those parts of the decoder have no reference MD5 here (some are reached by , +/// 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 /// : 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. /// @@ -30,6 +31,23 @@ public sealed class H264ConformanceTests [DataRow("FRExt1_Panasonic_D")] [DataRow("FRExt3_Panasonic_E")] [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"); [TestMethod] @@ -44,23 +62,6 @@ public sealed class H264ConformanceTests } [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("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")] @@ -123,6 +124,12 @@ public sealed class H264ConformanceTests [DataRow("FRExt1_Panasonic_D")] [DataRow("FRExt3_Panasonic_E")] [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) { // Pictures nobody refers to and nobody wants are not reconstructed (only their headers count): every frame diff --git a/tests/Febe.Tests/Media/H264/H264RobustnessTests.cs b/tests/Febe.Tests/Media/H264/H264RobustnessTests.cs index fb326c1..5cc7aff 100644 --- a/tests/Febe.Tests/Media/H264/H264RobustnessTests.cs +++ b/tests/Febe.Tests/Media/H264/H264RobustnessTests.cs @@ -22,10 +22,16 @@ public sealed class H264RobustnessTests [DataRow("FRExt1_Panasonic_D", 2650)] [DataRow("FRExt3_Panasonic_E", 2651)] [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) { - var folder = Path.Combine(AppContext.BaseDirectory, "Media", "H264", "Conformita", name); - var data = File.ReadAllBytes(Directory.EnumerateFiles(folder).Single(f => Path.GetExtension(f) is ".264" or ".jsv" or ".avc")); + var data = File.ReadAllBytes(H264ConformanceTests.StreamFile(H264ConformanceTests.Folder(name))); var random = new Random(seed); for (var trial = 0; trial < 60; trial++) { diff --git a/tests/Febe.Tests/Media/H264/H264TablesTests.cs b/tests/Febe.Tests/Media/H264/H264TablesTests.cs index 3db5255..9e3efb9 100644 --- a/tests/Febe.Tests/Media/H264/H264TablesTests.cs +++ b/tests/Febe.Tests/Media/H264/H264TablesTests.cs @@ -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, 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]