diff --git a/docs/decisioni.md b/docs/decisioni.md
index aa18f8b..34a2b00 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 | Per il decodificatore HEVC si tengono nel repository 146 flussi della serie di conformità ITU-T H.265.1 (136 Main, Main 10 e Main Still Picture, 10 RExt), circa 29 MB, in `tests/Febe.Tests/Media/H265/Conformita`: flusso, `readme` originale e `riferimento.md5` con l'MD5 di tutto il YUV ufficiale e, per i 15 flussi che hanno il YUV nello zip, di ogni fotogramma. Le prove di decodifica sono inconcludenti finché il decodificatore non c'è, e quelle RExt finché Alberto non decide se servono; gli hash SEI delle immagini si leggono già con un lettore scritto dalla norma (D.3.19) | Un riferimento ufficiale per ogni strumento di HEVC prima di scriverne il decodificatore, senza i YUV (centinaia di MB) e senza i flussi grandi già coperti da altri (elenco in LEGGIMI.md). Le 146 prove inconcludenti sono saltate per la CI, che oggi non ne ammette nessuna: il ramo non passa la verifica finché il decodificatore o una regola diversa non le toglie |
| 2026-11-18 | Decodificatore HEVC (ITU-T H.265), prima parte, scritto in casa in `src/Febe.Core/Codecs/H265` accanto a quello H.264: unità NAL Annex B e `hvcC`, VPS/SPS/PPS con liste di scala, VUI e indicatori RExt, intestazione di slice, POC, RPS, DPB e uscita (C.5.2), CABAC con le tabelle d'inizio della norma, albero di codifica, unità di predizione, residui (sign data hiding, transform skip), predizione intra, trasformate, PCM, deblocking e SAO, tile, WPP e segmenti dipendenti. Riusa da H.264 `rangeTabLps`, `transIdxLps` e la lettura delle unità NAL. Le slice P e B si rifiutano con un'eccezione: la predizione inter è la tappa successiva; con un interruttore interno le prove ne leggono la sintassi fino a `end_of_slice_segment_flag`, con le unità di predizione grigie. Profili accettati: 4:2:0 fino a 12 bit senza strumenti RExt | I 12 flussi di sole slice I (Main, Main 10, Main Still Picture) coincidono col YUV ufficiale; nei 136 flussi Main e Main 10 ogni immagine di sole slice I coincide con l'MD5 SEI del codificatore, dove il flusso lo porta, e ogni slice P e B si legge fino in fondo: un primo controllo della sintassi inter, che senza predizione non si può confrontare con gli hash |
| 2026-11-18 | Decodificatore HEVC, seconda parte: predizione inter scritta dalla norma in `H265Decoder.Inter.cs` (liste di riferimento di §8.3.4 con le modifiche, merge con candidati spaziali, temporale, bi-predittivi combinati e nulli, livello di merge parallelo, AMVP con scala per distanza di POC, TMVP sull'immagine co-locata alla griglia di 16×16, interpolazione a 8 prese per la luma e 4 per il croma, predizione pesata di base ed esplicita, niente bi-predizione per 8×4 e 4×8) e intensità del deblocking dal moto (immagini di riferimento confrontate per identità, a prescindere dalla lista). Ogni immagine tiene il moto di ogni blocco 4×4, la slice di ogni CTB e le liste delle sue slice (POC e lungo termine), che servono a chi la prende come co-locata. Un riferimento che manca è un'immagine grigia, intra, fuori dal DPB e mai in uscita (§8.3.3.2, ma senza metterla nel DPB per non cambiare il riempimento del buffer). I filtri d'interpolazione lavorano 8 campioni per volta coi vettori della BCL (`Vector128`), a 16 bit quando i campioni sono a 8 bit | I 136 flussi Main, Main 10 e Main Still Picture della serie di conformità danno esattamente il YUV ufficiale (MD5 di tutto il file, e di ogni fotogramma dove c'è) e ogni immagine coincide col suo hash SEI dove il flusso lo porta: confermati anche il numero di fotogrammi e gli MD5 scelti per i flussi senza YUV. Coi vettori l'interpolazione costa circa la metà; 1080p a 8 bit va a 20–25 fotogrammi al secondo su questa macchina |
+| 2026-11-18 | Decodificatore HEVC, terza parte: anche le estensioni di formato (RExt), perché i loro 10 flussi sono nella serie di conformità: 4:0:0, 4:2:2 (due blocchi di croma quadrati per unità di trasformata con i loro cbf, modi intra della tabella 8-3, QP del croma senza la tabella del 4:2:0), 4:4:4 (un modo di croma per blocco NxN, croma filtrato come la luma), fino a 12 bit, predizione fra componenti, RDPCM implicito ed esplicito, rotazione e contesto unico del transform skip, smoothing intra spento, adattamento persistente di Rice (salvato e ripreso con i contesti di WPP e dei segmenti dipendenti), `chroma_qp_offset_list`, deblocking del croma sulla sua griglia di 8 campioni e SAO con CTB di croma non quadrati. Restano rifiutati con un'eccezione la precisione estesa e l'allineamento del CABAC, che nessun flusso della serie usa. Tile, WPP, segmenti dipendenti, liste di scala e riferimenti a lungo termine erano già nelle parti precedenti; una prova nuova controlla che ognuno sia acceso in almeno un flusso. Il ritaglio dei fotogrammi in uscita usa array non inizializzati | I 146 flussi della serie danno esattamente il YUV ufficiale e ogni immagine coincide col suo hash SEI dove c'è: nessuna prova è più inconcludente, quindi la regola della CI che non ne ammette di saltate è rispettata. La tabella 8-3 è stata ricavata dalla geometria degli angoli (spostamento orizzontale dimezzato) e confermata dagli hash di `ADJUST_IPRED_ANGLE_A` e dei flussi 4:2:2. Su questa macchina, in Release: 416×240 da 160 a 600 fotogrammi al secondo, 1080p a 8 bit 26–27 (35 senza la copia ritagliata), 4:2:2 a 10 bit 9; il deblocking e il SAO pesano circa un quinto, il resto è lettura CABAC e ricostruzione; nei cicli delle CTU non si alloca nulla |
diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.Filters.cs b/src/Febe.Core/Codecs/H265/H265Decoder.Filters.cs
index 4043f08..b57d60d 100644
--- a/src/Febe.Core/Codecs/H265/H265Decoder.Filters.cs
+++ b/src/Febe.Core/Codecs/H265/H265Decoder.Filters.cs
@@ -191,7 +191,7 @@ public sealed partial class H265Decoder
private static bool Far(int ax, int ay, int bx, int by) => Math.Abs(ax - bx) >= 4 || Math.Abs(ay - by) >= 4;
- /// Filters every vertical (or horizontal) edge of the picture: luma on the 8×8 grid, chroma on the 16×16 one.
+ /// Filters every vertical (or horizontal) edge of the picture: luma on the 8×8 grid, chroma on the 8×8 grid of chroma samples.
private void Deblock(Picture picture, bool vertical)
{
var edges = vertical ? edgeV : edgeH;
@@ -201,6 +201,14 @@ public sealed partial class H265Decoder
var scaleY = 1 << (sps.BitDepthY - 8);
var log2Ctb = sps.Log2CtbSize;
var checkFlags = pictureHasUnfilteredBlocks;
+
+ // Chroma edges (§8.7.2.5.5) lie on the 8×8 grid of chroma samples and are filtered in segments of 4 chroma
+ // samples, each taking bS and QP from the luma segment at its start: a vertical edge every 8 << sx luma columns,
+ // a segment every 4 << sy luma rows (and the other way round for horizontal edges).
+ var chroma = sps.ChromaArrayType != 0;
+ int sx = sps.ChromaShiftX, sy = sps.ChromaShiftY;
+ int edgeMask = vertical ? (8 << sx) - 1 : (8 << sy) - 1;
+ int segmentMask = vertical ? (4 << sy) - 1 : (4 << sx) - 1;
for (var gy = 0; gy < h4; gy++)
{
for (var gx = 0; gx < w4; gx++)
@@ -236,11 +244,10 @@ public sealed partial class H265Decoder
FilterLuma(luma, origin, vertical ? 1 : stride, vertical ? stride : 1, beta, tc, noP, noQ, maxY);
}
- // Chroma (§8.7.2.5.5): bS 2 only, edges on the chroma 8×8 grid; the segment of 4 chroma samples takes the
- // values of the first luma segment of its 8 luma samples.
- if (bS == 2 && (vertical ? (x & 15) == 0 && (y & 7) == 0 : (y & 15) == 0 && (x & 7) == 0))
+ // Chroma: bS 2 only.
+ if (bS == 2 && chroma && (vertical ? (x & edgeMask) == 0 && (y & segmentMask) == 0 : (y & edgeMask) == 0 && (x & segmentMask) == 0))
{
- FilterChromaEdge(picture, x >> 1, y >> 1, vertical, qpL, header.TcOffsetDiv2, noP, noQ);
+ FilterChromaEdge(picture, x >> sx, y >> sy, vertical, qpL, header.TcOffsetDiv2, noP, noQ);
}
}
}
@@ -254,8 +261,7 @@ public sealed partial class H265Decoder
var lines = Math.Min(4, vertical ? picture.ChromaHeight - yc : picture.ChromaWidth - xc);
for (var c = 1; c <= 2; c++)
{
- var qPi = qpL + (c == 1 ? pps.CbQpOffset : pps.CrQpOffset);
- var qpC = qPi < 30 ? qPi : qPi > 43 ? qPi - 6 : H265Tables.ChromaQp30To43[qPi - 30];
+ var qpC = H265Tables.ChromaQp(qpL + (c == 1 ? pps.CbQpOffset : pps.CrQpOffset), sps.ChromaArrayType);
var tc = H265Tables.Tc[Math.Clamp(qpC + 2 + (tcOffsetDiv2 * 2), 0, 53)] * scale;
if (tc == 0)
{
@@ -372,13 +378,14 @@ public sealed partial class H265Decoder
var log2Ctb = sps.Log2CtbSize;
var heightInCtbs = sps.HeightInCtbs;
Span neighbours = stackalloc bool[9];
- for (var c = 0; c < 3; c++)
+ var components = sps.ChromaArrayType == 0 ? 1 : 3;
+ for (var c = 0; c < components; c++)
{
var plane = picture.Planes[c];
var width = c == 0 ? picture.Width : picture.ChromaWidth;
var height = c == 0 ? picture.Height : picture.ChromaHeight;
- var shift = c == 0 ? 0 : 1;
- var ctbSize = (1 << log2Ctb) >> shift;
+ int sx = c == 0 ? 0 : sps.ChromaShiftX, sy = c == 0 ? 0 : sps.ChromaShiftY;
+ int ctbWidth = (1 << log2Ctb) >> sx, ctbHeight = (1 << log2Ctb) >> sy;
var bitDepth = c == 0 ? sps.BitDepthY : sps.BitDepthC;
var max = (1 << bitDepth) - 1;
if (saoSource.Length < plane.Length)
@@ -403,12 +410,12 @@ public sealed partial class H265Decoder
}
int cx = rs % widthInCtbs, cy = rs / widthInCtbs;
- int x0 = cx * ctbSize, y0 = cy * ctbSize;
- int x1 = Math.Min(x0 + ctbSize, width), y1 = Math.Min(y0 + ctbSize, height);
+ int x0 = cx * ctbWidth, y0 = cy * ctbHeight;
+ int x1 = Math.Min(x0 + ctbWidth, width), y1 = Math.Min(y0 + ctbHeight, height);
var offsets = saoOffset.AsSpan(at * 4, 4);
if (type == 1)
{
- SaoBand(plane, width, x0, y0, x1, y1, saoClass[at], offsets, bitDepth, max, shift);
+ SaoBand(plane, width, x0, y0, x1, y1, saoClass[at], offsets, bitDepth, max, sx, sy);
}
else
{
@@ -420,7 +427,7 @@ public sealed partial class H265Decoder
}
}
- SaoEdge(plane, width, x0, y0, x1, y1, saoClass[at], offsets, max, shift, neighbours);
+ SaoEdge(plane, width, x0, y0, x1, y1, saoClass[at], offsets, max, sx, sy, neighbours);
}
}
}
@@ -459,7 +466,7 @@ public sealed partial class H265Decoder
return pps.LoopFilterAcrossTilesEnabled || pps.TileIdRs[nb] == pps.TileIdRs[rs];
}
- private void SaoBand(ushort[] plane, int stride, int x0, int y0, int x1, int y1, int position, ReadOnlySpan offsets, int bitDepth, int max, int shift)
+ private void SaoBand(ushort[] plane, int stride, int x0, int y0, int x1, int y1, int position, ReadOnlySpan offsets, int bitDepth, int max, int sx, int sy)
{
Span table = stackalloc int[32];
for (var k = 0; k < 4; k++)
@@ -474,7 +481,7 @@ public sealed partial class H265Decoder
var row = y * stride;
for (var x = x0; x < x1; x++)
{
- if (check && (blockFlags[Grid(x << shift, y << shift)] & FlagNoFilter) != 0)
+ if (check && (blockFlags[Grid(x << sx, y << sy)] & FlagNoFilter) != 0)
{
continue;
}
@@ -489,7 +496,7 @@ public sealed partial class H265Decoder
}
}
- private void SaoEdge(ushort[] plane, int stride, int x0, int y0, int x1, int y1, int eoClass, ReadOnlySpan offsets, int max, int shift, ReadOnlySpan neighbours)
+ private void SaoEdge(ushort[] plane, int stride, int x0, int y0, int x1, int y1, int eoClass, ReadOnlySpan offsets, int max, int sx, int sy, ReadOnlySpan neighbours)
{
// hPos and vPos of table 8-14 (the second neighbour is the opposite of the first).
int dx = eoClass switch { 0 => -1, 1 => 0, 2 => -1, _ => 1 };
@@ -518,7 +525,7 @@ public sealed partial class H265Decoder
continue;
}
- if (check && (blockFlags[Grid(x << shift, y << shift)] & FlagNoFilter) != 0)
+ if (check && (blockFlags[Grid(x << sx, y << sy)] & FlagNoFilter) != 0)
{
continue;
}
diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.Inter.cs b/src/Febe.Core/Codecs/H265/H265Decoder.Inter.cs
index 80774e9..73d43ed 100644
--- a/src/Febe.Core/Codecs/H265/H265Decoder.Inter.cs
+++ b/src/Febe.Core/Codecs/H265/H265Decoder.Inter.cs
@@ -544,26 +544,34 @@ public sealed partial class H265Decoder
{
var weighted = slice.Type == SliceType.P ? pps.WeightedPred : pps.WeightedBipred;
var picture = cur!;
- for (var c = 0; c < 3; c++)
+ var components = sps.ChromaArrayType == 0 ? 1 : 3;
+ for (var c = 0; c < components; c++)
{
int x0 = xPb, y0 = yPb, w = width, h = height;
+ int mx0 = motion.X0, my0 = motion.Y0, mx1 = motion.X1, my1 = motion.Y1;
if (c > 0)
{
- x0 >>= 1;
- y0 >>= 1;
- w >>= 1;
- h >>= 1;
+ // Chroma vectors in eighths of a chroma sample (8-228, 8-229): mvCLX = mvLX * 2 / SubWidthC (SubHeightC).
+ int sx = sps.ChromaShiftX, sy = sps.ChromaShiftY;
+ x0 >>= sx;
+ y0 >>= sy;
+ w >>= sx;
+ h >>= sy;
+ mx0 <<= 1 - sx;
+ mx1 <<= 1 - sx;
+ my0 <<= 1 - sy;
+ my1 <<= 1 - sy;
}
var bitDepth = c == 0 ? sps.BitDepthY : sps.BitDepthC;
if (motion.Ref0 >= 0)
{
- Interpolate(slice.RefPicList[0][motion.Ref0], c, x0, y0, w, h, motion.X0, motion.Y0, bitDepth, predL0);
+ Interpolate(slice.RefPicList[0][motion.Ref0], c, x0, y0, w, h, mx0, my0, bitDepth, predL0);
}
if (motion.Ref1 >= 0)
{
- Interpolate(slice.RefPicList[1][motion.Ref1], c, x0, y0, w, h, motion.X1, motion.Y1, bitDepth, predL1);
+ Interpolate(slice.RefPicList[1][motion.Ref1], c, x0, y0, w, h, mx1, my1, bitDepth, predL1);
}
var plane = picture.Planes[c];
diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.Intra.cs b/src/Febe.Core/Codecs/H265/H265Decoder.Intra.cs
index ae255e9..d9c5bd7 100644
--- a/src/Febe.Core/Codecs/H265/H265Decoder.Intra.cs
+++ b/src/Febe.Core/Codecs/H265/H265Decoder.Intra.cs
@@ -22,19 +22,20 @@ public sealed partial class H265Decoder
var bitDepth = cIdx == 0 ? sps.BitDepthY : sps.BitDepthC;
var n = 1 << log2;
var n2 = 2 * n;
- var shift = cIdx == 0 ? 0 : 1; // 4:2:0
- var unit = 4 >> shift;
- int xL = x0 << shift, yL = y0 << shift;
+ // Neighbours are looked up in luma locations; availability is known by 4×4 luma blocks.
+ int sx = cIdx == 0 ? 0 : sps.ChromaShiftX, sy = cIdx == 0 ? 0 : sps.ChromaShiftY;
+ int unitV = 4 >> sy, unitH = 4 >> sx;
+ int xL = x0 << sx, yL = y0 << sy;
var line = refLine.AsSpan(0, (4 * n) + 1);
var available = refAvailable.AsSpan(0, (4 * n) + 1);
var constrained = pps.ConstrainedIntraPred;
var any = false;
// Left and below-left, top to bottom.
- for (var k = 0; k < n2; k += unit)
+ for (var k = 0; k < n2; k += unitV)
{
- var ok = IntraNeighbour(xL, yL, (x0 - 1) << shift, (y0 + k) << shift, constrained);
- for (var j = 0; j < unit; j++)
+ var ok = IntraNeighbour(xL, yL, (x0 - 1) << sx, (y0 + k) << sy, constrained);
+ for (var j = 0; j < unitV; j++)
{
var index = n2 - 1 - (k + j);
available[index] = ok;
@@ -47,7 +48,7 @@ public sealed partial class H265Decoder
any |= ok;
}
- var corner = IntraNeighbour(xL, yL, (x0 - 1) << shift, (y0 - 1) << shift, constrained);
+ var corner = IntraNeighbour(xL, yL, (x0 - 1) << sx, (y0 - 1) << sy, constrained);
available[n2] = corner;
if (corner)
{
@@ -56,19 +57,19 @@ public sealed partial class H265Decoder
}
// Above and above-right, left to right.
- for (var k = 0; k < n2; k += unit)
+ for (var k = 0; k < n2; k += unitH)
{
- var ok = IntraNeighbour(xL, yL, (x0 + k) << shift, (y0 - 1) << shift, constrained);
+ var ok = IntraNeighbour(xL, yL, (x0 + k) << sx, (y0 - 1) << sy, constrained);
if (ok)
{
- plane.AsSpan(((y0 - 1) * stride) + x0 + k, unit).CopyTo(refRow);
- for (var j = 0; j < unit; j++)
+ plane.AsSpan(((y0 - 1) * stride) + x0 + k, unitH).CopyTo(refRow);
+ for (var j = 0; j < unitH; j++)
{
line[n2 + 1 + k + j] = refRow[j];
}
}
- for (var j = 0; j < unit; j++)
+ for (var j = 0; j < unitH; j++)
{
available[n2 + 1 + k + j] = ok;
}
@@ -104,9 +105,9 @@ public sealed partial class H265Decoder
}
}
- // Filtering (§8.4.4.2.3), luma only in 4:2:0.
+ // Filtering (§8.4.4.2.3): luma, and chroma in 4:4:4, unless intra_smoothing_disabled_flag.
Span p = line;
- if (cIdx == 0 && mode != 1 && n != 4)
+ if ((cIdx == 0 || sps.ChromaArrayType == 3) && !sps.IntraSmoothingDisabled && mode != 1 && n != 4)
{
var minDistVerHor = Math.Min(Math.Abs(mode - 26), Math.Abs(mode - 10));
var threshold = n == 8 ? 7 : n == 16 ? 1 : 0;
@@ -115,7 +116,7 @@ public sealed partial class H265Decoder
var filtered = refFiltered.AsSpan(0, line.Length);
var last = 4 * n;
var limit = 1 << (bitDepth - 5);
- if (sps.StrongIntraSmoothing && n == 32
+ if (cIdx == 0 && sps.StrongIntraSmoothing && n == 32
&& Math.Abs(line[n2] + line[last] - (2 * line[n2 + n])) < limit
&& Math.Abs(line[n2] + line[0] - (2 * line[n2 - n])) < limit)
{
@@ -234,7 +235,8 @@ public sealed partial class H265Decoder
}
}
- if (cIdx == 0 && n < 32)
+ // disableIntraBoundaryFilter (§8.4.4.2.6): implicit RDPCM of a coding unit without transform and quantisation.
+ if (cIdx == 0 && n < 32 && !(sps.ImplicitRdpcmEnabled && cuTransquantBypass))
{
if (mode == 26)
{
diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.Residual.cs b/src/Febe.Core/Codecs/H265/H265Decoder.Residual.cs
index bde9ba4..36d82c6 100644
--- a/src/Febe.Core/Codecs/H265/H265Decoder.Residual.cs
+++ b/src/Febe.Core/Codecs/H265/H265Decoder.Residual.cs
@@ -6,6 +6,12 @@ public sealed partial class H265Decoder
/// ctxIdxMap of sig_coeff_flag in 4×4 blocks (9-55), by raster position.
private static readonly byte[] s_sigCtxMap4x4 = [0, 1, 4, 5, 2, 3, 4, 5, 6, 6, 8, 8, 7, 7, 8, 8];
+ /// No residual DPCM; horizontal; vertical (§8.6.8, the direction of explicit_rdpcm_dir_flag + 1).
+ private const int RdpcmNone = 0;
+
+ private const int RdpcmHorizontal = 1;
+ private const int RdpcmVertical = 2;
+
/// TransCoeffLevel of the block being decoded, raster order (y << log2) + x; zero outside it.
private readonly int[] coefficients = new int[32 * 32];
@@ -16,25 +22,42 @@ public sealed partial class H265Decoder
private readonly int[] transformTemp = new int[32 * 32];
private readonly byte[] codedSubBlocks = new byte[64];
+ /// The luma residual of the transform unit, for the cross-component prediction of its chroma (§8.6.6).
+ private readonly int[] lumaResidual = new int[32 * 32];
+
/// Decodes the residual of one transform block and adds it to the prediction in the picture.
/// Colour component.
/// Left of the block, in samples of the component.
/// Top of the block, in samples of the component.
/// Log2 of the block size.
/// The intra prediction mode of the block, −1 for inter.
- private void Residual(int cIdx, int x0, int y0, int log2, int predModeIntra)
+ /// ResScaleVal of the cross-component prediction of a chroma block, 0 for none.
+ private void Residual(int cIdx, int x0, int y0, int log2, int predModeIntra, int resScale)
{
- var count = ParseResidual(cIdx, log2, predModeIntra, out var transformSkip, out var maxX, out var maxY);
+ var count = ParseResidual(cIdx, log2, predModeIntra, out var transformSkip, out var maxX, out var maxY, out var rdpcm);
var size = 1 << log2;
var bitDepth = cIdx == 0 ? sps.BitDepthY : sps.BitDepthC;
var total = size * size;
+
+ // transform_skip_rotation_enabled_flag: the residual of 4×4 intra blocks without a transform is rotated by 180°.
+ var rotate = sps.TransformSkipRotationEnabled && log2 == 2 && cuIntra && (transformSkip || cuTransquantBypass);
if (cuTransquantBypass)
{
- Array.Copy(coefficients, residual, total);
+ if (rotate)
+ {
+ for (var i = 0; i < total; i++)
+ {
+ residual[i] = coefficients[total - 1 - i];
+ }
+ }
+ else
+ {
+ Array.Copy(coefficients, residual, total);
+ }
}
else
{
- Dequantise(cIdx, log2, count, bitDepth);
+ Dequantise(cIdx, log2, count, bitDepth, transformSkip);
if (transformSkip)
{
// §8.6.4.2: r = d << tsShift, then the same rounding as after a transform.
@@ -43,7 +66,7 @@ public sealed partial class H265Decoder
var add = 1 << (bdShift - 1);
for (var i = 0; i < total; i++)
{
- residual[i] = ((coefficients[i] << tsShift) + add) >> bdShift;
+ residual[i] = ((coefficients[rotate ? total - 1 - i : i] << tsShift) + add) >> bdShift;
}
}
else if (count == 1 && nonzero[0] == 0 && !(cuIntra && cIdx == 0 && log2 == 2))
@@ -60,28 +83,99 @@ public sealed partial class H265Decoder
}
}
+ if (rdpcm != RdpcmNone)
+ {
+ AccumulateResidual(log2, rdpcm == RdpcmVertical);
+ }
+
// Clear the coefficients for the next block.
for (var i = 0; i < count; i++)
{
coefficients[nonzero[i]] = 0;
}
+ if (cIdx == 0)
+ {
+ if (pps.CrossComponentPredictionEnabled)
+ {
+ Array.Copy(residual, lumaResidual, total);
+ }
+ }
+ else if (resScale != 0)
+ {
+ AddCrossComponent(total, resScale);
+ }
+
+ AddResidual(cIdx, x0, y0, log2, bitDepth);
+ }
+
+ /// A chroma block without coefficients whose residual is only the cross-component prediction (§8.6.6).
+ private void CrossComponentResidual(int cIdx, int x0, int y0, int log2, int resScale)
+ {
+ var total = 1 << (2 * log2);
+ residual.AsSpan(0, total).Clear();
+ AddCrossComponent(total, resScale);
+ AddResidual(cIdx, x0, y0, log2, sps.BitDepthC);
+ }
+
+ /// The residual modification process for transform blocks using cross-component prediction (8-xx of §8.6.6).
+ private void AddCrossComponent(int total, int resScale)
+ {
+ int bitDepthY = sps.BitDepthY, bitDepthC = sps.BitDepthC;
+ for (var i = 0; i < total; i++)
+ {
+ residual[i] += (resScale * ((lumaResidual[i] << bitDepthC) >> bitDepthY)) >> 3;
+ }
+ }
+
+ /// The directional residual modification (§8.6.8): each residual sample accumulates the previous ones.
+ private void AccumulateResidual(int log2, bool vertical)
+ {
+ var size = 1 << log2;
+ if (vertical)
+ {
+ for (var y = 1; y < size; y++)
+ {
+ var row = y << log2;
+ for (var x = 0; x < size; x++)
+ {
+ residual[row + x] += residual[row - size + x];
+ }
+ }
+ }
+ else
+ {
+ for (var y = 0; y < size; y++)
+ {
+ var row = y << log2;
+ for (var x = 1; x < size; x++)
+ {
+ residual[row + x] += residual[row + x - 1];
+ }
+ }
+ }
+ }
+
+ /// The picture construction (§8.6.7): prediction plus residual, clipped to the bit depth.
+ private void AddResidual(int cIdx, int x0, int y0, int log2, int bitDepth)
+ {
+ var size = 1 << log2;
var plane = cur!.Planes[cIdx];
var stride = cur.Stride(cIdx);
var max = (1 << bitDepth) - 1;
for (var y = 0; y < size; y++)
{
- var row = ((y0 + y) * stride) + x0;
- var r = y << log2;
- for (var x = 0; x < size; x++)
+ var row = plane.AsSpan(((y0 + y) * stride) + x0, size);
+ var r = residual.AsSpan(y << log2, size);
+ for (var x = 0; x < row.Length; x++)
{
- plane[row + x] = (ushort)Math.Clamp(plane[row + x] + residual[r + x], 0, max);
+ row[x] = (ushort)Math.Clamp(row[x] + r[x], 0, max);
}
}
}
/// The scaling process for transform coefficients (§8.6.3), on the nonzero coefficients.
- private void Dequantise(int cIdx, int log2, int count, int bitDepth)
+ private void Dequantise(int cIdx, int log2, int count, int bitDepth, bool transformSkip)
{
int qp;
if (cIdx == 0)
@@ -92,8 +186,7 @@ public sealed partial class H265Decoder
{
var offset = cIdx == 1 ? pps.CbQpOffset + slice.CbQpOffset + cuQpOffsetCb : pps.CrQpOffset + slice.CrQpOffset + cuQpOffsetCr;
var qPi = Math.Clamp(qpY + offset, -sps.QpBdOffsetC, 57);
- var qPc = qPi < 30 ? qPi : qPi > 43 ? qPi - 6 : H265Tables.ChromaQp30To43[qPi - 30];
- qp = qPc + sps.QpBdOffsetC;
+ qp = H265Tables.ChromaQp(qPi, sps.ChromaArrayType) + sps.QpBdOffsetC;
}
var bdShift = bitDepth + log2 - 5;
@@ -101,7 +194,9 @@ public sealed partial class H265Decoder
var scale = (long)H265Tables.LevelScale[qp % 6] << (qp / 6);
var list = pps.ScalingList ?? sps.ScalingList;
byte[]? factors = null;
- if (sps.ScalingListEnabled && list is not null)
+
+ // m is 16 without scaling lists, and for transform skip blocks larger than 4×4 (8-xx).
+ if (sps.ScalingListEnabled && list is not null && !(transformSkip && log2 > 2))
{
factors = list.Factors[((log2 - 2) * 6) + (cuIntra ? 0 : 3) + cIdx];
}
@@ -117,9 +212,9 @@ public sealed partial class H265Decoder
///
/// residual_coding(): fills and ; returns the number of nonzero
- /// coefficients and the largest column and row that hold one.
+ /// coefficients and the largest column and row that hold one, and the residual DPCM of the block (§8.6.8).
///
- private int ParseResidual(int cIdx, int log2, int predModeIntra, out bool transformSkip, out int maxX, out int maxY)
+ private int ParseResidual(int cIdx, int log2, int predModeIntra, out bool transformSkip, out int maxX, out int maxY, out int rdpcm)
{
transformSkip = false;
if (pps.TransformSkipEnabled && !cuTransquantBypass && log2 <= pps.Log2MaxTransformSkipSize)
@@ -127,6 +222,28 @@ public sealed partial class H265Decoder
transformSkip = cabac.Flag(CabacTables.TransformSkipFlag + (cIdx == 0 ? 0 : 1));
}
+ // Residual DPCM of blocks without a transform: explicit_rdpcm_flag in inter coding units, implicit in intra ones
+ // predicted horizontally (mode 10) or vertically (mode 26).
+ var untransformed = transformSkip || cuTransquantBypass;
+ rdpcm = RdpcmNone;
+ var explicitRdpcm = false;
+ if (untransformed)
+ {
+ if (!cuIntra && sps.ExplicitRdpcmEnabled)
+ {
+ var c = cIdx == 0 ? 0 : 1;
+ if (cabac.Flag(CabacTables.ExplicitRdpcmFlag + c))
+ {
+ explicitRdpcm = true;
+ rdpcm = cabac.Flag(CabacTables.ExplicitRdpcmDirFlag + c) ? RdpcmVertical : RdpcmHorizontal;
+ }
+ }
+ else if (cuIntra && sps.ImplicitRdpcmEnabled && predModeIntra is 10 or 26)
+ {
+ rdpcm = predModeIntra == 26 ? RdpcmVertical : RdpcmHorizontal;
+ }
+ }
+
// last_sig_coeff_x_prefix, last_sig_coeff_y_prefix and their suffixes (§9.3.4.2.3).
int ctxOffset, ctxShift;
if (cIdx == 0)
@@ -169,7 +286,7 @@ public sealed partial class H265Decoder
// scanIdx (§7.4.9.11): mode-dependent scans for intra 4×4 blocks and 8×8 luma blocks.
var scanIdx = 0;
- if (predModeIntra >= 0 && (log2 == 2 || (log2 == 3 && cIdx == 0)))
+ if (predModeIntra >= 0 && (log2 == 2 || (log2 == 3 && (cIdx == 0 || sps.ChromaArrayType == 3))))
{
if (predModeIntra is >= 6 and <= 14)
{
@@ -210,7 +327,17 @@ public sealed partial class H265Decoder
var lastScanPos = H265Tables.ScanPosition4x4[scanIdx][((lastY & 3) << 2) + (lastX & 3)];
codedSubBlocks.AsSpan(0, sbWidth * sbWidth).Clear();
- var signHidingEnabled = pps.SignDataHidingEnabled && !cuTransquantBypass;
+ // No sign data hiding without a transform where the residual is accumulated (§7.3.8.11).
+ var signHidingEnabled = pps.SignDataHidingEnabled && !cuTransquantBypass
+ && !(cuIntra && sps.ImplicitRdpcmEnabled && transformSkip && predModeIntra is 10 or 26) && !explicitRdpcm;
+
+ // transform_skip_context_enabled_flag: one context for every sig_coeff_flag of a block without a transform.
+ var singleSigCtx = sps.TransformSkipContextEnabled && untransformed ? (cIdx == 0 ? 42 : 16) : -1;
+
+ // The persistent Rice adaptation (§9.3.3.11): StatCoeff by component and transform, no bound on cRiceParam.
+ var persistentRice = sps.PersistentRiceAdaptationEnabled;
+ var sbType = (cIdx == 0 ? 0 : 2) + (untransformed ? 1 : 0);
+ var riceLimit = persistentRice ? 16 : 4;
var greater1Ctx = 1;
var firstSubBlock = true;
var count = 0;
@@ -278,7 +405,11 @@ public sealed partial class H265Decoder
if (n > 0 || !inferSbDcSigCoeff)
{
int sigCtx;
- if (log2 == 2)
+ if (singleSigCtx >= 0)
+ {
+ sigCtx = singleSigCtx;
+ }
+ else if (log2 == 2)
{
sigCtx = s_sigCtxMap4x4[(yP << 2) + xP];
}
@@ -379,8 +510,10 @@ public sealed partial class H265Decoder
signs = 0;
}
- // coeff_abs_level_remaining (§9.3.3.11) with the Rice parameter of §9.3.3.11 (v1: starts at 0, at most 4).
- var rice = 0;
+ // coeff_abs_level_remaining (§9.3.3.11): the Rice parameter starts at 0 (at StatCoeff / 4 with the
+ // persistent adaptation, which the first value of the sub-block updates) and grows with the levels.
+ var rice = persistentRice ? statCoeff[sbType] >> 2 : 0;
+ var firstRemaining = persistentRice;
var sumAbs = 0;
for (var k = 0; k < sigCount; k++)
{
@@ -390,9 +523,24 @@ public sealed partial class H265Decoder
{
var remaining = CoeffAbsLevelRemaining(rice);
absolute = baseLevel + remaining;
+ if (firstRemaining)
+ {
+ ref var stat = ref statCoeff[sbType];
+ if (remaining >= 3 << (stat >> 2))
+ {
+ stat++;
+ }
+ else if (2 * remaining < 1 << (stat >> 2) && stat > 0)
+ {
+ stat--;
+ }
+
+ firstRemaining = false;
+ }
+
if (absolute > 3 * (1 << rice))
{
- rice = Math.Min(rice + 1, 4);
+ rice = Math.Min(rice + 1, riceLimit);
}
}
diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.Slice.cs b/src/Febe.Core/Codecs/H265/H265Decoder.Slice.cs
index 7cafd57..e96b45a 100644
--- a/src/Febe.Core/Codecs/H265/H265Decoder.Slice.cs
+++ b/src/Febe.Core/Codecs/H265/H265Decoder.Slice.cs
@@ -30,6 +30,12 @@ public sealed partial class H265Decoder
private readonly CabacEngine cabac = new();
private readonly byte[] wppContexts = new byte[CabacTables.ContextCount];
private readonly byte[] dsContexts = new byte[CabacTables.ContextCount];
+
+ /// StatCoeff of the persistent Rice adaptation (§9.3.3.11), kept and synchronised with the contexts.
+ private readonly int[] statCoeff = new int[4];
+
+ private readonly int[] wppStatCoeff = new int[4];
+ private readonly int[] dsStatCoeff = new int[4];
private List slices = [];
private Picture? cur;
@@ -90,7 +96,11 @@ public sealed partial class H265Decoder
private bool cuIntra;
private bool cuTransquantBypass;
private int cuPartMode;
- private int cuIntraModeC;
+
+ /// IntraPredModeC of each prediction block (one unless 4:4:4 with NxN), and whether intra_chroma_pred_mode was 4.
+ private readonly int[] cuChromaModes = new int[4];
+
+ private readonly bool[] cuChromaDm = new bool[4];
private int cuMaxTrafoDepth;
private bool cuIntraSplit;
@@ -152,6 +162,8 @@ public sealed partial class H265Decoder
{
sliceIdx = slices.Count - 1;
resetQpPrev = true;
+ cuQpOffsetCb = 0;
+ cuQpOffsetCr = 0;
}
data = nal.Rbsp;
@@ -180,7 +192,7 @@ public sealed partial class H265Decoder
// Initialisation of the context variables (§9.3.2.2 to §9.3.2.4).
if (tileStart)
{
- cabac.InitContexts(initType, h.SliceQpY);
+ InitEntropy(initType, h.SliceQpY);
}
else if (wppRowStart)
{
@@ -188,20 +200,20 @@ public sealed partial class H265Decoder
var available = ctbY > 0 && ctbX + 1 < widthInCtbs && ctbSlice[topRight] == sliceIdx && pps.TileIdRs[topRight] == tile;
if (available)
{
- wppContexts.CopyTo(cabac.Contexts, 0);
+ LoadEntropy(wppContexts, wppStatCoeff);
}
else
{
- cabac.InitContexts(initType, h.SliceQpY);
+ InitEntropy(initType, h.SliceQpY);
}
}
else if (h.Dependent)
{
- dsContexts.CopyTo(cabac.Contexts, 0);
+ LoadEntropy(dsContexts, dsStatCoeff);
}
else
{
- cabac.InitContexts(initType, h.SliceQpY);
+ InitEntropy(initType, h.SliceQpY);
}
}
@@ -214,7 +226,7 @@ public sealed partial class H265Decoder
CodingTreeUnit();
if (pps.EntropyCodingSyncEnabled && ctbX - colStart <= 1)
{
- cabac.Contexts.CopyTo(wppContexts, 0);
+ SaveEntropy(wppContexts, wppStatCoeff);
}
var end = cabac.Terminate() == 1;
@@ -223,7 +235,7 @@ public sealed partial class H265Decoder
{
if (pps.DependentSliceSegmentsEnabled)
{
- cabac.Contexts.CopyTo(dsContexts, 0);
+ SaveEntropy(dsContexts, dsStatCoeff);
}
return;
@@ -255,6 +267,27 @@ public sealed partial class H265Decoder
}
}
+ /// The initialisation of §9.3.2.2: the context variables, and StatCoeff to 0.
+ private void InitEntropy(int initType, int sliceQp)
+ {
+ cabac.InitContexts(initType, sliceQp);
+ Array.Clear(statCoeff);
+ }
+
+ /// The synchronisation process of §9.3.2.4: contexts and StatCoeff from a stored state.
+ private void LoadEntropy(byte[] contexts, int[] stat)
+ {
+ contexts.CopyTo(cabac.Contexts, 0);
+ stat.CopyTo(statCoeff, 0);
+ }
+
+ /// The storage process of §9.3.2.3.
+ private void SaveEntropy(byte[] contexts, int[] stat)
+ {
+ cabac.Contexts.CopyTo(contexts, 0);
+ statCoeff.CopyTo(stat, 0);
+ }
+
private void CodingTreeUnit()
{
var log2 = sps.Log2CtbSize;
@@ -518,7 +551,7 @@ public sealed partial class H265Decoder
if (rqtRootCbf)
{
cuMaxTrafoDepth = cuIntra ? sps.MaxTransformHierarchyDepthIntra + (cuIntraSplit ? 1 : 0) : sps.MaxTransformHierarchyDepthInter;
- TransformTree(x0, y0, x0, y0, log2, 0, 0, false, false);
+ TransformTree(x0, y0, x0, y0, log2, 0, 0, 0);
}
}
}
@@ -593,12 +626,12 @@ public sealed partial class H265Decoder
var pbSize = cuIntraSplit ? 1 << (log2 - 1) : 1 << log2;
Span prev = stackalloc bool[4];
Span list = stackalloc int[3];
+ Span lumaModes = stackalloc int[4];
for (var i = 0; i < count; i++)
{
prev[i] = cabac.Flag(CabacTables.PrevIntraLumaPredFlag);
}
- var firstMode = 0;
for (var i = 0; i < count; i++)
{
var xPb = x0 + ((i & 1) * pbSize);
@@ -648,23 +681,33 @@ public sealed partial class H265Decoder
}
FillGrid(intraModeMap, xPb, yPb, pbSize, pbSize, (byte)mode);
- if (i == 0)
- {
- firstMode = mode;
- }
+ lumaModes[i] = mode;
}
- // intra_chroma_pred_mode (table 8-2 for ChromaArrayType 1): 4 is the luma mode, 0 to 3 are planar, vertical,
- // horizontal and DC, replaced by mode 34 when they equal the luma mode.
- var chroma = !cabac.Flag(CabacTables.IntraChromaPredMode) ? 4 : cabac.BypassBits(2);
- cuIntraModeC = chroma switch
+ if (sps.ChromaArrayType == 0)
{
- 0 => firstMode == 0 ? 34 : 0,
- 1 => firstMode == 26 ? 34 : 26,
- 2 => firstMode == 10 ? 34 : 10,
- 3 => firstMode == 1 ? 34 : 1,
- _ => firstMode,
- };
+ return;
+ }
+
+ // intra_chroma_pred_mode (§8.4.3, table 8-2): 4 is the luma mode, 0 to 3 are planar, vertical, horizontal and DC,
+ // replaced by mode 34 when they equal the luma mode. One for each prediction block in 4:4:4, one for the coding
+ // unit otherwise (with the mode of its first block); in 4:2:2 the mode is then mapped by table 8-3.
+ var chromaCount = sps.ChromaArrayType == 3 ? count : 1;
+ for (var i = 0; i < chromaCount; i++)
+ {
+ var luma = lumaModes[i];
+ var chroma = !cabac.Flag(CabacTables.IntraChromaPredMode) ? 4 : cabac.BypassBits(2);
+ var mode = chroma switch
+ {
+ 0 => luma == 0 ? 34 : 0,
+ 1 => luma == 26 ? 34 : 26,
+ 2 => luma == 10 ? 34 : 10,
+ 3 => luma == 1 ? 34 : 1,
+ _ => luma,
+ };
+ cuChromaModes[i] = sps.ChromaArrayType == 2 ? H265Tables.ChromaMode422[mode] : mode;
+ cuChromaDm[i] = chroma == 4;
+ }
}
/// candIntraPredModeX of §8.4.2.
@@ -705,18 +748,19 @@ public sealed partial class H265Decoder
}
}
- var chromaSize = size >> 1;
shift = sps.BitDepthC - sps.PcmBitDepthC;
bits = sps.PcmBitDepthC;
- for (var c = 1; c <= 2; c++)
+ int sx = sps.ChromaShiftX, sy = sps.ChromaShiftY;
+ int chromaWidth = size >> sx, chromaHeight = size >> sy, xc = x0 >> sx, yc = y0 >> sy;
+ for (var c = 1; c <= 2 && sps.ChromaArrayType != 0; c++)
{
plane = cur.Planes[c];
stride = cur.ChromaWidth;
- for (var y = 0; y < chromaSize; y++)
+ for (var y = 0; y < chromaHeight; y++)
{
- for (var x = 0; x < chromaSize; x++)
+ for (var x = 0; x < chromaWidth; x++)
{
- plane[(((y0 >> 1) + y) * stride) + (x0 >> 1) + x] = (ushort)(reader.Read(bits) << shift);
+ plane[((yc + y) * stride) + xc + x] = (ushort)(reader.Read(bits) << shift);
}
}
}
@@ -936,7 +980,11 @@ public sealed partial class H265Decoder
return (value << count) | cabac.BypassBits(count);
}
- private void TransformTree(int x0, int y0, int xBase, int yBase, int log2, int depth, int blkIdx, bool parentCbfCb, bool parentCbfCr)
+ ///
+ /// transform_tree() (§7.3.8.8). holds the chroma coded block flags of the parent: bit 0
+ /// cbf_cb, bit 1 the cbf_cb of the second (lower) 4:2:2 block, bits 2 and 3 the same for cbf_cr.
+ ///
+ private void TransformTree(int x0, int y0, int xBase, int yBase, int log2, int depth, int blkIdx, int parentCbf)
{
bool split;
var interSplit = sps.MaxTransformHierarchyDepthInter == 0 && !cuIntra && cuPartMode != Part2Nx2N && depth == 0;
@@ -949,42 +997,54 @@ public sealed partial class H265Decoder
split = log2 > sps.Log2MaxTbSize || (cuIntraSplit && depth == 0) || interSplit;
}
- bool cbfCb, cbfCr;
- if (log2 > 2)
+ var chromaType = sps.ChromaArrayType;
+ var cbf = 0;
+ if ((log2 > 2 && chromaType != 0) || chromaType == 3)
{
- cbfCb = (depth == 0 || parentCbfCb) && cabac.Flag(CabacTables.CbfChroma + depth);
- cbfCr = (depth == 0 || parentCbfCr) && cabac.Flag(CabacTables.CbfChroma + depth);
+ // In 4:2:2 a block that is not split further (or splits into 4×4 luma blocks) has two chroma blocks per
+ // component, one above the other, each with its flag.
+ var second = chromaType == 2 && (!split || log2 == 3);
+ if (depth == 0 || (parentCbf & 1) != 0)
+ {
+ cbf |= cabac.Flag(CabacTables.CbfChroma + depth) ? 1 : 0;
+ cbf |= second && cabac.Flag(CabacTables.CbfChroma + depth) ? 2 : 0;
+ }
+
+ if (depth == 0 || (parentCbf & 4) != 0)
+ {
+ cbf |= cabac.Flag(CabacTables.CbfChroma + depth) ? 4 : 0;
+ cbf |= second && cabac.Flag(CabacTables.CbfChroma + depth) ? 8 : 0;
+ }
}
- else
+ else if (chromaType != 0)
{
- // 4×4 luma blocks: the chroma of the four is coded once, with the parent's flags (§7.4.9.8).
- cbfCb = parentCbfCb;
- cbfCr = parentCbfCr;
+ // 4×4 luma blocks in 4:2:0 and 4:2:2: the chroma of the four is coded once, with the parent's flags (§7.4.9.8).
+ cbf = parentCbf;
}
if (split)
{
var half = 1 << (log2 - 1);
- TransformTree(x0, y0, x0, y0, log2 - 1, depth + 1, 0, cbfCb, cbfCr);
- TransformTree(x0 + half, y0, x0, y0, log2 - 1, depth + 1, 1, cbfCb, cbfCr);
- TransformTree(x0, y0 + half, x0, y0, log2 - 1, depth + 1, 2, cbfCb, cbfCr);
- TransformTree(x0 + half, y0 + half, x0, y0, log2 - 1, depth + 1, 3, cbfCb, cbfCr);
+ TransformTree(x0, y0, x0, y0, log2 - 1, depth + 1, 0, cbf);
+ TransformTree(x0 + half, y0, x0, y0, log2 - 1, depth + 1, 1, cbf);
+ TransformTree(x0, y0 + half, x0, y0, log2 - 1, depth + 1, 2, cbf);
+ TransformTree(x0 + half, y0 + half, x0, y0, log2 - 1, depth + 1, 3, cbf);
return;
}
var cbfLuma = true;
- if (cuIntra || depth != 0 || cbfCb || cbfCr)
+ if (cuIntra || depth != 0 || cbf != 0)
{
cbfLuma = cabac.Flag(CabacTables.CbfLuma + (depth == 0 ? 1 : 0));
}
- TransformUnit(x0, y0, xBase, yBase, log2, blkIdx, cbfLuma, cbfCb, cbfCr);
+ TransformUnit(x0, y0, xBase, yBase, log2, blkIdx, cbfLuma, cbf);
}
- private void TransformUnit(int x0, int y0, int xBase, int yBase, int log2, int blkIdx, bool cbfLuma, bool cbfCb, bool cbfCr)
+ private void TransformUnit(int x0, int y0, int xBase, int yBase, int log2, int blkIdx, bool cbfLuma, int cbf)
{
var size = 1 << log2;
- var cbfChroma = cbfCb || cbfCr;
+ var cbfChroma = cbf != 0;
if (cbfLuma || cbfChroma)
{
if (pps.CuQpDeltaEnabled && !isCuQpDeltaCoded)
@@ -1033,7 +1093,6 @@ public sealed partial class H265Decoder
}
var lumaMode = cuIntra ? intraModeMap[Grid(x0, y0)] : -1;
- var chromaMode = cuIntra ? cuIntraModeC : -1;
if (cuIntra)
{
PredictIntra(0, x0, y0, log2, lumaMode);
@@ -1041,7 +1100,7 @@ public sealed partial class H265Decoder
if (cbfLuma)
{
- Residual(0, x0, y0, log2, lumaMode);
+ Residual(0, x0, y0, log2, lumaMode, 0);
FillGrid(blockFlags, x0, y0, size, size, FlagCoded, true);
}
@@ -1055,54 +1114,80 @@ public sealed partial class H265Decoder
MarkHorizontal(x0, y0, size, 2);
}
- if (log2 > 2)
+ var chromaType = sps.ChromaArrayType;
+ if (chromaType == 0)
{
- int xc = x0 >> 1, yc = y0 >> 1;
- if (cuIntra)
+ return;
+ }
+
+ int sx = sps.ChromaShiftX, sy = sps.ChromaShiftY;
+ if (log2 > 2 || chromaType == 3)
+ {
+ // In 4:4:4 an NxN coding unit has a chroma mode for each of its four blocks.
+ var part = 0;
+ if (cuIntraSplit && chromaType == 3)
{
- PredictIntra(1, xc, yc, log2 - 1, cuIntraModeC);
+ var half = 1 << (cuLog2 - 1);
+ part = (y0 >= cuY + half ? 2 : 0) + (x0 >= cuX + half ? 1 : 0);
}
- if (cbfCb)
- {
- Residual(1, xc, yc, log2 - 1, chromaMode);
- }
-
- if (cuIntra)
- {
- PredictIntra(2, xc, yc, log2 - 1, cuIntraModeC);
- }
-
- if (cbfCr)
- {
- Residual(2, xc, yc, log2 - 1, chromaMode);
- }
+ ChromaBlocks(x0 >> sx, y0 >> sy, chromaType == 3 ? log2 : log2 - 1, cbf, part, cbfLuma);
}
else if (blkIdx == 3)
{
- int xc = xBase >> 1, yc = yBase >> 1;
- if (cuIntra)
- {
- PredictIntra(1, xc, yc, 2, cuIntraModeC);
- }
+ ChromaBlocks(xBase >> sx, yBase >> sy, 2, cbf, 0, false);
+ }
+ }
- if (cbfCb)
+ ///
+ /// The chroma blocks of a transform unit (two per component in 4:2:2, one above the other): prediction, then the
+ /// residual, with cross_comp_pred() (§7.3.8.12) when the luma block has coefficients.
+ ///
+ private void ChromaBlocks(int xc, int yc, int log2, int cbf, int part, bool lumaCoded)
+ {
+ var mode = cuIntra ? cuChromaModes[part] : -1;
+ var crossComponent = lumaCoded && pps.CrossComponentPredictionEnabled && (!cuIntra || cuChromaDm[part]);
+ var blocks = sps.ChromaArrayType == 2 ? 2 : 1;
+ for (var c = 1; c <= 2; c++)
+ {
+ var resScale = crossComponent ? CrossComponentPrediction(c - 1) : 0;
+ for (var t = 0; t < blocks; t++)
{
- Residual(1, xc, yc, 2, chromaMode);
- }
+ var y = yc + (t << log2);
+ if (cuIntra)
+ {
+ PredictIntra(c, xc, y, log2, mode);
+ }
- if (cuIntra)
- {
- PredictIntra(2, xc, yc, 2, cuIntraModeC);
- }
-
- if (cbfCr)
- {
- Residual(2, xc, yc, 2, chromaMode);
+ if ((cbf & (1 << (((c - 1) * 2) + t))) != 0)
+ {
+ Residual(c, xc, y, log2, mode, resScale);
+ }
+ else if (resScale != 0)
+ {
+ CrossComponentResidual(c, xc, y, log2, resScale);
+ }
}
}
}
+ /// log2_res_scale_abs_plus1 and res_scale_sign_flag of one chroma component, as ResScaleVal (7.4.9.12).
+ private int CrossComponentPrediction(int c)
+ {
+ var value = 0;
+ while (value < 4 && cabac.Flag(CabacTables.Log2ResScaleAbsPlus1 + (4 * c) + value))
+ {
+ value++;
+ }
+
+ if (value == 0)
+ {
+ return 0;
+ }
+
+ return cabac.Flag(CabacTables.ResScaleSignFlag + c) ? -(1 << (value - 1)) : 1 << (value - 1);
+ }
+
///
/// availableN of the z-scan order (§6.4.1), for luma locations: inside the picture, already decoded, in the same
/// slice and the same tile.
diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.cs b/src/Febe.Core/Codecs/H265/H265Decoder.cs
index d786611..b59092e 100644
--- a/src/Febe.Core/Codecs/H265/H265Decoder.cs
+++ b/src/Febe.Core/Codecs/H265/H265Decoder.cs
@@ -4,11 +4,13 @@ namespace Febe.Core.Codecs.H265;
///
/// An HEVC (ITU-T H.265 | ISO/IEC 23008-2) decoder written from the Recommendation, for the Main, Main 10 and Main Still
-/// Picture profiles: 4:2:0 at 8 to 10 bits (up to 12 accepted), tiles, wavefronts, dependent slice segments, PCM, transform
-/// skip, sign data hiding, scaling lists, inter prediction (merge, AMVP, temporal motion vector prediction, weighted
-/// prediction), deblocking and SAO. Not handled (an
-/// ): the range extensions (4:0:0, 4:2:2, 4:4:4 and their coding tools), separate colour planes
-/// and the layers above 0 of scalable and multiview streams, which are ignored.
+/// Picture profiles and the format range extensions up to 12 bits: 4:0:0, 4:2:0, 4:2:2 and 4:4:4, tiles, wavefronts,
+/// dependent slice segments, PCM, transform skip, sign data hiding, scaling lists, inter prediction (merge, AMVP, temporal
+/// motion vector prediction, weighted prediction), deblocking and SAO, and the range extension tools (cross-component
+/// prediction, implicit and explicit RDPCM, transform skip rotation and contexts, persistent Rice adaptation, chroma QP
+/// offset lists, intra smoothing disabled, high precision offsets). Not handled (an ): extended
+/// precision processing, the CABAC bypass alignment, separate colour planes, bit depths above 12; the layers above 0 of
+/// scalable and multiview streams are ignored.
///
public sealed partial class H265Decoder
{
@@ -248,14 +250,14 @@ public sealed partial class H265Decoder
return;
}
- if (s.ChromaArrayType != 1 || s.BitDepthY > 12 || s.BitDepthC > 12)
+ if (s.SeparateColourPlane || s.BitDepthY > 12 || s.BitDepthC > 12)
{
- throw new H265Exception("Solo video HEVC 4:2:0 fino a 12 bit.");
+ throw new H265Exception("Solo video HEVC fino a 12 bit, senza piani di colore separati.");
}
- if (s.UsesRangeExtensionTools || p.UsesRangeExtensionTools)
+ if (s.UsesUnsupportedTools)
{
- throw new H265Exception("Gli strumenti delle estensioni di formato HEVC non sono gestiti.");
+ throw new H265Exception("La precisione estesa e l'allineamento CABAC delle estensioni di formato HEVC non sono gestiti.");
}
p.Activate(s);
diff --git a/src/Febe.Core/Codecs/H265/H265Tables.cs b/src/Febe.Core/Codecs/H265/H265Tables.cs
index 8de4390..a7850a8 100644
--- a/src/Febe.Core/Codecs/H265/H265Tables.cs
+++ b/src/Febe.Core/Codecs/H265/H265Tables.cs
@@ -2,7 +2,7 @@ namespace Febe.Core.Codecs.H265;
///
/// Constant tables of ITU-T H.265, transcribed from the text of the Recommendation: scan orders (§6.5.3–6.5.5), default
-/// scaling lists (table 7-6), intra prediction angles (tables 8-4 and 8-5), the chroma QP mapping (table 8-10), the
+/// scaling lists (table 7-6), intra prediction angles (tables 8-4 and 8-5), the 4:2:2 chroma intra modes (table 8-3), the chroma QP mapping (table 8-10), the
/// thresholds of the deblocking filter (table 8-12) and the transform matrices (§8.6.4.2).
///
internal static class H265Tables
@@ -20,6 +20,21 @@ internal static class H265Tables
/// QpC as a function of qPi for ChromaArrayType 1 (table 8-10), for qPi from 30 to 43.
internal static readonly byte[] ChromaQp30To43 = [29, 30, 31, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37];
+ ///
+ /// The 4:2:2 intra prediction mode of chroma (table 8-3) from modeIdc, the mode table 8-2 gives: for chroma samples
+ /// twice as tall as they are wide, the mode whose angle is closest to the luma one with the horizontal displacement
+ /// halved (horizontal modes: the vertical one doubled; past 45° a mode of the other direction).
+ ///
+ internal static readonly byte[] ChromaMode422 =
+ [
+ 0, 1, 2, 2, 2, 2, 3, 5, 7, 8, 10, 12, 13, 15, 17, 18, 19, 20,
+ 21, 22, 23, 23, 24, 24, 25, 25, 26, 27, 27, 28, 28, 29, 29, 30, 31,
+ ];
+
+ /// QpC of chroma from qPi (8-258 to 8-261, table 8-10): the table for 4:2:0, Min(qPi, 51) otherwise.
+ internal static int ChromaQp(int qPi, int chromaArrayType) =>
+ chromaArrayType != 1 ? Math.Min(qPi, 51) : qPi < 30 ? qPi : qPi > 43 ? qPi - 6 : ChromaQp30To43[qPi - 30];
+
/// β′ for Q from 0 to 51 (table 8-12).
internal static readonly byte[] Beta =
[
diff --git a/src/Febe.Core/Codecs/H265/ParameterSets.cs b/src/Febe.Core/Codecs/H265/ParameterSets.cs
index 591d3ab..17ea217 100644
--- a/src/Febe.Core/Codecs/H265/ParameterSets.cs
+++ b/src/Febe.Core/Codecs/H265/ParameterSets.cs
@@ -336,7 +336,7 @@ internal sealed class Sps
internal bool TemporalMvpEnabled;
internal bool StrongIntraSmoothing;
- // Range extension (§7.3.2.2.2): parsed; streams that use these tools are refused for now.
+ // Range extension (§7.3.2.2.2): every tool is decoded except extended precision and the bypass alignment.
internal bool TransformSkipRotationEnabled;
internal bool TransformSkipContextEnabled;
internal bool ImplicitRdpcmEnabled;
@@ -372,10 +372,16 @@ internal sealed class Sps
internal int HighestTid => MaxSubLayersMinus1;
- internal bool UsesRangeExtensionTools =>
- TransformSkipRotationEnabled || TransformSkipContextEnabled || ImplicitRdpcmEnabled || ExplicitRdpcmEnabled
- || ExtendedPrecisionProcessing || IntraSmoothingDisabled || HighPrecisionOffsetsEnabled
- || PersistentRiceAdaptationEnabled || CabacBypassAlignmentEnabled;
+ ///
+ /// The range extension tools the decoder does not handle: extended_precision_processing_flag and
+ /// cabac_bypass_alignment_enabled_flag, which only the 16-bit and High Throughput 4:4:4 profiles use.
+ ///
+ internal bool UsesUnsupportedTools => ExtendedPrecisionProcessing || CabacBypassAlignmentEnabled;
+
+ /// log2 of SubWidthC and SubHeightC (table 6-1).
+ internal int ChromaShiftX => SubWidthC - 1;
+
+ internal int ChromaShiftY => SubHeightC - 1;
internal static Sps Parse(BitReader r)
{
@@ -753,9 +759,6 @@ internal sealed class Pps
internal int[] RowBd = [];
- internal bool UsesRangeExtensionTools => CrossComponentPredictionEnabled || ChromaQpOffsetListEnabled
- || Log2SaoOffsetScaleLuma != 0 || Log2SaoOffsetScaleChroma != 0 || Log2MaxTransformSkipSize != 2;
-
internal static Pps Parse(BitReader r)
{
var p = new Pps
diff --git a/src/Febe.Core/Codecs/H265/Picture.cs b/src/Febe.Core/Codecs/H265/Picture.cs
index 8407614..fd90641 100644
--- a/src/Febe.Core/Codecs/H265/Picture.cs
+++ b/src/Febe.Core/Codecs/H265/Picture.cs
@@ -98,7 +98,7 @@ internal sealed class Picture
private static ushort[] Crop(ushort[] plane, int stride, int x0, int y0, int width, int height)
{
- var result = new ushort[width * height];
+ var result = GC.AllocateUninitializedArray(width * height);
for (var y = 0; y < height; y++)
{
plane.AsSpan(((y0 + y) * stride) + x0, width).CopyTo(result.AsSpan(y * width, width));
diff --git a/tests/Febe.Tests/Media/H265/Conformita/LEGGIMI.md b/tests/Febe.Tests/Media/H265/Conformita/LEGGIMI.md
index ae3ff5c..e84fc23 100644
--- a/tests/Febe.Tests/Media/H265/Conformita/LEGGIMI.md
+++ b/tests/Febe.Tests/Media/H265/Conformita/LEGGIMI.md
@@ -1,10 +1,10 @@
# Flussi di conformità H.265 (HEVC)
Questi flussi provano il decodificatore HEVC scritto in casa (`src/Febe.Core/Codecs/H265`), che serve per i video HEVC
-e per le foto HEIC (profilo Main Still Picture). Tutti i 136 flussi Main, Main 10 e Main Still Picture danno esattamente
-i fotogrammi del YUV ufficiale (`H265ConformanceTests.FramesMatchTheReference`), e ogni immagine decodificata coincide
-con l'hash SEI del suo codificatore dove il flusso lo porta (`H265DecoderTests.EveryPictureMatchesItsHash`). Le prove
-dei flussi RExt restano inconcludenti finché Alberto non decide se servono.
+e per le foto HEIC (profilo Main Still Picture). Tutti i 146 flussi, i 136 Main, Main 10 e Main Still Picture e i 10
+delle estensioni di formato (RExt), danno esattamente i fotogrammi del YUV ufficiale
+(`H265ConformanceTests.FramesMatchTheReference`), e ogni immagine decodificata coincide con l'hash SEI del suo
+codificatore dove il flusso lo porta (`H265DecoderTests.EveryPictureMatchesItsHash`). Nessuna prova è inconcludente.
## Provenienza
@@ -252,11 +252,15 @@ con le righe per fotogramma.
| Insiemi di parametri | `VPSID_A_VIDYO_2`, `VPSSPSPPS_A_MainConcept_1`, `PPS_A_qualcomm_7`, `PS_B_VIDYO_3`, `EXT_A_ericsson_4`, `SLPPLP_A_VIDYO_2`, `TSCL_A_VIDYO_5`, `TSCL_B_VIDYO_4`, `HRD_A_Fujitsu_3`, `FILLER_A_Sony_1` |
| Dimensioni estreme | `PICSIZE_C_Bossen_1`, `PICSIZE_D_Bossen_1`, `AMP_A_Samsung_7` (2560×1600), `WPP_D_ericsson_MAIN_2` (1 CTB di larghezza) |
-## Estensioni di formato (RExt): inconcludenti
+## Estensioni di formato (RExt)
-Un piccolo gruppo di flussi `RExt` (4:0:0, 4:2:2, 4:4:4, 12 bit e i loro strumenti) è qui solo per avere il riferimento
-pronto: le loro prove restano **inconcludenti** finché Alberto non dice se «HEVC» per Febe li comprende (le foto HEIC e
-i video dei telefoni sono Main, Main 10 o Main Still Picture). Nessuno di questi zip conteneva il YUV.
+Un piccolo gruppo di flussi `RExt` (4:0:0, 4:2:2, 4:4:4, 12 bit e i loro strumenti). Le foto HEIC e i video dei
+telefoni sono Main, Main 10 o Main Still Picture, ma questi flussi erano nella serie e il decodificatore li decodifica
+tutti esattamente: 4:0:0, 4:2:2 (due blocchi di croma per unità di trasformata, modi intra della tabella 8-3), 4:4:4,
+fino a 12 bit, predizione fra componenti, RDPCM implicito, rotazione e contesto unico del transform skip, smoothing
+intra spento, adattamento persistente di Rice, `chroma_qp_offset_list`. Restano rifiutati con un'eccezione la
+precisione estesa (`extended_precision_processing_flag`, i profili a 16 bit) e l'allineamento del CABAC
+(`cabac_bypass_alignment_enabled_flag`), che nessun flusso qui usa. Nessuno di questi zip conteneva il YUV.
| Flusso | Profilo | Dimensioni | Fotogrammi | YUV | Che cosa prova |
|---|---|---|---:|:-:|---|
@@ -286,7 +290,7 @@ quelli grandi il cui strumento è già provato da altri.
| `OPFLAG_B_Qualcomm_1` | 2,1 MB | `pic_output_flag` è già in `OPFLAG_A_Qualcomm_1` e `OPFLAG_C_Qualcomm_1` |
| `AMP_D_Hisilicon_3`, `AMP_E_Hisilicon_3`, `AMP_F_Hisilicon_3` | 0,6–0,8 MB l'uno | AMP a 1080p, già in `AMP_A_Samsung_7` e `AMP_B_Samsung_7` |
| `PICSIZE_A_Bossen_1`, `PICSIZE_B_Bossen_1` | grandi | 1056×8440 e 8440×1056 al livello 5.1: la forma estrema è già in `PICSIZE_C/D` al livello 4.1 |
-| il resto di `RExt` | | 16 bit ed EXTPREC, alto rendimento 4:4:4 (WPP di Apple), CCP a 10 e 12 bit, `Main_422_10_A/B`, `TSCTX`, `ExplicitRdpcm`, `PERSIST_RPARAM`, `QMATRIX`, `SAO_A_RExt`, `WAVETILES`, `Bitdepth_B` e gli altri `GENERAL`: finché Alberto non decide sulle estensioni basta il gruppo piccolo qui sopra |
+| il resto di `RExt` | | 16 bit ed EXTPREC, alto rendimento 4:4:4 (WPP di Apple), CCP a 10 e 12 bit, `Main_422_10_A/B`, `TSCTX`, `ExplicitRdpcm`, `PERSIST_RPARAM`, `QMATRIX`, `SAO_A_RExt`, `WAVETILES`, `Bitdepth_B` e gli altri `GENERAL`: le estensioni non servono ai file dei telefoni, basta il gruppo piccolo qui sopra |
Le estensioni multistrato e 3D (MV-HEVC, SHVC, SCC) non sono nemmeno state guardate.
@@ -296,3 +300,9 @@ Le estensioni multistrato e 3D (MV-HEVC, SHVC, SCC) non sono nemmeno state guard
la disposizione a 16 bit di `TSUNEQBD_A_MAIN10_Technicolor_2` (10 e 9 bit) erano scelte nostre: il decodificatore le
ha confermate tutte: i suoi fotogrammi, in quel numero e in quella disposizione, hanno esattamente l'MD5 ufficiale
dello zip, che non può coincidere per caso.
+- L'RDPCM esplicito (`explicit_rdpcm_flag`, solo nelle CU inter con transform skip o senza perdita) è acceso nell'SPS
+ di `Bitdepth_A_RExt_Sony_1` e `CCP_8bit_RExt_QCOM_1`, che coincidono, ma non si è contato quante CU lo usino davvero:
+ la prova vera sarebbe `ExplicitRdpcm_A/B`, rimasto fuori.
+- `H265DecoderTests.TheSetExercisesEveryTool` controlla che ogni strumento che il decodificatore dichiara (tile anche non
+ uniformi e senza deblocking fra i tile, WPP, segmenti dipendenti, liste di scala nell'SPS e nel PPS, lungo termine,
+ PCM e gli strumenti RExt) sia acceso in almeno un flusso: acceso, non per forza usato in ogni sua variante.
diff --git a/tests/Febe.Tests/Media/H265/H265ConformanceStream.cs b/tests/Febe.Tests/Media/H265/H265ConformanceStream.cs
index f4bdafb..12e0f99 100644
--- a/tests/Febe.Tests/Media/H265/H265ConformanceStream.cs
+++ b/tests/Febe.Tests/Media/H265/H265ConformanceStream.cs
@@ -35,7 +35,7 @@ internal sealed partial class H265ConformanceStream
/// The readme of the stream's authors, as published.
public string ReadmePath { get; private set; } = "";
- /// Format range extensions (4:0:0, 4:2:2, 4:4:4, more than 10 bits, RExt tools): not covered by «HEVC» for now.
+ /// Format range extensions (4:0:0, 4:2:2, 4:4:4, more than 10 bits, RExt tools).
public bool IsRangeExtension => Name.Contains("_RExt_", StringComparison.Ordinal);
/// Output size, or null when the stream changes size (then only lists them).
diff --git a/tests/Febe.Tests/Media/H265/H265ConformanceTests.cs b/tests/Febe.Tests/Media/H265/H265ConformanceTests.cs
index d62357d..89d3bab 100644
--- a/tests/Febe.Tests/Media/H265/H265ConformanceTests.cs
+++ b/tests/Febe.Tests/Media/H265/H265ConformanceTests.cs
@@ -4,10 +4,10 @@ using Febe.Core.Codecs.H265;
namespace Febe.Tests.Codecs.H265;
///
-/// The streams of the ITU-T H.265.1 conformance set in Media/H265/Conformita (see LEGGIMI.md there). Every Main, Main 10
-/// and Main Still Picture stream must give exactly the frames of its official YUV (the MD5 of each frame where the YUV
-/// came with the stream, of the whole YUV for all); the range extension streams (4:0:0, 4:2:2, 4:4:4, 12 bits, RExt
-/// tools) stay inconclusive until Alberto says whether «HEVC» covers them.
+/// The streams of the ITU-T H.265.1 conformance set in Media/H265/Conformita (see LEGGIMI.md there). Every stream, Main,
+/// Main 10, Main Still Picture and the format range extensions (4:0:0, 4:2:2, 4:4:4, 12 bits, RExt tools), must give
+/// exactly the frames of its official YUV (the MD5 of each frame where the YUV came with the stream, of the whole YUV for
+/// all).
///
[TestClass]
public sealed class H265ConformanceTests
@@ -19,11 +19,6 @@ public sealed class H265ConformanceTests
public void FramesMatchTheReference(string name)
{
var stream = H265ConformanceStream.Load(name);
- if (stream.IsRangeExtension)
- {
- Assert.Inconclusive($"{name}: estensione di formato (RExt, {stream.Chroma} a {stream.LumaBitDepth} bit), da decodificare solo se Alberto la vuole.");
- }
-
var frames = new List();
var decoder = new H265Decoder();
decoder.FrameOutput += frame => frames.Add(frame.ToYuvFile());
diff --git a/tests/Febe.Tests/Media/H265/H265DecoderTests.cs b/tests/Febe.Tests/Media/H265/H265DecoderTests.cs
index 7327088..276866e 100644
--- a/tests/Febe.Tests/Media/H265/H265DecoderTests.cs
+++ b/tests/Febe.Tests/Media/H265/H265DecoderTests.cs
@@ -1,22 +1,22 @@
using Febe.Core.Codecs.H264;
using Febe.Core.Codecs.H265;
+using Pps = Febe.Core.Codecs.H265.Pps;
+using Sps = Febe.Core.Codecs.H265.Sps;
namespace Febe.Tests.Codecs.H265;
///
-/// The HEVC decoder beyond the whole frames of : every decoded picture of every Main and
-/// Main 10 stream, in decoding order and before cropping, against the hash its encoder wrote in the bitstream (so a wrong
+/// The HEVC decoder beyond the whole frames of : every decoded picture of every stream
+/// of the set, in decoding order and before cropping, against the hash its encoder wrote in the bitstream (so a wrong
/// picture is found where it first goes wrong, also when it is never output); length-prefixed samples; damaged streams.
///
[TestClass]
public sealed class H265DecoderTests
{
- public static IEnumerable