From da84c79f7e90de5ac5b3fe4e411be4b747847483 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 18 Nov 2026 17:31:12 +0100 Subject: [PATCH] Decodificatore H.264 per i formati dei profili High: 4:2:2, 4:4:4, piani separati, 4:0:0, da 8 a 14 bit, senza perdita (#58) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Il decodificatore rifiutava tutto ciò che non era 4:2:0 a 8 bit, così i video 4:2:2, monocromatici o a 10 bit restavano senza miniatura. Ora i campioni stanno in piani di uno o due byte e i nuclei di predizione, trasformata e filtro sono generici su byte e ushort, specializzati dal JIT: a 8 bit i tempi restano quelli di prima (misurati sui flussi di conformità, 100,4%). - 4:2:2: DC della crominanza 2x4 con qP + 3, tabelle CAVLC di nC -2, contesti CABAC per NumC8x8, predizione intra 8x16, vettore verticale a piena risoluzione, bordi della crominanza alle righe 4, 8 e 12. - 4:4:4: Cb e Cr codificati come la luminanza in CAVLC, con le loro matrici e il filtro della luminanza; separate_colour_plane_flag come tre immagini monocromatiche con i propri dati di macroblocco e di moto. - 4:0:0 senza sintassi della crominanza; in uscita la crominanza 4:2:0 al valore medio, come il file ufficiale. - Profondità da 8 a 14 bit: QP da -QpBdOffset, soglie del deblocking e scarti dei pesi scalati; uscita a due byte little-endian. - Senza perdita: qpprime_y_zero_transform_bypass_flag a QP'Y 0, con la DPCM della predizione intra orizzontale e verticale. - VideoFrameDecoder converte in RGB alla profondità e al campionamento del fotogramma. I dieci flussi 4:2:2 (8 e 10 bit) e 4:0:0 della serie ITU-T coincidono con la ricostruzione ufficiale e passano fra i verificati. 4:4:4, piani separati, senza perdita e 11-14 bit si provano con flussi sintetici (H264FormatTests). Il CABAC in 4:4:4 con i piani insieme si rifiuta: mancano i contesti 460-1023. Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 1 + src/Febe.Core/Codecs/H264/CavlcTables.cs | 44 +- .../Codecs/H264/H264Decoder.Deblock.cs | 328 ++++--- .../Codecs/H264/H264Decoder.Entropy.cs | 59 +- .../Codecs/H264/H264Decoder.Motion.cs | 119 ++- .../Codecs/H264/H264Decoder.Slice.cs | 805 +++++++++++++----- src/Febe.Core/Codecs/H264/H264Decoder.cs | 157 +++- src/Febe.Core/Codecs/H264/H264Tables.cs | 6 + src/Febe.Core/Codecs/H264/InterPrediction.cs | 75 +- src/Febe.Core/Codecs/H264/IntraPrediction.cs | 161 ++-- src/Febe.Core/Codecs/H264/ParameterSets.cs | 34 +- src/Febe.Core/Codecs/H264/Picture.cs | 141 ++- src/Febe.Core/Codecs/H264/Samples.cs | 43 + src/Febe.Core/Codecs/H264/SliceHeader.cs | 16 +- src/Febe.Core/Codecs/H264/Transform.cs | 95 ++- src/Febe.Core/Library/VideoFrameDecoder.cs | 78 +- .../Febe.Tests/Media/Containers/TestVideos.cs | 2 +- .../Containers/VideoFrameDecoderTests.cs | 38 + .../Media/H264/Conformita/LEGGIMI.md | 34 +- .../Media/H264/H264ConformanceTests.cs | 30 +- .../Febe.Tests/Media/H264/H264FormatTests.cs | 178 ++++ .../Febe.Tests/Media/H264/H264TablesTests.cs | 2 + .../Febe.Tests/Media/H264/SyntheticStreams.cs | 177 ++++ 23 files changed, 2016 insertions(+), 607 deletions(-) create mode 100644 src/Febe.Core/Codecs/H264/Samples.cs create mode 100644 tests/Febe.Tests/Media/H264/H264FormatTests.cs diff --git a/docs/decisioni.md b/docs/decisioni.md index 0940936..0830abe 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -430,3 +430,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 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 | | 2026-11-18 | Il decodificatore H.264 gestisce gli strumenti di Baseline ed Extended: gruppi di slice (FMO, tipi da 0 a 6 e cambio con `slice_group_change_cycle`), slice in ordine qualunque (ASO), slice ridondanti (si decodifica la primaria, le ridondanti si saltano), partizionamento dei dati (NAL 2, 3 e 4, solo CAVLC come vuole lo standard) e slice SP e SI con QS (§8.6). Una partizione B o C che manca lascia a zero il residuo che porta e, da quel macroblocco in poi, anche quello della partizione che ne dipende (il nC delle due partizioni conta i coefficienti dei vicini dell'altra, tranne che con la predizione intra vincolata). I macroblocchi delle slice SP e SI contano come intra per il filtro di deblocking. Dove la serie ITU-T non ha flussi (partizionamento, slice ridondanti, SI, `sp_for_switch_flag`) la prova riscrive flussi verificati lasciando intatti i bit dei macroblocchi (`StreamRewriter`) e chiede di nuovo il riferimento ufficiale; le SI con un flusso sintetico i cui valori sono calcolati a mano | I cinque flussi FMO, ASO e SP della serie coincidono ora fotogramma per fotogramma con la ricostruzione ufficiale. Riscrivere flussi già verificati dà un riferimento vero anche alle parti che nessun flusso ufficiale usa, senza inventare formati né scaricare altro; restano senza riferimento ufficiale le slice SI, `sp_for_switch_flag` a 1 e il ripiego per le partizioni mancanti, che segue la dipendenza dello standard invece di un decodificatore di riferimento | +| 2026-11-18 | Il decodificatore H.264 gestisce i formati dei profili High: 4:2:2 (DC della crominanza 2×4 con qP + 3, tabelle CAVLC di nC −2, contesti CABAC per NumC8x8, predizione intra 8×16, compensazione con il vettore verticale a piena risoluzione, bordi orizzontali della crominanza alle righe 4, 8 e 12 anche con la trasformata 8×8 della luminanza), 4:4:4 con Cb e Cr codificati come la luminanza (solo CAVLC) e con `separate_colour_plane_flag` (tre immagini monocromatiche, una per `colour_plane_id`, ciascuna con i suoi dati di macroblocco e di moto e le matrici di quantizzazione del suo componente), 4:0:0, profondità da 8 a 14 bit (QP da −QpBdOffset, soglie del deblocking e scarti dei pesi scalati) e la codifica senza perdita (`qpprime_y_zero_transform_bypass_flag` a QP′Y 0, con la DPCM della predizione intra orizzontale e verticale). I campioni stanno in piani di byte, uno o due per campione: i nuclei di predizione, trasformata e filtro sono generici su `byte` e `ushort` e il JIT li specializza, così a 8 bit nulla rallenta (stessi tempi di prima sui flussi di conformità). Oltre gli 8 bit `H264Frame` ha due byte little-endian per campione, come i file di riferimento; un 4:0:0 esce con la crominanza 4:2:0 al valore medio, un 4:4:4 a piani separati come 4:4:4 con la profondità della luminanza; la conversione in RGB usa nero, ampiezza e centro della crominanza alla profondità del fotogramma e campiona la crominanza secondo il formato. Il CABAC in 4:4:4 con i piani insieme si rifiuta con un'`H264Exception`, come le slice SP e SI fuori da 4:2:0 a 8 bit | I dieci flussi 4:2:2 (8 e 10 bit, CABAC e CAVLC) e 4:0:0 della serie di conformità coincidono ora fotogramma per fotogramma con la ricostruzione ufficiale. Per il CABAC in 4:4:4 servono i valori iniziali dei contesti 460–1023 (tabelle 9-24–9-33), non ancora trascritti dallo standard: rifiutare è meglio che decodificare male. Senza flussi ufficiali con ricostruzione per 4:4:4, piani separati, senza perdita e 11–14 bit, quelle parti si provano con flussi sintetici di I_PCM e di Intra_16x16 i cui campioni si conoscono. Scelte non verificate su un riferimento: nel 4:4:4 il bS 2 conta anche i coefficienti di Cb e Cr, nel bordo sinistro misto di MBAFF in 4:2:2 e 4:4:4 ogni riga di crominanza prende il bS della riga di luminanza omonima, un macroblocco senza perdita usa per il deblocking della crominanza il QPC di QPY 0 come gli I_PCM | diff --git a/src/Febe.Core/Codecs/H264/CavlcTables.cs b/src/Febe.Core/Codecs/H264/CavlcTables.cs index 92f822c..5178c84 100644 --- a/src/Febe.Core/Codecs/H264/CavlcTables.cs +++ b/src/Febe.Core/Codecs/H264/CavlcTables.cs @@ -1,7 +1,8 @@ namespace Febe.Core.Codecs.H264; /// -/// The variable-length codes of CAVLC (ITU-T H.264, tables 9-5, 9-7, 9-8, 9-9 and 9-10), written as bit strings and +/// The variable-length codes of CAVLC (ITU-T H.264, tables 9-5, 9-7, 9-8, 9-9 and 9-10, with the columns of the +/// 4:2:2 chroma DC: nC = −2 and table 9-9 (b)), written as bit strings and /// turned once into lookup tables indexed by the next 16 bits of the stream. /// internal static class CavlcTables @@ -82,6 +83,20 @@ internal static class CavlcTables "000010", "00000011", "00000010", "0000000", ]; + /// coeff_token for the chroma DC of 4:2:2 (nC = −2, eight coefficients). + private static readonly string?[] CoeffTokenChroma422Dc = + [ + "1", null, null, null, + "0001111", "01", null, null, + "0001110", "0001101", "001", null, + "000000111", "0001100", "0001011", "00001", + "000000110", "000000101", "0001010", "000001", + "0000000111", "0000000110", "000000100", "0001001", + "00000000111", "00000000110", "0000000101", "0001000", + "000000000111", "000000000110", "00000000101", "0000000100", + "0000000000111", "000000000101", "000000000100", "00000000100", + ]; + /// total_zeros of 4×4 blocks, indexed [TotalCoeff − 1][total_zeros]. private static readonly string[][] TotalZeros4x4 = [ @@ -110,6 +125,18 @@ internal static class CavlcTables ["1", "0"], ]; + /// total_zeros of the 4:2:2 chroma DC (table 9-9 (b)), indexed [TotalCoeff − 1][total_zeros]. + private static readonly string[][] TotalZerosChroma422Dc = + [ + ["1", "010", "011", "0010", "0011", "0001", "00001", "00000"], + ["000", "01", "001", "100", "101", "110", "111"], + ["000", "001", "01", "10", "110", "111"], + ["110", "00", "01", "10", "111"], + ["00", "01", "10", "11"], + ["00", "01", "1"], + ["0", "1"], + ]; + /// run_before, indexed [Min(zerosLeft, 7) − 1][run_before]. private static readonly string[][] RunBefore = [ @@ -122,13 +149,18 @@ internal static class CavlcTables ["111", "110", "101", "100", "011", "010", "001", "0001", "00001", "000001", "0000001", "00000001", "000000001", "0000000001", "00000000001"], ]; - /// Lookup tables of coeff_token: [0..2] by nC class, [3] for nC ≥ 8 (fixed 6 bits), [4] for the chroma DC. + /// + /// Lookup tables of coeff_token: [0..2] by nC class, [3] for nC ≥ 8 (fixed 6 bits), [4] for the 4:2:0 chroma DC, [5] + /// for the 4:2:2 one. + /// internal static readonly ushort[][] CoeffTokenLookup = BuildCoeffTokenLookups(); internal static readonly ushort[][] TotalZerosLookup = BuildLookups(TotalZeros4x4); internal static readonly ushort[][] TotalZerosChromaDcLookup = BuildLookups(TotalZerosChromaDc); + internal static readonly ushort[][] TotalZerosChroma422DcLookup = BuildLookups(TotalZerosChroma422Dc); + internal static readonly ushort[][] RunBeforeLookup = BuildLookups(RunBefore); /// All the code tables, for the self-checks of the tests (prefix-free, complete where the standard is). @@ -138,6 +170,7 @@ internal static class CavlcTables yield return ("coeff_token 1", CoeffToken1); yield return ("coeff_token 2", CoeffToken2); yield return ("coeff_token -1", CoeffTokenChromaDc); + yield return ("coeff_token -2", CoeffTokenChroma422Dc); for (var i = 0; i < TotalZeros4x4.Length; i++) { yield return ($"total_zeros {i + 1}", TotalZeros4x4[i]); @@ -148,6 +181,11 @@ internal static class CavlcTables yield return ($"total_zeros DC {i + 1}", TotalZerosChromaDc[i]); } + for (var i = 0; i < TotalZerosChroma422Dc.Length; i++) + { + yield return ($"total_zeros DC 4:2:2 {i + 1}", TotalZerosChroma422Dc[i]); + } + for (var i = 0; i < RunBefore.Length; i++) { yield return ($"run_before {i + 1}", RunBefore[i]); @@ -212,6 +250,6 @@ internal static class CavlcTables } } - return [Build(CoeffToken0), Build(CoeffToken1), Build(CoeffToken2), Build(fixedLength), Build(CoeffTokenChromaDc)]; + return [Build(CoeffToken0), Build(CoeffToken1), Build(CoeffToken2), Build(fixedLength), Build(CoeffTokenChromaDc), Build(CoeffTokenChroma422Dc)]; } } diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Deblock.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Deblock.cs index 2da83e7..87f52d9 100644 --- a/src/Febe.Core/Codecs/H264/H264Decoder.Deblock.cs +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Deblock.cs @@ -1,10 +1,16 @@ +using static Febe.Core.Codecs.H264.Samples; + namespace Febe.Core.Codecs.H264; public sealed partial class H264Decoder { + /// The luma-like plane the deblocking filter is working on: Y, or one colour plane coded separately. + private byte[] deblockLuma = []; + /// /// Deblocking filter (§8.7) of the picture just decoded, macroblock by macroblock in address order: a frame, one - /// field (its rows only, as a picture of its own), or an MBAFF frame (pairs, top then bottom macroblock). + /// field (its rows only, as a picture of its own), or an MBAFF frame (pairs, top then bottom macroblock). Colour planes + /// coded separately are filtered one by one, each as a monochrome picture with its own macroblock data. /// private void Deblock(Picture picture) { @@ -19,25 +25,59 @@ public sealed partial class H264Decoder return; } - if (curStructure != 0) + if (!separatePlanes) { - DeblockRows(picture, 2, curStructure - 1); + DeblockPlane(picture, picture.Y); + return; } - else if (activeSps!.MbAdaptiveFrameField) + + for (var k = 0; k < 3; k++) { - DeblockPairs(picture); + SelectColourPlane(k); + picture.SelectPlane(k); + DeblockPlane(picture, picture.Plane(k)); + } + + SelectColourPlane(0); + picture.SelectPlane(0); + } + + private void DeblockPlane(Picture picture, byte[] luma) + { + deblockLuma = luma; + if (wide) + { + DeblockPicture(picture); } else { - DeblockRows(picture, 1, 0); + DeblockPicture(picture); + } + } + + private void DeblockPicture(Picture picture) + where T : unmanaged + { + if (curStructure != 0) + { + DeblockRows(picture, 2, curStructure - 1); + } + else if (activeSps!.MbAdaptiveFrameField) + { + DeblockPairs(picture); + } + else + { + DeblockRows(picture, 1, 0); } } /// A frame ( 1) or the field of ( 2). - private void DeblockRows(Picture picture, int rowStep, int parity) + private void DeblockRows(Picture picture, int rowStep, int parity) + where T : unmanaged { var w = widthInMbs; - int width = picture.Width, cwidth = width / 2; + int width = picture.Width, cwidth = picture.ChromaWidth; int stride = width * rowStep, cstride = cwidth * rowStep; Span bs = stackalloc byte[4]; var rows = heightInMbs / rowStep; @@ -58,21 +98,21 @@ public sealed partial class H264Decoder continue; } - var lumaOrigin = ((((row * 16 * rowStep) + parity) * width)) + (mx * 16); - var chromaOrigin = ((((row * 8 * rowStep) + parity) * cwidth)) + (mx * 8); + var lumaOrigin = (((row * 16 * rowStep) + parity) * width) + (mx * 16); + var chromaOrigin = (((row * mbHeightC * rowStep) + parity) * cwidth) + (mx * mbWidthC); if (mx > 0 && mbSlice[m - 1] >= 0 && (disable != 2 || mbSlice[m - 1] == s)) { - MbEdge(picture, m - 1, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + MbEdge(picture, m - 1, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); } - InnerEdges(picture, 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); + MbEdge(picture, up, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); } - InnerEdges(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + InnerEdges(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); } } } @@ -81,10 +121,11 @@ public sealed partial class H264Decoder /// An MBAFF frame. Between a frame and a field pair the left edge is filtered row by row, each row against the /// macroblock that holds it; the top edge of a frame macroblock under a field pair twice, once per field (§8.7.1). /// - private void DeblockPairs(Picture picture) + private void DeblockPairs(Picture picture) + where T : unmanaged { var w = widthInMbs; - int width = picture.Width, cwidth = width / 2; + int width = picture.Width, cwidth = picture.ChromaWidth; Span bs = stackalloc byte[4]; Span rowBs = stackalloc byte[16]; Span rowMb = stackalloc int[16]; @@ -113,14 +154,14 @@ public sealed partial class H264Decoder if (isField) { lumaOrigin = (((pairY * 32) + bottom) * width) + (mx * 16); - chromaOrigin = (((pairY * 16) + bottom) * cwidth) + (mx * 8); + chromaOrigin = (((pairY * 2 * mbHeightC) + bottom) * cwidth) + (mx * mbWidthC); stride = 2 * width; cstride = 2 * cwidth; } else { lumaOrigin = ((((2 * pairY) + bottom) * 16) * width) + (mx * 16); - chromaOrigin = ((((2 * pairY) + bottom) * 8) * cwidth) + (mx * 8); + chromaOrigin = ((((2 * pairY) + bottom) * mbHeightC) * cwidth) + (mx * mbWidthC); stride = width; cstride = cwidth; } @@ -132,20 +173,20 @@ public sealed partial class H264Decoder var leftField = field[leftTop]; if (leftField == isField) { - MbEdge(picture, leftTop + (bottom * w), m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + MbEdge(picture, leftTop + (bottom * w), m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); } else { - MixedLeftEdge(picture, m, leftTop, isField, bottom != 0, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, rowBs, rowMb); + MixedLeftEdge(picture, m, leftTop, isField, bottom != 0, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, rowBs, rowMb); } } - InnerEdges(picture, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + InnerEdges(picture, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); // Top edge. if (!isField && bottom == 1) { - MbEdge(picture, m - w, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + MbEdge(picture, m - w, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); } else if (pairY > 0) { @@ -157,18 +198,18 @@ public sealed partial class H264Decoder // A frame macroblock under a field pair: each field of its top rows against that field. for (var j = 0; j < 2; j++) { - MbEdge(picture, aboveTop + (j * w), m, false, lumaOrigin + (j * width), 2 * width, chromaOrigin + (j * cwidth), 2 * cwidth, alphaOffset, betaOffset, bs); + MbEdge(picture, aboveTop + (j * w), m, false, lumaOrigin + (j * width), 2 * width, chromaOrigin + (j * cwidth), 2 * cwidth, alphaOffset, betaOffset, bs); } } else { var pm = isField && bottom == 0 && field[aboveTop] ? aboveTop : aboveTop + w; - MbEdge(picture, pm, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + MbEdge(picture, pm, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); } } } - InnerEdges(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + InnerEdges(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); } } } @@ -176,11 +217,13 @@ public sealed partial class H264Decoder /// /// The left edge of an MBAFF macroblock whose left pair is of the other kind (frame and field): bS and qP row by - /// row, from the macroblock holding each row of the left pair. + /// row, from the macroblock holding each row of the left pair. A chroma row takes the bS of a luma row: in 4:2:0 the + /// mapping of §8.7.2.1, in 4:2:2 and 4:4:4 (as many chroma rows as luma rows) the row itself. /// - private void MixedLeftEdge( + 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) + where T : unmanaged { var w = widthInMbs; var leftField = picture.MbField[leftTop]; @@ -191,6 +234,7 @@ public sealed partial class H264Decoder rowBs[r] = (byte)BoundaryStrength(picture, pm, (((yM & 15) >> 2) * 4) + 3, m, (r >> 2) * 4, true, true); } + var luma = Plane(deblockLuma); for (var r = 0; r < 16; r++) { if (rowBs[r] == 0) @@ -198,18 +242,22 @@ public sealed partial class H264Decoder continue; } - var qpav = (mbQp[rowMb[r]] + mbQp[m] + 1) >> 1; - var indexA = Math.Clamp(qpav + alphaOffset, 0, 51); - int alpha = H264Tables.Alpha[indexA], beta = H264Tables.Beta[Math.Clamp(qpav + betaOffset, 0, 51)]; - if (alpha != 0 && beta != 0) + if (Thresholds(mbQp[rowMb[r]], mbQp[m], alphaOffset, betaOffset, bitDepthY, out var alpha, out var beta, out var indexA)) { - FilterLuma(picture.Y, lumaOrigin + (r * stride), 1, rowBs[r], alpha, beta, indexA); + FilterLuma(luma, lumaOrigin + (r * stride), 1, rowBs[r], alpha, beta, indexA, bitDepthY - 8, maxY); } } - for (var k = 0; k < 8; k++) + if (chromaArrayType == 0) { - var lumaRow = isField && !leftField ? 2 * k : (4 * (k >> 1)) + (k & 1); + return; + } + + var cb = Plane(picture.Cb); + var cr = Plane(picture.Cr); + for (var k = 0; k < mbHeightC; k++) + { + var lumaRow = mbHeightC == 16 ? k : isField && !leftField ? 2 * k : (4 * (k >> 1)) + (k & 1); var strength = rowBs[lumaRow]; if (strength == 0) { @@ -219,20 +267,28 @@ public sealed partial class H264Decoder var pm = rowMb[lumaRow]; for (var c = 0; c < 2; c++) { - var qpav = (mbQpC[(pm * 2) + c] + mbQpC[(m * 2) + c] + 1) >> 1; - var indexA = Math.Clamp(qpav + alphaOffset, 0, 51); - int alpha = H264Tables.Alpha[indexA], beta = H264Tables.Beta[Math.Clamp(qpav + betaOffset, 0, 51)]; - if (alpha != 0 && beta != 0) + if (!Thresholds(mbQpC[(pm * 2) + c], mbQpC[(m * 2) + c], alphaOffset, betaOffset, bitDepthC, out var alpha, out var beta, out var indexA)) { - FilterChroma(c == 0 ? picture.Cb : picture.Cr, chromaOrigin + (k * cstride), 1, strength, alpha, beta, indexA); + continue; + } + + var plane = c == 0 ? cb : cr; + if (chromaArrayType == 3) + { + FilterLuma(plane, chromaOrigin + (k * cstride), 1, strength, alpha, beta, indexA, bitDepthC - 8, maxC); + } + else + { + FilterChroma(plane, chromaOrigin + (k * cstride), 1, strength, alpha, beta, indexA, bitDepthC - 8, maxC); } } } } /// A macroblock edge between (left or above) and , luma and chroma. - private void MbEdge( + 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) + where T : unmanaged { for (var i = 0; i < 4; i++) { @@ -246,24 +302,44 @@ public sealed partial class H264Decoder } int along = vertical ? stride : 1, across = vertical ? 1 : stride; - LumaEdge(picture.Y, lumaOrigin, along, across, bs, mbQp[pm], mbQp[qm], alphaOffset, betaOffset); + Edge(Plane(deblockLuma), lumaOrigin, along, across, bs, 16, mbQp[pm], mbQp[qm], alphaOffset, betaOffset, bitDepthY, chromaStyle: false); + if (chromaArrayType == 0) + { + return; + } + int calong = vertical ? cstride : 1, cacross = vertical ? 1 : cstride; + var count = vertical ? mbHeightC : mbWidthC; for (var c = 0; c < 2; c++) { - ChromaEdge(c == 0 ? picture.Cb : picture.Cr, chromaOrigin, calong, cacross, bs, mbQpC[(pm * 2) + c], mbQpC[(qm * 2) + c], alphaOffset, betaOffset); + Edge(Plane(c == 0 ? picture.Cb : picture.Cr), chromaOrigin, calong, cacross, bs, count, mbQpC[(pm * 2) + c], mbQpC[(qm * 2) + c], alphaOffset, betaOffset, bitDepthC, chromaStyle: chromaArrayType != 3); } } - /// The internal edges of macroblock in one direction (luma 4, 8, 12; chroma 4). - private void InnerEdges( + /// + /// The internal edges of macroblock in one direction: luma 4, 8, 12 (only 8 with the 8×8 + /// transform); chroma at the same luma positions where they fall on a 4×4 chroma block edge — 4 for 4:2:0, the + /// rows 4, 8 and 12 of 4:2:2 (whatever the transform of luma), all the luma edges in 4:4:4. + /// + private void InnerEdges( Picture picture, int m, bool vertical, int lumaOrigin, int stride, int chromaOrigin, int cstride, int alphaOffset, int betaOffset, Span bs) + where T : unmanaged { var t8 = mbT8[m]; int along = vertical ? stride : 1, across = vertical ? 1 : stride; int calong = vertical ? cstride : 1, cacross = vertical ? 1 : cstride; + var chromaSize = vertical ? mbWidthC : mbHeightC; + var count = vertical ? mbHeightC : mbWidthC; for (var edge = 1; edge < 4; edge++) { - if (t8 && (edge & 1) != 0) + var lumaEdge = !t8 || (edge & 1) == 0; + var chromaEdge = chromaArrayType switch + { + 0 => false, + 3 => lumaEdge, + _ => chromaSize == 16 || edge == 2, + }; + if (!lumaEdge && !chromaEdge) { continue; } @@ -279,55 +355,67 @@ public sealed partial class H264Decoder continue; } - var offset = edge * 4 * (vertical ? 1 : stride); - LumaEdge(picture.Y, lumaOrigin + offset, along, across, bs, mbQp[m], mbQp[m], alphaOffset, betaOffset); - if (edge == 2) + if (lumaEdge) { - var coffset = 4 * (vertical ? 1 : cstride); + var offset = edge * 4 * (vertical ? 1 : stride); + Edge(Plane(deblockLuma), lumaOrigin + offset, along, across, bs, 16, mbQp[m], mbQp[m], alphaOffset, betaOffset, bitDepthY, chromaStyle: false); + } + + if (chromaEdge) + { + var position = edge * chromaSize / 4; + var coffset = position * (vertical ? 1 : cstride); for (var c = 0; c < 2; c++) { - ChromaEdge(c == 0 ? picture.Cb : picture.Cr, chromaOrigin + coffset, calong, cacross, bs, mbQpC[(m * 2) + c], mbQpC[(m * 2) + c], alphaOffset, betaOffset); + Edge(Plane(c == 0 ? picture.Cb : picture.Cr), chromaOrigin + coffset, calong, cacross, bs, count, mbQpC[(m * 2) + c], mbQpC[(m * 2) + c], alphaOffset, betaOffset, bitDepthC, chromaStyle: chromaArrayType != 3); } } } } - private static void LumaEdge(byte[] plane, int origin, int along, int across, ReadOnlySpan bs, int qpP, int qpQ, int alphaOffset, int betaOffset) + /// + /// α, β and indexA of an edge (§8.7.2.2) from the qP of its two sides, scaled to the bit depth (equations 8-466, + /// 8-467); false when the edge is not filtered. + /// + private static bool Thresholds(int qpP, int qpQ, int alphaOffset, int betaOffset, int bitDepth, out int alpha, out int beta, out int indexA) { var qpav = (qpP + qpQ + 1) >> 1; - var indexA = Math.Clamp(qpav + alphaOffset, 0, 51); - int alpha = H264Tables.Alpha[indexA], beta = H264Tables.Beta[Math.Clamp(qpav + betaOffset, 0, 51)]; - if (alpha == 0 || beta == 0) - { - return; - } - - for (var k = 0; k < 16; k++) - { - var strength = bs[k >> 2]; - if (strength != 0) - { - FilterLuma(plane, origin + (k * along), across, strength, alpha, beta, indexA); - } - } + indexA = Math.Clamp(qpav + alphaOffset, 0, 51); + alpha = H264Tables.Alpha[indexA] << (bitDepth - 8); + beta = H264Tables.Beta[Math.Clamp(qpav + betaOffset, 0, 51)] << (bitDepth - 8); + return alpha != 0 && beta != 0; } - private static void ChromaEdge(byte[] plane, int origin, int along, int across, ReadOnlySpan bs, int qpP, int qpQ, int alphaOffset, int betaOffset) + /// + /// The samples along one edge (16 in luma; 8 or 16 in chroma), each with the bS of its 4×4 + /// luma block; the filter of chroma (chromaStyleFilteringFlag) or that of luma, which 4:4:4 uses for Cb and Cr. + /// + private static void Edge(Span plane, int origin, int along, int across, ReadOnlySpan bs, int count, int qpP, int qpQ, int alphaOffset, int betaOffset, int bitDepth, bool chromaStyle) + where T : unmanaged { - var qpav = (qpP + qpQ + 1) >> 1; - var indexA = Math.Clamp(qpav + alphaOffset, 0, 51); - int alpha = H264Tables.Alpha[indexA], beta = H264Tables.Beta[Math.Clamp(qpav + betaOffset, 0, 51)]; - if (alpha == 0 || beta == 0) + if (!Thresholds(qpP, qpQ, alphaOffset, betaOffset, bitDepth, out var alpha, out var beta, out var indexA)) { return; } - for (var k = 0; k < 8; k++) + var shift = count == 16 ? 2 : 1; + var bdShift = bitDepth - 8; + var max = (1 << bitDepth) - 1; + for (var k = 0; k < count; k++) { - var strength = bs[k >> 1]; - if (strength != 0) + var strength = bs[k >> shift]; + if (strength == 0) { - FilterChroma(plane, origin + (k * along), across, strength, alpha, beta, indexA); + continue; + } + + if (chromaStyle) + { + FilterChroma(plane, origin + (k * along), across, strength, alpha, beta, indexA, bdShift, max); + } + else + { + FilterLuma(plane, origin + (k * along), across, strength, alpha, beta, indexA, bdShift, max); } } } @@ -417,51 +505,71 @@ public sealed partial class H264Decoder private static bool MvFar(short[] mv, int a, int b, int verticalLimit) => Math.Abs(mv[a] - mv[b]) >= 4 || Math.Abs(mv[a + 1] - mv[b + 1]) >= verticalLimit; + /// + /// The transform block holding the 4×4 luma block has coefficients; in 4:4:4 (not coded as + /// separate planes) those of the Cb and Cr blocks at the same place count too. + /// private bool HasCoefficients(int m, int blk) { - var baseIndex = m * 24; - if (!mbT8[m]) + var planes = chromaArrayType == 3 ? 3 : 1; + for (var plane = 0; plane < planes; plane++) { - return nz[baseIndex + blk] != 0; + var baseIndex = (m * NzPerMb) + (plane * 16); + if (!mbT8[m]) + { + if (nz[baseIndex + blk] != 0) + { + return true; + } + + continue; + } + + // The 8×8 transform block containing the 4×4 block. + var r0 = ((blk >> 3) * 8) + (((blk & 3) >> 1) * 2); + if ((nz[baseIndex + r0] | nz[baseIndex + r0 + 1] | nz[baseIndex + r0 + 4] | nz[baseIndex + r0 + 5]) != 0) + { + return true; + } } - // The 8×8 transform block containing the 4×4 block. - var r0 = ((blk >> 3) * 8) + (((blk & 3) >> 1) * 2); - return (nz[baseIndex + r0] | nz[baseIndex + r0 + 1] | nz[baseIndex + r0 + 4] | nz[baseIndex + r0 + 5]) != 0; + return false; } - private static void FilterLuma(byte[] s, int o, int step, int bS, int alpha, int beta, int indexA) + /// The filter of luma edges (§8.7.2.3, §8.7.2.4), also that of Cb and Cr in 4:4:4; tC0 scaled by . + private static void FilterLuma(Span s, int o, int step, int bS, int alpha, int beta, int indexA, int bdShift, int max) + where T : unmanaged { - int p0 = s[o - step], q0 = s[o]; + int p0 = Get(s[o - step]), q0 = Get(s[o]); if (Math.Abs(p0 - q0) >= alpha) { return; } - int p1 = s[o - (2 * step)], q1 = s[o + step]; + int p1 = Get(s[o - (2 * step)]), q1 = Get(s[o + step]); if (Math.Abs(p1 - p0) >= beta || Math.Abs(q1 - q0) >= beta) { return; } - int p2 = s[o - (3 * step)], q2 = s[o + (2 * step)]; + int p2 = Get(s[o - (3 * step)]), q2 = Get(s[o + (2 * step)]); var ap = Math.Abs(p2 - p0) < beta; var aq = Math.Abs(q2 - q0) < beta; if (bS < 4) { - int tc0 = H264Tables.Tc0[(indexA * 3) + bS - 1]; + var tc0 = H264Tables.Tc0[(indexA * 3) + bS - 1] << bdShift; var tc = tc0 + (ap ? 1 : 0) + (aq ? 1 : 0); var delta = Math.Clamp((((q0 - p0) << 2) + (p1 - q1) + 4) >> 3, -tc, tc); - s[o - step] = Clip(p0 + delta); - s[o] = Clip(q0 - delta); + s[o - step] = Make(Clip(p0 + delta, max)); + s[o] = Make(Clip(q0 - delta, max)); if (ap) { - s[o - (2 * step)] = (byte)(p1 + Math.Clamp((p2 + ((p0 + q0 + 1) >> 1) - (p1 << 1)) >> 1, -tc0, tc0)); + s[o - (2 * step)] = Make(p1 + Math.Clamp((p2 + ((p0 + q0 + 1) >> 1) - (p1 << 1)) >> 1, -tc0, tc0)); } if (aq) { - s[o + step] = (byte)(q1 + Math.Clamp((q2 + ((p0 + q0 + 1) >> 1) - (q1 << 1)) >> 1, -tc0, tc0)); + s[o + step] = Make(q1 + Math.Clamp((q2 + ((p0 + q0 + 1) >> 1) - (q1 << 1)) >> 1, -tc0, tc0)); } return; @@ -470,38 +578,40 @@ public sealed partial class H264Decoder var strong = Math.Abs(p0 - q0) < ((alpha >> 2) + 2); if (ap && strong) { - int p3 = s[o - (4 * step)]; - s[o - step] = (byte)((p2 + (2 * p1) + (2 * p0) + (2 * q0) + q1 + 4) >> 3); - s[o - (2 * step)] = (byte)((p2 + p1 + p0 + q0 + 2) >> 2); - s[o - (3 * step)] = (byte)(((2 * p3) + (3 * p2) + p1 + p0 + q0 + 4) >> 3); + var p3 = Get(s[o - (4 * step)]); + s[o - step] = Make((p2 + (2 * p1) + (2 * p0) + (2 * q0) + q1 + 4) >> 3); + s[o - (2 * step)] = Make((p2 + p1 + p0 + q0 + 2) >> 2); + s[o - (3 * step)] = Make(((2 * p3) + (3 * p2) + p1 + p0 + q0 + 4) >> 3); } else { - s[o - step] = (byte)(((2 * p1) + p0 + q1 + 2) >> 2); + s[o - step] = Make(((2 * p1) + p0 + q1 + 2) >> 2); } if (aq && strong) { - int q3 = s[o + (3 * step)]; - s[o] = (byte)((p1 + (2 * p0) + (2 * q0) + (2 * q1) + q2 + 4) >> 3); - s[o + step] = (byte)((p0 + q0 + q1 + q2 + 2) >> 2); - s[o + (2 * step)] = (byte)(((2 * q3) + (3 * q2) + q1 + q0 + p0 + 4) >> 3); + var q3 = Get(s[o + (3 * step)]); + s[o] = Make((p1 + (2 * p0) + (2 * q0) + (2 * q1) + q2 + 4) >> 3); + s[o + step] = Make((p0 + q0 + q1 + q2 + 2) >> 2); + s[o + (2 * step)] = Make(((2 * q3) + (3 * q2) + q1 + q0 + p0 + 4) >> 3); } else { - s[o] = (byte)(((2 * q1) + q0 + p1 + 2) >> 2); + s[o] = Make(((2 * q1) + q0 + p1 + 2) >> 2); } } - private static void FilterChroma(byte[] s, int o, int step, int bS, int alpha, int beta, int indexA) + /// The filter of the chroma edges of 4:2:0 and 4:2:2 (chromaStyleFilteringFlag). + private static void FilterChroma(Span s, int o, int step, int bS, int alpha, int beta, int indexA, int bdShift, int max) + where T : unmanaged { - int p0 = s[o - step], q0 = s[o]; + int p0 = Get(s[o - step]), q0 = Get(s[o]); if (Math.Abs(p0 - q0) >= alpha) { return; } - int p1 = s[o - (2 * step)], q1 = s[o + step]; + int p1 = Get(s[o - (2 * step)]), q1 = Get(s[o + step]); if (Math.Abs(p1 - p0) >= beta || Math.Abs(q1 - q0) >= beta) { return; @@ -509,16 +619,14 @@ public sealed partial class H264Decoder if (bS < 4) { - var tc = H264Tables.Tc0[(indexA * 3) + bS - 1] + 1; + var tc = (H264Tables.Tc0[(indexA * 3) + bS - 1] << bdShift) + 1; var delta = Math.Clamp((((q0 - p0) << 2) + (p1 - q1) + 4) >> 3, -tc, tc); - s[o - step] = Clip(p0 + delta); - s[o] = Clip(q0 - delta); + s[o - step] = Make(Clip(p0 + delta, max)); + s[o] = Make(Clip(q0 - delta, max)); return; } - s[o - step] = (byte)(((2 * p1) + p0 + q1 + 2) >> 2); - s[o] = (byte)(((2 * q1) + q0 + p1 + 2) >> 2); + s[o - step] = Make(((2 * p1) + p0 + q1 + 2) >> 2); + s[o] = Make(((2 * q1) + q0 + p1 + 2) >> 2); } - - private static byte Clip(int v) => (byte)(v < 0 ? 0 : v > 255 ? 255 : v); } diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Entropy.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Entropy.cs index c163e01..7aa4b1a 100644 --- a/src/Febe.Core/Codecs/H264/H264Decoder.Entropy.cs +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Entropy.cs @@ -336,6 +336,13 @@ public sealed partial class H264Decoder { if (!cabacMode) { + if (numC8x8 == 0) + { + // Without chroma syntax (monochrome, 4:4:4, separate planes) the code covers the luma bits only. + var luma = rd.ReadUe(15); + return intra ? H264Tables.CbpIntraNoChroma[luma] : H264Tables.CbpInterNoChroma[luma]; + } + var code = rd.ReadUe(47); return intra ? H264Tables.CbpIntra[code] : H264Tables.CbpInter[code]; } @@ -368,7 +375,12 @@ public sealed partial class H264Decoder cbp |= cabac.Decision(73 + condA + (2 * condB)) << b8; } - var a = mbA >= 0 ? mbCbp[mbA] >> 4 : 0; + if (numC8x8 == 0) + { + return cbp; + } + + var a =mbA >= 0 ? mbCbp[mbA] >> 4 : 0; var b = mbB >= 0 ? mbCbp[mbB] >> 4 : 0; var inc = (a != 0 ? 1 : 0) + (b != 0 ? 2 : 0); if (cabac.Decision(77 + inc) != 0) @@ -417,7 +429,7 @@ public sealed partial class H264Decoder int nC; if (cat == 3) { - nC = -1; + nC = numC8x8 == 2 ? -2 : -1; } else if (cat == 4) { @@ -425,11 +437,12 @@ public sealed partial class H264Decoder } else { - nC = LumaNc(blk); + nC = LumaNc(blk, comp); } var table = nC switch { + -2 => CavlcTables.CoeffTokenLookup[5], -1 => CavlcTables.CoeffTokenLookup[4], < 2 => CavlcTables.CoeffTokenLookup[0], < 4 => CavlcTables.CoeffTokenLookup[1], @@ -515,7 +528,8 @@ public sealed partial class H264Decoder var zerosLeft = 0; if (total < maxNum) { - var tz = cat == 3 ? CavlcTables.TotalZerosChromaDcLookup[total - 1] : CavlcTables.TotalZerosLookup[total - 1]; + var tz = cat != 3 ? CavlcTables.TotalZerosLookup[total - 1] + : numC8x8 == 2 ? CavlcTables.TotalZerosChroma422DcLookup[total - 1] : CavlcTables.TotalZerosChromaDcLookup[total - 1]; var e = tz[rd.Peek(16)]; if (e == 0) { @@ -575,18 +589,18 @@ public sealed partial class H264Decoder private bool HiddenByPartitioning(int n) => partitioned && pps.ConstrainedIntraPred && !IsIntra(n) && IsIntra(mb); /// nC of a luma 4×4 block (raster index) from the blocks to its left and above (§9.2.1). - private int LumaNc(int raster) + private int LumaNc(int raster, int plane) { int bx = raster & 3, by = raster >> 2; bool hasA = true, hasB = true; int nA = 0, nB = 0; if (bx > 0) { - nA = nz[(mb * 24) + raster - 1]; + nA = nz[(mb * NzPerMb) + (plane * 16) + raster - 1]; } else if (Locate(-1, by * 4, 16, out var yM) is var a and >= 0) { - nA = HiddenByPartitioning(a) ? 0 : nz[(a * 24) + (((yM & 15) >> 2) * 4) + 3]; + nA = HiddenByPartitioning(a) ? 0 : nz[(a * NzPerMb) + (plane * 16) + (((yM & 15) >> 2) * 4) + 3]; } else { @@ -595,11 +609,11 @@ public sealed partial class H264Decoder if (by > 0) { - nB = nz[(mb * 24) + raster - 4]; + nB = nz[(mb * NzPerMb) + (plane * 16) + raster - 4]; } else if (Locate(bx * 4, -1, 16, out _) is var b and >= 0) { - nB = HiddenByPartitioning(b) ? 0 : nz[(b * 24) + 12 + bx]; + nB = HiddenByPartitioning(b) ? 0 : nz[(b * NzPerMb) + (plane * 16) + 12 + bx]; } else { @@ -609,19 +623,20 @@ public sealed partial class H264Decoder return hasA && hasB ? (nA + nB + 1) >> 1 : hasA ? nA : hasB ? nB : 0; } + /// nC of a chroma AC block of 4:2:0 or 4:2:2 (blocks in raster order, two per row). private int ChromaNc(int b, int comp) { int bx = b & 1, by = b >> 1; - var baseIndex = 16 + (comp * 4); + var baseIndex = 16 + (comp * 16); bool hasA = true, hasB = true; int nA = 0, nB = 0; if (bx > 0) { - nA = nz[(mb * 24) + baseIndex + b - 1]; + nA = nz[(mb * NzPerMb) + baseIndex + b - 1]; } - else if (Locate(-1, by * 4, 8, out var yM) is var a and >= 0) + else if (Locate(-1, by * 4, mbHeightC, out var yM) is var a and >= 0) { - nA = HiddenByPartitioning(a) ? 0 : nz[(a * 24) + baseIndex + (((yM & 7) >> 2) * 2) + 1]; + nA = HiddenByPartitioning(a) ? 0 : nz[(a * NzPerMb) + baseIndex + (((yM & (mbHeightC - 1)) >> 2) * 2) + 1]; } else { @@ -630,11 +645,11 @@ public sealed partial class H264Decoder if (by > 0) { - nB = nz[(mb * 24) + baseIndex + b - 2]; + nB = nz[(mb * NzPerMb) + baseIndex + b - 2]; } - else if (Locate(bx * 4, -1, 8, out _) is var n and >= 0) + else if (Locate(bx * 4, -1, mbHeightC, out _) is var n and >= 0) { - nB = HiddenByPartitioning(n) ? 0 : nz[(n * 24) + baseIndex + 2 + bx]; + nB = HiddenByPartitioning(n) ? 0 : nz[(n * NzPerMb) + baseIndex + (mbHeightC / 2) - 2 + bx]; } else { @@ -683,14 +698,14 @@ public sealed partial class H264Decoder var last = -1; for (var i = 0; i < maxNum - 1; i++) { - var ctx = cat == 5 ? sig8x8[i] : cat == 3 ? Math.Min(i, 2) : i; + var ctx = cat == 5 ? sig8x8[i] : cat == 3 ? Math.Min(i / numC8x8, 2) : i; if (cabac.Decision(sigBase + ctx) == 0) { continue; } significant[i] = true; - var lastCtx = cat == 5 ? H264Tables.LastContext8x8[i] : cat == 3 ? Math.Min(i, 2) : i; + var lastCtx = cat == 5 ? H264Tables.LastContext8x8[i] : cat == 3 ? Math.Min(i / numC8x8, 2) : i; if (cabac.Decision(lastBase + lastCtx) != 0) { last = i; @@ -808,13 +823,13 @@ public sealed partial class H264Decoder } else { - n = left ? Locate(-1, by * 4, 8, out var yM) : Locate(bx * 4, -1, 8, out yM); + n = left ? Locate(-1, by * 4, mbHeightC, out var yM) : Locate(bx * 4, -1, mbHeightC, out yM); if (n < 0) { return currentIntra ? 1 : 0; } - index = left ? ((((yM & 7) >> 2) * 2) + 1) : 2 + bx; + index = left ? ((((yM & (mbHeightC - 1)) >> 2) * 2) + 1) : (mbHeightC / 2) - 2 + bx; } if (mbKind[n] == MbKind.IPcm) @@ -822,7 +837,7 @@ public sealed partial class H264Decoder return 1; } - return nz[(n * 24) + 16 + (comp * 4) + index] != 0 ? 1 : 0; + return nz[(n * NzPerMb) + 16 + (comp * 16) + index] != 0 ? 1 : 0; } default: @@ -849,7 +864,7 @@ public sealed partial class H264Decoder return 1; } - return nz[(n * 24) + index] != 0 ? 1 : 0; + return nz[(n * NzPerMb) + index] != 0 ? 1 : 0; } } } diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs index 08bb5a5..300fe51 100644 --- a/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs @@ -555,11 +555,28 @@ public sealed partial class H264Decoder } } + /// + /// 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. + /// /// /// 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) + { + if (wide) + { + MotionCompensate(px, py, w, h); + } + else + { + MotionCompensate(px, py, w, h); + } + } + + private void MotionCompensate(int px, int py, int w, int h) + where T : unmanaged { var picture = cur!; var b8 = ((py >> 3) * 2) + (px >> 3); @@ -571,8 +588,8 @@ public sealed partial class H264Decoder var x = (mbX * 16) + px; var y = ((mbField ? mbY >> 1 : mbY) * 16) + py; - Span a = stackalloc byte[256]; - Span b = stackalloc byte[256]; + Span a = stackalloc T[256]; + Span b = stackalloc T[256]; var size = w * h; var pa = a[..size]; var pb = b[..size]; @@ -589,74 +606,98 @@ public sealed partial class H264Decoder int mv0x = picture.Mv[i0], mv0y = picture.Mv[i0 + 1], mv1x = picture.Mv[i1], mv1y = picture.Mv[i1 + 1]; int width = picture.Width, height = picture.Height; - // Luma. - if (use0) - { - var field = e0.Parity >= 0; - InterPrediction.Luma(e0.Pic!.Y, field ? e0.Parity * width : 0, field ? 2 * width : width, width, field ? height / 2 : height, (x * 4) + mv0x, (y * 4) + mv0y, w, h, pa); - } - - if (use1) - { - var field = e1.Parity >= 0; - InterPrediction.Luma(e1.Pic!.Y, field ? e1.Parity * width : 0, field ? 2 * width : width, width, field ? height / 2 : height, (x * 4) + mv1x, (y * 4) + mv1y, w, h, use0 ? pb : pa); - } - - Combine(pa, pb, use0, use1, r0, r1, 0); - for (var row = 0; row < h; row++) - { - pa.Slice(row * w, w).CopyTo(picture.Y.AsSpan(lumaO + ((py + row) * lumaStride) + px, w)); - } - - // Chroma; between fields of opposite parity the vertical vector moves by a quarter of a chroma row (Table 8-9). - int cw = w / 2, ch = h / 2, cwidth = width / 2, cheight = height / 2; - var csize = cw * ch; - var ca = a[..csize]; - var cb = b[..csize]; - var parity = mbY & 1; - var adjust0 = e0.Parity < 0 || e0.Parity == parity ? 0 : parity == 0 ? -2 : 2; - var adjust1 = e1.Parity < 0 || e1.Parity == parity ? 0 : parity == 0 ? -2 : 2; - for (var comp = 1; comp <= 2; comp++) + // Luma, or the colour plane of the slice; in 4:4:4 Cb and Cr too, with the same interpolation (§8.4.2.2). + for (var plane = 0; plane < LumaLikePlanes; plane++) { + var source = plane == 0 ? colourPlane : plane; + var max = plane == 0 ? maxY : maxC; if (use0) { var field = e0.Parity >= 0; - InterPrediction.Chroma(comp == 1 ? e0.Pic!.Cb : e0.Pic!.Cr, field ? e0.Parity * cwidth : 0, field ? 2 * cwidth : cwidth, cwidth, field ? cheight / 2 : cheight, (x * 4) + mv0x, (y * 4) + mv0y + adjust0, cw, ch, ca); + InterPrediction.Luma(Samples.Plane(e0.Pic!.Plane(source)), field ? e0.Parity * width : 0, field ? 2 * width : width, width, field ? height / 2 : height, (x * 4) + mv0x, (y * 4) + mv0y, w, h, pa, max); } if (use1) { var field = e1.Parity >= 0; - InterPrediction.Chroma(comp == 1 ? e1.Pic!.Cb : e1.Pic!.Cr, field ? e1.Parity * cwidth : 0, field ? 2 * cwidth : cwidth, cwidth, field ? cheight / 2 : cheight, (x * 4) + mv1x, (y * 4) + mv1y + adjust1, cw, ch, use0 ? cb : ca); + InterPrediction.Luma(Samples.Plane(e1.Pic!.Plane(source)), field ? e1.Parity * width : 0, field ? 2 * width : width, width, field ? height / 2 : height, (x * 4) + mv1x, (y * 4) + mv1y, w, h, use0 ? pb : pa, max); } - Combine(ca, cb, use0, use1, r0, r1, comp); - var plane = comp == 1 ? picture.Cb : picture.Cr; + Combine(pa, pb, use0, use1, r0, r1, plane, plane == 0 ? bitDepthY : bitDepthC); + var target = Samples.Plane(picture.Plane(source)); + for (var row = 0; row < h; row++) + { + pa.Slice(row * w, w).CopyTo(target.Slice(lumaO + ((py + row) * lumaStride) + px, w)); + } + } + + if (numC8x8 == 0) + { + return; + } + + // Chroma of 4:2:0 and 4:2:2 in eighths of a chroma sample: 4:2:2 has full vertical resolution, so its vertical + // vector is in eighths already doubled (§8.4.1.4, §8.4.2.2.2); between fields of opposite parity the vertical + // vector of 4:2:0 moves by a quarter of a chroma row (Table 8-9). + var full = chromaArrayType == 2; + int cw = w / 2, ch = full ? h : h / 2, cwidth = picture.ChromaWidth, cheight = picture.ChromaHeight; + var csize = cw * ch; + var ca = a[..csize]; + var cb = b[..csize]; + var parity = mbY & 1; + var adjust0 = full || e0.Parity < 0 || e0.Parity == parity ? 0 : parity == 0 ? -2 : 2; + var adjust1 = full || e1.Parity < 0 || e1.Parity == parity ? 0 : parity == 0 ? -2 : 2; + var ey0 = full ? ((y * 4) + mv0y) * 2 : (y * 4) + mv0y + adjust0; + var ey1 = full ? ((y * 4) + mv1y) * 2 : (y * 4) + mv1y + adjust1; + var cy = full ? py : py / 2; + for (var comp = 1; comp <= 2; comp++) + { + if (use0) + { + var field = e0.Parity >= 0; + InterPrediction.Chroma(Samples.Plane(comp == 1 ? e0.Pic!.Cb : e0.Pic!.Cr), field ? e0.Parity * cwidth : 0, field ? 2 * cwidth : cwidth, cwidth, field ? cheight / 2 : cheight, (x * 4) + mv0x, ey0, cw, ch, ca); + } + + if (use1) + { + var field = e1.Parity >= 0; + InterPrediction.Chroma(Samples.Plane(comp == 1 ? e1.Pic!.Cb : e1.Pic!.Cr), field ? e1.Parity * cwidth : 0, field ? 2 * cwidth : cwidth, cwidth, field ? cheight / 2 : cheight, (x * 4) + mv1x, ey1, cw, ch, use0 ? cb : ca); + } + + Combine(ca, cb, use0, use1, r0, r1, comp, bitDepthC); + var plane = Samples.Plane(comp == 1 ? picture.Cb : picture.Cr); for (var row = 0; row < ch; row++) { - ca.Slice(row * cw, cw).CopyTo(plane.AsSpan(chromaO + (((py / 2) + row) * chromaStride) + (px / 2), cw)); + ca.Slice(row * cw, cw).CopyTo(plane.Slice(chromaO + ((cy + row) * chromaStride) + (px / 2), cw)); } } } - private void Combine(Span a, ReadOnlySpan b, bool use0, bool use1, int r0, int r1, int comp) + /// + /// The weighted sample prediction (§8.4.2.3) of component (0 luma, 1 Cb, 2 Cr): the offsets + /// are in units of 8-bit samples, scaled to . + /// + private void Combine(Span a, ReadOnlySpan b, bool use0, bool use1, int r0, int r1, int comp, int bitDepth) + where T : unmanaged { // Explicit weights are by frame for the field macroblocks of an MBAFF frame (refIdxWP = refIdx >> 1). var fieldMb = mbaff && mbField; int w0Index = fieldMb ? r0 >> 1 : r0, w1Index = fieldMb ? r1 >> 1 : r1; + var shift = bitDepth - 8; + var max = (1 << bitDepth) - 1; if (use0 && use1) { if (weightMode == 1 && sh.Weights is { } weights && sh.Offsets is { } offsets) { var logWd = comp == 0 ? sh.LumaLog2WeightDenom : sh.ChromaLog2WeightDenom; - InterPrediction.WeightTwo(a, b, logWd, weights[0][(w0Index * 3) + comp], weights[1][(w1Index * 3) + comp], offsets[0][(w0Index * 3) + comp], offsets[1][(w1Index * 3) + comp]); + InterPrediction.WeightTwo(a, b, logWd, weights[0][(w0Index * 3) + comp], weights[1][(w1Index * 3) + comp], offsets[0][(w0Index * 3) + comp] << shift, offsets[1][(w1Index * 3) + comp] << shift, max); } else if (weightMode == 2) { var w0 = fieldMb ? implicitField[mbY & 1][(r0 * 2 * sh.NumRefIdxActiveL1) + r1] : implicitW0[(r0 * sh.NumRefIdxActiveL1) + r1]; - InterPrediction.WeightTwo(a, b, 5, w0, 64 - w0, 0, 0); + InterPrediction.WeightTwo(a, b, 5, w0, 64 - w0, 0, 0, max); } else { @@ -671,7 +712,7 @@ public sealed partial class H264Decoder var list = use0 ? 0 : 1; var r = use0 ? w0Index : w1Index; var logWd = comp == 0 ? sh.LumaLog2WeightDenom : sh.ChromaLog2WeightDenom; - InterPrediction.WeightOne(a, logWd, w[list][(r * 3) + comp], o[list][(r * 3) + comp]); + InterPrediction.WeightOne(a, logWd, w[list][(r * 3) + comp], o[list][(r * 3) + comp] << shift, max); } } } diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Slice.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Slice.cs index 0b7bd0f..972326c 100644 --- a/src/Febe.Core/Codecs/H264/H264Decoder.Slice.cs +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Slice.cs @@ -1,3 +1,5 @@ +using static Febe.Core.Codecs.H264.Samples; + namespace Febe.Core.Codecs.H264; public sealed partial class H264Decoder @@ -25,6 +27,12 @@ public sealed partial class H264Decoder private const int Shape8x16 = 2; private const int Shape8x8 = 3; + /// + /// Entries of per macroblock: the 16 luma 4×4 blocks, then 16 for Cb and 16 for Cr (4:2:0 uses 4 of + /// them, 4:2:2 8, 4:4:4 all, as luma). + /// + private const int NzPerMb = 48; + /// Prediction lists of the two partitions of B_16x8 and B_8x16 (mb_type 4–21): 1 L0, 2 L1, 3 both. private static readonly byte[] BPartPred = [ @@ -37,6 +45,12 @@ public sealed partial class H264Decoder /// B sub-macroblock types 0–12: shape (0 8×8, 1 8×4, 2 4×8, 3 4×4). private static readonly byte[] BSubShape = [0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3]; + /// + /// The raster position (row × 2 + column) of the chroma DC coefficients of 4:2:2 in parsing order (equation 8-330: + /// c = [c0 c2; c1 c5; c3 c6; c4 c7]). + /// + private static readonly byte[] ChromaDc422Scan = [0, 2, 1, 4, 6, 3, 5, 7]; + private readonly List<(int Disable, int Alpha, int Beta)> sliceFilters = []; private readonly RefEntry[][] refList = [[], []]; private readonly CabacEngine cabac = new(); @@ -44,11 +58,17 @@ public sealed partial class H264Decoder private int widthInMbs; private int heightInMbs; private int mbCount; + + // The data of the macroblocks of the colour plane being decoded (see MacroblockState). private int[] mbSlice = []; private MbKind[] mbKind = []; private byte[] mbCbp = []; - private byte[] mbQp = []; - private byte[] mbQpC = []; + + /// QPY of each macroblock for the deblocking filter (0 for I_PCM and lossless macroblocks); negative above 8 bits. + private sbyte[] mbQp = []; + + /// QPC of Cb and Cr of each macroblock (from QPY, before QpBdOffsetC: negative values above 8 bits). + private sbyte[] mbQpC = []; private bool[] mbT8 = []; private sbyte[] intraModes = []; private byte[] chromaModes = []; @@ -57,6 +77,34 @@ public sealed partial class H264Decoder private byte[] mvdAbs = []; private bool[] subDirect = []; + /// One per colour plane when the planes of 4:4:4 are coded separately, else one. + private MacroblockState[] planeStates = []; + + // The format of the active sequence (§6.2, §7.4.2.1.1). + private int chromaArrayType = 1; + private int mbWidthC = 8; + private int mbHeightC = 8; + + /// NumC8x8 of §7.4.5: chroma 8×8 blocks of each component (1 in 4:2:0, 2 in 4:2:2; 0 without that chroma). + private int numC8x8 = 1; + + private int bitDepthY = 8; + private int bitDepthC = 8; + private int maxY = 255; + private int maxC = 255; + private int qpBdOffsetY; + private int qpBdOffsetC; + private bool transformBypass; + + /// Samples of two bytes: some component has more than 8 bits. + private bool wide; + + /// separate_colour_plane_flag: each slice codes one colour plane as a monochrome picture. + private bool separatePlanes; + + /// The colour plane the current slice codes (0 unless the planes are separate): its samples are the «luma». + private int colourPlane; + // Slice state. private SliceHeader sh = null!; private Sps sps = null!; @@ -64,6 +112,8 @@ public sealed partial class H264Decoder private RbspReader rd = null!; private bool cabacMode; private int sliceNum; + + /// QPY of the macroblock being decoded (QPY,PRED before its mb_qp_delta): −QpBdOffsetY to 51. private int qp; private int lastQpDelta; private Pps? scalePps; @@ -87,6 +137,9 @@ public sealed partial class H264Decoder /// The current macroblock is a field macroblock (of a field picture or a field pair). private bool mbField; + /// The current macroblock is lossless: TransformBypassModeFlag (qpprime_y_zero_transform_bypass_flag and QP′Y 0). + private bool bypass; + private int lumaO; private int lumaStride; private int chromaO; @@ -106,13 +159,17 @@ public sealed partial class H264Decoder private int pairD; private readonly bool[] blkDone = new bool[16]; - private readonly int[] lumaCoef = new int[256]; - private readonly bool[] lumaHas = new bool[16]; - private readonly int[] chromaCoef = new int[2 * 4 * 16]; - private readonly bool[] chromaHas = new bool[8]; - /// The chroma DC levels as parsed (component × 4), for the macroblocks reconstructed in QS. - private readonly int[] chromaDcLevels = new int[8]; + /// The coefficients of the luma-like planes: Y, and Cb and Cr in 4:4:4 (plane × 256 + block × 16 + position). + private readonly int[] lumaCoef = new int[3 * 256]; + private readonly bool[] lumaHas = new bool[3 * 16]; + + /// The coefficients of 4:2:0 and 4:2:2 chroma: (component × 8 + block) × 16 + raster position. + private readonly int[] chromaCoef = new int[2 * 8 * 16]; + private readonly bool[] chromaHas = new bool[16]; + + /// The chroma DC levels as parsed (component × 8), for the macroblocks reconstructed in QS. + private readonly int[] chromaDcLevels = new int[16]; /// The residual being parsed is kept as levels, not scaled: P macroblocks of SP slices and SI macroblocks. private bool rawLevels; @@ -129,23 +186,91 @@ public sealed partial class H264Decoder private readonly int[] mvdValue = new int[2 * 16 * 2]; private int shape; - private void AllocateMacroblockState(int width, int height) + /// Planes coded like luma in the current macroblock: 3 in 4:4:4 (Y, Cb, Cr), else 1. + private int LumaLikePlanes => chromaArrayType == 3 ? 3 : 1; + + /// The macroblock data of one colour plane: the whole of it when the planes are not separate. + private sealed class MacroblockState(int mbCount) + { + internal readonly int[] Slice = new int[mbCount]; + internal readonly MbKind[] Kind = new MbKind[mbCount]; + internal readonly byte[] Cbp = new byte[mbCount]; + internal readonly sbyte[] Qp = new sbyte[mbCount]; + internal readonly sbyte[] QpC = new sbyte[mbCount * 2]; + internal readonly bool[] T8 = new bool[mbCount]; + internal readonly sbyte[] IntraModes = new sbyte[mbCount * 16]; + internal readonly byte[] ChromaModes = new byte[mbCount]; + internal readonly byte[] Nz = new byte[mbCount * NzPerMb]; + internal readonly byte[] CbfDc = new byte[mbCount]; + internal readonly byte[] MvdAbs = new byte[2 * mbCount * 16 * 2]; + internal readonly bool[] SubDirect = new bool[mbCount * 4]; + } + + private void AllocateMacroblockState(int width, int height, int planes) { widthInMbs = width; heightInMbs = height; mbCount = width * height; - mbSlice = new int[mbCount]; - mbKind = new MbKind[mbCount]; - mbCbp = new byte[mbCount]; - mbQp = new byte[mbCount]; - mbQpC = new byte[mbCount * 2]; - mbT8 = new bool[mbCount]; - intraModes = new sbyte[mbCount * 16]; - chromaModes = new byte[mbCount]; - nz = new byte[mbCount * 24]; - cbfDc = new byte[mbCount]; - mvdAbs = new byte[2 * mbCount * 16 * 2]; - subDirect = new bool[mbCount * 4]; + planeStates = new MacroblockState[planes]; + for (var i = 0; i < planes; i++) + { + planeStates[i] = new MacroblockState(mbCount); + } + + UsePlaneState(0); + } + + private void UsePlaneState(int k) + { + var s = planeStates[k]; + mbSlice = s.Slice; + mbKind = s.Kind; + mbCbp = s.Cbp; + mbQp = s.Qp; + mbQpC = s.QpC; + mbT8 = s.T8; + intraModes = s.IntraModes; + chromaModes = s.ChromaModes; + nz = s.Nz; + cbfDc = s.CbfDc; + mvdAbs = s.MvdAbs; + subDirect = s.SubDirect; + } + + /// + /// Separate colour planes: the macroblock data of plane , in the decoder and in every picture a + /// slice can refer to (direct prediction reads the motion of the co-located plane). + /// + private void SelectColourPlane(int k) + { + colourPlane = k; + UsePlaneState(Math.Min(k, planeStates.Length - 1)); + cur?.SelectPlane(k); + foreach (var p in dpb) + { + p.SelectPlane(k); + } + } + + /// The format of a sequence that becomes active: chroma geometry, bit depths, lossless coding. + private void ConfigureFormat(Sps s) + { + chromaArrayType = s.ChromaArrayType; + separatePlanes = s.SeparateColourPlane; + mbWidthC = chromaArrayType == 0 ? 0 : 16 / s.SubWidthC; + mbHeightC = chromaArrayType == 0 ? 0 : 16 / s.SubHeightC; + numC8x8 = chromaArrayType is 1 or 2 ? 4 / (s.SubWidthC * s.SubHeightC) : 0; + bitDepthY = s.BitDepthLuma; + + // The colour planes coded separately are monochrome pictures: all three have the luma bit depth. + bitDepthC = separatePlanes ? s.BitDepthLuma : s.BitDepthChroma; + maxY = (1 << bitDepthY) - 1; + maxC = (1 << bitDepthC) - 1; + qpBdOffsetY = s.QpBdOffsetY; + qpBdOffsetC = 6 * (bitDepthC - 8); + transformBypass = s.TransformBypass; + wide = bitDepthY > 8 || (s.ChromaFormatIdc != 0 && bitDepthC > 8); + colourPlane = 0; } private bool IsIntra(int m) => mbKind[m] is MbKind.I4x4 or MbKind.I8x8 or MbKind.I16x16 or MbKind.IPcm or MbKind.SI; @@ -158,6 +283,13 @@ public sealed partial class H264Decoder private bool IsSkip(int m) => mbKind[m] is MbKind.PSkip or MbKind.BSkip; + /// QPC of a chroma component (0 Cb, 1 Cr) for (§8.5.8, Table 8-15): from −QpBdOffsetC up. + private int ChromaQpFor(int qpY, int comp) + { + var qpi = Math.Clamp(qpY + (comp == 0 ? pps.ChromaQpIndexOffset : pps.SecondChromaQpIndexOffset), -qpBdOffsetC, 51); + return qpi < 0 ? qpi : H264Tables.ChromaQp[qpi]; + } + private void DecodeSliceData(RbspReader reader, NalUnit nal, SliceHeader header, Sps s, Pps p) { _ = nal; @@ -173,12 +305,21 @@ public sealed partial class H264Decoder sliceFilters.Add((header.DisableDeblocking, header.AlphaOffset, header.BetaOffset)); sliceSwitching.Add(header.IsSwitching); anySwitching |= header.IsSwitching; - if (header.IsSwitching && p.Transform8x8Mode) + if (header.IsSwitching && (p.Transform8x8Mode || wide || chromaArrayType != 1)) { - throw new H264Exception("Slice SP o SI con la trasformata 8×8: combinazione non ammessa."); + // SP and SI slices exist only in the Extended profile: 4:2:0, 8 bits, no 8×8 transform. + throw new H264Exception("Slice SP o SI fuori dal profilo Extended (trasformata 8×8, 4:2:2/4:4:4 o più di 8 bit): combinazione non ammessa."); } + + if (cabacMode && chromaArrayType == 3) + { + // The residual of Cb and Cr of 4:4:4 uses the contexts 460–1023 (block categories 6–13), whose initial + // values (tables 9-24 to 9-33) are not transcribed yet; the separate colour planes use those of luma. + throw new H264Exception("CABAC in 4:4:4 senza piani separati non gestito: mancano i contesti 460–1023."); + } + qp = p.PicInitQp + header.QpDelta; - if (qp is < 0 or > 51) + if (qp < -qpBdOffsetY || qp > 51) { throw new H264Exception("QP della slice non valido."); } @@ -486,33 +627,34 @@ public sealed partial class H264Decoder } var width = cur!.Width; - var cwidth = width / 2; + var cwidth = cur.ChromaWidth; 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); + chromaO = (((pairY * 2 * mbHeightC) + parity) * cwidth) + (mbX * mbWidthC); chromaStride = 2 * cwidth; } else { lumaO = (mbY * 16 * width) + (mbX * 16); lumaStride = width; - chromaO = (mbY * 8 * cwidth) + (mbX * 8); + chromaO = (mbY * mbHeightC * cwidth) + (mbX * mbWidthC); 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. + /// The macroblock covering the luma ( 16) or chroma (MbHeightC) 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. The chroma blocks are 8 wide unless they are of 4:4:4, which uses + /// the luma locations. /// private int Locate(int xN, int yN, int maxH, out int yM) { yM = yN; - var maxW = maxH; + var maxW = maxH == 16 ? 16 : 8; if (yN >= maxH || (xN >= maxW && yN >= 0)) { return -1; @@ -628,11 +770,12 @@ public sealed partial class H264Decoder { PlaceMacroblock(addr); Array.Clear(blkDone); - Array.Clear(nz, mb * 24, 24); + Array.Clear(nz, mb * NzPerMb, NzPerMb); cbfDc[mb] = 0; mbCbp[mb] = 0; mbT8[mb] = false; chromaModes[mb] = 0; + bypass = false; intraModes.AsSpan(mb * 16, 16).Fill(2); var picture = cur!; for (var list = 0; list < 2; list++) @@ -694,8 +837,7 @@ public sealed partial class H264Decoder private void DecodeSkip() { mbKind[mb] = sh.IsB ? MbKind.BSkip : MbKind.PSkip; - mbQp[mb] = (byte)qp; - SetChromaQp(); + StoreQp(); lastQpDelta = 0; if (sh.IsB) { @@ -716,10 +858,16 @@ public sealed partial class H264Decoder } } - private void SetChromaQp() + /// + /// The QP of the macroblock for the deblocking filter, from the current QPY: 0 for a lossless macroblock as for + /// I_PCM (§8.7.2.2), and QPC of both chroma components from that value. + /// + private void StoreQp() { - mbQpC[mb * 2] = H264Tables.ChromaQp[Math.Clamp(mbQp[mb] + pps.ChromaQpIndexOffset, 0, 51)]; - mbQpC[(mb * 2) + 1] = H264Tables.ChromaQp[Math.Clamp(mbQp[mb] + pps.SecondChromaQpIndexOffset, 0, 51)]; + var filterQp = transformBypass && qp + qpBdOffsetY == 0 ? 0 : qp; + mbQp[mb] = (sbyte)filterQp; + mbQpC[mb * 2] = (sbyte)ChromaQpFor(filterQp, 0); + mbQpC[(mb * 2) + 1] = (sbyte)ChromaQpFor(filterQp, 1); } private void DecodeIntra(int type) @@ -747,10 +895,13 @@ public sealed partial class H264Decoder cbp = ((((type - 1) / 4) % 3) << 4) | (type >= 13 ? 15 : 0); } - chromaModes[mb] = (byte)ReadChromaPredMode(); - if (chromaModes[mb] > 3) + if (chromaArrayType is 1 or 2) { - throw new H264Exception("Modo di predizione della crominanza non valido."); + chromaModes[mb] = (byte)ReadChromaPredMode(); + if (chromaModes[mb] > 3) + { + throw new H264Exception("Modo di predizione della crominanza non valido."); + } } if (type == 0) @@ -771,9 +922,15 @@ public sealed partial class H264Decoder lastQpDelta = 0; } - mbQp[mb] = (byte)qp; - SetChromaQp(); - ReconstructIntra(predMode16); + StoreQp(); + if (wide) + { + ReconstructIntra(predMode16); + } + else + { + ReconstructIntra(predMode16); + } } /// The SI macroblock (mb_type 0 of an SI slice): Intra_4x4 prediction, levels in QS (§7.4.5, §8.6.2). @@ -803,20 +960,21 @@ public sealed partial class H264Decoder lastQpDelta = 0; } - mbQp[mb] = (byte)qp; - SetChromaQp(); - ReconstructIntra(0); + StoreQp(); + ReconstructIntra(0); } + /// mb_qp_delta (§7.4.5): QPY wraps within −QpBdOffsetY to 51. private void ApplyQpDelta(int delta) { - if (delta is < -26 or > 25) + if (delta < -(26 + (qpBdOffsetY / 2)) || delta > 25 + (qpBdOffsetY / 2)) { throw new H264Exception("mb_qp_delta non valido."); } lastQpDelta = delta; - qp = (qp + delta + 52) % 52; + qp = ((qp + delta + 52 + (2 * qpBdOffsetY)) % (52 + qpBdOffsetY)) - qpBdOffsetY; + bypass = transformBypass && qp + qpBdOffsetY == 0; } private void ReadIntraModes(bool t8) @@ -893,11 +1051,39 @@ public sealed partial class H264Decoder private void DecodePcm() { mbKind[mb] = MbKind.IPcm; + if (wide) + { + DecodePcm(); + } + else + { + DecodePcm(); + } - // The samples are category 3: in partition B of a partitioned slice (grey when it is missing). + nz.AsSpan(mb * NzPerMb, NzPerMb).Fill(16); + mbCbp[mb] = 0x2F; + mbQp[mb] = 0; // the deblocking filter uses qP = 0 for I_PCM; the running QP is unchanged + mbQpC[mb * 2] = (sbyte)ChromaQpFor(0, 0); + mbQpC[(mb * 2) + 1] = (sbyte)ChromaQpFor(0, 1); + lastQpDelta = 0; + intraModes.AsSpan(mb * 16, 16).Fill(2); + if (cabacMode) + { + cabac.Start(rd); + } + } + + /// The samples of an I_PCM macroblock (§7.3.5): BitDepth bits each, luma then (if any) Cb and Cr. + private void DecodePcm() + where T : unmanaged + { + // The samples are category 3: in partition B of a partitioned slice (the middle value when it is missing). var main = rd; var source = ResidualReader(intra: true); var picture = cur!; + var luma = Plane(picture.Plane(colourPlane)); + var cb = Plane(picture.Cb); + var cr = Plane(picture.Cr); if (source is not null) { rd = source; @@ -913,55 +1099,49 @@ public sealed partial class H264Decoder { for (var x = 0; x < 16; x++) { - picture.Y[lumaO + (y * lumaStride) + x] = (byte)rd.Read(8); + luma[lumaO + (y * lumaStride) + x] = Make((int)rd.Read(bitDepthY)); } } - for (var c = 0; c < 2; c++) + if (chromaArrayType != 0) { - var plane = c == 0 ? picture.Cb : picture.Cr; - for (var y = 0; y < 8; y++) + for (var c = 0; c < 2; c++) { - for (var x = 0; x < 8; x++) + var plane = c == 0 ? cb : cr; + for (var y = 0; y < mbHeightC; y++) { - plane[chromaO + (y * chromaStride) + x] = (byte)rd.Read(8); + for (var x = 0; x < mbWidthC; x++) + { + plane[chromaO + (y * chromaStride) + x] = Make((int)rd.Read(bitDepthC)); + } } } } + if (rd.BitsLeft < 0) + { + throw new H264Exception("Campioni I_PCM troncati."); + } + ResidualRead?.Invoke(start, rd.Position, true, true); rd = main; - } - else - { - for (var y = 0; y < 16; y++) - { - picture.Y.AsSpan(lumaO + (y * lumaStride), 16).Fill(128); - } - - for (var y = 0; y < 8; y++) - { - picture.Cb.AsSpan(chromaO + (y * chromaStride), 8).Fill(128); - picture.Cr.AsSpan(chromaO + (y * chromaStride), 8).Fill(128); - } + return; } - nz.AsSpan(mb * 24, 24).Fill(16); - mbCbp[mb] = 0x2F; - mbQp[mb] = 0; // the deblocking filter uses qP = 0 for I_PCM; the running QP is unchanged - mbQpC[mb * 2] = H264Tables.ChromaQp[Math.Clamp(pps.ChromaQpIndexOffset, 0, 51)]; - mbQpC[(mb * 2) + 1] = H264Tables.ChromaQp[Math.Clamp(pps.SecondChromaQpIndexOffset, 0, 51)]; - lastQpDelta = 0; - intraModes.AsSpan(mb * 16, 16).Fill(2); - if (cabacMode) + for (var y = 0; y < 16; y++) { - cabac.Start(rd); + luma.Slice(lumaO + (y * lumaStride), 16).Fill(Make(1 << (bitDepthY - 1))); + } + + for (var y = 0; y < mbHeightC; y++) + { + cb.Slice(chromaO + (y * chromaStride), mbWidthC).Fill(Make(1 << (bitDepthC - 1))); + cr.Slice(chromaO + (y * chromaStride), mbWidthC).Fill(Make(1 << (bitDepthC - 1))); } } private void DecodeInter(int type) { - var picture = cur!; var isB = sh.IsB; var direct16 = isB && type == 0; mbKind[mb] = direct16 ? MbKind.BDirect : isB ? MbKind.BInter : MbKind.PInter; @@ -1112,8 +1292,7 @@ public sealed partial class H264Decoder lastQpDelta = 0; } - mbQp[mb] = (byte)qp; - SetChromaQp(); + StoreQp(); // Motion vectors, partition by partition in decoding order, then the prediction. if (direct16) @@ -1194,9 +1373,13 @@ public sealed partial class H264Decoder { ReconstructSwitchingInter(); } + else if (wide) + { + AddInterResidual(); + } else { - AddInterResidual(); + AddInterResidual(); } } @@ -1313,11 +1496,14 @@ public sealed partial class H264Decoder private void ClearResidual() { - Array.Clear(lumaCoef); + Array.Clear(lumaCoef, 0, 256 * LumaLikePlanes); Array.Clear(lumaHas); - Array.Clear(chromaCoef); - Array.Clear(chromaHas); - Array.Clear(chromaDcLevels); + if (numC8x8 != 0) + { + Array.Clear(chromaCoef); + Array.Clear(chromaHas); + Array.Clear(chromaDcLevels); + } } /// @@ -1340,21 +1526,60 @@ public sealed partial class H264Decoder rd = main; } - /// residual() of §7.3.5.3, with the scaling of §8.5 applied as the levels are read. + /// + /// residual() of §7.3.5.3, with the scaling of §8.5 applied as the levels are read: luma, then the chroma of 4:2:0 and + /// 4:2:2, or the Cb and Cr planes of 4:4:4 coded like luma. + /// private void ParseResidual(bool intra16, int cbp, bool intra) + { + ParseLumaLike(0, intra16, cbp, intra); + if (numC8x8 != 0) + { + ParseChroma(cbp >> 4, intra); + } + else if (chromaArrayType == 3) + { + ParseLumaLike(1, intra16, cbp, intra); + ParseLumaLike(2, intra16, cbp, intra); + } + } + + /// + /// residual_luma() of one plane (0 Y; 1 Cb and 2 Cr of 4:4:4, with QP′C and their own scaling lists): the + /// Intra_16x16 DC, then each coded 8×8 block, as 8×8 or four 4×4 blocks. + /// + private void ParseLumaLike(int plane, bool intra16, int cbp, bool intra) { var t8 = mbT8[mb]; - var listY = intra ? 0 : 3; - var qpDiv = qp / 6; - var qpMod = qp % 6; - var scale4 = ls4[listY]; + int qP; + int[] scale4, scale8; + if (plane == 0) + { + // A colour plane coded separately has QP′Y and the scaling lists of its component (iYCbCr, §8.5.9). + qP = qp + qpBdOffsetY; + scale4 = ls4[(intra ? 0 : 3) + colourPlane]; + scale8 = ls8[(colourPlane * 2) + (intra ? 0 : 1)]; + } + else + { + qP = ChromaQpFor(qp, plane - 1) + qpBdOffsetC; + scale4 = ls4[(intra ? 1 : 4) + plane - 1]; + scale8 = ls8[(plane * 2) + (intra ? 0 : 1)]; + } + + var qpDiv = qP / 6; + var qpMod = qP % 6; + var coef = lumaCoef.AsSpan(plane * 256, 256); + var has = lumaHas.AsSpan(plane * 16, 16); + var nzBase = (mb * NzPerMb) + (plane * 16); + var raw = rawLevels || bypass; // 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); + var count = ReadBlock(0, 0, plane, levels, 16); Span c = stackalloc int[16]; c.Clear(); for (var k = 0; k < 16; k++) @@ -1364,15 +1589,20 @@ public sealed partial class H264Decoder if (count > 0) { - Transform.Hadamard4x4(c); + // Lossless: the DC levels are the DC residuals of the blocks (§8.5.10); else the Hadamard transform. + if (!bypass) + { + Transform.Hadamard4x4(c); + } + var ls = scale4[qpMod * 16]; for (var i = 0; i < 16; i++) { - var v = qp >= 36 ? (c[i] * ls) << (qpDiv - 6) : ((c[i] * ls) + (1 << (5 - qpDiv))) >> (6 - qpDiv); - lumaCoef[i * 16] = v; + var v = bypass ? c[i] : qP >= 36 ? (c[i] * ls) << (qpDiv - 6) : ((c[i] * ls) + (1 << (5 - qpDiv))) >> (6 - qpDiv); + coef[i * 16] = v; if (v != 0) { - lumaHas[i] = true; + has[i] = true; } } } @@ -1388,10 +1618,10 @@ public sealed partial class H264Decoder continue; } - ReadBlock(5, b8, 0, levels, 64); - DequantizeInto8x8(b8, levels, intra); + ReadBlock(5, b8, plane, levels, 64); + DequantizeInto8x8(coef, has, b8, levels, scale8, qP); var r0 = ((b8 >> 1) * 8) + ((b8 & 1) * 2); - nz[(mb * 24) + r0] = nz[(mb * 24) + r0 + 1] = nz[(mb * 24) + r0 + 4] = nz[(mb * 24) + r0 + 5] = 1; + nz[nzBase + r0] = nz[nzBase + r0 + 1] = nz[nzBase + r0 + 4] = nz[nzBase + r0 + 5] = 1; continue; } @@ -1411,23 +1641,23 @@ public sealed partial class H264Decoder if (intra16) { - var count = ReadBlock(1, raster, 0, levels, 15); - nz[(mb * 24) + raster] = (byte)count; + var count = ReadBlock(1, raster, plane, levels, 15); + nz[nzBase + raster] = (byte)count; for (var k = 0; k < 15; k++) { var level = levels[k]; if (level != 0) { var pos = scan4[k + 1]; - lumaCoef[(raster * 16) + pos] = Scale4(level, scale4[(qpMod * 16) + pos], qpDiv); - lumaHas[raster] = true; + coef[(raster * 16) + pos] = raw ? level : Scale4(level, scale4[(qpMod * 16) + pos], qpDiv); + has[raster] = true; } } } else { - var count = ReadBlock(2, raster, 0, levels, 16); - nz[(mb * 24) + raster] = (byte)count; + var count = ReadBlock(2, raster, plane, levels, 16); + nz[nzBase + raster] = (byte)count; if (t8) { for (var k = 0; k < 16; k++) @@ -1444,8 +1674,8 @@ public sealed partial class H264Decoder if (level != 0) { var pos = scan4[k]; - lumaCoef[(raster * 16) + pos] = rawLevels ? level : Scale4(level, scale4[(qpMod * 16) + pos], qpDiv); - lumaHas[raster] = true; + coef[(raster * 16) + pos] = raw ? level : Scale4(level, scale4[(qpMod * 16) + pos], qpDiv); + has[raster] = true; } } } @@ -1453,17 +1683,25 @@ public sealed partial class H264Decoder if (t8 && coded) { - DequantizeInto8x8(b8, levels4, intra); + DequantizeInto8x8(coef, has, b8, levels4, scale8, qP); } } + } - var chromaCbp = cbp >> 4; + /// + /// The chroma residual of 4:2:0 and 4:2:2 (§7.3.5.3): the DC of each component (4 or 8 coefficients, through the 2×2 + /// or 2×4 transform), then the AC of each 4×4 block (blocks in raster order, two per row). + /// + private void ParseChroma(int chromaCbp, bool intra) + { + var blocks = 4 * numC8x8; + var scan4 = mbField ? H264Tables.FieldScan4x4 : H264Tables.ZigZag4x4; if (chromaCbp != 0) { - Span dc = stackalloc int[4]; + Span dc = stackalloc int[8]; for (var c = 0; c < 2; c++) { - var count = ReadBlock(3, 0, c, levels, 4); + var count = ReadBlock(3, 0, c, levels, blocks); if (count == 0) { continue; @@ -1471,24 +1709,54 @@ public sealed partial class H264Decoder if (rawLevels) { - levels.AsSpan(0, 4).CopyTo(chromaDcLevels.AsSpan(c * 4, 4)); + levels.AsSpan(0, 4).CopyTo(chromaDcLevels.AsSpan(c * 8, 4)); continue; } - var qpc = H264Tables.ChromaQp[Math.Clamp(qp + (c == 0 ? pps.ChromaQpIndexOffset : pps.SecondChromaQpIndexOffset), 0, 51)]; - var ls = ls4[(intra ? 1 : 4) + c][(qpc % 6) * 16]; - int c0 = levels[0], c1 = levels[1], c2 = levels[2], c3 = levels[3]; - dc[0] = c0 + c1 + c2 + c3; - dc[1] = c0 - c1 + c2 - c3; - dc[2] = c0 + c1 - c2 - c3; - dc[3] = c0 - c1 - c2 + c3; - for (var b = 0; b < 4; b++) + var qpc = ChromaQpFor(qp, c) + qpBdOffsetC; + var ls4c = ls4[(intra ? 1 : 4) + c]; + if (blocks == 4) { - var v = ((dc[b] * ls) << (qpc / 6)) >> 5; - chromaCoef[((c * 4) + b) * 16] = v; - if (v != 0) + int c0 = levels[0], c1 = levels[1], c2 = levels[2], c3 = levels[3]; + if (bypass) { - chromaHas[(c * 4) + b] = true; + (dc[0], dc[1], dc[2], dc[3]) = (c0, c1, c2, c3); + } + else + { + var ls = ls4c[(qpc % 6) * 16]; + dc[0] = (((c0 + c1 + c2 + c3) * ls) << (qpc / 6)) >> 5; + dc[1] = (((c0 - c1 + c2 - c3) * ls) << (qpc / 6)) >> 5; + dc[2] = (((c0 + c1 - c2 - c3) * ls) << (qpc / 6)) >> 5; + dc[3] = (((c0 - c1 - c2 + c3) * ls) << (qpc / 6)) >> 5; + } + } + else + { + for (var k = 0; k < 8; k++) + { + dc[ChromaDc422Scan[k]] = levels[k]; + } + + if (!bypass) + { + // §8.5.11.2: the DC of 4:2:2 is scaled with qP,DC = QP′C + 3. + Transform.ChromaDc422(dc); + var qpDc = qpc + 3; + var ls = ls4c[(qpDc % 6) * 16]; + for (var b = 0; b < 8; b++) + { + dc[b] = qpDc >= 36 ? (dc[b] * ls) << ((qpDc / 6) - 6) : ((dc[b] * ls) + (1 << (5 - (qpDc / 6)))) >> (6 - (qpDc / 6)); + } + } + } + + for (var b = 0; b < blocks; b++) + { + chromaCoef[((c * 8) + b) * 16] = dc[b]; + if (dc[b] != 0) + { + chromaHas[(c * 8) + b] = true; } } } @@ -1496,22 +1764,23 @@ public sealed partial class H264Decoder if ((chromaCbp & 2) != 0) { + var raw = rawLevels || bypass; for (var c = 0; c < 2; c++) { - var qpc = H264Tables.ChromaQp[Math.Clamp(qp + (c == 0 ? pps.ChromaQpIndexOffset : pps.SecondChromaQpIndexOffset), 0, 51)]; + var qpc = ChromaQpFor(qp, c) + qpBdOffsetC; var scale = ls4[(intra ? 1 : 4) + c]; - for (var b = 0; b < 4; b++) + for (var b = 0; b < blocks; b++) { var count = ReadBlock(4, b, c, levels, 15); - nz[(mb * 24) + 16 + (c * 4) + b] = (byte)count; + nz[(mb * NzPerMb) + 16 + (c * 16) + b] = (byte)count; for (var k = 0; k < 15; k++) { var level = levels[k]; if (level != 0) { var pos = scan4[k + 1]; - chromaCoef[(((c * 4) + b) * 16) + pos] = rawLevels ? level : Scale4(level, scale[((qpc % 6) * 16) + pos], qpc / 6); - chromaHas[(c * 4) + b] = true; + chromaCoef[(((c * 8) + b) * 16) + pos] = raw ? level : Scale4(level, scale[((qpc % 6) * 16) + pos], qpc / 6); + chromaHas[(c * 8) + b] = true; } } } @@ -1522,11 +1791,10 @@ public sealed partial class H264Decoder private static int Scale4(int level, int ls, int qpDiv) => qpDiv >= 4 ? (level * ls) << (qpDiv - 4) : ((level * ls) + (1 << (3 - qpDiv))) >> (4 - qpDiv); - private void DequantizeInto8x8(int b8, int[] source, bool intra) + private void DequantizeInto8x8(Span coef, Span has, int b8, int[] source, int[] scale, int qP) { - var scale = ls8[intra ? 0 : 1]; - var qpDiv = qp / 6; - var qpMod = qp % 6; + 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++) @@ -1538,22 +1806,31 @@ public sealed partial class H264Decoder } 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); + if (bypass) + { + coef[(b8 * 64) + pos] = level; + } + else + { + var ls = scale[(qpMod * 64) + pos]; + coef[(b8 * 64) + pos] = qP >= 36 ? (level * ls) << (qpDiv - 6) : ((level * ls) + (1 << (5 - qpDiv))) >> (6 - qpDiv); + } + any = true; } if (any) { - lumaHas[b8] = true; + has[b8] = true; } } 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). + /// The rows of the left neighbour usable for intra prediction, one bit per row (16 luma rows, or MbHeightC chroma + /// ones): 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) { @@ -1580,7 +1857,6 @@ public sealed partial class H264Decoder if (n >= 0 && IntraUsable(n)) { mask |= 1 << r; - } } @@ -1589,10 +1865,14 @@ public sealed partial class H264Decoder private static bool Rows(int mask, int first, int count) => ((mask >> first) & ((1 << count) - 1)) == (1 << count) - 1; - private void ReconstructIntra(int predMode16) + /// + /// The intra macroblock: the luma-like planes (Y, or the colour plane; Cb and Cr too in 4:4:4, with the luma modes) + /// predicted and reconstructed block by block, then the chroma of 4:2:0 and 4:2:2. + /// + private void ReconstructIntra(int predMode16) + where T : unmanaged { var picture = cur!; - var stride = lumaStride; var constrained = pps.ConstrainedIntraPred; var nB = Locate(0, -1, 16, out _); var nC = Locate(16, -1, 16, out _); @@ -1600,13 +1880,55 @@ public sealed partial class H264Decoder var b = nB >= 0 && (!constrained || IntraUsable(nB)); var c = nC >= 0 && (!constrained || IntraUsable(nC)); var d = nD >= 0 && (!constrained || IntraUsable(nD)); - var si = mbKind[mb] == MbKind.SI; var left = LeftRows(16, constrained); - Span block = stackalloc int[64]; + if (mbKind[mb] == MbKind.SI) + { + ReconstructSi(picture, left, b, c, d); + return; + } + + IntraLumaLike(Plane(picture.Plane(colourPlane)), 0, predMode16, left, b, c, d, bitDepthY, maxY); + if (chromaArrayType == 3) + { + IntraLumaLike(Plane(picture.Cb), 1, predMode16, left, b, c, d, bitDepthC, maxC); + IntraLumaLike(Plane(picture.Cr), 2, predMode16, left, b, c, d, bitDepthC, maxC); + return; + } + + if (numC8x8 == 0) + { + return; + } + + var chromaLeft = LeftRows(mbHeightC, constrained); + var groups = 0; + for (var g = 0; g < mbHeightC / 4; g++) + { + groups |= Rows(chromaLeft, g * 4, 4) ? 1 << g : 0; + } + + var mode = chromaModes[mb]; + IntraPrediction.PredictChroma(Plane(picture.Cb), chromaO, chromaStride, mode, mbHeightC, groups, b, d, bitDepthC); + IntraPrediction.PredictChroma(Plane(picture.Cr), chromaO, chromaStride, mode, mbHeightC, groups, b, d, bitDepthC); + + // Lossless: under horizontal (1) and vertical (2) chroma prediction the residual is accumulated (§8.5.15). + AddChromaResidual(mode == 1 ? 1 : mode == 2 ? 2 : 0); + } + + /// + /// One luma-like plane of an intra macroblock: the plane at the luma location of the macroblock, with the + /// coefficients of (0 Y or colour plane, 1 Cb, 2 Cr of 4:4:4). + /// + private void IntraLumaLike(Span samples, int plane, int predMode16, int left, bool b, bool c, bool d, int bitDepth, int max) + where T : unmanaged + { + var stride = lumaStride; + var coef = lumaCoef.AsSpan(plane * 256, 256); + var has = lumaHas.AsSpan(plane * 16, 16); + Span block = stackalloc int[256]; switch (mbKind[mb]) { case MbKind.I4x4: - case MbKind.SI: for (var i = 0; i < 16; i++) { var raster = H264Tables.BlockToRaster[i]; @@ -1621,19 +1943,24 @@ public sealed partial class H264Decoder } else { - topRight = bx < 3 && blkDone[((by - 1) * 4) + bx + 1]; + // The block above right is available when it comes earlier in decoding order. + topRight = bx < 3 && H264Tables.RasterToBlock[((by - 1) * 4) + bx + 1] < i; } var o = LumaOffset(bx * 4, by * 4); - IntraPrediction.Predict4x4(picture.Y, o, stride, intraModes[(mb * 16) + raster], hasLeft, top, topRight, topLeft); - if (si) + var mode = intraModes[(mb * 16) + raster]; + IntraPrediction.Predict4x4(samples, o, stride, mode, hasLeft, top, topRight, topLeft, bitDepth); + if (has[raster]) { - SwitchingTransform.Luma4x4(picture.Y, o, stride, lumaCoef.AsSpan(raster * 16, 16), sh.Qs, sh.Qs, levelInQs: true); - } - else if (lumaHas[raster]) - { - lumaCoef.AsSpan(raster * 16, 16).CopyTo(block); - Transform.Add4x4(block[..16], picture.Y, o, stride); + coef.Slice(raster * 16, 16).CopyTo(block); + if (bypass) + { + Transform.AddBypass(block[..16], 4, 4, mode == 0 ? 2 : mode == 1 ? 1 : 0, samples, o, stride, max); + } + else + { + Transform.Add4x4(block[..16], samples, o, stride, max); + } } blkDone[raster] = true; @@ -1649,43 +1976,94 @@ public sealed partial class H264Decoder 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)], hasLeft, top, topRight, topLeft); - if (lumaHas[i]) + var mode = intraModes[(mb * 16) + (by * 8) + (bx * 2)]; + IntraPrediction.Predict8x8(samples, o, stride, mode, hasLeft, top, topRight, topLeft, bitDepth); + if (has[i]) { - lumaCoef.AsSpan(i * 64, 64).CopyTo(block); - Transform.Add8x8(block, picture.Y, o, stride); + coef.Slice(i * 64, 64).CopyTo(block); + if (bypass) + { + Transform.AddBypass(block[..64], 8, 8, mode == 0 ? 2 : mode == 1 ? 1 : 0, samples, o, stride, max); + } + else + { + Transform.Add8x8(block[..64], samples, o, stride, max); + } } } break; default: { - IntraPrediction.Predict16x16(picture.Y, LumaOffset(0, 0), stride, predMode16, Rows(left, 0, 16), b, d); + IntraPrediction.Predict16x16(samples, LumaOffset(0, 0), stride, predMode16, Rows(left, 0, 16), b, d, bitDepth); + if (bypass) + { + // The residual of the whole macroblock, accumulated across the blocks under horizontal (1) or + // vertical (0) prediction (§8.5.15 with nW = nH = 16). + if (!has.Contains(true)) + { + break; + } + + GatherBlocks(coef, block, 16, 16); + Transform.AddBypass(block, 16, 16, predMode16 == 0 ? 2 : predMode16 == 1 ? 1 : 0, samples, LumaOffset(0, 0), stride, max); + break; + } + for (var raster = 0; raster < 16; raster++) { - if (lumaHas[raster]) + if (has[raster]) { - lumaCoef.AsSpan(raster * 16, 16).CopyTo(block); - Transform.Add4x4(block[..16], picture.Y, LumaOffset((raster & 3) * 4, (raster >> 2) * 4), stride); + coef.Slice(raster * 16, 16).CopyTo(block); + Transform.Add4x4(block[..16], samples, LumaOffset((raster & 3) * 4, (raster >> 2) * 4), stride, max); } } break; } } + } - 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); - if (si) + /// + /// The 4×4 blocks of (16 coefficients each, raster within the block; blocks in raster order, + /// / 4 per row) as one × raster. + /// + private static void GatherBlocks(ReadOnlySpan coef, Span output, int w, int h) + { + var perRow = w / 4; + for (var y = 0; y < h; y++) { - SwitchingChroma(levelInQs: true); + for (var x = 0; x < w; x++) + { + var blk = ((y >> 2) * perRow) + (x >> 2); + output[(y * w) + x] = coef[(blk * 16) + ((y & 3) * 4) + (x & 3)]; + } } - else + } + + /// The SI macroblock: Intra_4x4 prediction, each block rebuilt in QS (§8.6.2); 4:2:0 and 8 bits only. + private void ReconstructSi(Picture picture, int left, bool b, bool c, bool d) + { + var y = Plane(picture.Y); + for (var i = 0; i < 16; i++) { - AddChromaResidual(); + var raster = H264Tables.BlockToRaster[i]; + int bx = raster & 3, by = raster >> 2; + var hasLeft = bx > 0 || Rows(left, by * 4, 4); + var top = by > 0 || b; + var topLeft = (bx > 0 && by > 0) || (bx == 0 && by > 0 ? Rows(left, (by * 4) - 1, 1) : bx > 0 && by == 0 ? b : d); + var topRight = by == 0 ? (bx < 3 ? b : c) : bx < 3 && H264Tables.RasterToBlock[((by - 1) * 4) + bx + 1] < i; + var o = LumaOffset(bx * 4, by * 4); + IntraPrediction.Predict4x4(y, o, lumaStride, intraModes[(mb * 16) + raster], hasLeft, top, topRight, topLeft, 8); + SwitchingTransform.Luma4x4(picture.Y, o, lumaStride, lumaCoef.AsSpan(raster * 16, 16), sh.Qs, sh.Qs, levelInQs: true); + blkDone[raster] = true; } + + var chromaLeft = LeftRows(8, pps.ConstrainedIntraPred); + var groups = (Rows(chromaLeft, 0, 4) ? 1 : 0) | (Rows(chromaLeft, 4, 4) ? 2 : 0); + IntraPrediction.PredictChroma(Plane(picture.Cb), chromaO, chromaStride, chromaModes[mb], 8, groups, b, d, 8); + IntraPrediction.PredictChroma(Plane(picture.Cr), chromaO, chromaStride, chromaModes[mb], 8, groups, b, d, 8); + SwitchingChroma(levelInQs: true); } /// A P macroblock of an SP slice, its prediction in place: every block is rebuilt in QS (§8.6.1). @@ -1708,58 +2086,103 @@ public sealed partial class H264Decoder { var offset = c == 0 ? pps.ChromaQpIndexOffset : pps.SecondChromaQpIndexOffset; var qsc = H264Tables.ChromaQp[Math.Clamp(sh.Qs + offset, 0, 51)]; - SwitchingTransform.Chroma(c == 0 ? picture.Cb : picture.Cr, chromaO, chromaStride, chromaCoef.AsSpan(c * 64, 64), chromaDcLevels.AsSpan(c * 4, 4), mbQpC[(mb * 2) + c], qsc, levelInQs); + SwitchingTransform.Chroma(c == 0 ? picture.Cb : picture.Cr, chromaO, chromaStride, chromaCoef.AsSpan(c * 128, 64), chromaDcLevels.AsSpan(c * 8, 4), mbQpC[(mb * 2) + c], qsc, levelInQs); } } - private void AddInterResidual() + /// The residual of an inter macroblock, added to its prediction: every luma-like plane, then the chroma. + private void AddInterResidual() + where T : unmanaged { var picture = cur!; - var stride = lumaStride; Span block = stackalloc int[64]; - if (mbT8[mb]) + for (var plane = 0; plane < LumaLikePlanes; plane++) { - for (var i = 0; i < 4; i++) + var samples = Plane(plane == 0 ? picture.Plane(colourPlane) : picture.Plane(plane)); + var max = plane == 0 ? maxY : maxC; + var coef = lumaCoef.AsSpan(plane * 256, 256); + var has = lumaHas.AsSpan(plane * 16, 16); + if (mbT8[mb]) { - if (lumaHas[i]) + for (var i = 0; i < 4; i++) { - lumaCoef.AsSpan(i * 64, 64).CopyTo(block); - Transform.Add8x8(block, picture.Y, LumaOffset((i & 1) * 8, (i >> 1) * 8), stride); + if (has[i]) + { + coef.Slice(i * 64, 64).CopyTo(block); + var o = LumaOffset((i & 1) * 8, (i >> 1) * 8); + if (bypass) + { + Transform.AddBypass(block, 8, 8, 0, samples, o, lumaStride, max); + } + else + { + Transform.Add8x8(block, samples, o, lumaStride, max); + } + } } } - } - else - { - for (var raster = 0; raster < 16; raster++) + else { - if (lumaHas[raster]) + for (var raster = 0; raster < 16; raster++) { - lumaCoef.AsSpan(raster * 16, 16).CopyTo(block); - Transform.Add4x4(block[..16], picture.Y, LumaOffset((raster & 3) * 4, (raster >> 2) * 4), stride); + if (has[raster]) + { + coef.Slice(raster * 16, 16).CopyTo(block); + var o = LumaOffset((raster & 3) * 4, (raster >> 2) * 4); + if (bypass) + { + Transform.AddBypass(block[..16], 4, 4, 0, samples, o, lumaStride, max); + } + else + { + Transform.Add4x4(block[..16], samples, o, lumaStride, max); + } + } } } } - AddChromaResidual(); + if (numC8x8 != 0) + { + AddChromaResidual(0); + } } - private void AddChromaResidual() + /// + /// The chroma residual of 4:2:0 and 4:2:2, block by block; in a lossless macroblock the whole MbWidthC × MbHeightC + /// residual of each component, accumulated as says (1 horizontal, 2 vertical, §8.5.15). + /// + private void AddChromaResidual(int dpcm) + where T : unmanaged { var picture = cur!; - Span block = stackalloc int[16]; + var blocks = 4 * numC8x8; + Span block = stackalloc int[128]; for (var c = 0; c < 2; c++) { - var plane = c == 0 ? picture.Cb : picture.Cr; - for (var b = 0; b < 4; b++) + var plane = Plane(c == 0 ? picture.Cb : picture.Cr); + if (bypass) { - if (!chromaHas[(c * 4) + b]) + if (!chromaHas.AsSpan(c * 8, blocks).Contains(true)) { continue; } - chromaCoef.AsSpan(((c * 4) + b) * 16, 16).CopyTo(block); + GatherBlocks(chromaCoef.AsSpan(c * 128, blocks * 16), block, 8, mbHeightC); + Transform.AddBypass(block[..(8 * mbHeightC)], 8, mbHeightC, dpcm, plane, chromaO, chromaStride, maxC); + continue; + } + + for (var b = 0; b < blocks; b++) + { + if (!chromaHas[(c * 8) + b]) + { + continue; + } + + chromaCoef.AsSpan(((c * 8) + b) * 16, 16).CopyTo(block); var o = chromaO + ((b >> 1) * 4 * chromaStride) + ((b & 1) * 4); - Transform.Add4x4(block, plane, o, chromaStride); + Transform.Add4x4(block[..16], plane, o, chromaStride, maxC); } } } diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.cs b/src/Febe.Core/Codecs/H264/H264Decoder.cs index 3094ce4..f1c72cc 100644 --- a/src/Febe.Core/Codecs/H264/H264Decoder.cs +++ b/src/Febe.Core/Codecs/H264/H264Decoder.cs @@ -14,8 +14,10 @@ public enum H264AccessPoint } /// -/// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Extended, Main and High -/// profiles in 4:2:0 with 8-bit samples — CAVLC and CABAC, I, P and B slices, 8×8 transform and scaling matrices, spatial +/// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Extended, Main and the High +/// profiles — 4:2:0, 4:2:2, 4:4:4 (also with the colour planes coded separately) and monochrome, 8 to 14 bits per sample, +/// lossless macroblocks (qpprime_y_zero_transform_bypass_flag) — CAVLC and CABAC, I, P and B slices, 8×8 transform and +/// scaling matrices, spatial /// and temporal direct prediction, list modification, memory management operations and long-term references, /// deblocking — for progressive frames and for interlaced video: field pictures, frames and fields mixed picture by /// picture (PAFF), frames of frame and field macroblock pairs (MBAFF). Frames come out whole: the two fields of a pair are @@ -23,8 +25,9 @@ public enum H264AccessPoint /// SI slices (switching pictures), slice data partitioning (NAL units 2–4); redundant coded pictures are skipped, the /// primary one is decoded. Written from the standard but not yet checked against a conformance stream: explicit and /// implicit weighted prediction, gaps in frame_num, I_PCM, SI macroblocks and sp_for_switch_flag, data partitioning -/// (checked only on conformance streams split into partitions). Not handled (an ): -/// 4:2:2/4:4:4 and depths above 8 bits. +/// (checked only on conformance streams split into partitions), 4:4:4, separate colour planes, lossless coding and bit +/// depths above 10. Not handled (an ): CABAC in 4:4:4 with the colour planes coded together +/// (its contexts 460–1023 are not transcribed yet), SP and SI slices outside 4:2:0 at 8 bits. /// public sealed partial class H264Decoder { @@ -304,18 +307,7 @@ public sealed partial class H264Decoder private SliceHeader ParseSliceHeader(RbspReader reader, NalUnit nal, out Sps sps, out Pps pps) { - var header = SliceHeader.Parse(reader, nal, sequences, pictures, out sps, out pps); - if (sps.ChromaFormatIdc != 1 || sps.BitDepthLuma != 8 || sps.BitDepthChroma != 8) - { - throw new H264Exception("Solo video 4:2:0 a 8 bit."); - } - - if (sps.TransformBypass) - { - throw new H264Exception("La codifica senza perdita non è gestita."); - } - - return header; + return SliceHeader.Parse(reader, nal, sequences, pictures, out sps, out pps); } /// A slice whose header is read: the picture it belongs to, then its macroblocks. @@ -332,6 +324,11 @@ public sealed partial class H264Decoder return; } + if (separatePlanes) + { + SelectColourPlane(header.ColourPlaneId); + } + if (!header.IsIntra && !HasReference()) { // A P or B slice without any picture to predict from: decoding started away from a random access point @@ -368,6 +365,9 @@ public sealed partial class H264Decoder return false; } + // Colour planes coded separately: the macroblocks of the plane of the slice. + var slices = separatePlanes ? planeStates[h.ColourPlaneId].Slice : mbSlice; + var w = sps.WidthInMbs; int index; if (h.FieldPic) @@ -383,7 +383,7 @@ public sealed partial class H264Decoder index = h.FirstMb; } - return (uint)index < (uint)mbSlice.Length && mbSlice[index] >= 0; + return (uint)index < (uint)slices.Length && slices[index] >= 0; } /// Whether a picture other than the one being decoded can be predicted from. @@ -411,7 +411,7 @@ public sealed partial class H264Decoder { if (activeSps is null || !ReferenceEquals(activeSps, sps)) { - if (activeSps is null || activeSps.WidthInMbs != sps.WidthInMbs || activeSps.HeightInMbs != sps.HeightInMbs) + if (activeSps is null || !SameLayout(activeSps, sps)) { if (openField is { } waiting && activeSps is not null) { @@ -421,10 +421,11 @@ public sealed partial class H264Decoder dpb.Clear(); pool.Clear(); - AllocateMacroblockState(sps.WidthInMbs, sps.HeightInMbs); + AllocateMacroblockState(sps.WidthInMbs, sps.HeightInMbs, sps.SeparateColourPlane ? 3 : 1); } activeSps = sps; + ConfigureFormat(sps); } var idr = nal.Type == 5; @@ -480,7 +481,10 @@ public sealed partial class H264Decoder sliceFilters.Clear(); sliceSwitching.Clear(); anySwitching = false; - Array.Fill(mbSlice, -1); + foreach (var state in planeStates) + { + Array.Fill(state.Slice, -1); + } // A picture nobody refers to and nobody wants: its header has set the state above, its slices are not decoded. picSkipped = nal.RefIdc == 0 && Wanted is { } wanted && !wanted(picture.DecodeIndex); @@ -495,18 +499,31 @@ public sealed partial class H264Decoder while (pool.Count > 0) { var p = pool.Pop(); - if (p.Fits(sps.WidthInMbs, sps.HeightInMbs) && !p.InDpb && !ReferenceEquals(p, openField)) + if (p.Fits(sps.WidthInMbs, sps.HeightInMbs, sps.ChromaFormatIdc, BytesPerSample, PlaneCount(sps)) && !p.InDpb && !ReferenceEquals(p, openField)) { p.ShortMask = p.LongMask = 0; p.NonExisting = false; - Array.Clear(p.RefPic); + p.ClearReferences(); return p; } } - return new Picture(sps.WidthInMbs, sps.HeightInMbs); + return new Picture(sps.WidthInMbs, sps.HeightInMbs, sps.ChromaFormatIdc, BytesPerSample, PlaneCount(sps)); } + private int BytesPerSample => wide ? 2 : 1; + + private static int PlaneCount(Sps sps) => sps.SeparateColourPlane ? 3 : 1; + + /// Two sequences whose pictures and macroblock data have the same shape: size, chroma format, sample size. + private static bool SameLayout(Sps a, Sps b) => + a.WidthInMbs == b.WidthInMbs && a.HeightInMbs == b.HeightInMbs && a.ChromaFormatIdc == b.ChromaFormatIdc + && a.SeparateColourPlane == b.SeparateColourPlane && SampleBytes(a) == SampleBytes(b); + + /// Bytes of each stored sample of a sequence: 2 when luma, or chroma if present, has more than 8 bits. + private static int SampleBytes(Sps s) => + s.BitDepthLuma > 8 || (s.ChromaFormatIdc != 0 && !s.SeparateColourPlane && s.BitDepthChroma > 8) ? 2 : 1; + /// 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) { @@ -669,8 +686,7 @@ public sealed partial class H264Decoder gap.TopPoc = gap.BottomPoc = 0; gap.Decoded = 3; gap.CodedAsFields = false; - Array.Fill(gap.MbIntra, true); - Array.Clear(gap.MbField); + gap.MarkAsGap(); SlidingWindow(sps, n, null); gap.ShortMask = 3; AddToDpb(gap); @@ -774,51 +790,98 @@ public sealed partial class H264Decoder } } + /// + /// The frame of a picture, cropped (§7.4.2.1.1, CropUnitX and CropUnitY). A monochrome frame gets chroma planes of + /// 4:2:0 size at the middle value, the rows of a field without its pair the middle value too, as the reference + /// decoder writes them; colour planes coded separately come out as 4:4:4 with the luma bit depth. + /// private static H264Frame Crop(Picture p, Sps sps) { - var cropUnitY = sps.FrameMbsOnly ? 2 : 4; - var left = sps.CropLeft * 2; - var top = sps.CropTop * cropUnitY; - var width = Math.Max(2, p.Width - left - (sps.CropRight * 2)); - var height = Math.Max(2, p.Height - top - (sps.CropBottom * cropUnitY)); - var y = new byte[width * height]; - for (var r = 0; r < height; r++) - { - Array.Copy(p.Y, ((top + r) * p.Width) + left, y, r * width, width); - } + var bps = p.BytesPerSample; + var format = sps.ChromaFormatIdc; + var bitDepthY = sps.BitDepthLuma; + var bitDepthC = format == 0 || sps.SeparateColourPlane ? bitDepthY : sps.BitDepthChroma; + int unitX = sps.CropUnitX, unitY = sps.CropUnitY; + var left = sps.CropLeft * unitX; + var top = sps.CropTop * unitY; + var width = Math.Max(2, p.Width - left - (sps.CropRight * unitX)); + var height = Math.Max(2, p.Height - top - (sps.CropBottom * unitY)); + var y = CopyRect(p.Y, p.Width, left, top, width, height, bps); - int cw = (width + 1) / 2, ch = (height + 1) / 2, pcw = p.Width / 2; - var cb = new byte[cw * ch]; - var cr = new byte[cw * ch]; - for (var r = 0; r < ch; r++) + byte[] cb, cr; + int ch, chromaTop; + if (format == 0) { - Array.Copy(p.Cb, (((top / 2) + r) * pcw) + (left / 2), cb, r * cw, cw); - Array.Copy(p.Cr, (((top / 2) + r) * pcw) + (left / 2), cr, r * cw, cw); + int cw = (width + 1) / 2; + ch = (height + 1) / 2; + chromaTop = 0; + cb = new byte[cw * ch * bps]; + FillMiddle(cb, bps, bitDepthC); + cr = (byte[])cb.Clone(); + } + else + { + int subW = sps.SubWidthC, subH = sps.SubHeightC; + var cw = (width + subW - 1) / subW; + ch = (height + subH - 1) / subH; + chromaTop = top / subH; + cb = CopyRect(p.Cb, p.ChromaWidth, left / subW, chromaTop, cw, ch, bps); + cr = CopyRect(p.Cr, p.ChromaWidth, left / subW, chromaTop, cw, ch, bps); } if (p.Decoded != 3) { // A field without its pair: the rows of the missing field are grey, as the reference decoder writes them. var missing = p.Decoded == 1 ? 1 : 0; + var rowY = width * bps; for (var r = 0; r < height; r++) { if (((top + r) & 1) == missing) { - y.AsSpan(r * width, width).Fill(128); + FillMiddle(y.AsSpan(r * rowY, rowY), bps, bitDepthY); } } - for (var r = 0; r < ch; r++) + if (format != 0) { - if ((((top / 2) + r) & 1) == missing) + var rowC = cb.Length / ch; + for (var r = 0; r < ch; r++) { - cb.AsSpan(r * cw, cw).Fill(128); - cr.AsSpan(r * cw, cw).Fill(128); + if (((chromaTop + r) & 1) == missing) + { + FillMiddle(cb.AsSpan(r * rowC, rowC), bps, bitDepthC); + FillMiddle(cr.AsSpan(r * rowC, rowC), bps, bitDepthC); + } } } } - return new H264Frame(width, height, y, cb, cr, p.Poc, p.Period, p.DecodeIndex, sps.MatrixCoefficients, sps.FullRange); + return new H264Frame(width, height, y, cb, cr, p.Poc, p.Period, p.DecodeIndex, sps.MatrixCoefficients, sps.FullRange, format, bitDepthY, bitDepthC); + } + + /// A × rectangle of a plane samples wide. + private static byte[] CopyRect(byte[] plane, int stride, int left, int top, int width, int height, int bps) + { + var result = new byte[width * height * bps]; + for (var r = 0; r < height; r++) + { + Array.Copy(plane, (((top + r) * stride) + left) * bps, result, r * width * bps, width * bps); + } + + return result; + } + + /// Samples at the middle value 2^(bitDepth − 1). + private static void FillMiddle(Span samples, int bps, int bitDepth) + { + if (bps == 1) + { + samples.Fill((byte)(1 << (bitDepth - 1))); + } + else + { + System.Runtime.InteropServices.MemoryMarshal.Cast(samples).Fill((ushort)(1 << (bitDepth - 1))); + } } private void AddToDpb(Picture p) diff --git a/src/Febe.Core/Codecs/H264/H264Tables.cs b/src/Febe.Core/Codecs/H264/H264Tables.cs index 80a43eb..0a92440 100644 --- a/src/Febe.Core/Codecs/H264/H264Tables.cs +++ b/src/Febe.Core/Codecs/H264/H264Tables.cs @@ -39,6 +39,12 @@ internal static class H264Tables 17, 18, 20, 24, 19, 21, 26, 28, 23, 27, 29, 30, 22, 25, 38, 41, ]; + /// coded_block_pattern of Intra_4x4 and Intra_8x8 macroblocks from codeNum without chroma syntax (table 9-4, ChromaArrayType 0 and 3). + internal static readonly byte[] CbpIntraNoChroma = [15, 0, 7, 11, 13, 14, 3, 5, 10, 12, 1, 2, 4, 8, 6, 9]; + + /// coded_block_pattern of inter macroblocks from codeNum without chroma syntax (table 9-4, ChromaArrayType 0 and 3). + internal static readonly byte[] CbpInterNoChroma = [0, 1, 2, 4, 8, 3, 5, 10, 12, 15, 7, 11, 13, 14, 6, 9]; + /// normAdjust4x4 values v[m][0..2] (equation 8-315). internal static readonly byte[,] NormAdjust4x4 = { diff --git a/src/Febe.Core/Codecs/H264/InterPrediction.cs b/src/Febe.Core/Codecs/H264/InterPrediction.cs index 179f3f9..c040f99 100644 --- a/src/Febe.Core/Codecs/H264/InterPrediction.cs +++ b/src/Febe.Core/Codecs/H264/InterPrediction.cs @@ -1,6 +1,11 @@ +using static Febe.Core.Codecs.H264.Samples; + namespace Febe.Core.Codecs.H264; -/// Fractional sample interpolation (§8.4.2.2) and weighted sample prediction (§8.4.2.3). +/// +/// Fractional sample interpolation (§8.4.2.2) and weighted sample prediction (§8.4.2.3), at any bit depth (max is +/// 2^BitDepth − 1). The luma interpolation serves also the Cb and Cr planes of 4:4:4. +/// internal static class InterPrediction { /// @@ -9,7 +14,8 @@ internal static class InterPrediction /// 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(byte[] plane, int origin, int stride, int pw, int ph, int qx, int qy, int w, int h, Span dst) + internal static void Luma(ReadOnlySpan plane, int origin, int stride, int pw, int ph, int qx, int qy, int w, int h, Span dst, int max) + where T : unmanaged { int xInt = qx >> 2, yInt = qy >> 2, xFrac = qx & 3, yFrac = qy & 3; @@ -27,15 +33,23 @@ internal static class InterPrediction } var rowBase = origin + (sy * stride); + var target = win.Slice(r * ww, ww); + if (inside) + { + var source = plane.Slice(rowBase + xInt - 2, ww); + for (var c = 0; c < ww; c++) + { + target[c] = Get(source[c]); + } + + continue; + } + for (var c = 0; c < ww; c++) { var sx = xInt - 2 + c; - if (!inside) - { - sx = sx < 0 ? 0 : sx >= pw ? pw - 1 : sx; - } - - win[(r * ww) + c] = plane[rowBase + sx]; + sx = sx < 0 ? 0 : sx >= pw ? pw - 1 : sx; + target[c] = Get(plane[rowBase + sx]); } } @@ -45,7 +59,7 @@ internal static class InterPrediction { for (var x = 0; x < w; x++) { - dst[(y * w) + x] = (byte)win[((y + 2) * ww) + x + 2]; + dst[(y * w) + x] = Make(win[((y + 2) * ww) + x + 2]); } } @@ -65,7 +79,7 @@ internal static class InterPrediction { var b = ((y + 2) * ww) + x; var v = win[b] - (5 * win[b + 1]) + (20 * win[b + 2]) + (20 * win[b + 3]) - (5 * win[b + 4]) + win[b + 5]; - bh[(y * w) + x] = Clip((v + 16) >> 5); + bh[(y * w) + x] = Clip((v + 16) >> 5, max); } } } @@ -78,7 +92,7 @@ internal static class InterPrediction { var b = (y * ww) + x + 2; var v = win[b] - (5 * win[b + ww]) + (20 * win[b + (2 * ww)]) + (20 * win[b + (3 * ww)]) - (5 * win[b + (4 * ww)]) + win[b + (5 * ww)]; - vh[(y * (w + 1)) + x] = Clip((v + 16) >> 5); + vh[(y * (w + 1)) + x] = Clip((v + 16) >> 5, max); } } } @@ -103,7 +117,7 @@ internal static class InterPrediction { var b = (y * w) + x; var v = b1[b] - (5 * b1[b + w]) + (20 * b1[b + (2 * w)]) + (20 * b1[b + (3 * w)]) - (5 * b1[b + (4 * w)]) + b1[b + (5 * w)]; - jc[b] = Clip((v + 512) >> 10); + jc[b] = Clip((v + 512) >> 10, max); } } } @@ -163,16 +177,17 @@ internal static class InterPrediction break; } - dst[(y * w) + x] = (byte)value; + dst[(y * w) + x] = Make(value); } } } /// - /// Chroma prediction (4:2:0) of a × block whose corner, in eighths of a - /// chroma sample, is (, ), from a plane view as for . + /// Chroma prediction (4:2:0 and 4:2:2) of a × block whose corner, in eighths + /// of a chroma sample, is (, ), from a plane view as for . /// - internal static void Chroma(byte[] plane, int origin, int stride, int pw, int ph, int ex, int ey, int w, int h, Span dst) + internal static void Chroma(ReadOnlySpan plane, int origin, int stride, int pw, int ph, int ex, int ey, int w, int h, Span dst) + where T : unmanaged { int xInt = ex >> 3, yInt = ey >> 3, xFrac = ex & 7, yFrac = ey & 7; int wA = (8 - xFrac) * (8 - yFrac), wB = xFrac * (8 - yFrac), wC = (8 - xFrac) * yFrac, wD = xFrac * yFrac; @@ -184,40 +199,42 @@ internal static class InterPrediction { var x0 = Math.Clamp(xInt + x, 0, pw - 1); var x1 = Math.Clamp(xInt + x + 1, 0, pw - 1); - dst[(y * w) + x] = (byte)(((wA * plane[y0 + x0]) + (wB * plane[y0 + x1]) + (wC * plane[y1 + x0]) + (wD * plane[y1 + x1]) + 32) >> 6); + dst[(y * w) + x] = Make(((wA * Get(plane[y0 + x0])) + (wB * Get(plane[y0 + x1])) + (wC * Get(plane[y1 + x0])) + (wD * Get(plane[y1 + x1])) + 32) >> 6); } } } /// Default bi-prediction average (equation 8-273), into . - internal static void Average(Span a, ReadOnlySpan b) + internal static void Average(Span a, ReadOnlySpan b) + where T : unmanaged { for (var i = 0; i < a.Length; i++) { - a[i] = (byte)((a[i] + b[i] + 1) >> 1); + a[i] = Make((Get(a[i]) + Get(b[i]) + 1) >> 1); } } - /// Weighted prediction from one list (equation 8-270). - internal static void WeightOne(Span a, int logWd, int weight, int offset) + /// Weighted prediction from one list (equation 8-270); is already scaled to the bit depth. + internal static void WeightOne(Span a, int logWd, int weight, int offset, int max) + where T : unmanaged { for (var i = 0; i < a.Length; i++) { - var v = logWd >= 1 ? ((a[i] * weight) + (1 << (logWd - 1))) >> logWd : a[i] * weight; - a[i] = (byte)Clip(v + offset); + var s = Get(a[i]); + var v = logWd >= 1 ? ((s * weight) + (1 << (logWd - 1))) >> logWd : s * weight; + a[i] = Make(Clip(v + offset, max)); } } - /// Weighted bi-prediction (equation 8-272), into . - internal static void WeightTwo(Span a, ReadOnlySpan b, int logWd, int w0, int w1, int o0, int o1) + /// Weighted bi-prediction (equation 8-272), into ; the offsets are already scaled to the bit depth. + internal static void WeightTwo(Span a, ReadOnlySpan b, int logWd, int w0, int w1, int o0, int o1, int max) + where T : unmanaged { var offset = (o0 + o1 + 1) >> 1; for (var i = 0; i < a.Length; i++) { - var v = (((a[i] * w0) + (b[i] * w1) + (1 << logWd)) >> (logWd + 1)) + offset; - a[i] = (byte)Clip(v); + var v = (((Get(a[i]) * w0) + (Get(b[i]) * w1) + (1 << logWd)) >> (logWd + 1)) + offset; + a[i] = Make(Clip(v, max)); } } - - private static int Clip(int v) => v < 0 ? 0 : v > 255 ? 255 : v; } diff --git a/src/Febe.Core/Codecs/H264/IntraPrediction.cs b/src/Febe.Core/Codecs/H264/IntraPrediction.cs index 39c77f0..e03ec3e 100644 --- a/src/Febe.Core/Codecs/H264/IntraPrediction.cs +++ b/src/Febe.Core/Codecs/H264/IntraPrediction.cs @@ -1,25 +1,33 @@ +using static Febe.Core.Codecs.H264.Samples; + namespace Febe.Core.Codecs.H264; -/// Intra prediction of luma 4×4, 8×8 and 16×16 blocks and of 4:2:0 chroma (§8.3), written into the plane. +/// +/// Intra prediction (§8.3) written into the plane: luma 4×4, 8×8 and 16×16 blocks (also the Cb and Cr planes of 4:4:4, +/// predicted like luma, and the colour planes coded separately) and the chroma of 4:2:0 and 4:2:2, at any bit depth: a +/// missing neighbour counts as 1 << (BitDepth − 1). +/// internal static class IntraPrediction { /// Intra_4x4 (§8.3.1.2) of the block at . - internal static void Predict4x4(byte[] p, int o, int stride, int mode, bool left, bool top, bool topRight, bool topLeft) + internal static void Predict4x4(Span p, int o, int stride, int mode, bool left, bool top, bool topRight, bool topLeft, int bitDepth) + where T : unmanaged { + var mid = 1 << (bitDepth - 1); Span t = stackalloc int[8]; Span l = stackalloc int[4]; for (var i = 0; i < 4; i++) { - t[i] = top ? p[o - stride + i] : 128; - l[i] = left ? p[o + (i * stride) - 1] : 128; + t[i] = top ? Get(p[o - stride + i]) : mid; + l[i] = left ? Get(p[o + (i * stride) - 1]) : mid; } for (var i = 4; i < 8; i++) { - t[i] = topRight ? p[o - stride + i] : t[3]; + t[i] = topRight ? Get(p[o - stride + i]) : t[3]; } - var tl = topLeft ? p[o - stride - 1] : 128; + var tl = topLeft ? Get(p[o - stride - 1]) : mid; switch (mode) { case 0: // Vertical @@ -27,7 +35,7 @@ internal static class IntraPrediction { for (var x = 0; x < 4; x++) { - p[o + (y * stride) + x] = (byte)t[x]; + p[o + (y * stride) + x] = Make(t[x]); } } @@ -35,10 +43,7 @@ internal static class IntraPrediction case 1: // Horizontal for (var y = 0; y < 4; y++) { - for (var x = 0; x < 4; x++) - { - p[o + (y * stride) + x] = (byte)l[y]; - } + p.Slice(o + (y * stride), 4).Fill(Make(l[y])); } break; @@ -59,7 +64,7 @@ internal static class IntraPrediction } else { - dc = 128; + dc = mid; } Fill(p, o, stride, 4, 4, dc); @@ -71,7 +76,7 @@ internal static class IntraPrediction { for (var x = 0; x < 4; x++) { - p[o + (y * stride) + x] = (byte)(x == 3 && y == 3 + p[o + (y * stride) + x] = Make(x == 3 && y == 3 ? (t[6] + (3 * t[7]) + 2) >> 2 : (t[x + y] + (2 * t[x + y + 1]) + t[x + y + 2] + 2) >> 2); } @@ -98,7 +103,7 @@ internal static class IntraPrediction { for (var x = 0; x < 4; x++) { - p[o + (y * stride) + x] = (byte)Directional(e, 4, mode, x, y, 4); + p[o + (y * stride) + x] = Make(Directional(e, 4, mode, x, y, 4)); } } @@ -207,22 +212,24 @@ internal static class IntraPrediction private static int L(ReadOnlySpan e, int c, int i) => e[c - 1 - i]; /// Intra_8x8 with the reference sample filtering of §8.3.2.2.1. - internal static void Predict8x8(byte[] p, int o, int stride, int mode, bool left, bool top, bool topRight, bool topLeft) + internal static void Predict8x8(Span p, int o, int stride, int mode, bool left, bool top, bool topRight, bool topLeft, int bitDepth) + where T : unmanaged { + var mid = 1 << (bitDepth - 1); Span t = stackalloc int[16]; Span l = stackalloc int[8]; for (var i = 0; i < 8; i++) { - t[i] = top ? p[o - stride + i] : 128; - l[i] = left ? p[o + (i * stride) - 1] : 128; + t[i] = top ? Get(p[o - stride + i]) : mid; + l[i] = left ? Get(p[o + (i * stride) - 1]) : mid; } for (var i = 8; i < 16; i++) { - t[i] = topRight ? p[o - stride + i] : t[7]; + t[i] = topRight ? Get(p[o - stride + i]) : t[7]; } - var tl = topLeft ? p[o - stride - 1] : 128; + var tl = topLeft ? Get(p[o - stride - 1]) : mid; // Filtered references p′. Span ft = stackalloc int[16]; @@ -273,7 +280,7 @@ internal static class IntraPrediction { for (var x = 0; x < 8; x++) { - p[o + (y * stride) + x] = (byte)ft[x]; + p[o + (y * stride) + x] = Make(ft[x]); } } @@ -281,10 +288,7 @@ internal static class IntraPrediction case 1: for (var y = 0; y < 8; y++) { - for (var x = 0; x < 8; x++) - { - p[o + (y * stride) + x] = (byte)fl[y]; - } + p.Slice(o + (y * stride), 8).Fill(Make(fl[y])); } break; @@ -297,7 +301,7 @@ internal static class IntraPrediction sumL += fl[i]; } - var dc = top && left ? (sumT + sumL + 8) >> 4 : left ? (sumL + 4) >> 3 : top ? (sumT + 4) >> 3 : 128; + var dc = top && left ? (sumT + sumL + 8) >> 4 : left ? (sumL + 4) >> 3 : top ? (sumT + 4) >> 3 : mid; Fill(p, o, stride, 8, 8, dc); break; } @@ -307,7 +311,7 @@ internal static class IntraPrediction { for (var x = 0; x < 8; x++) { - p[o + (y * stride) + x] = (byte)(x == 7 && y == 7 + p[o + (y * stride) + x] = Make(x == 7 && y == 7 ? (ft[14] + (3 * ft[15]) + 2) >> 2 : (ft[x + y] + (2 * ft[x + y + 1]) + ft[x + y + 2] + 2) >> 2); } @@ -332,7 +336,7 @@ internal static class IntraPrediction { for (var x = 0; x < 8; x++) { - p[o + (y * stride) + x] = (byte)Directional(e, 8, mode, x, y, 8); + p[o + (y * stride) + x] = Make(Directional(e, 8, mode, x, y, 8)); } } @@ -342,22 +346,22 @@ internal static class IntraPrediction } /// Intra_16x16 (§8.3.3). - internal static void Predict16x16(byte[] p, int o, int stride, int mode, bool left, bool top, bool topLeft) + internal static void Predict16x16(Span p, int o, int stride, int mode, bool left, bool top, bool topLeft, int bitDepth) + where T : unmanaged { switch (mode) { case 0: for (var y = 0; y < 16; y++) { - Array.Copy(p, o - stride, p, o + (y * stride), 16); + p.Slice(o - stride, 16).CopyTo(p.Slice(o + (y * stride), 16)); } break; case 1: for (var y = 0; y < 16; y++) { - var v = p[o + (y * stride) - 1]; - p.AsSpan(o + (y * stride), 16).Fill(v); + p.Slice(o + (y * stride), 16).Fill(p[o + (y * stride) - 1]); } break; @@ -368,68 +372,73 @@ internal static class IntraPrediction { if (top) { - sumT += p[o - stride + i]; + sumT += Get(p[o - stride + i]); } if (left) { - sumL += p[o + (i * stride) - 1]; + sumL += Get(p[o + (i * stride) - 1]); } } - var dc = top && left ? (sumT + sumL + 16) >> 5 : left ? (sumL + 8) >> 4 : top ? (sumT + 8) >> 4 : 128; + var dc = top && left ? (sumT + sumL + 16) >> 5 : left ? (sumL + 8) >> 4 : top ? (sumT + 8) >> 4 : 1 << (bitDepth - 1); Fill(p, o, stride, 16, 16, dc); break; } default: - Plane(p, o, stride, 16, 16, topLeft); + Plane(p, o, stride, 16, 16, topLeft, (1 << bitDepth) - 1); break; } } /// - /// Chroma prediction of one 8×8 4:2:0 component (§8.3.4): 0 DC, 1 horizontal, 2 vertical, 3 plane. The left - /// samples of the upper and of the lower four rows may differ in availability (an MBAFF frame with constrained intra - /// prediction, where they come from two macroblocks): the DC prediction of each 4×4 block uses its own. + /// Chroma prediction of one component of 4:2:0 (8×8) or 4:2:2 (8×16) (§8.3.4): 0 DC, 1 horizontal, 2 vertical, 3 + /// plane. Bit g of says whether the left samples of rows 4g to 4g + 3 are available: they + /// may differ (an MBAFF frame with constrained intra prediction, where they come from two macroblocks), and the DC + /// prediction of each 4×4 block uses its own. /// - internal static void PredictChroma(byte[] p, int o, int stride, int mode, bool leftUpper, bool leftLower, bool top, bool topLeft) + internal static void PredictChroma(Span p, int o, int stride, int mode, int height, int leftRows, bool top, bool topLeft, int bitDepth) + where T : unmanaged { + var mid = 1 << (bitDepth - 1); switch (mode) { case 0: - for (var by = 0; by < 2; by++) + for (var by = 0; by < height / 4; by++) { + var left = ((leftRows >> by) & 1) != 0; for (var bx = 0; bx < 2; bx++) { var b = o + (by * 4 * stride) + (bx * 4); - var left = by == 0 ? leftUpper : leftLower; int sumT = 0, sumL = 0; for (var i = 0; i < 4; i++) { if (top) { - sumT += p[o - stride + (bx * 4) + i]; + sumT += Get(p[o - stride + (bx * 4) + i]); } if (left) { - sumL += p[o + (((by * 4) + i) * stride) - 1]; + sumL += Get(p[o + (((by * 4) + i) * stride) - 1]); } } + // §8.3.4.1–8.3.4.3: the blocks at (0, 0) and those off the first row and column use both edges, + // the others of the first row prefer the top one, those of the first column the left one. int dc; - if ((bx == 0 && by == 0) || (bx == 1 && by == 1)) + if ((bx == 0 && by == 0) || (bx > 0 && by > 0)) { - dc = top && left ? (sumT + sumL + 4) >> 3 : left ? (sumL + 2) >> 2 : top ? (sumT + 2) >> 2 : 128; + dc = top && left ? (sumT + sumL + 4) >> 3 : left ? (sumL + 2) >> 2 : top ? (sumT + 2) >> 2 : mid; } - else if (bx == 1) + else if (bx > 0) { - dc = top ? (sumT + 2) >> 2 : left ? (sumL + 2) >> 2 : 128; + dc = top ? (sumT + 2) >> 2 : left ? (sumL + 2) >> 2 : mid; } else { - dc = left ? (sumL + 2) >> 2 : top ? (sumT + 2) >> 2 : 128; + dc = left ? (sumL + 2) >> 2 : top ? (sumT + 2) >> 2 : mid; } Fill(p, b, stride, 4, 4, dc); @@ -438,28 +447,31 @@ internal static class IntraPrediction break; case 1: - for (var y = 0; y < 8; y++) + for (var y = 0; y < height; y++) { - var v = p[o + (y * stride) - 1]; - p.AsSpan(o + (y * stride), 8).Fill(v); + p.Slice(o + (y * stride), 8).Fill(p[o + (y * stride) - 1]); } break; case 2: - for (var y = 0; y < 8; y++) + for (var y = 0; y < height; y++) { - Array.Copy(p, o - stride, p, o + (y * stride), 8); + p.Slice(o - stride, 8).CopyTo(p.Slice(o + (y * stride), 8)); } break; default: - Plane(p, o, stride, 8, 8, topLeft); + Plane(p, o, stride, 8, height, topLeft, (1 << bitDepth) - 1); break; } } - /// Plane prediction of a 16×16 luma or 8×8 chroma block. - private static void Plane(byte[] p, int o, int stride, int w, int h, bool topLeft) + /// + /// Plane prediction of a 16×16 luma block or of an 8×8 or 8×16 chroma one (equations 8-125 to 8-131 and 8-138 to + /// 8-145): the gradient of a 16-sample side is weighed by 5, of an 8-sample side by 34. + /// + private static void Plane(Span p, int o, int stride, int w, int h, bool topLeft, int max) + where T : unmanaged { _ = topLeft; // the plane mode is only used when all three neighbours are available var hw = w / 2; @@ -467,48 +479,41 @@ internal static class IntraPrediction int sumH = 0, sumV = 0; for (var i = 0; i < hw; i++) { - var right = p[o - stride + hw + i]; + var right = Get(p[o - stride + hw + i]); var leftIndex = hw - 2 - i; - var leftSample = leftIndex >= 0 ? p[o - stride + leftIndex] : p[o - stride - 1]; + var leftSample = Get(leftIndex >= 0 ? p[o - stride + leftIndex] : p[o - stride - 1]); sumH += (i + 1) * (right - leftSample); } for (var i = 0; i < hh; i++) { - var below = p[o + ((hh + i) * stride) - 1]; + var below = Get(p[o + ((hh + i) * stride) - 1]); var aboveIndex = hh - 2 - i; - var aboveSample = aboveIndex >= 0 ? p[o + (aboveIndex * stride) - 1] : p[o - stride - 1]; + var aboveSample = Get(aboveIndex >= 0 ? p[o + (aboveIndex * stride) - 1] : p[o - stride - 1]); sumV += (i + 1) * (below - aboveSample); } - var a = 16 * (p[o + ((h - 1) * stride) - 1] + p[o - stride + w - 1]); - int b, c; - if (w == 16) - { - b = ((5 * sumH) + 32) >> 6; - c = ((5 * sumV) + 32) >> 6; - } - else - { - b = ((34 * sumH) + 32) >> 6; - c = ((34 * sumV) + 32) >> 6; - } - + var a = 16 * (Get(p[o + ((h - 1) * stride) - 1]) + Get(p[o - stride + w - 1])); + var b = (((w == 16 ? 5 : 34) * sumH) + 32) >> 6; + var c = (((h == 16 ? 5 : 34) * sumV) + 32) >> 6; for (var y = 0; y < h; y++) { - for (var x = 0; x < w; x++) + var row = p.Slice(o + (y * stride), w); + var v = a + (c * (y - (hh - 1))) - (b * (hw - 1)) + 16; + for (var x = 0; x < w; x++, v += b) { - var v = (a + (b * (x - (hw - 1))) + (c * (y - (hh - 1))) + 16) >> 5; - p[o + (y * stride) + x] = (byte)Math.Clamp(v, 0, 255); + row[x] = Make(Clip(v >> 5, max)); } } } - private static void Fill(byte[] p, int o, int stride, int w, int h, int value) + private static void Fill(Span p, int o, int stride, int w, int h, int value) + where T : unmanaged { + var sample = Make(value); for (var y = 0; y < h; y++) { - p.AsSpan(o + (y * stride), w).Fill((byte)value); + p.Slice(o + (y * stride), w).Fill(sample); } } } diff --git a/src/Febe.Core/Codecs/H264/ParameterSets.cs b/src/Febe.Core/Codecs/H264/ParameterSets.cs index 0267d42..3bae7bb 100644 --- a/src/Febe.Core/Codecs/H264/ParameterSets.cs +++ b/src/Febe.Core/Codecs/H264/ParameterSets.cs @@ -13,10 +13,31 @@ internal sealed class Sps internal int LevelIdc; internal int Id; internal int ChromaFormatIdc = 1; + + /// separate_colour_plane_flag: the three colour planes of 4:4:4 are coded as three monochrome pictures. + internal bool SeparateColourPlane; + internal int BitDepthLuma = 8; internal int BitDepthChroma = 8; + + /// qpprime_y_zero_transform_bypass_flag: macroblocks with QP′Y 0 are lossless (§8.5.15). internal bool TransformBypass; + /// ChromaArrayType (§7.4.2.1.1): chroma_format_idc, or 0 when the colour planes are separate. + internal int ChromaArrayType => SeparateColourPlane ? 0 : ChromaFormatIdc; + + /// SubWidthC (Table 6-1): 2 for 4:2:0 and 4:2:2, 1 for 4:4:4. + internal int SubWidthC => ChromaFormatIdc == 3 ? 1 : 2; + + /// SubHeightC (Table 6-1): 2 for 4:2:0, 1 for 4:2:2 and 4:4:4. + internal int SubHeightC => ChromaFormatIdc == 1 ? 2 : 1; + + /// QpBdOffsetY = 6 × bit_depth_luma_minus8. + internal int QpBdOffsetY => 6 * (BitDepthLuma - 8); + + /// QpBdOffsetC = 6 × bit_depth_chroma_minus8. + internal int QpBdOffsetC => 6 * (BitDepthChroma - 8); + /// Scaling lists 0–5 (4×4) and 6–11 (8×8) in zig-zag order, after the fall-back rule A. internal byte[][] ScalingLists = ScalingMatrix.Flat(); @@ -46,6 +67,12 @@ internal sealed class Sps internal int MaxFrameNum => 1 << Log2MaxFrameNum; + /// CropUnitX of §7.4.2.1.1: 1 without chroma (or in 4:4:4), else SubWidthC. + internal int CropUnitX => ChromaArrayType == 0 ? 1 : SubWidthC; + + /// CropUnitY of §7.4.2.1.1, doubled when the frames may be coded as fields. + internal int CropUnitY => (ChromaArrayType == 0 ? 1 : SubHeightC) * (FrameMbsOnly ? 1 : 2); + internal int HeightInMbs => (2 - (FrameMbsOnly ? 1 : 0)) * HeightInMapUnits; internal static Sps Parse(RbspReader r) @@ -59,7 +86,7 @@ internal sealed class Sps s.ChromaFormatIdc = r.ReadUe(3); if (s.ChromaFormatIdc == 3) { - r.Skip(1); // separate_colour_plane_flag + s.SeparateColourPlane = r.ReadFlag(); } s.BitDepthLuma = r.ReadUe(6) + 8; @@ -123,9 +150,8 @@ internal sealed class Sps s.CropTop = r.ReadUe(8192); s.CropBottom = r.ReadUe(8192); - // §7.4.2.1.1: the cropped frame keeps at least one sample (CropUnitX = 2, CropUnitY = 2 for frames in 4:2:0). - var cropUnitY = 2 * (s.FrameMbsOnly ? 1 : 2); - if (2 * (s.CropLeft + s.CropRight) >= s.WidthInMbs * 16 || cropUnitY * (s.CropTop + s.CropBottom) >= s.HeightInMbs * 16) + // §7.4.2.1.1: the cropped frame keeps at least one sample. + if (s.CropUnitX * (s.CropLeft + s.CropRight) >= s.WidthInMbs * 16 || s.CropUnitY * (s.CropTop + s.CropBottom) >= s.HeightInMbs * 16) { throw new H264Exception("Ritaglio dell'immagine non valido."); } diff --git a/src/Febe.Core/Codecs/H264/Picture.cs b/src/Febe.Core/Codecs/H264/Picture.cs index 5643055..afe6c1b 100644 --- a/src/Febe.Core/Codecs/H264/Picture.cs +++ b/src/Febe.Core/Codecs/H264/Picture.cs @@ -2,34 +2,49 @@ namespace Febe.Core.Codecs.H264; /// /// A frame store of the decoded picture buffer: a decoded frame, or the two fields of a complementary field pair (its -/// even rows are the top field, its odd rows the bottom one), with what later pictures need from it: samples (4:2:0, -/// 8 bits, the full macroblock area), motion vectors and references of every block (for direct prediction and the -/// deblocking of the pictures that follow), and its marking. +/// even rows are the top field, its odd rows the bottom one), with what later pictures need from it: samples (the full +/// macroblock area, one or two bytes per sample), motion vectors and references of every block (for direct prediction +/// and the deblocking of the pictures that follow), and its marking. /// /// /// 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 (). +/// field units and refer to fields (). When the three colour planes of 4:4:4 are coded separately +/// (separate_colour_plane_flag) each has macroblocks of its own: the motion data is kept per plane, and +/// chooses the one the properties show. /// internal sealed class Picture { - internal Picture(int widthInMbs, int heightInMbs) + private readonly MotionPlane[] motion; + private MotionPlane selected; + + /// Width in macroblocks. + /// Height in macroblocks. + /// chroma_format_idc: 0 monochrome (no chroma planes), 1 4:2:0, 2 4:2:2, 3 4:4:4. + /// 1 up to 8 bits, 2 above. + /// 3 when the colour planes are coded separately, else 1. + internal Picture(int widthInMbs, int heightInMbs, int chromaFormat = 1, int bytesPerSample = 1, int colourPlanes = 1) { WidthInMbs = widthInMbs; HeightInMbs = heightInMbs; Width = widthInMbs * 16; Height = heightInMbs * 16; + ChromaFormat = chromaFormat; + BytesPerSample = bytesPerSample; + ChromaWidth = chromaFormat == 0 ? 0 : chromaFormat == 3 ? Width : Width / 2; + ChromaHeight = chromaFormat == 0 ? 0 : chromaFormat == 1 ? Height / 2 : Height; var mbs = widthInMbs * heightInMbs; - Y = new byte[Width * Height]; - Cb = new byte[Width * Height / 4]; - Cr = new byte[Width * Height / 4]; - Mv = new short[2 * mbs * 16 * 2]; - RefIdx = new sbyte[2 * mbs * 4]; - RefPic = new Picture?[2 * mbs * 4]; - RefPar = new sbyte[2 * mbs * 4]; - MbIntra = new bool[mbs]; - MbField = new bool[mbs]; + Y = new byte[Width * Height * bytesPerSample]; + Cb = new byte[ChromaWidth * ChromaHeight * bytesPerSample]; + Cr = new byte[ChromaWidth * ChromaHeight * bytesPerSample]; + motion = new MotionPlane[colourPlanes]; + for (var i = 0; i < colourPlanes; i++) + { + motion[i] = new MotionPlane(mbs); + } + + selected = motion[0]; } internal int WidthInMbs { get; } @@ -40,6 +55,17 @@ internal sealed class Picture internal int Height { get; } + /// chroma_format_idc of the samples (3 also for separate colour planes). + internal int ChromaFormat { get; } + + internal int BytesPerSample { get; } + + /// Width of the Cb and Cr planes in samples (0 for monochrome). + internal int ChromaWidth { get; } + + /// Height of the Cb and Cr planes in samples (0 for monochrome). + internal int ChromaHeight { get; } + internal byte[] Y { get; } internal byte[] Cb { get; } @@ -47,21 +73,46 @@ internal sealed class Picture internal byte[] Cr { get; } /// Motion vectors: [((list * mbs + mb) * 16 + raster 4×4 block) * 2 + component], quarter samples. - internal short[] Mv { get; } + internal short[] Mv => selected.Mv; /// Reference indices: [(list * mbs + mb) * 4 + 8×8 block]; −1 when the list is not used. - internal sbyte[] RefIdx { get; } + internal sbyte[] RefIdx => selected.RefIdx; /// The frame store each 8×8 block refers to, by list (same index as ). - internal Picture?[] RefPic { get; } + internal Picture?[] RefPic => selected.RefPic; /// The field of referred to: 0 top, 1 bottom, −1 the frame (same index as ). - internal sbyte[] RefPar { get; } + internal sbyte[] RefPar => selected.RefPar; - internal bool[] MbIntra { get; } + internal bool[] MbIntra => selected.MbIntra; /// Field macroblocks: those of field pictures and the field pairs of MBAFF frames. - internal bool[] MbField { get; } + internal bool[] MbField => selected.MbField; + + /// The plane of colour component (0 Y, 1 Cb, 2 Cr). + internal byte[] Plane(int k) => k == 0 ? Y : k == 1 ? Cb : Cr; + + /// Shows the motion data of colour plane (only one exists unless the planes are separate). + internal void SelectPlane(int k) => selected = motion[Math.Min(k, motion.Length - 1)]; + + /// A store taken from the pool: no block refers to any picture yet. + internal void ClearReferences() + { + foreach (var m in motion) + { + Array.Clear(m.RefPic); + } + } + + /// A frame inferred for a gap in frame_num: all its macroblocks count as intra frame macroblocks. + internal void MarkAsGap() + { + foreach (var m in motion) + { + Array.Fill(m.MbIntra, true); + Array.Clear(m.MbField); + } + } internal int MbCount => WidthInMbs * HeightInMbs; @@ -127,7 +178,20 @@ internal sealed class Picture /// 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; + internal bool Fits(int widthInMbs, int heightInMbs, int chromaFormat, int bytesPerSample, int colourPlanes) => + WidthInMbs == widthInMbs && HeightInMbs == heightInMbs && ChromaFormat == chromaFormat && BytesPerSample == bytesPerSample + && motion.Length == colourPlanes; + + /// The motion data of the macroblocks of one colour plane. + private sealed class MotionPlane(int mbs) + { + internal readonly short[] Mv = new short[2 * mbs * 16 * 2]; + internal readonly sbyte[] RefIdx = new sbyte[2 * mbs * 4]; + internal readonly Picture?[] RefPic = new Picture?[2 * mbs * 4]; + internal readonly sbyte[] RefPar = new sbyte[2 * mbs * 4]; + internal readonly bool[] MbIntra = new bool[mbs]; + internal readonly bool[] MbField = new bool[mbs]; + } } /// A reference picture of a list: a frame ( −1) or one field of a frame store. @@ -138,22 +202,45 @@ internal readonly record struct RefEntry(Picture? Pic, int Parity) internal bool IsLongTerm => Pic!.IsLongTerm(Parity); } -/// A decoded frame, cropped, in planar YUV 4:2:0. +/// +/// A decoded frame, cropped, in planar YUV. Up to 8 bits each sample is a byte; above, two bytes, little-endian (as the +/// reference decoders write their files). A monochrome frame (4:0:0) comes with Cb and Cr planes of 4:2:0 size at the +/// middle value 2^(BitDepthChroma − 1), as reference decoders write it too. +/// /// Luma width after cropping. /// Luma height after cropping. -/// Luma, × . -/// Blue-difference chroma, (Width + 1) / 2 × (Height + 1) / 2. +/// Luma, × samples. +/// Blue-difference chroma, × samples. /// Red-difference chroma, same size as . /// Picture order count: frames are shown by increasing value within a . /// Increases at each IDR picture. /// Position of the frame in decoding order (0 for the first). /// matrix_coefficients of the VUI (1 = BT.709, 5 and 6 = BT.601, 2 = unspecified). /// video_full_range_flag of the VUI. +/// chroma_format_idc: 0 monochrome, 1 4:2:0, 2 4:2:2, 3 4:4:4. +/// Bits of each luma sample, 8 to 14. +/// Bits of each chroma sample, 8 to 14. public sealed record H264Frame( - int Width, int Height, byte[] Y, byte[] Cb, byte[] Cr, int Poc, int Period, long DecodeIndex, int MatrixCoefficients, bool FullRange) + int Width, int Height, byte[] Y, byte[] Cb, byte[] Cr, int Poc, int Period, long DecodeIndex, int MatrixCoefficients, bool FullRange, + int ChromaFormat = 1, int BitDepthLuma = 8, int BitDepthChroma = 8) { - /// The frame as one I420 buffer (Y, then Cb, then Cr), as reference decoders write it. - public byte[] ToI420() + /// Width of and in samples. + public int ChromaWidth => ChromaFormat == 3 ? Width : (Width + 1) / 2; + + /// Height of and in samples. + public int ChromaHeight => ChromaFormat is 2 or 3 ? Height : (Height + 1) / 2; + + /// Bytes of every sample of the three planes: 2 when either bit depth is above 8, else 1. + public int BytesPerSample => BitDepthLuma > 8 || BitDepthChroma > 8 ? 2 : 1; + + /// Luma sample (row × Width + column), whatever the bit depth. + public int LumaAt(int index) => BytesPerSample == 2 ? Y[2 * index] | (Y[(2 * index) + 1] << 8) : Y[index]; + + /// Sample of a chroma plane (row × ChromaWidth + column), whatever the bit depth. + public int ChromaAt(byte[] plane, int index) => BytesPerSample == 2 ? plane[2 * index] | (plane[(2 * index) + 1] << 8) : plane[index]; + + /// The frame as one planar buffer (Y, then Cb, then Cr), as reference decoders write it. + public byte[] ToPlanar() { var buffer = new byte[Y.Length + Cb.Length + Cr.Length]; Y.CopyTo(buffer, 0); diff --git a/src/Febe.Core/Codecs/H264/Samples.cs b/src/Febe.Core/Codecs/H264/Samples.cs new file mode 100644 index 0000000..eadfbbd --- /dev/null +++ b/src/Febe.Core/Codecs/H264/Samples.cs @@ -0,0 +1,43 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Febe.Core.Codecs.H264; + +/// +/// The two sample types of the decoder: for 8-bit video, above 8 bits (up to 14, +/// High 4:4:4). The planes of a picture are byte arrays of one or two bytes per sample (little-endian, as the official +/// reconstructions store them); the prediction, transform and filter code is generic over the sample type, and the JIT +/// compiles it once for each, so 8-bit video pays nothing for the wider one. +/// +internal static class Samples +{ + /// The value of a sample. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static int Get(T sample) + where T : unmanaged => + typeof(T) == typeof(byte) ? Unsafe.As(ref sample) : Unsafe.As(ref sample); + + /// A sample of value , already within the range of the bit depth. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static T Make(int value) + where T : unmanaged + { + if (typeof(T) == typeof(byte)) + { + var b = (byte)value; + return Unsafe.As(ref b); + } + + var u = (ushort)value; + return Unsafe.As(ref u); + } + + /// A plane stored as bytes, seen as samples of type . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static Span Plane(byte[] plane) + where T : unmanaged => MemoryMarshal.Cast(plane.AsSpan()); + + /// Clip1 of §5.7: within 0... + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static int Clip(int value, int max) => value < 0 ? 0 : value > max ? max : value; +} diff --git a/src/Febe.Core/Codecs/H264/SliceHeader.cs b/src/Febe.Core/Codecs/H264/SliceHeader.cs index 2b1e77e..86c94eb 100644 --- a/src/Febe.Core/Codecs/H264/SliceHeader.cs +++ b/src/Febe.Core/Codecs/H264/SliceHeader.cs @@ -16,6 +16,10 @@ internal sealed class SliceHeader internal int FirstMb; internal SliceType Type; internal int PpsId; + + /// colour_plane_id: the colour plane (0 Y, 1 Cb, 2 Cr) of a slice when the planes are coded separately. + internal int ColourPlaneId; + internal int FrameNum; internal bool FieldPic; internal bool BottomField; @@ -89,6 +93,15 @@ internal sealed class SliceHeader throw new H264Exception("Slice senza i suoi insiemi di parametri."); } + if (sps.SeparateColourPlane) + { + h.ColourPlaneId = (int)r.Read(2); + if (h.ColourPlaneId > 2) + { + throw new H264Exception("colour_plane_id non valido."); + } + } + h.FrameNum = (int)r.Read(sps.Log2MaxFrameNum); if (!sps.FrameMbsOnly) { @@ -280,7 +293,8 @@ internal sealed class SliceHeader private static void ParseWeights(RbspReader r, SliceHeader h, Sps sps) { h.LumaLog2WeightDenom = r.ReadUe(7); - var chroma = sps.ChromaFormatIdc != 0; + // No chroma weights without chroma: monochrome, or each colour plane coded separately (ChromaArrayType 0). + var chroma = sps.ChromaArrayType != 0; if (chroma) { h.ChromaLog2WeightDenom = r.ReadUe(7); diff --git a/src/Febe.Core/Codecs/H264/Transform.cs b/src/Febe.Core/Codecs/H264/Transform.cs index c699218..f02dc5f 100644 --- a/src/Febe.Core/Codecs/H264/Transform.cs +++ b/src/Febe.Core/Codecs/H264/Transform.cs @@ -1,10 +1,16 @@ +using static Febe.Core.Codecs.H264.Samples; + namespace Febe.Core.Codecs.H264; -/// Inverse transforms of §8.5.12 and §8.5.13, adding the residual to the prediction already in the plane. +/// +/// Inverse transforms of §8.5.12 and §8.5.13, adding the residual to the prediction already in the plane, and the +/// transform bypass of lossless macroblocks (§8.5.15), at any bit depth (max is 2^BitDepth − 1). +/// internal static class Transform { /// Inverse 4×4 transform of scaled coefficients (raster order), added to the 4×4 block at . - internal static void Add4x4(Span d, byte[] plane, int o, int stride) + internal static void Add4x4(Span d, Span plane, int o, int stride, int max) + where T : unmanaged { for (var i = 0; i < 4; i++) { @@ -20,15 +26,16 @@ internal static class Transform { int f0 = d[j], f1 = d[4 + j], f2 = d[8 + j], f3 = d[12 + j]; int g0 = f0 + f2, g1 = f0 - f2, g2 = (f1 >> 1) - f3, g3 = f1 + (f3 >> 1); - AddSample(plane, o + j, g0 + g3); - AddSample(plane, o + stride + j, g1 + g2); - AddSample(plane, o + (2 * stride) + j, g1 - g2); - AddSample(plane, o + (3 * stride) + j, g0 - g3); + AddSample(plane, o + j, g0 + g3, max); + AddSample(plane, o + stride + j, g1 + g2, max); + AddSample(plane, o + (2 * stride) + j, g1 - g2, max); + AddSample(plane, o + (3 * stride) + j, g0 - g3, max); } } /// Inverse 8×8 transform (§8.5.13), added to the 8×8 block at . - internal static void Add8x8(Span d, byte[] plane, int o, int stride) + internal static void Add8x8(Span d, Span plane, int o, int stride, int max) + where T : unmanaged { Span tmp = stackalloc int[8]; for (var i = 0; i < 8; i++) @@ -48,7 +55,47 @@ internal static class Transform Butterfly8(column, tmp); for (var i = 0; i < 8; i++) { - AddSample(plane, o + (i * stride) + j, tmp[i]); + AddSample(plane, o + (i * stride) + j, tmp[i], max); + } + } + } + + /// + /// The residual of a lossless block (TransformBypassModeFlag, §8.5.15): holds the + /// × coefficients in raster order, which are the residual itself; under an + /// intra prediction that is horizontal ( 1) or vertical (2) each sample adds those before it + /// along the direction of the prediction. The result is added to the prediction in the plane. + /// + internal static void AddBypass(Span r, int w, int h, int dpcm, Span plane, int o, int stride, int max) + where T : unmanaged + { + if (dpcm == 1) + { + for (var y = 0; y < h; y++) + { + for (var x = 1; x < w; x++) + { + r[(y * w) + x] += r[(y * w) + x - 1]; + } + } + } + else if (dpcm == 2) + { + for (var y = 1; y < h; y++) + { + for (var x = 0; x < w; x++) + { + r[(y * w) + x] += r[((y - 1) * w) + x]; + } + } + } + + for (var y = 0; y < h; y++) + { + var row = plane.Slice(o + (y * stride), w); + for (var x = 0; x < w; x++) + { + row[x] = Make(Clip(Get(row[x]) + r[(y * w) + x], max)); } } } @@ -97,9 +144,35 @@ internal static class Transform } } - private static void AddSample(byte[] plane, int index, int residual) + /// + /// The inverse transform of the eight chroma DC coefficients of 4:2:2 (equation 8-329): f = A · c · B, with c of four + /// rows and two columns in raster order, A the 4×4 matrix of and B = [1 1; 1 −1]; in place. + /// + internal static void ChromaDc422(Span c) { - var v = plane[index] + ((residual + 32) >> 6); - plane[index] = (byte)(v < 0 ? 0 : v > 255 ? 255 : v); + // c · B on each row. + for (var i = 0; i < 4; i++) + { + int a = c[2 * i], b = c[(2 * i) + 1]; + c[2 * i] = a + b; + c[(2 * i) + 1] = a - b; + } + + // A · (c · B) on each column. + for (var j = 0; j < 2; j++) + { + int f0 = c[j], f1 = c[2 + j], f2 = c[4 + j], f3 = c[6 + j]; + int e0 = f0 + f1, e1 = f0 - f1, e2 = f2 + f3, e3 = f2 - f3; + c[j] = e0 + e2; + c[2 + j] = e0 - e2; + c[4 + j] = e1 - e3; + c[6 + j] = e1 + e3; + } + } + + private static void AddSample(Span plane, int index, int residual, int max) + where T : unmanaged + { + plane[index] = Make(Clip(Get(plane[index]) + ((residual + 32) >> 6), max)); } } diff --git a/src/Febe.Core/Library/VideoFrameDecoder.cs b/src/Febe.Core/Library/VideoFrameDecoder.cs index c86c632..ce39e00 100644 --- a/src/Febe.Core/Library/VideoFrameDecoder.cs +++ b/src/Febe.Core/Library/VideoFrameDecoder.cs @@ -469,25 +469,35 @@ public sealed class VideoFrameDecoder } } - /// A coarse grid of mean luma and chroma values, to compare frames without their compression noise. + /// + /// A coarse grid of mean luma and chroma values, to compare frames without their compression noise; values on the + /// 8-bit scale whatever the bit depth, the chroma at any sampling (its own grid over its own plane). + /// private static double[] Grid(H264Frame frame) { var grid = new double[GridSize * GridSize * 2]; var counts = new int[GridSize * GridSize]; + var wide = frame.BytesPerSample == 2; + ReadOnlySpan y16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Y) : default; + var lumaShift = frame.BitDepthLuma - 8; for (var y = 0; y < frame.Height; y++) { var gy = y * GridSize / frame.Height; - var row = frame.Y.AsSpan(y * frame.Width, frame.Width); - for (var x = 0; x < row.Length; x++) + var start = y * frame.Width; + for (var x = 0; x < frame.Width; x++) { var cell = (gy * GridSize) + (x * GridSize / frame.Width); - grid[cell] += row[x]; + grid[cell] += wide ? y16[start + x] >> lumaShift : frame.Y[start + x]; counts[cell]++; } } - var cw = (frame.Width + 1) / 2; - var ch = (frame.Height + 1) / 2; + var cw = frame.ChromaWidth; + var ch = frame.ChromaHeight; + ReadOnlySpan cb16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Cb) : default; + ReadOnlySpan cr16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Cr) : default; + var chromaShift = frame.BitDepthChroma - 8; + var middle = 1 << (frame.BitDepthChroma - 1); var chromaCounts = new int[GridSize * GridSize]; for (var y = 0; y < ch; y++) { @@ -496,7 +506,19 @@ public sealed class VideoFrameDecoder { var cell = (gy * GridSize) + (x * GridSize / cw); var i = (y * cw) + x; - grid[(GridSize * GridSize) + cell] += (Math.Abs(frame.Cb[i] - 128) + Math.Abs(frame.Cr[i] - 128)) / 2.0; + int u, v; + if (wide) + { + u = Math.Abs(cb16[i] - middle) >> chromaShift; + v = Math.Abs(cr16[i] - middle) >> chromaShift; + } + else + { + u = Math.Abs(frame.Cb[i] - 128); + v = Math.Abs(frame.Cr[i] - 128); + } + + grid[(GridSize * GridSize) + cell] += (u + v) / 2.0; chromaCounts[cell]++; } } @@ -512,8 +534,10 @@ public sealed class VideoFrameDecoder } /// - /// The frame in RGB: BT.709 or BT.601 coefficients as the stream says (unspecified: BT.709 from 720 lines up), limited - /// or full range, reduced by an integer factor to fit , then rotated clockwise. + /// The frame in RGB: BT.709, BT.601 or BT.2020 coefficients as the stream says (unspecified: BT.709 from 720 lines + /// up), limited or full range at the bit depth of the frame (limited: black at 16 · 2^(n − 8), luma span 219 · 2^(n − 8), + /// chroma 224 · 2^(n − 8) around 2^(n − 1)), any chroma sampling (4:2:0, 4:2:2, 4:4:4; monochrome comes with grey + /// chroma), reduced by an integer factor to fit , then rotated clockwise. /// internal static VideoImage ToImage(H264Frame frame, int rotation, int maxLongSide) { @@ -527,9 +551,11 @@ public sealed class VideoFrameDecoder _ => frame.Height >= 720 ? (0.2126, 0.0722) : (0.299, 0.114), }; var kg = 1 - kr - kb; - var yScale = frame.FullRange ? 1.0 : 255.0 / 219.0; - var cScale = frame.FullRange ? 1.0 : 255.0 / 224.0; - var yOffset = frame.FullRange ? 0 : 16; + int lumaBits = frame.BitDepthLuma - 8, chromaBits = frame.BitDepthChroma - 8; + var yScale = frame.FullRange ? 255.0 / ((1 << frame.BitDepthLuma) - 1) : 255.0 / (219 << lumaBits); + var cScale = frame.FullRange ? 255.0 / ((1 << frame.BitDepthChroma) - 1) : 255.0 / (224 << chromaBits); + var yOffset = frame.FullRange ? 0 : 16 << lumaBits; + var middle = 1 << (frame.BitDepthChroma - 1); const int Shift = 16; const double One = 1 << Shift; var cy = (int)Math.Round(yScale * One); @@ -549,7 +575,13 @@ public sealed class VideoFrameDecoder var width = Math.Max(1, frame.Width / factor); var height = Math.Max(1, frame.Height / factor); var rgb = new byte[width * height * 3]; - var cw = (frame.Width + 1) / 2; + var cw = frame.ChromaWidth; + var shiftX = frame.ChromaFormat == 3 ? 0 : 1; + var shiftY = frame.ChromaFormat is 2 or 3 ? 0 : 1; + var wide = frame.BytesPerSample == 2; + ReadOnlySpan y16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Y) : default; + ReadOnlySpan cb16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Cb) : default; + ReadOnlySpan cr16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Cr) : default; var area = factor * factor; for (var oy = 0; oy < height; oy++) { @@ -560,13 +592,25 @@ public sealed class VideoFrameDecoder { var y = (oy * factor) + dy; var lumaRow = y * frame.Width; - var chromaRow = (y >> 1) * cw; + var chromaRow = (y >> shiftY) * cw; for (var dx = 0; dx < factor; dx++) { var x = (ox * factor) + dx; - var l = (frame.Y[lumaRow + x] - yOffset) * cy; - var u = frame.Cb[chromaRow + (x >> 1)] - 128; - var v = frame.Cr[chromaRow + (x >> 1)] - 128; + var ci = chromaRow + (x >> shiftX); + int l, u, v; + if (wide) + { + l = (y16[lumaRow + x] - yOffset) * cy; + u = cb16[ci] - middle; + v = cr16[ci] - middle; + } + else + { + l = (frame.Y[lumaRow + x] - yOffset) * cy; + u = frame.Cb[ci] - middle; + v = frame.Cr[ci] - middle; + } + r += Clip((l + (crR * v) + Half) >> Shift); g += Clip((l - (cbG * u) - (crG * v) + Half) >> Shift); b += Clip((l + (cbB * u) + Half) >> Shift); diff --git a/tests/Febe.Tests/Media/Containers/TestVideos.cs b/tests/Febe.Tests/Media/Containers/TestVideos.cs index 3dea09d..879d3b3 100644 --- a/tests/Febe.Tests/Media/Containers/TestVideos.cs +++ b/tests/Febe.Tests/Media/Containers/TestVideos.cs @@ -59,7 +59,7 @@ internal sealed class ElementaryStream /// MD5 values of frames in output order. public static List Md5InOutputOrder(IEnumerable frames) => frames.OrderBy(f => f.Period).ThenBy(f => f.Poc).ThenBy(f => f.DecodeIndex) - .Select(f => Convert.ToHexStringLower(MD5.HashData(f.ToI420()))) + .Select(f => Convert.ToHexStringLower(MD5.HashData(f.ToPlanar()))) .ToList(); public static ElementaryStream Load(string name) => FromAnnexB(name, AnnexB(name)); diff --git a/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs b/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs index cbc7a5f..9717895 100644 --- a/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs +++ b/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs @@ -104,6 +104,44 @@ public sealed class VideoFrameDecoderTests Assert.IsTrue(other[1] > 20, $"{other[0]} {other[1]} {other[2]}"); } + [TestMethod] + public void TenBitSamplesKeepTheirRange() + { + // 10 bits, two bytes each, little-endian: limited range has black at 64, white at 940, neutral chroma at 512. + static byte[] Samples(int count, int value) => [.. Enumerable.Range(0, count).SelectMany(_ => new[] { (byte)value, (byte)(value >> 8) })]; + static H264Frame Flat(int y, int cb, int cr, bool full) => + new(2, 2, Samples(4, y), Samples(1, cb), Samples(1, cr), 0, 0, 0, 1, full, ChromaFormat: 1, BitDepthLuma: 10, BitDepthChroma: 10); + + CollectionAssert.AreEqual(new byte[] { 0, 0, 0 }, VideoFrameDecoder.ToImage(Flat(64, 512, 512, false), 0, 0).Rgb[..3]); + CollectionAssert.AreEqual(new byte[] { 255, 255, 255 }, VideoFrameDecoder.ToImage(Flat(940, 512, 512, false), 0, 0).Rgb[..3]); + CollectionAssert.AreEqual(new byte[] { 255, 255, 255 }, VideoFrameDecoder.ToImage(Flat(1023, 512, 512, true), 0, 0).Rgb[..3]); + + // Pure red of BT.709 at 8 bits (Y 63, Cb 102, Cr 240) is the same colour at 10 bits (× 4). + var eight = VideoFrameDecoder.ToImage(new H264Frame(2, 2, [63, 63, 63, 63], [102], [240], 0, 0, 0, 1, false), 0, 0).Rgb[..3]; + var ten = VideoFrameDecoder.ToImage(Flat(63 * 4, 102 * 4, 240 * 4, false), 0, 0).Rgb[..3]; + for (var i = 0; i < 3; i++) + { + Assert.IsLessThanOrEqualTo(1, Math.Abs(eight[i] - ten[i]), $"componente {i}: {eight[i]} e {ten[i]}"); + } + } + + [TestMethod] + [DataRow(2)] + [DataRow(3)] + public void EveryChromaSamplingReachesItsOwnPixels(int chromaFormat) + { + // A 2×2 frame of grey luma; in 4:2:2 each row has its own chroma sample, in 4:4:4 each pixel. The top row is + // blue (Cb high), the bottom one red (Cr high). + var cw = chromaFormat == 3 ? 2 : 1; + byte[] cb = [.. Enumerable.Repeat((byte)200, cw), .. Enumerable.Repeat((byte)128, cw)]; + byte[] cr = [.. Enumerable.Repeat((byte)128, cw), .. Enumerable.Repeat((byte)200, cw)]; + var frame = new H264Frame(2, 2, [128, 128, 128, 128], cb, cr, 0, 0, 0, 1, true, ChromaFormat: chromaFormat); + var rgb = VideoFrameDecoder.ToImage(frame, 0, 0).Rgb; + Assert.IsGreaterThan(rgb[0] + 50, (int)rgb[2], "in alto prevale il blu"); + Assert.IsGreaterThan(rgb[(2 * 3) + 2] + 50, (int)rgb[2 * 3], "in basso prevale il rosso"); + CollectionAssert.AreEqual(rgb[..3], rgb[3..6], "la riga in alto è uniforme"); + } + [TestMethod] public async Task AVideoOfAStillPictureIsRecognised() { diff --git a/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md b/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md index 804dfe9..a025e98 100644 --- a/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md +++ b/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md @@ -40,7 +40,8 @@ del riferimento. ## I flussi verificati -`H264ConformanceTests.FramesMatchTheReference`, tutti 4:2:0 a 8 bit. A immagini intere, sulla sequenza «Foreman»: +`H264ConformanceTests.FramesMatchTheReference`: 4:2:0 a 8 bit, poi 4:2:2 a 8 e 10 bit e 4:0:0. A immagini intere, sulla +sequenza «Foreman»: | Flusso | Profilo, formato | Che cosa prova | |---|---|---| @@ -106,17 +107,9 @@ Per gli strumenti che nessun flusso della serie usa, `H264ExtendedToolsTests` ri Le slice SI e `sp_for_switch_flag` a 1 non hanno flussi: le prova un flusso sintetico di `H264SyntheticStreamTests`, con i valori calcolati a mano dalle equazioni di §8.6.2. -`H264ConformanceTests.SvcBaseLayerMatchesTheReference`: lo strato base dei tre flussi SVC qui sotto, con -`riferimento-base.md5`. +Formati di High 4:2:2 e High, CIF; oltre gli 8 bit due byte little-endian per campione. -## I flussi delle parti ancora da fare - -`H264ConformanceTests.FeaturesStillToDo`: il decodificatore oggi rifiuta queste parti con un'`H264Exception` (o, per SVC -e MVC, dà solo lo strato o la vista base), e la prova è **inconclusiva** con il messaggio «da fare: …», così la serie -resta verde e il vuoto si vede. Quando una di queste coincide con il riferimento la prova **fallisce** apposta, per -ricordare di spostarla fra i flussi verificati. - -**4:2:2, 8 e 10 bit** (High 4:2:2), CIF, 5 fotogrammi ciascuno: +**4:2:2, 8 e 10 bit** (High 4:2:2), 5 fotogrammi ciascuno: | Flusso | Che cosa prova | |---|---| @@ -129,8 +122,23 @@ ricordare di spostarla fra i flussi verificati. | `FREXT2_TANDBERG_A` | 8 bit, slice I e P, CAVLC, deblocking attivo | | `FREXT3_TANDBERG_A` | 8 bit, slice I, B e P, CAVLC | -**Monocromatico 4:0:0** (High), CIF, 100 fotogrammi: `HPCAMOLQ_BRCM_B` (CABAC) e `HPCVMOLQ_BRCM_B` (CAVLC), con -slice B, diretta temporale e matrici di quantizzazione. +**Monocromatico 4:0:0** (High), 100 fotogrammi: `HPCAMOLQ_BRCM_B` (CABAC) e `HPCVMOLQ_BRCM_B` (CAVLC), con +slice B, diretta temporale e matrici di quantizzazione; escono con i due piani di crominanza 4:2:0 al valore medio, +come nel file ufficiale. + +Le parti dei profili High che la serie qui non ha con la ricostruzione (4:4:4, piani di colore separati, codifica senza +perdita con la sua DPCM, profondità da 11 a 14 bit, 10 bit in 4:2:0) le prova `H264FormatTests` con flussi sintetici +di I_PCM e di Intra_16x16 senza perdita, i cui campioni si conoscono esattamente. Il CABAC in 4:4:4 con i piani insieme +non è gestito (mancano i contesti 460–1023) e il decodificatore lo rifiuta. + +`H264ConformanceTests.SvcBaseLayerMatchesTheReference`: lo strato base dei tre flussi SVC qui sotto, con +`riferimento-base.md5`. + +## I flussi delle parti ancora da fare + +`H264ConformanceTests.FeaturesStillToDo`: per SVC e MVC il decodificatore dà solo lo strato o la vista base, e la +prova è **inconclusiva** con il messaggio «da fare: …», così la serie resta verde e il vuoto si vede. Quando una di queste coincide con il riferimento la prova **fallisce** apposta, per +ricordare di spostarla fra i flussi verificati. **SVC** (Scalable Baseline; lo strato base è Baseline): diff --git a/tests/Febe.Tests/Media/H264/H264ConformanceTests.cs b/tests/Febe.Tests/Media/H264/H264ConformanceTests.cs index e8857c2..0ea5b09 100644 --- a/tests/Febe.Tests/Media/H264/H264ConformanceTests.cs +++ b/tests/Febe.Tests/Media/H264/H264ConformanceTests.cs @@ -9,12 +9,14 @@ namespace Febe.Tests.Codecs.H264; /// MD5 of the corresponding frame of the official reconstruction (see Conformita/LEGGIMI.md). The verified streams include /// interlaced video — field pictures, PAFF, MBAFF, both together — with memory management operations, long-term /// references and POC type 1 on fields (MR6_BT_B, MR9_BT_B), slice groups of every map type with slices in any order -/// (FM1_BT_B, FM1_FT_E, FM2_SVA_C) and SP slices (sp1_bt_a, sp2_bt_b; sp2 with the deblocking filter on). None of them +/// (FM1_BT_B, FM1_FT_E, FM2_SVA_C), SP slices (sp1_bt_a, sp2_bt_b; sp2 with the deblocking filter on), 4:2:2 at 8 and 10 +/// bits with CABAC and CAVLC (Hi422FR10–15_SONY_A, FREXT2/3_TANDBERG_A) and monochrome 4:0:0 (HPCAMOLQ_BRCM_B, +/// HPCVMOLQ_BRCM_B). None of them /// uses weighted prediction, gaps in frame_num, I_PCM, SI slices, sp_for_switch_flag, data partitioning or redundant /// slices: data partitioning, redundant slices and other slice orders are checked on conformance streams rewritten by /// (), SI slices and the rest by /// , without an official reference. The streams of the parts the decoder does not -/// handle yet (4:2:2, more than 8 bits, 4:0:0, SVC, MVC) are in : they are inconclusive +/// handle yet (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. /// @@ -56,6 +58,16 @@ public sealed class H264ConformanceTests [DataRow("FM1_BT_B")] [DataRow("sp1_bt_a")] [DataRow("sp2_bt_b")] + [DataRow("Hi422FR10_SONY_A")] + [DataRow("Hi422FR11_SONY_A")] + [DataRow("Hi422FR12_SONY_A")] + [DataRow("Hi422FR13_SONY_A")] + [DataRow("Hi422FR14_SONY_A")] + [DataRow("Hi422FR15_SONY_A")] + [DataRow("FREXT2_TANDBERG_A")] + [DataRow("FREXT3_TANDBERG_A")] + [DataRow("HPCAMOLQ_BRCM_B")] + [DataRow("HPCVMOLQ_BRCM_B")] public void FramesMatchTheReference(string name) => AssertMatches(name, "riferimento.md5"); [TestMethod] @@ -70,16 +82,6 @@ public sealed class H264ConformanceTests } [TestMethod] - [DataRow("Hi422FR10_SONY_A", "4:2:2 a 8 bit, solo slice I (CABAC)")] - [DataRow("Hi422FR11_SONY_A", "4:2:2 a 8 bit con slice P (CABAC)")] - [DataRow("Hi422FR12_SONY_A", "4:2:2 a 8 bit con slice B (CABAC)")] - [DataRow("Hi422FR13_SONY_A", "4:2:2 a 10 bit, solo slice I (CABAC)")] - [DataRow("Hi422FR14_SONY_A", "4:2:2 a 10 bit con slice P (CABAC)")] - [DataRow("Hi422FR15_SONY_A", "4:2:2 a 10 bit con slice B (CABAC)")] - [DataRow("FREXT2_TANDBERG_A", "4:2:2 a 8 bit con slice P (CAVLC)")] - [DataRow("FREXT3_TANDBERG_A", "4:2:2 a 8 bit con slice B (CAVLC)")] - [DataRow("HPCAMOLQ_BRCM_B", "monocromatico 4:0:0 (CABAC, High)")] - [DataRow("HPCVMOLQ_BRCM_B", "monocromatico 4:0:0 (CAVLC, High)")] [DataRow("SVCBMT-13", "SVC, qualità MGS e scalabilità temporale (strato L2)")] [DataRow("SVCBST-19", "SVC, scalabilità spaziale e temporale (strato L1, 640×480)")] [DataRow("SVCBCT-1", "SVC, qualità CGS e scalabilità temporale (strato L1)")] @@ -154,7 +156,7 @@ public sealed class H264ConformanceTests { var expected = all.Single(f => f.DecodeIndex == frame.DecodeIndex); Assert.AreEqual((expected.Poc, expected.Period), (frame.Poc, frame.Period), $"{name}: ordine del fotogramma {frame.DecodeIndex}"); - CollectionAssert.AreEqual(expected.ToI420(), frame.ToI420(), $"{name}: fotogramma {frame.DecodeIndex}"); + CollectionAssert.AreEqual(expected.ToPlanar(), frame.ToPlanar(), $"{name}: fotogramma {frame.DecodeIndex}"); } } @@ -222,7 +224,7 @@ public sealed class H264ConformanceTests private static List OutputOrder(List frames) => frames.OrderBy(f => f.Period).ThenBy(f => f.Poc).ThenBy(f => f.DecodeIndex).ToList(); - private static string Md5(H264Frame frame) => Convert.ToHexStringLower(MD5.HashData(frame.ToI420())); + private static string Md5(H264Frame frame) => Convert.ToHexStringLower(MD5.HashData(frame.ToPlanar())); /// /// The frame MD5s of a riferimento.md5, in output order, and the number of frames its first line declares (0 when diff --git a/tests/Febe.Tests/Media/H264/H264FormatTests.cs b/tests/Febe.Tests/Media/H264/H264FormatTests.cs new file mode 100644 index 0000000..d56f489 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/H264FormatTests.cs @@ -0,0 +1,178 @@ +using Febe.Core.Codecs.H264; +using static Febe.Tests.Codecs.H264.SyntheticStreams; + +namespace Febe.Tests.Codecs.H264; + +/// +/// The formats of the High profiles on tiny streams written by , where the conformance +/// streams in the repository have no reference: every chroma format at every bit depth, the colour planes of 4:4:4 +/// coded separately, lossless macroblocks with their DPCM, the CABAC of 4:4:4 that is refused. +/// +[TestClass] +public sealed class H264FormatTests +{ + [TestMethod] + [DataRow(0, 8, 8)] + [DataRow(0, 12, 9)] + [DataRow(1, 10, 10)] + [DataRow(1, 8, 10)] + [DataRow(2, 12, 9)] + [DataRow(3, 14, 14)] + [DataRow(3, 9, 8)] + public void PcmSamplesKeepTheirFormatAndBitDepth(int chromaFormat, int bitDepthLuma, int bitDepthChroma) + { + // Two I_PCM macroblocks side by side: every sample is written as it is, at its bit depth. + var h = new HighSettings(chromaFormat, bitDepthLuma, bitDepthChroma, WidthInMbs: 2); + int luma = (1 << bitDepthLuma) - 3, cb = (1 << (bitDepthChroma - 1)) - 7, cr = (1 << bitDepthChroma) - 2; + var frames = Decode([.. HighSps(h), .. HighPps(h), .. HighIdr(h, b => + { + Pcm(b, h, luma, cb, cr); + Pcm(b, h, luma, cb, cr); + })]); + + Assert.HasCount(1, frames); + var f = frames[0]; + Assert.AreEqual(32, f.Width); + Assert.AreEqual(16, f.Height); + Assert.AreEqual(chromaFormat, f.ChromaFormat); + Assert.AreEqual(bitDepthLuma, f.BitDepthLuma); + + // Monochrome comes out with 4:2:0 chroma at the middle value, at the luma bit depth (as the reference decoder writes it). + var depthC = chromaFormat == 0 ? bitDepthLuma : bitDepthChroma; + Assert.AreEqual(depthC, f.BitDepthChroma); + var bytes = Math.Max(bitDepthLuma, depthC) > 8 ? 2 : 1; + Assert.HasCount(32 * 16 * bytes, f.Y); + var (cw, ch) = chromaFormat switch + { + 3 => (32, 16), + 2 => (16, 16), + _ => (16, 8), + }; + Assert.AreEqual(cw, f.ChromaWidth); + Assert.AreEqual(ch, f.ChromaHeight); + Assert.HasCount(cw * ch * bytes, f.Cb); + Assert.HasCount(cw * ch * bytes, f.Cr); + for (var i = 0; i < 32 * 16; i++) + { + Assert.AreEqual(luma, f.LumaAt(i), $"luma {i}"); + } + + int expectedCb = chromaFormat == 0 ? 1 << (depthC - 1) : cb, expectedCr = chromaFormat == 0 ? 1 << (depthC - 1) : cr; + for (var i = 0; i < cw * ch; i++) + { + Assert.AreEqual(expectedCb, f.ChromaAt(f.Cb, i), $"Cb {i}"); + Assert.AreEqual(expectedCr, f.ChromaAt(f.Cr, i), $"Cr {i}"); + } + } + + [TestMethod] + [DataRow(8)] + [DataRow(10)] + public void SeparateColourPlanesMakeOneFrame(int bitDepth) + { + // separate_colour_plane_flag: three slices of the same IDR picture, one per colour_plane_id, each a monochrome + // picture of I_PCM macroblocks at the luma bit depth. + var h = new HighSettings(3, bitDepth, bitDepth, SeparatePlanes: true, WidthInMbs: 2); + int[] values = [11 << (bitDepth - 8), 22 << (bitDepth - 8), 33 << (bitDepth - 8)]; + var stream = new List([.. HighSps(h), .. HighPps(h)]); + for (var plane = 0; plane < 3; plane++) + { + var v = values[plane]; + stream.AddRange(HighIdr(h, b => + { + Pcm(b, h, v, 0, 0); + Pcm(b, h, v, 0, 0); + }, plane)); + } + + var frames = Decode([.. stream]); + Assert.HasCount(1, frames); + var f = frames[0]; + Assert.AreEqual(3, f.ChromaFormat); + Assert.AreEqual(bitDepth, f.BitDepthChroma); + Assert.AreEqual(32, f.ChromaWidth); + for (var i = 0; i < 32 * 16; i++) + { + Assert.AreEqual(values[0], f.LumaAt(i), $"Y {i}"); + Assert.AreEqual(values[1], f.ChromaAt(f.Cb, i), $"Cb {i}"); + Assert.AreEqual(values[2], f.ChromaAt(f.Cr, i), $"Cr {i}"); + } + } + + [TestMethod] + [DataRow(0, 8, 1)] + [DataRow(0, 8, 0)] + [DataRow(0, 8, 2)] + [DataRow(0, 10, 1)] + [DataRow(1, 8, 0)] + [DataRow(2, 10, 1)] + [DataRow(3, 8, 1)] + [DataRow(3, 8, 0)] + [DataRow(3, 12, 2)] + public void ALosslessMacroblockAccumulatesItsResidual(int chromaFormat, int bitDepth, int mode) + { + // An I_PCM macroblock, then an Intra_16x16 one predicted from it at QP′Y 0 with qpprime_y_zero_transform_bypass_flag: + // lossless (§8.5.15). Its only residual is a DC level on the first 4×4 block of each luma-like plane, taken as + // it is (no transform, no scaling) and accumulated along the prediction: horizontal (mode 1) adds it to the whole + // first row, vertical (mode 0, the I_PCM macroblock above) to the whole first column, DC (mode 2) only to the + // first sample. + var vertical = mode == 0; + var h = new HighSettings(chromaFormat, bitDepth, bitDepth, Lossless: true, WidthInMbs: vertical ? 1 : 2, HeightInMbs: vertical ? 2 : 1); + var shift = bitDepth - 8; + int[] pcm = [100 << shift, 60 << shift, 180 << shift]; + int[] dc = [1, 2, -1]; + var frames = Decode([.. HighSps(h), .. HighPps(h), .. HighIdr(h, b => + { + Pcm(b, h, pcm[0], pcm[1], pcm[2]); + Intra16x16Dc(b, h, mode, dc); + })]); + + Assert.HasCount(1, frames); + var f = frames[0]; + var planes = chromaFormat == 3 ? 3 : 1; + for (var p = 0; p < planes; p++) + { + var plane = p == 0 ? f.Y : p == 1 ? f.Cb : f.Cr; + for (var y = 0; y < 16; y++) + { + for (var x = 0; x < 16; x++) + { + var touched = mode == 1 ? y == 0 : mode == 0 ? x == 0 : x == 0 && y == 0; + var expected = pcm[p] + (touched ? dc[p] : 0); + var index = vertical ? ((16 + y) * 16) + x : (y * 32) + 16 + x; + var actual = p == 0 ? f.LumaAt(index) : f.ChromaAt(plane, index); + Assert.AreEqual(expected, actual, $"piano {p}, ({x}, {y})"); + } + } + } + + if (chromaFormat is 1 or 2) + { + // Chroma: DC prediction from the I_PCM chroma, no residual. + for (var i = 0; i < f.ChromaWidth * f.ChromaHeight; i++) + { + Assert.AreEqual(pcm[1], f.ChromaAt(f.Cb, i), $"Cb {i}"); + Assert.AreEqual(pcm[2], f.ChromaAt(f.Cr, i), $"Cr {i}"); + } + } + } + + [TestMethod] + public void CabacIn444IsRefusedUntilItsContextsAreWritten() + { + // The residual of Cb and Cr of 4:4:4 with CABAC needs the contexts 460–1023: not transcribed yet, so the slice is + // refused rather than decoded wrong. + var h = new HighSettings(3, Cabac: true); + Assert.ThrowsExactly(() => Decode([.. HighSps(h), .. HighPps(h), .. HighIdr(h, b => b.Bits(0, 8))])); + } + + private static List Decode(byte[] stream) + { + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(stream); + decoder.Flush(); + return frames; + } +} diff --git a/tests/Febe.Tests/Media/H264/H264TablesTests.cs b/tests/Febe.Tests/Media/H264/H264TablesTests.cs index 9e3efb9..32ae67d 100644 --- a/tests/Febe.Tests/Media/H264/H264TablesTests.cs +++ b/tests/Febe.Tests/Media/H264/H264TablesTests.cs @@ -41,6 +41,8 @@ public sealed class H264TablesTests { CollectionAssert.AreEquivalent(Enumerable.Range(0, 48).ToArray(), H264Tables.CbpIntra.Select(b => (int)b).ToArray()); CollectionAssert.AreEquivalent(Enumerable.Range(0, 48).ToArray(), H264Tables.CbpInter.Select(b => (int)b).ToArray()); + CollectionAssert.AreEquivalent(Enumerable.Range(0, 16).ToArray(), H264Tables.CbpIntraNoChroma.Select(b => (int)b).ToArray()); + CollectionAssert.AreEquivalent(Enumerable.Range(0, 16).ToArray(), H264Tables.CbpInterNoChroma.Select(b => (int)b).ToArray()); } [TestMethod] diff --git a/tests/Febe.Tests/Media/H264/SyntheticStreams.cs b/tests/Febe.Tests/Media/H264/SyntheticStreams.cs index a3af7c1..b06bcf5 100644 --- a/tests/Febe.Tests/Media/H264/SyntheticStreams.cs +++ b/tests/Febe.Tests/Media/H264/SyntheticStreams.cs @@ -203,6 +203,183 @@ internal static class SyntheticStreams return Nal(0x65, bits); } + /// + /// Settings of a High 4:4:4 Predictive sequence (profile_idc 244): chroma format, bit depths, separate colour planes, + /// lossless macroblocks (qpprime_y_zero_transform_bypass_flag, with the slices at QP′Y 0), CABAC. + /// + internal sealed record HighSettings( + int ChromaFormat = 1, + int BitDepthLuma = 8, + int BitDepthChroma = 8, + bool SeparatePlanes = false, + bool Lossless = false, + int WidthInMbs = 1, + int HeightInMbs = 1, + bool Cabac = false) + { + /// ChromaArrayType: no chroma syntax for monochrome and separate planes. + internal int ChromaArrayType => SeparatePlanes ? 0 : ChromaFormat; + + /// Chroma samples of each component in a macroblock. + internal int ChromaSamples => ChromaArrayType switch + { + 0 => 0, + 1 => 64, + 2 => 128, + _ => 256, + }; + } + + /// The sequence parameter set of (§7.3.2.1.1), POC type 2, no VUI. + internal static byte[] HighSps(HighSettings h) + { + var bits = new BitWriter(); + bits.Bits(244, 8); // profile_idc: High 4:4:4 Predictive + bits.Bits(0, 8); // constraint flags + bits.Bits(30, 8); // level_idc + bits.Ue(0); // seq_parameter_set_id + bits.Ue((uint)h.ChromaFormat); + if (h.ChromaFormat == 3) + { + bits.Bits(h.SeparatePlanes ? 1u : 0u, 1); + } + + bits.Ue((uint)h.BitDepthLuma - 8); + bits.Ue((uint)h.BitDepthChroma - 8); + bits.Bits(h.Lossless ? 1u : 0u, 1); // qpprime_y_zero_transform_bypass_flag + bits.Bits(0, 1); // seq_scaling_matrix_present_flag + bits.Ue(0); // log2_max_frame_num_minus4 + bits.Ue(2); // pic_order_cnt_type + bits.Ue(1); // max_num_ref_frames + bits.Bits(0, 1); // gaps_in_frame_num_value_allowed_flag + bits.Ue((uint)h.WidthInMbs - 1); + bits.Ue((uint)h.HeightInMbs - 1); + bits.Bits(1, 1); // frame_mbs_only_flag + bits.Bits(1, 1); // direct_8x8_inference_flag + bits.Bits(0, 1); // frame_cropping_flag + bits.Bits(0, 1); // vui_parameters_present_flag + return Nal(0x67, bits); + } + + /// The picture parameter set of : QP′Y 0 (QPY −QpBdOffsetY) when lossless, else 26. + internal static byte[] HighPps(HighSettings h) + { + var bits = new BitWriter(); + bits.Ue(0); // pic_parameter_set_id + bits.Ue(0); // seq_parameter_set_id + bits.Bits(h.Cabac ? 1u : 0u, 1); // entropy_coding_mode_flag + bits.Bits(0, 1); // bottom_field_pic_order_in_frame_present_flag + bits.Ue(0); // num_slice_groups_minus1 + bits.Ue(0); // num_ref_idx_l0_default_active_minus1 + bits.Ue(0); // num_ref_idx_l1_default_active_minus1 + bits.Bits(0, 1); // weighted_pred_flag + bits.Bits(0, 2); // weighted_bipred_idc + bits.Se(h.Lossless ? -26 - (6 * (h.BitDepthLuma - 8)) : 0); // pic_init_qp_minus26 + bits.Se(0); // pic_init_qs_minus26 + bits.Se(0); // chroma_qp_index_offset + bits.Bits(1, 1); // deblocking_filter_control_present_flag + bits.Bits(0, 1); // constrained_intra_pred_flag + bits.Bits(0, 1); // redundant_pic_cnt_present_flag + return Nal(0x68, bits); + } + + /// + /// One I slice of an IDR picture of (for separate planes, the slice of ), + /// deblocking off, its macroblocks written by . + /// + internal static byte[] HighIdr(HighSettings h, Action macroblocks, int colourPlane = 0) + { + var bits = new BitWriter(); + bits.Ue(0); // first_mb_in_slice + bits.Ue(7); // slice_type: I (all slices of the picture) + bits.Ue(0); // pic_parameter_set_id + if (h.SeparatePlanes) + { + bits.Bits((uint)colourPlane, 2); + } + + bits.Bits(0, 4); // frame_num + bits.Ue(0); // idr_pic_id + bits.Bits(0, 1); // no_output_of_prior_pics_flag + bits.Bits(0, 1); // long_term_reference_flag + bits.Se(0); // slice_qp_delta + bits.Ue(1); // disable_deblocking_filter_idc: off + macroblocks(bits); + return Nal(0x65, bits); + } + + /// + /// An I_PCM macroblock (CAVLC): its luma samples all , then (with chroma syntax) Cb and Cr all + /// and , at the bit depths of . + /// + internal static void Pcm(BitWriter bits, HighSettings h, int luma, int cb, int cr) + { + bits.Ue(25); // mb_type: I_PCM + bits.Align(); // pcm_alignment_zero_bit + for (var i = 0; i < 256; i++) + { + bits.Bits((uint)luma, h.BitDepthLuma); + } + + for (var c = 0; c < 2; c++) + { + for (var i = 0; i < h.ChromaSamples; i++) + { + bits.Bits((uint)(c == 0 ? cb : cr), h.BitDepthChroma); + } + } + } + + /// + /// An Intra_16x16 macroblock (CAVLC) without AC residual, prediction mode (0 vertical, + /// 1 horizontal, 2 DC; chroma DC if the chroma has syntax), and in each luma-like plane (Y; Cb and Cr too in 4:4:4) one + /// DC level of on the first block. The neighbour it predicts from must be I_PCM: its blocks + /// count 16 coefficients, so nC is 16 and coeff_token the 6-bit code of §9.2.1. + /// + internal static void Intra16x16Dc(BitWriter bits, HighSettings h, int mode, int[] dc) + { + bits.Ue((uint)(1 + mode)); // mb_type: I_16x16__0_0 + if (h.ChromaArrayType is 1 or 2) + { + bits.Ue(0); // intra_chroma_pred_mode: DC + } + + bits.Se(0); // mb_qp_delta + var planes = h.ChromaArrayType == 3 ? 3 : 1; + for (var p = 0; p < planes; p++) + { + var level = dc[p]; + if (level == 0) + { + bits.Bits(0b000011, 6); // coeff_token: TotalCoeff 0 + continue; + } + + if (Math.Abs(level) == 1) + { + bits.Bits(0b000001, 6); // coeff_token: TotalCoeff 1, TrailingOnes 1 + bits.Bits(level < 0 ? 1u : 0u, 1); // trailing_ones_sign_flag + } + else + { + // coeff_token: TotalCoeff 1, TrailingOnes 0; level_prefix with suffixLength 0, the first level after + // fewer than three trailing ones counting from 2 (levelCode = 2 |level| − 4, + 1 when negative). + bits.Bits(0b000000, 6); + var levelCode = (2 * Math.Abs(level)) - 4 + (level < 0 ? 1 : 0); + if (levelCode >= 14) + { + throw new ArgumentOutOfRangeException(nameof(dc), "Livello troppo grande per questo flusso di prova."); + } + + bits.Bits(1, levelCode + 1); // level_prefix: levelCode zeros then a one + } + + bits.Bits(1, 1); // total_zeros: 0 + } + + // No chroma residual: the mb_type says coded_block_pattern chroma 0. + } + private static byte[] Nal(byte header, BitWriter bits) { bits.Bits(1, 1); // rbsp_stop_one_bit