Decodificatore HEVC, seconda parte: predizione inter, tutti i flussi Main e Main 10 coincidono (#58)
La predizione inter scritta dalla norma ITU-T H.265 (§8.3.4, §8.5.3): liste di riferimento con le modifiche, merge con candidati spaziali, temporale, bi-predittivi combinati e nulli e livello di merge parallelo, AMVP con la scala per distanza di POC, TMVP sull'immagine co-locata, interpolazione a 8 prese per la luma e 4 per il croma, predizione pesata di base ed esplicita. Il deblocking prende l'intensità 1 anche dal moto; ogni immagine conserva il moto dei blocchi 4x4, la slice di ogni CTB e le liste delle sue slice per chi la usa come co-locata. Un riferimento mancante diventa un'immagine grigia fuori dal DPB. I filtri d'interpolazione usano i vettori della BCL (Vector128). Perché: senza inter nessun video HEVC reale si decodifica. Ora i 136 flussi Main, Main 10 e Main Still Picture della serie ITU-T H.265.1 danno esattamente il YUV ufficiale e ogni immagine il suo hash SEI; questo conferma anche il numero di fotogrammi e gli MD5 scelti per i flussi senza YUV. Restano inconcludenti solo i 10 flussi RExt, in attesa della decisione di Alberto. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f77b5e4db6
commit
d5e1282261
10 files changed
+1219
-125
No files matched your search
@@ -429,3 +429,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 2026-11-18 | Ciò che il decodificatore dei fotogrammi offre ma la produzione non usa ancora: `AnalyseStillnessAsync` (video di un'immagine ferma) e `Mp4Writer` (rimpacchettare con moov in testa) sono pronti per una tappa successiva e oggi servono solo alle prove; la miniatura di un video passa ancora da un BMP decodificato da SkiaSharp (tappa C1: dare `VideoImage` direttamente al ridimensionamento e al codificatore JPEG scritti in casa, senza BMP) | La riga del 18 novembre sui video li descriveva come se fossero già usati. Il passaggio per BMP resta finché SkiaSharp è nel programma |
|
||||
| 2026-11-18 | 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 |
|
||||
@@ -119,8 +119,11 @@ public sealed partial class H265Decoder
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>bS of §8.7.2.4 between the 4×4 blocks <paramref name="p"/> and <paramref name="q"/> of the grid.</summary>
|
||||
private int BoundaryStrength(int p, int q, int kind)
|
||||
/// <summary>
|
||||
/// bS of §8.7.2.4 between the 4×4 blocks <paramref name="p"/> and <paramref name="q"/> of the grid, in the CTBs
|
||||
/// <paramref name="ctbP"/> and <paramref name="ctbQ"/>.
|
||||
/// </summary>
|
||||
private int BoundaryStrength(Picture picture, int p, int q, int kind, int ctbP, int ctbQ)
|
||||
{
|
||||
if (predMode[p] == ModeIntra || predMode[q] == ModeIntra)
|
||||
{
|
||||
@@ -132,10 +135,62 @@ public sealed partial class H265Decoder
|
||||
return 1;
|
||||
}
|
||||
|
||||
// The motion conditions need the motion data of inter prediction, which is not decoded yet.
|
||||
return 0;
|
||||
// The motion: the pictures referred to (whichever the list), how many vectors, how far apart (4 = one sample).
|
||||
var mp = picture.Motion[p];
|
||||
var mq = picture.Motion[q];
|
||||
if (mp.Ref0 < 0 && mp.Ref1 < 0)
|
||||
{
|
||||
// A block of a CTB that no slice decoded.
|
||||
return 0;
|
||||
}
|
||||
|
||||
var sliceP = slices[ctbSlice[ctbP]];
|
||||
var sliceQ = ctbP == ctbQ ? sliceP : slices[ctbSlice[ctbQ]];
|
||||
var p0 = mp.Ref0 >= 0 ? sliceP.RefPicList[0][mp.Ref0] : null;
|
||||
var p1 = mp.Ref1 >= 0 ? sliceP.RefPicList[1][mp.Ref1] : null;
|
||||
var q0 = mq.Ref0 >= 0 ? sliceQ.RefPicList[0][mq.Ref0] : null;
|
||||
var q1 = mq.Ref1 >= 0 ? sliceQ.RefPicList[1][mq.Ref1] : null;
|
||||
var countP = (p0 is null ? 0 : 1) + (p1 is null ? 0 : 1);
|
||||
var countQ = (q0 is null ? 0 : 1) + (q1 is null ? 0 : 1);
|
||||
if (countP != countQ)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (countP == 1)
|
||||
{
|
||||
if (!ReferenceEquals(p0 ?? p1, q0 ?? q1))
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
int pX = p0 is null ? mp.X1 : mp.X0, pY = p0 is null ? mp.Y1 : mp.Y0;
|
||||
int qX = q0 is null ? mq.X1 : mq.X0, qY = q0 is null ? mq.Y1 : mq.Y0;
|
||||
return Far(pX, pY, qX, qY) ? 1 : 0;
|
||||
}
|
||||
|
||||
var straight = ReferenceEquals(p0, q0) && ReferenceEquals(p1, q1);
|
||||
var crossed = ReferenceEquals(p0, q1) && ReferenceEquals(p1, q0);
|
||||
if (!straight && !crossed)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!ReferenceEquals(p0, p1))
|
||||
{
|
||||
// Two different pictures: the vectors that refer to the same picture are compared.
|
||||
return straight
|
||||
? (Far(mp.X0, mp.Y0, mq.X0, mq.Y0) || Far(mp.X1, mp.Y1, mq.X1, mq.Y1) ? 1 : 0)
|
||||
: (Far(mp.X0, mp.Y0, mq.X1, mq.Y1) || Far(mp.X1, mp.Y1, mq.X0, mq.Y0) ? 1 : 0);
|
||||
}
|
||||
|
||||
// Both vectors of both blocks refer to one picture: bS 1 only when both pairings differ.
|
||||
return (Far(mp.X0, mp.Y0, mq.X0, mq.Y0) || Far(mp.X1, mp.Y1, mq.X1, mq.Y1))
|
||||
&& (Far(mp.X0, mp.Y0, mq.X1, mq.Y1) || Far(mp.X1, mp.Y1, mq.X0, mq.Y0)) ? 1 : 0;
|
||||
}
|
||||
|
||||
private static bool Far(int ax, int ay, int bx, int by) => Math.Abs(ax - bx) >= 4 || Math.Abs(ay - by) >= 4;
|
||||
|
||||
/// <summary>Filters every vertical (or horizontal) edge of the picture: luma on the 8×8 grid, chroma on the 16×16 one.</summary>
|
||||
private void Deblock(Picture picture, bool vertical)
|
||||
{
|
||||
@@ -158,13 +213,15 @@ public sealed partial class H265Decoder
|
||||
}
|
||||
|
||||
var p = vertical ? q - 1 : q - w4;
|
||||
var bS = BoundaryStrength(p, q, kind);
|
||||
var ctbQ = ((gy << 2 >> log2Ctb) * widthInCtbs) + (gx << 2 >> log2Ctb);
|
||||
var ctbP = vertical ? ((gy << 2 >> log2Ctb) * widthInCtbs) + ((gx - 1) << 2 >> log2Ctb) : (((gy - 1) << 2 >> log2Ctb) * widthInCtbs) + (gx << 2 >> log2Ctb);
|
||||
var bS = BoundaryStrength(picture, p, q, kind, ctbP, ctbQ);
|
||||
if (bS == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var header = slices[ctbSlice[((gy << 2 >> log2Ctb) * widthInCtbs) + (gx << 2 >> log2Ctb)]];
|
||||
var header = slices[ctbSlice[ctbQ]];
|
||||
int qpP = qpMap[p], qpQ = qpMap[q];
|
||||
var qpL = (qpQ + qpP + 1) >> 1;
|
||||
var beta = H265Tables.Beta[Math.Clamp(qpL + (header.BetaOffsetDiv2 * 2), 0, 51)] * scaleY;
|
||||
|
||||
@@ -0,0 +1,957 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics;
|
||||
|
||||
namespace Febe.Core.Codecs.H265;
|
||||
|
||||
/// <summary>
|
||||
/// Inter prediction (§8.5.3): reference picture lists (§8.3.4), merge mode and AMVP with their spatial and temporal
|
||||
/// candidates, fractional sample interpolation and weighted sample prediction.
|
||||
/// </summary>
|
||||
public sealed partial class H265Decoder
|
||||
{
|
||||
/// <summary>fL of table 8-11 (luma, quarter samples 1 to 3), taps at −3 to +4.</summary>
|
||||
private static readonly sbyte[] s_lumaFilter =
|
||||
[
|
||||
0, 0, 0, 64, 0, 0, 0, 0,
|
||||
-1, 4, -10, 58, 17, -5, 1, 0,
|
||||
-1, 4, -11, 40, 40, -11, 4, -1,
|
||||
0, 1, -5, 17, 58, -10, 4, -1,
|
||||
];
|
||||
|
||||
/// <summary>fC of table 8-12 (chroma, eighth samples 1 to 7), taps at −1 to +2.</summary>
|
||||
private static readonly sbyte[] s_chromaFilter =
|
||||
[
|
||||
0, 64, 0, 0,
|
||||
-2, 58, 10, -2,
|
||||
-4, 54, 16, -2,
|
||||
-6, 46, 28, -4,
|
||||
-4, 36, 36, -4,
|
||||
-4, 28, 46, -6,
|
||||
-2, 16, 54, -4,
|
||||
-2, 10, 58, -2,
|
||||
];
|
||||
|
||||
/// <summary>l0CandIdx and l1CandIdx of table 8-7 (combined bi-predictive merging candidates).</summary>
|
||||
private static readonly byte[] s_combinedL0 = [0, 1, 0, 2, 1, 2, 0, 3, 1, 3, 2, 3];
|
||||
|
||||
private static readonly byte[] s_combinedL1 = [1, 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2];
|
||||
|
||||
/// <summary>predSamplesL0 and predSamplesL1 of the block being predicted, at 14-bit precision.</summary>
|
||||
private readonly short[] predL0 = new short[64 * 64];
|
||||
|
||||
private readonly short[] predL1 = new short[64 * 64];
|
||||
|
||||
/// <summary>The reference samples a block needs, padded at the picture edges (8-228, 8-229).</summary>
|
||||
private readonly ushort[] refBlock = new ushort[(64 + 7) * (64 + 7)];
|
||||
|
||||
/// <summary>The horizontal pass of a block filtered in both directions.</summary>
|
||||
private readonly short[] filterTemp = new short[(64 + 7) * 64];
|
||||
|
||||
/// <summary>RefPicList0 and RefPicList1 of a P or B slice (§8.3.4), its collocated picture and NoBackwardPredFlag.</summary>
|
||||
private void BuildReferencePictureLists(SliceHeader h)
|
||||
{
|
||||
var total = refStCurrBefore.Count + refStCurrAfter.Count + refLtCurr.Count;
|
||||
if (total == 0 || total != h.NumPicTotalCurr)
|
||||
{
|
||||
throw new H265Exception("Insieme di riferimento che non corrisponde alla slice.");
|
||||
}
|
||||
|
||||
Span<int> temp = stackalloc int[Math.Max(16, total)];
|
||||
var lists = h.Type == SliceType.B ? 2 : 1;
|
||||
h.NoBackwardPred = true;
|
||||
for (var list = 0; list < lists; list++)
|
||||
{
|
||||
// RefPicListTemp0 is StCurrBefore, StCurrAfter, LtCurr; RefPicListTemp1 swaps the first two; both repeat
|
||||
// until they hold Max(num_ref_idx_active, NumPicTotalCurr) entries. An entry is its index in that order.
|
||||
var active = h.NumRefIdxActive[list];
|
||||
var length = Math.Max(active, total);
|
||||
if (temp.Length < length)
|
||||
{
|
||||
temp = new int[length];
|
||||
}
|
||||
|
||||
int before = refStCurrBefore.Count, after = refStCurrAfter.Count;
|
||||
var r = 0;
|
||||
while (r < length)
|
||||
{
|
||||
for (var i = 0; i < (list == 0 ? before : after) && r < length; i++)
|
||||
{
|
||||
temp[r++] = list == 0 ? i : before + i;
|
||||
}
|
||||
|
||||
for (var i = 0; i < (list == 0 ? after : before) && r < length; i++)
|
||||
{
|
||||
temp[r++] = list == 0 ? before + i : i;
|
||||
}
|
||||
|
||||
for (var i = 0; i < refLtCurr.Count && r < length; i++)
|
||||
{
|
||||
temp[r++] = before + after + i;
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < active; i++)
|
||||
{
|
||||
var entry = temp[h.ListModification[list] ? h.ListEntry[list][i] : i];
|
||||
var longTerm = entry >= before + after;
|
||||
var picture = entry < before ? refStCurrBefore[entry] : !longTerm ? refStCurrAfter[entry - before] : refLtCurr[entry - before - after];
|
||||
h.RefPicList[list][i] = picture;
|
||||
h.RefPoc[list][i] = picture.Poc;
|
||||
h.RefIsLongTerm[list][i] = longTerm;
|
||||
h.NoBackwardPred &= picture.Poc <= cur!.Poc;
|
||||
}
|
||||
}
|
||||
|
||||
h.ColPic = null;
|
||||
if (h.TemporalMvpEnabled)
|
||||
{
|
||||
var list = h.Type == SliceType.B && !h.CollocatedFromL0 ? 1 : 0;
|
||||
if (h.CollocatedRefIdx >= h.NumRefIdxActive[list])
|
||||
{
|
||||
throw new H265Exception("Immagine co-locata fuori dalla lista.");
|
||||
}
|
||||
|
||||
h.ColPic = h.RefPicList[list][h.CollocatedRefIdx];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The prediction block availability (§6.4.2) of the neighbour (xN, yN) of a prediction block of the current coding
|
||||
/// unit, false also when the neighbour is intra.
|
||||
/// </summary>
|
||||
private bool NeighbourAvailable(int xPb, int yPb, int nPbW, int nPbH, int partIdx, int xN, int yN)
|
||||
{
|
||||
var size = 1 << cuLog2;
|
||||
bool available;
|
||||
if (xN >= cuX && yN >= cuY && xN < cuX + size && yN < cuY + size)
|
||||
{
|
||||
// In the same coding block: everything decoded before, except partition 2 seen from partition 1 of NxN.
|
||||
available = !((nPbW << 1) == size && (nPbH << 1) == size && partIdx == 1 && cuY + nPbH <= yN && cuX + nPbW > xN);
|
||||
}
|
||||
else
|
||||
{
|
||||
available = Available(xPb, yPb, xN, yN);
|
||||
}
|
||||
|
||||
return available && predMode[Grid(xN, yN)] != ModeIntra;
|
||||
}
|
||||
|
||||
/// <summary>The motion of a merged prediction unit (§8.5.3.2.2 to §8.5.3.2.5).</summary>
|
||||
private MvField MergeMotion(int xPb, int yPb, int nPbW, int nPbH, int partIdx, int mergeIdx)
|
||||
{
|
||||
var originalSize = nPbW + nPbH;
|
||||
var level = pps.Log2ParallelMergeLevel;
|
||||
if (level > 2 && cuLog2 == 3)
|
||||
{
|
||||
// singleMCLFlag: every prediction unit of an 8×8 coding unit shares the list of the 2N×2N one.
|
||||
xPb = cuX;
|
||||
yPb = cuY;
|
||||
nPbW = nPbH = 8;
|
||||
partIdx = 0;
|
||||
}
|
||||
|
||||
var motion = cur!.Motion;
|
||||
Span<MvField> list = stackalloc MvField[5];
|
||||
var count = 0;
|
||||
|
||||
// Spatial candidates (§8.5.3.2.3), in the order A1, B1, B0, A0, B2.
|
||||
int xA1 = xPb - 1, yA1 = yPb + nPbH - 1;
|
||||
var availableA1 = !SameMergeRegion(xPb, yPb, xA1, yA1, level)
|
||||
&& !(partIdx == 1 && cuPartMode is PartNx2N or PartnLx2N or PartnRx2N)
|
||||
&& NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xA1, yA1);
|
||||
var a1 = availableA1 ? motion[Grid(xA1, yA1)] : default;
|
||||
if (availableA1)
|
||||
{
|
||||
list[count++] = a1;
|
||||
}
|
||||
|
||||
int xB1 = xPb + nPbW - 1, yB1 = yPb - 1;
|
||||
var availableB1 = !SameMergeRegion(xPb, yPb, xB1, yB1, level)
|
||||
&& !(partIdx == 1 && cuPartMode is Part2NxN or Part2NxnU or Part2NxnD)
|
||||
&& NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB1, yB1);
|
||||
var b1 = availableB1 ? motion[Grid(xB1, yB1)] : default;
|
||||
var flagB1 = availableB1 && !(availableA1 && a1.SameAs(b1));
|
||||
if (flagB1)
|
||||
{
|
||||
list[count++] = b1;
|
||||
}
|
||||
|
||||
if (mergeIdx < count)
|
||||
{
|
||||
return Restricted(list[mergeIdx], originalSize);
|
||||
}
|
||||
|
||||
int xB0 = xPb + nPbW, yB0 = yPb - 1;
|
||||
var availableB0 = !SameMergeRegion(xPb, yPb, xB0, yB0, level) && NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB0, yB0);
|
||||
var flagB0 = false;
|
||||
if (availableB0)
|
||||
{
|
||||
var b0 = motion[Grid(xB0, yB0)];
|
||||
flagB0 = !(availableB1 && b1.SameAs(b0));
|
||||
if (flagB0)
|
||||
{
|
||||
list[count++] = b0;
|
||||
}
|
||||
}
|
||||
|
||||
int xA0 = xPb - 1, yA0 = yPb + nPbH;
|
||||
var availableA0 = !SameMergeRegion(xPb, yPb, xA0, yA0, level) && NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xA0, yA0);
|
||||
var flagA0 = false;
|
||||
if (availableA0)
|
||||
{
|
||||
var a0 = motion[Grid(xA0, yA0)];
|
||||
flagA0 = !(availableA1 && a1.SameAs(a0));
|
||||
if (flagA0)
|
||||
{
|
||||
list[count++] = a0;
|
||||
}
|
||||
}
|
||||
|
||||
if (count < 4)
|
||||
{
|
||||
// B2 only when one of the four others is missing.
|
||||
int xB2 = xPb - 1, yB2 = yPb - 1;
|
||||
if (!SameMergeRegion(xPb, yPb, xB2, yB2, level) && NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB2, yB2))
|
||||
{
|
||||
var b2 = motion[Grid(xB2, yB2)];
|
||||
if (!(availableA1 && a1.SameAs(b2)) && !(availableB1 && b1.SameAs(b2)))
|
||||
{
|
||||
list[count++] = b2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (mergeIdx < count)
|
||||
{
|
||||
return Restricted(list[mergeIdx], originalSize);
|
||||
}
|
||||
|
||||
// The temporal candidate (§8.5.3.2.8), reference index 0 in each list.
|
||||
if (slice.TemporalMvpEnabled)
|
||||
{
|
||||
var candidate = MvField.Intra;
|
||||
if (TemporalMotionVector(xPb, yPb, nPbW, nPbH, 0, 0, out var x0, out var y0))
|
||||
{
|
||||
candidate.Ref0 = 0;
|
||||
candidate.X0 = x0;
|
||||
candidate.Y0 = y0;
|
||||
}
|
||||
|
||||
if (slice.Type == SliceType.B && TemporalMotionVector(xPb, yPb, nPbW, nPbH, 1, 0, out var x1, out var y1))
|
||||
{
|
||||
candidate.Ref1 = 0;
|
||||
candidate.X1 = x1;
|
||||
candidate.Y1 = y1;
|
||||
}
|
||||
|
||||
if (candidate.Ref0 >= 0 || candidate.Ref1 >= 0)
|
||||
{
|
||||
list[count++] = candidate;
|
||||
}
|
||||
}
|
||||
|
||||
if (mergeIdx < count)
|
||||
{
|
||||
return Restricted(list[mergeIdx], originalSize);
|
||||
}
|
||||
|
||||
var max = slice.MaxNumMergeCand;
|
||||
|
||||
// Combined bi-predictive candidates (§8.5.3.2.4).
|
||||
if (slice.Type == SliceType.B && count > 1 && count < max)
|
||||
{
|
||||
var original = count;
|
||||
for (var combIdx = 0; combIdx < original * (original - 1) && count < max; combIdx++)
|
||||
{
|
||||
var l0 = list[s_combinedL0[combIdx]];
|
||||
var l1 = list[s_combinedL1[combIdx]];
|
||||
if (l0.Ref0 >= 0 && l1.Ref1 >= 0
|
||||
&& (!ReferenceEquals(slice.RefPicList[0][l0.Ref0], slice.RefPicList[1][l1.Ref1]) || l0.X0 != l1.X1 || l0.Y0 != l1.Y1))
|
||||
{
|
||||
list[count++] = new MvField { Ref0 = l0.Ref0, X0 = l0.X0, Y0 = l0.Y0, Ref1 = l1.Ref1, X1 = l1.X1, Y1 = l1.Y1 };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (mergeIdx < count)
|
||||
{
|
||||
return Restricted(list[mergeIdx], originalSize);
|
||||
}
|
||||
|
||||
// Zero candidates (§8.5.3.2.5).
|
||||
var numRefIdx = slice.Type == SliceType.P ? slice.NumRefIdxActive[0] : Math.Min(slice.NumRefIdxActive[0], slice.NumRefIdxActive[1]);
|
||||
var zeroIdx = mergeIdx - count;
|
||||
var refIdx = (sbyte)(zeroIdx < numRefIdx ? zeroIdx : 0);
|
||||
var zero = new MvField { Ref0 = refIdx, Ref1 = slice.Type == SliceType.B ? refIdx : (sbyte)-1 };
|
||||
return Restricted(zero, originalSize);
|
||||
}
|
||||
|
||||
private static bool SameMergeRegion(int xPb, int yPb, int xN, int yN, int level) =>
|
||||
xPb >> level == xN >> level && yPb >> level == yN >> level;
|
||||
|
||||
/// <summary>8×4 and 4×8 prediction units are never bi-predicted (8-118): list 1 is dropped.</summary>
|
||||
private static MvField Restricted(MvField motion, int originalSize)
|
||||
{
|
||||
if (originalSize == 12 && motion.Ref0 >= 0 && motion.Ref1 >= 0)
|
||||
{
|
||||
motion.Ref1 = -1;
|
||||
motion.X1 = motion.Y1 = 0;
|
||||
}
|
||||
|
||||
return motion;
|
||||
}
|
||||
|
||||
/// <summary>mvpLX of AMVP (§8.5.3.2.6, §8.5.3.2.7) for list <paramref name="x"/> and a reference index.</summary>
|
||||
private (int X, int Y) PredictedMotionVector(int xPb, int yPb, int nPbW, int nPbH, int partIdx, int x, int refIdx, int mvpFlag)
|
||||
{
|
||||
var motion = cur!.Motion;
|
||||
var target = slice.RefPicList[x][refIdx];
|
||||
var targetLongTerm = slice.RefIsLongTerm[x][refIdx];
|
||||
var poc = cur.Poc;
|
||||
|
||||
// A: A0 then A1.
|
||||
int xA0 = xPb - 1, yA0 = yPb + nPbH, yA1 = yPb + nPbH - 1;
|
||||
var availableA0 = NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xA0, yA0);
|
||||
var availableA1 = NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xA0, yA1);
|
||||
var isScaled = availableA0 || availableA1;
|
||||
var flagA = false;
|
||||
int ax = 0, ay = 0;
|
||||
for (var k = 0; k < 2 && !flagA; k++)
|
||||
{
|
||||
if (k == 0 ? availableA0 : availableA1)
|
||||
{
|
||||
flagA = SameReference(motion[Grid(xA0, k == 0 ? yA0 : yA1)], x, target, out ax, out ay);
|
||||
}
|
||||
}
|
||||
|
||||
for (var k = 0; k < 2 && !flagA; k++)
|
||||
{
|
||||
if (k == 0 ? availableA0 : availableA1)
|
||||
{
|
||||
flagA = ScaledCandidate(motion[Grid(xA0, k == 0 ? yA0 : yA1)], x, target, targetLongTerm, poc, out ax, out ay);
|
||||
}
|
||||
}
|
||||
|
||||
// B: B0, B1 then B2.
|
||||
int xB0 = xPb + nPbW, xB1 = xPb + nPbW - 1, xB2 = xPb - 1, yB = yPb - 1;
|
||||
var availableB0 = NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB0, yB);
|
||||
var availableB1 = NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB1, yB);
|
||||
var availableB2 = NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB2, yB);
|
||||
var flagB = false;
|
||||
int bx = 0, by = 0;
|
||||
for (var k = 0; k < 3 && !flagB; k++)
|
||||
{
|
||||
if (k == 0 ? availableB0 : k == 1 ? availableB1 : availableB2)
|
||||
{
|
||||
flagB = SameReference(motion[Grid(k == 0 ? xB0 : k == 1 ? xB1 : xB2, yB)], x, target, out bx, out by);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isScaled)
|
||||
{
|
||||
if (flagB)
|
||||
{
|
||||
flagA = true;
|
||||
ax = bx;
|
||||
ay = by;
|
||||
}
|
||||
|
||||
flagB = false;
|
||||
for (var k = 0; k < 3 && !flagB; k++)
|
||||
{
|
||||
if (k == 0 ? availableB0 : k == 1 ? availableB1 : availableB2)
|
||||
{
|
||||
flagB = ScaledCandidate(motion[Grid(k == 0 ? xB0 : k == 1 ? xB1 : xB2, yB)], x, target, targetLongTerm, poc, out bx, out by);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// mvpListLX (8-182): A, B unless equal to A, then the temporal candidate, then zeros.
|
||||
Span<int> candidates = stackalloc int[4];
|
||||
var count = 0;
|
||||
if (flagA)
|
||||
{
|
||||
candidates[0] = ax;
|
||||
candidates[1] = ay;
|
||||
count = 1;
|
||||
}
|
||||
|
||||
if (flagB && !(flagA && ax == bx && ay == by))
|
||||
{
|
||||
candidates[count * 2] = bx;
|
||||
candidates[(count * 2) + 1] = by;
|
||||
count++;
|
||||
}
|
||||
|
||||
if (count < 2 && mvpFlag >= count && slice.TemporalMvpEnabled
|
||||
&& TemporalMotionVector(xPb, yPb, nPbW, nPbH, x, refIdx, out var cx, out var cy))
|
||||
{
|
||||
candidates[count * 2] = cx;
|
||||
candidates[(count * 2) + 1] = cy;
|
||||
count++;
|
||||
}
|
||||
|
||||
return mvpFlag < count ? (candidates[mvpFlag * 2], candidates[(mvpFlag * 2) + 1]) : (0, 0);
|
||||
}
|
||||
|
||||
/// <summary>The first conditions of §8.5.3.2.7: the neighbour refers to the same picture, in list X or in list Y.</summary>
|
||||
private bool SameReference(in MvField n, int x, Picture target, out int mx, out int my)
|
||||
{
|
||||
if (x == 0)
|
||||
{
|
||||
if (n.Ref0 >= 0 && ReferenceEquals(slice.RefPicList[0][n.Ref0], target))
|
||||
{
|
||||
(mx, my) = (n.X0, n.Y0);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (n.Ref1 >= 0 && ReferenceEquals(slice.RefPicList[1][n.Ref1], target))
|
||||
{
|
||||
(mx, my) = (n.X1, n.Y1);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (n.Ref1 >= 0 && ReferenceEquals(slice.RefPicList[1][n.Ref1], target))
|
||||
{
|
||||
(mx, my) = (n.X1, n.Y1);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (n.Ref0 >= 0 && ReferenceEquals(slice.RefPicList[0][n.Ref0], target))
|
||||
{
|
||||
(mx, my) = (n.X0, n.Y0);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
mx = my = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The second conditions of §8.5.3.2.7: a neighbour whose reference is long-term exactly when the target is, its
|
||||
/// vector scaled by the POC distances when both are short-term.
|
||||
/// </summary>
|
||||
private bool ScaledCandidate(in MvField n, int x, Picture target, bool targetLongTerm, int poc, out int mx, out int my)
|
||||
{
|
||||
for (var pass = 0; pass < 2; pass++)
|
||||
{
|
||||
var list = pass == 0 ? x : 1 - x;
|
||||
var refIdx = list == 0 ? n.Ref0 : n.Ref1;
|
||||
if (refIdx < 0 || slice.RefIsLongTerm[list][refIdx] != targetLongTerm)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
mx = list == 0 ? n.X0 : n.X1;
|
||||
my = list == 0 ? n.Y0 : n.Y1;
|
||||
if (!targetLongTerm)
|
||||
{
|
||||
var td = Math.Clamp(poc - slice.RefPoc[list][refIdx], -128, 127);
|
||||
var tb = Math.Clamp(poc - target.Poc, -128, 127);
|
||||
if (td != 0)
|
||||
{
|
||||
mx = ScaleMv(mx, td, tb);
|
||||
my = ScaleMv(my, td, tb);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
mx = my = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The scaling of a motion vector by POC distances (8-179 to 8-181, 8-205 to 8-207).</summary>
|
||||
private static int ScaleMv(int mv, int td, int tb)
|
||||
{
|
||||
var tx = (16384 + (Math.Abs(td) >> 1)) / td;
|
||||
var distScaleFactor = Math.Clamp(((tb * tx) + 32) >> 6, -4096, 4095);
|
||||
var product = distScaleFactor * mv;
|
||||
return Math.Clamp(Math.Sign(product) * ((Math.Abs(product) + 127) >> 8), -32768, 32767);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The temporal luma motion vector prediction (§8.5.3.2.8): the collocated block at the bottom right of the
|
||||
/// prediction block (inside the same CTB row) or else at its centre, on the 16×16 grid of the collocated picture.
|
||||
/// </summary>
|
||||
private bool TemporalMotionVector(int xPb, int yPb, int nPbW, int nPbH, int x, int refIdx, out short mx, out short my)
|
||||
{
|
||||
var col = slice.ColPic;
|
||||
if (col is null || !col.Fits(sps))
|
||||
{
|
||||
mx = my = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
int xBr = xPb + nPbW, yBr = yPb + nPbH;
|
||||
if (yPb >> sps.Log2CtbSize == yBr >> sps.Log2CtbSize && yBr < sps.Height && xBr < sps.Width
|
||||
&& CollocatedMotionVector(col, (xBr >> 4) << 4, (yBr >> 4) << 4, x, refIdx, out mx, out my))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
int xCtr = xPb + (nPbW >> 1), yCtr = yPb + (nPbH >> 1);
|
||||
return CollocatedMotionVector(col, (xCtr >> 4) << 4, (yCtr >> 4) << 4, x, refIdx, out mx, out my);
|
||||
}
|
||||
|
||||
/// <summary>The collocated motion vectors (§8.5.3.2.9).</summary>
|
||||
private bool CollocatedMotionVector(Picture col, int xCol, int yCol, int x, int refIdx, out short mx, out short my)
|
||||
{
|
||||
mx = my = 0;
|
||||
var n = col.Motion[Grid(xCol, yCol)];
|
||||
if (n.Ref0 < 0 && n.Ref1 < 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
int listCol = n.Ref0 < 0 ? 1 : n.Ref1 < 0 ? 0 : slice.NoBackwardPred ? x : slice.CollocatedFromL0 ? 1 : 0;
|
||||
var refIdxCol = listCol == 0 ? n.Ref0 : n.Ref1;
|
||||
var ctb = ((yCol >> col.Sps.Log2CtbSize) * col.Sps.WidthInCtbs) + (xCol >> col.Sps.Log2CtbSize);
|
||||
if (ctb >= col.CtbSlice.Length || col.CtbSlice[ctb] < 0 || col.CtbSlice[ctb] >= col.Slices.Count)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var colSlice = col.Slices[col.CtbSlice[ctb]];
|
||||
var longTerm = slice.RefIsLongTerm[x][refIdx];
|
||||
if (colSlice.RefIsLongTerm[listCol][refIdxCol] != longTerm)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
int vx = listCol == 0 ? n.X0 : n.X1, vy = listCol == 0 ? n.Y0 : n.Y1;
|
||||
var colPocDiff = col.Poc - colSlice.RefPoc[listCol][refIdxCol];
|
||||
var currPocDiff = cur!.Poc - slice.RefPoc[x][refIdx];
|
||||
if (!longTerm && colPocDiff != currPocDiff && colPocDiff != 0)
|
||||
{
|
||||
var td = Math.Clamp(colPocDiff, -128, 127);
|
||||
var tb = Math.Clamp(currPocDiff, -128, 127);
|
||||
vx = ScaleMv(vx, td, tb);
|
||||
vy = ScaleMv(vy, td, tb);
|
||||
}
|
||||
|
||||
mx = (short)vx;
|
||||
my = (short)vy;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The decoding process for inter sample prediction (§8.5.3.3) of one prediction block, written into the picture.</summary>
|
||||
private void PredictInter(int xPb, int yPb, int width, int height, in MvField motion)
|
||||
{
|
||||
var weighted = slice.Type == SliceType.P ? pps.WeightedPred : pps.WeightedBipred;
|
||||
var picture = cur!;
|
||||
for (var c = 0; c < 3; c++)
|
||||
{
|
||||
int x0 = xPb, y0 = yPb, w = width, h = height;
|
||||
if (c > 0)
|
||||
{
|
||||
x0 >>= 1;
|
||||
y0 >>= 1;
|
||||
w >>= 1;
|
||||
h >>= 1;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
if (motion.Ref1 >= 0)
|
||||
{
|
||||
Interpolate(slice.RefPicList[1][motion.Ref1], c, x0, y0, w, h, motion.X1, motion.Y1, bitDepth, predL1);
|
||||
}
|
||||
|
||||
var plane = picture.Planes[c];
|
||||
var stride = picture.Stride(c);
|
||||
if (weighted)
|
||||
{
|
||||
ExplicitWeights(plane, stride, x0, y0, w, h, c, motion, bitDepth);
|
||||
}
|
||||
else
|
||||
{
|
||||
DefaultWeights(plane, stride, x0, y0, w, h, motion, bitDepth);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The default weighted sample prediction (§8.5.3.3.4.2): a rounded shift, or the rounded mean of both lists.</summary>
|
||||
private void DefaultWeights(ushort[] plane, int stride, int x0, int y0, int w, int h, in MvField motion, int bitDepth)
|
||||
{
|
||||
var max = (1 << bitDepth) - 1;
|
||||
if (motion.Ref0 >= 0 && motion.Ref1 >= 0)
|
||||
{
|
||||
var shift = 15 - bitDepth;
|
||||
var offset = 1 << (shift - 1);
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
var row = plane.AsSpan(((y0 + y) * stride) + x0, w);
|
||||
var a = predL0.AsSpan(y * w, w);
|
||||
var b = predL1.AsSpan(y * w, w);
|
||||
for (var x = 0; x < row.Length; x++)
|
||||
{
|
||||
row[x] = (ushort)Math.Clamp((a[x] + b[x] + offset) >> shift, 0, max);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var source = motion.Ref0 >= 0 ? predL0 : predL1;
|
||||
var shift = 14 - bitDepth;
|
||||
var offset = shift > 0 ? 1 << (shift - 1) : 0;
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
var row = plane.AsSpan(((y0 + y) * stride) + x0, w);
|
||||
var a = source.AsSpan(y * w, w);
|
||||
for (var x = 0; x < row.Length; x++)
|
||||
{
|
||||
row[x] = (ushort)Math.Clamp((a[x] + offset) >> shift, 0, max);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The explicit weighted sample prediction (§8.5.3.3.4.3) with the weights and offsets of the slice header.</summary>
|
||||
private void ExplicitWeights(ushort[] plane, int stride, int x0, int y0, int w, int h, int c, in MvField motion, int bitDepth)
|
||||
{
|
||||
var max = (1 << bitDepth) - 1;
|
||||
var shift1 = 14 - bitDepth;
|
||||
var log2Wd = (c == 0 ? slice.LumaLog2WeightDenom : slice.ChromaLog2WeightDenom) + shift1;
|
||||
int w0 = 0, o0 = 0, w1 = 0, o1 = 0;
|
||||
if (motion.Ref0 >= 0)
|
||||
{
|
||||
w0 = c == 0 ? slice.LumaWeight[0][motion.Ref0] : slice.ChromaWeight[0][(motion.Ref0 * 2) + c - 1];
|
||||
o0 = c == 0 ? slice.LumaOffset[0][motion.Ref0] : slice.ChromaOffset[0][(motion.Ref0 * 2) + c - 1];
|
||||
}
|
||||
|
||||
if (motion.Ref1 >= 0)
|
||||
{
|
||||
w1 = c == 0 ? slice.LumaWeight[1][motion.Ref1] : slice.ChromaWeight[1][(motion.Ref1 * 2) + c - 1];
|
||||
o1 = c == 0 ? slice.LumaOffset[1][motion.Ref1] : slice.ChromaOffset[1][(motion.Ref1 * 2) + c - 1];
|
||||
}
|
||||
|
||||
if (motion.Ref0 >= 0 && motion.Ref1 >= 0)
|
||||
{
|
||||
var round = (o0 + o1 + 1) << log2Wd;
|
||||
var shift = log2Wd + 1;
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
var row = plane.AsSpan(((y0 + y) * stride) + x0, w);
|
||||
var a = predL0.AsSpan(y * w, w);
|
||||
var b = predL1.AsSpan(y * w, w);
|
||||
for (var x = 0; x < row.Length; x++)
|
||||
{
|
||||
row[x] = (ushort)Math.Clamp(((a[x] * w0) + (b[x] * w1) + round) >> shift, 0, max);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var source = motion.Ref0 >= 0 ? predL0 : predL1;
|
||||
var weight = motion.Ref0 >= 0 ? w0 : w1;
|
||||
var add = motion.Ref0 >= 0 ? o0 : o1;
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
var row = plane.AsSpan(((y0 + y) * stride) + x0, w);
|
||||
var a = source.AsSpan(y * w, w);
|
||||
if (log2Wd >= 1)
|
||||
{
|
||||
var rounding = 1 << (log2Wd - 1);
|
||||
for (var x = 0; x < row.Length; x++)
|
||||
{
|
||||
row[x] = (ushort)Math.Clamp((((a[x] * weight) + rounding) >> log2Wd) + add, 0, max);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var x = 0; x < row.Length; x++)
|
||||
{
|
||||
row[x] = (ushort)Math.Clamp((a[x] * weight) + add, 0, max);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The fractional sample interpolation (§8.5.3.3.3) of one component of a block from a reference picture, at 14-bit
|
||||
/// precision: 8 taps for luma in quarter samples, 4 taps for chroma in eighth samples.
|
||||
/// </summary>
|
||||
private void Interpolate(Picture reference, int c, int x0, int y0, int w, int h, int mvX, int mvY, int bitDepth, short[] output)
|
||||
{
|
||||
var luma = c == 0;
|
||||
var taps = luma ? 8 : 4;
|
||||
var before = luma ? 3 : 1;
|
||||
var fracBits = luma ? 2 : 3;
|
||||
var fracX = mvX & ((1 << fracBits) - 1);
|
||||
var fracY = mvY & ((1 << fracBits) - 1);
|
||||
var xInt = x0 + (mvX >> fracBits);
|
||||
var yInt = y0 + (mvY >> fracBits);
|
||||
var plane = reference.Planes[c];
|
||||
var planeWidth = luma ? reference.Width : reference.ChromaWidth;
|
||||
var planeHeight = luma ? reference.Height : reference.ChromaHeight;
|
||||
|
||||
// The reference samples, from (xInt − before, yInt − before): straight from the picture when they are all in it,
|
||||
// otherwise copied with the coordinates clamped to the picture.
|
||||
int left = xInt - before, top = yInt - before, rw = w + taps - 1, rh = h + taps - 1;
|
||||
ushort[] source;
|
||||
int origin, stride;
|
||||
if (left >= 0 && top >= 0 && left + rw <= planeWidth && top + rh <= planeHeight)
|
||||
{
|
||||
source = plane;
|
||||
stride = planeWidth;
|
||||
origin = (top * stride) + left;
|
||||
}
|
||||
else
|
||||
{
|
||||
source = refBlock;
|
||||
stride = rw;
|
||||
origin = 0;
|
||||
// The columns inside the picture are copied, those outside repeat the edge sample.
|
||||
var inStart = Math.Clamp(-left, 0, rw);
|
||||
var inEnd = Math.Clamp(planeWidth - left, inStart, rw);
|
||||
for (var y = 0; y < rh; y++)
|
||||
{
|
||||
var sourceRow = plane.AsSpan(Math.Clamp(top + y, 0, planeHeight - 1) * planeWidth, planeWidth);
|
||||
var row = refBlock.AsSpan(y * rw, rw);
|
||||
if (inEnd > inStart)
|
||||
{
|
||||
sourceRow.Slice(left + inStart, inEnd - inStart).CopyTo(row[inStart..]);
|
||||
}
|
||||
|
||||
row[..inStart].Fill(sourceRow[0]);
|
||||
row[inEnd..].Fill(sourceRow[^1]);
|
||||
}
|
||||
}
|
||||
|
||||
var shift1 = bitDepth - 8;
|
||||
var shift3 = 14 - bitDepth;
|
||||
var filters = luma ? s_lumaFilter : s_chromaFilter;
|
||||
if (fracX == 0 && fracY == 0)
|
||||
{
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
var row = source.AsSpan(origin + ((y + before) * stride) + before, w);
|
||||
var o = output.AsSpan(y * w, w);
|
||||
var x = 0;
|
||||
if (Vector128.IsHardwareAccelerated)
|
||||
{
|
||||
for (; x + 8 <= w; x += 8)
|
||||
{
|
||||
(Vector128.Create<ushort>(row.Slice(x, 8)).AsInt16() << shift3).CopyTo(o.Slice(x, 8));
|
||||
}
|
||||
}
|
||||
|
||||
for (; x < w; x++)
|
||||
{
|
||||
o[x] = (short)(row[x] << shift3);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (fracY == 0)
|
||||
{
|
||||
var f = filters.AsSpan(fracX * taps, taps);
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
FilterRow(source, origin + ((y + before) * stride), 1, f, w, shift1, output.AsSpan(y * w, w));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (fracX == 0)
|
||||
{
|
||||
var f = filters.AsSpan(fracY * taps, taps);
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
FilterRow(source, origin + (y * stride) + before, stride, f, w, shift1, output.AsSpan(y * w, w));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Both: the horizontal pass on every row the vertical one needs, then the vertical pass with a shift of 6.
|
||||
var fx = filters.AsSpan(fracX * taps, taps);
|
||||
for (var y = 0; y < rh; y++)
|
||||
{
|
||||
FilterRow(source, origin + (y * stride), 1, fx, w, shift1, filterTemp.AsSpan(y * w, w));
|
||||
}
|
||||
|
||||
var fy = filters.AsSpan(fracY * taps, taps);
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
FilterColumn(filterTemp, y * w, w, fy, w, output.AsSpan(y * w, w));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One row of a filter over samples, <paramref name="step"/> apart (1 horizontally, the stride vertically): 8 outputs
|
||||
/// at a time in vectors where the processor has them, the rest one by one.
|
||||
/// </summary>
|
||||
private static void FilterRow(ushort[] source, int start, int step, ReadOnlySpan<sbyte> f, int w, int shift, Span<short> output)
|
||||
{
|
||||
var x = 0;
|
||||
var taps = f.Length;
|
||||
var src = source.AsSpan(start);
|
||||
if (src.Length < w + ((taps - 1) * step) || output.Length < w)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(source));
|
||||
}
|
||||
|
||||
if (Vector128.IsHardwareAccelerated && w >= 8)
|
||||
{
|
||||
ref var s0 = ref MemoryMarshal.GetReference(src);
|
||||
ref var o0 = ref MemoryMarshal.GetReference(output);
|
||||
var st = (nuint)step;
|
||||
if (shift == 0)
|
||||
{
|
||||
// 8-bit samples: every product and every partial sum fits in 16 bits (at most 88 × 255).
|
||||
Vector128<short> c0 = Vector128.Create((short)f[0]), c1 = Vector128.Create((short)f[1]);
|
||||
Vector128<short> c2 = Vector128.Create((short)f[2]), c3 = Vector128.Create((short)f[3]);
|
||||
if (taps == 8)
|
||||
{
|
||||
Vector128<short> c4 = Vector128.Create((short)f[4]), c5 = Vector128.Create((short)f[5]);
|
||||
Vector128<short> c6 = Vector128.Create((short)f[6]), c7 = Vector128.Create((short)f[7]);
|
||||
for (; x + 8 <= w; x += 8)
|
||||
{
|
||||
var at = (nuint)x;
|
||||
var sum = (Vector128.LoadUnsafe(ref s0, at).AsInt16() * c0) + (Vector128.LoadUnsafe(ref s0, at + st).AsInt16() * c1)
|
||||
+ (Vector128.LoadUnsafe(ref s0, at + (2 * st)).AsInt16() * c2) + (Vector128.LoadUnsafe(ref s0, at + (3 * st)).AsInt16() * c3)
|
||||
+ (Vector128.LoadUnsafe(ref s0, at + (4 * st)).AsInt16() * c4) + (Vector128.LoadUnsafe(ref s0, at + (5 * st)).AsInt16() * c5)
|
||||
+ (Vector128.LoadUnsafe(ref s0, at + (6 * st)).AsInt16() * c6) + (Vector128.LoadUnsafe(ref s0, at + (7 * st)).AsInt16() * c7);
|
||||
sum.StoreUnsafe(ref o0, at);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (; x + 8 <= w; x += 8)
|
||||
{
|
||||
var at = (nuint)x;
|
||||
var sum = (Vector128.LoadUnsafe(ref s0, at).AsInt16() * c0) + (Vector128.LoadUnsafe(ref s0, at + st).AsInt16() * c1)
|
||||
+ (Vector128.LoadUnsafe(ref s0, at + (2 * st)).AsInt16() * c2) + (Vector128.LoadUnsafe(ref s0, at + (3 * st)).AsInt16() * c3);
|
||||
sum.StoreUnsafe(ref o0, at);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (; x + 8 <= w; x += 8)
|
||||
{
|
||||
var at = (nuint)x;
|
||||
Vector128<int> lo = Vector128<int>.Zero, hi = Vector128<int>.Zero;
|
||||
for (var k = 0; k < taps; k++)
|
||||
{
|
||||
var (a, b) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + ((nuint)k * st)));
|
||||
var c = Vector128.Create((int)f[k]);
|
||||
lo += a.AsInt32() * c;
|
||||
hi += b.AsInt32() * c;
|
||||
}
|
||||
|
||||
Vector128.Narrow(lo >> shift, hi >> shift).StoreUnsafe(ref o0, at);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (taps == 8)
|
||||
{
|
||||
int f0 = f[0], f1 = f[1], f2 = f[2], f3 = f[3], f4 = f[4], f5 = f[5], f6 = f[6], f7 = f[7];
|
||||
for (; x < w; x++)
|
||||
{
|
||||
var sum = (f0 * src[x]) + (f1 * src[x + step]) + (f2 * src[x + (2 * step)]) + (f3 * src[x + (3 * step)])
|
||||
+ (f4 * src[x + (4 * step)]) + (f5 * src[x + (5 * step)]) + (f6 * src[x + (6 * step)]) + (f7 * src[x + (7 * step)]);
|
||||
output[x] = (short)(sum >> shift);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int f0 = f[0], f1 = f[1], f2 = f[2], f3 = f[3];
|
||||
for (; x < w; x++)
|
||||
{
|
||||
var sum = (f0 * src[x]) + (f1 * src[x + step]) + (f2 * src[x + (2 * step)]) + (f3 * src[x + (3 * step)]);
|
||||
output[x] = (short)(sum >> shift);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The vertical pass over the 14-bit rows of the horizontal one (8-236, 8-246), shifted by 6.</summary>
|
||||
private static void FilterColumn(short[] source, int start, int stride, ReadOnlySpan<sbyte> f, int w, Span<short> output)
|
||||
{
|
||||
var x = 0;
|
||||
var taps = f.Length;
|
||||
var src = source.AsSpan(start);
|
||||
if (src.Length < w + ((taps - 1) * stride) || output.Length < w)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(source));
|
||||
}
|
||||
|
||||
if (Vector128.IsHardwareAccelerated && w >= 8)
|
||||
{
|
||||
ref var s0 = ref MemoryMarshal.GetReference(src);
|
||||
ref var o0 = ref MemoryMarshal.GetReference(output);
|
||||
var st = (nuint)stride;
|
||||
Vector128<int> c0 = Vector128.Create((int)f[0]), c1 = Vector128.Create((int)f[1]);
|
||||
Vector128<int> c2 = Vector128.Create((int)f[2]), c3 = Vector128.Create((int)f[3]);
|
||||
if (taps == 8)
|
||||
{
|
||||
Vector128<int> c4 = Vector128.Create((int)f[4]), c5 = Vector128.Create((int)f[5]);
|
||||
Vector128<int> c6 = Vector128.Create((int)f[6]), c7 = Vector128.Create((int)f[7]);
|
||||
for (; x + 8 <= w; x += 8)
|
||||
{
|
||||
var at = (nuint)x;
|
||||
var (a0, b0) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at));
|
||||
var (a1, b1) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + st));
|
||||
var (a2, b2) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (2 * st)));
|
||||
var (a3, b3) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (3 * st)));
|
||||
var (a4, b4) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (4 * st)));
|
||||
var (a5, b5) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (5 * st)));
|
||||
var (a6, b6) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (6 * st)));
|
||||
var (a7, b7) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (7 * st)));
|
||||
var lo = (a0 * c0) + (a1 * c1) + (a2 * c2) + (a3 * c3) + (a4 * c4) + (a5 * c5) + (a6 * c6) + (a7 * c7);
|
||||
var hi = (b0 * c0) + (b1 * c1) + (b2 * c2) + (b3 * c3) + (b4 * c4) + (b5 * c5) + (b6 * c6) + (b7 * c7);
|
||||
Vector128.Narrow(lo >> 6, hi >> 6).StoreUnsafe(ref o0, at);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (; x + 8 <= w; x += 8)
|
||||
{
|
||||
var at = (nuint)x;
|
||||
var (a0, b0) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at));
|
||||
var (a1, b1) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + st));
|
||||
var (a2, b2) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (2 * st)));
|
||||
var (a3, b3) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (3 * st)));
|
||||
var lo = (a0 * c0) + (a1 * c1) + (a2 * c2) + (a3 * c3);
|
||||
var hi = (b0 * c0) + (b1 * c1) + (b2 * c2) + (b3 * c3);
|
||||
Vector128.Narrow(lo >> 6, hi >> 6).StoreUnsafe(ref o0, at);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (taps == 8)
|
||||
{
|
||||
int f0 = f[0], f1 = f[1], f2 = f[2], f3 = f[3], f4 = f[4], f5 = f[5], f6 = f[6], f7 = f[7];
|
||||
for (; x < w; x++)
|
||||
{
|
||||
var sum = (f0 * src[x]) + (f1 * src[x + stride]) + (f2 * src[x + (2 * stride)]) + (f3 * src[x + (3 * stride)])
|
||||
+ (f4 * src[x + (4 * stride)]) + (f5 * src[x + (5 * stride)]) + (f6 * src[x + (6 * stride)]) + (f7 * src[x + (7 * stride)]);
|
||||
output[x] = (short)(sum >> 6);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int f0 = f[0], f1 = f[1], f2 = f[2], f3 = f[3];
|
||||
for (; x < w; x++)
|
||||
{
|
||||
var sum = (f0 * src[x]) + (f1 * src[x + stride]) + (f2 * src[x + (2 * stride)]) + (f3 * src[x + (3 * stride)]);
|
||||
output[x] = (short)(sum >> 6);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ 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];
|
||||
private readonly List<SliceHeader> slices = [];
|
||||
private List<SliceHeader> slices = [];
|
||||
|
||||
private Picture? cur;
|
||||
private Sps sps = null!;
|
||||
@@ -98,7 +98,9 @@ public sealed partial class H265Decoder
|
||||
{
|
||||
sps = s;
|
||||
pps = p;
|
||||
slices = cur!.Slices;
|
||||
slices.Clear();
|
||||
cur.Motion.AsSpan().Fill(MvField.Intra);
|
||||
widthInCtbs = s.WidthInCtbs;
|
||||
var nw = (s.Width + 3) >> 2;
|
||||
var nh = (s.Height + 3) >> 2;
|
||||
@@ -124,9 +126,14 @@ public sealed partial class H265Decoder
|
||||
}
|
||||
|
||||
var ctbs = s.CtbCount;
|
||||
if (ctbSlice.Length != ctbs)
|
||||
if (cur.CtbSlice.Length != ctbs)
|
||||
{
|
||||
cur.CtbSlice = new int[ctbs];
|
||||
}
|
||||
|
||||
ctbSlice = cur.CtbSlice;
|
||||
if (saoType.Length != ctbs * 3)
|
||||
{
|
||||
ctbSlice = new int[ctbs];
|
||||
saoType = new byte[ctbs * 3];
|
||||
saoClass = new byte[ctbs * 3];
|
||||
saoOffset = new short[ctbs * 12];
|
||||
@@ -465,7 +472,7 @@ public sealed partial class H265Decoder
|
||||
{
|
||||
cuIntra = false;
|
||||
FillGrid(predMode, x0, y0, size, size, ModeSkip);
|
||||
PredictionUnit(x0, y0, size, size, true, depth);
|
||||
PredictionUnit(x0, y0, size, size, true, depth, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -729,77 +736,81 @@ public sealed partial class H265Decoder
|
||||
switch (cuPartMode)
|
||||
{
|
||||
case Part2Nx2N:
|
||||
return PredictionUnit(x0, y0, size, size, false, depth);
|
||||
return PredictionUnit(x0, y0, size, size, false, depth, 0);
|
||||
case Part2NxN:
|
||||
{
|
||||
var merge = PredictionUnit(x0, y0, size, half, false, depth);
|
||||
PredictionUnit(x0, y0 + half, size, half, false, depth);
|
||||
var merge = PredictionUnit(x0, y0, size, half, false, depth, 0);
|
||||
PredictionUnit(x0, y0 + half, size, half, false, depth, 1);
|
||||
return merge;
|
||||
}
|
||||
|
||||
case PartNx2N:
|
||||
{
|
||||
var merge = PredictionUnit(x0, y0, half, size, false, depth);
|
||||
PredictionUnit(x0 + half, y0, half, size, false, depth);
|
||||
var merge = PredictionUnit(x0, y0, half, size, false, depth, 0);
|
||||
PredictionUnit(x0 + half, y0, half, size, false, depth, 1);
|
||||
return merge;
|
||||
}
|
||||
|
||||
case Part2NxnU:
|
||||
{
|
||||
var merge = PredictionUnit(x0, y0, size, quarter, false, depth);
|
||||
PredictionUnit(x0, y0 + quarter, size, size - quarter, false, depth);
|
||||
var merge = PredictionUnit(x0, y0, size, quarter, false, depth, 0);
|
||||
PredictionUnit(x0, y0 + quarter, size, size - quarter, false, depth, 1);
|
||||
return merge;
|
||||
}
|
||||
|
||||
case Part2NxnD:
|
||||
{
|
||||
var merge = PredictionUnit(x0, y0, size, size - quarter, false, depth);
|
||||
PredictionUnit(x0, y0 + size - quarter, size, quarter, false, depth);
|
||||
var merge = PredictionUnit(x0, y0, size, size - quarter, false, depth, 0);
|
||||
PredictionUnit(x0, y0 + size - quarter, size, quarter, false, depth, 1);
|
||||
return merge;
|
||||
}
|
||||
|
||||
case PartnLx2N:
|
||||
{
|
||||
var merge = PredictionUnit(x0, y0, quarter, size, false, depth);
|
||||
PredictionUnit(x0 + quarter, y0, size - quarter, size, false, depth);
|
||||
var merge = PredictionUnit(x0, y0, quarter, size, false, depth, 0);
|
||||
PredictionUnit(x0 + quarter, y0, size - quarter, size, false, depth, 1);
|
||||
return merge;
|
||||
}
|
||||
|
||||
case PartnRx2N:
|
||||
{
|
||||
var merge = PredictionUnit(x0, y0, size - quarter, size, false, depth);
|
||||
PredictionUnit(x0 + size - quarter, y0, quarter, size, false, depth);
|
||||
var merge = PredictionUnit(x0, y0, size - quarter, size, false, depth, 0);
|
||||
PredictionUnit(x0 + size - quarter, y0, quarter, size, false, depth, 1);
|
||||
return merge;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
var merge = PredictionUnit(x0, y0, half, half, false, depth);
|
||||
PredictionUnit(x0 + half, y0, half, half, false, depth);
|
||||
PredictionUnit(x0, y0 + half, half, half, false, depth);
|
||||
PredictionUnit(x0 + half, y0 + half, half, half, false, depth);
|
||||
var merge = PredictionUnit(x0, y0, half, half, false, depth, 0);
|
||||
PredictionUnit(x0 + half, y0, half, half, false, depth, 1);
|
||||
PredictionUnit(x0, y0 + half, half, half, false, depth, 2);
|
||||
PredictionUnit(x0 + half, y0 + half, half, half, false, depth, 3);
|
||||
return merge;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// prediction_unit() (§7.3.8.6) and mvd_coding() (§7.3.8.9). The motion data is read but not used yet: the samples of
|
||||
/// the unit are mid-grey (only with <see cref="ParseInterSlices"/>).
|
||||
/// prediction_unit() (§7.3.8.6) and mvd_coding() (§7.3.8.9), then the motion of the unit (merge or AMVP, §8.5.3.2)
|
||||
/// and its inter prediction samples (§8.5.3.3), to which the residual is added later.
|
||||
/// </summary>
|
||||
private bool PredictionUnit(int x0, int y0, int width, int height, bool skip, int depth)
|
||||
private bool PredictionUnit(int x0, int y0, int width, int height, bool skip, int depth, int partIdx)
|
||||
{
|
||||
MvField motion;
|
||||
var merge = skip || cabac.Flag(CabacTables.MergeFlag);
|
||||
if (merge)
|
||||
{
|
||||
var mergeIdx = 0;
|
||||
if (slice.MaxNumMergeCand > 1 && cabac.Flag(CabacTables.MergeIdx))
|
||||
{
|
||||
var index = 1;
|
||||
while (index < slice.MaxNumMergeCand - 1 && cabac.Bypass() == 1)
|
||||
mergeIdx = 1;
|
||||
while (mergeIdx < slice.MaxNumMergeCand - 1 && cabac.Bypass() == 1)
|
||||
{
|
||||
index++;
|
||||
mergeIdx++;
|
||||
}
|
||||
}
|
||||
|
||||
motion = MergeMotion(x0, y0, width, height, partIdx, mergeIdx);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -816,6 +827,9 @@ public sealed partial class H265Decoder
|
||||
}
|
||||
}
|
||||
|
||||
Span<int> refIdx = [-1, -1];
|
||||
Span<int> mvd = [0, 0, 0, 0];
|
||||
Span<int> mvpFlag = [0, 0];
|
||||
for (var list = 0; list < 2; list++)
|
||||
{
|
||||
if (interPredIdc == 1 - list)
|
||||
@@ -824,55 +838,72 @@ public sealed partial class H265Decoder
|
||||
}
|
||||
|
||||
var count = slice.NumRefIdxActive[list];
|
||||
var index = 0;
|
||||
if (count > 1)
|
||||
{
|
||||
var refIdx = 0;
|
||||
while (refIdx < count - 1 && (refIdx >= 2 ? cabac.Bypass() == 1 : cabac.Flag(CabacTables.RefIdx + refIdx)))
|
||||
while (index < count - 1 && (index >= 2 ? cabac.Bypass() == 1 : cabac.Flag(CabacTables.RefIdx + index)))
|
||||
{
|
||||
refIdx++;
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
refIdx[list] = index;
|
||||
if (!(list == 1 && slice.MvdL1Zero && interPredIdc == 2))
|
||||
{
|
||||
MvdCoding();
|
||||
MvdCoding(out mvd[list * 2], out mvd[(list * 2) + 1]);
|
||||
}
|
||||
|
||||
cabac.Flag(CabacTables.MvpFlag);
|
||||
mvpFlag[list] = cabac.Flag(CabacTables.MvpFlag) ? 1 : 0;
|
||||
}
|
||||
|
||||
motion = MvField.Intra;
|
||||
if (refIdx[0] >= 0)
|
||||
{
|
||||
var (x, y) = PredictedMotionVector(x0, y0, width, height, partIdx, 0, refIdx[0], mvpFlag[0]);
|
||||
motion.Ref0 = (sbyte)refIdx[0];
|
||||
motion.X0 = (short)(x + mvd[0]);
|
||||
motion.Y0 = (short)(y + mvd[1]);
|
||||
}
|
||||
|
||||
if (refIdx[1] >= 0)
|
||||
{
|
||||
var (x, y) = PredictedMotionVector(x0, y0, width, height, partIdx, 1, refIdx[1], mvpFlag[1]);
|
||||
motion.Ref1 = (sbyte)refIdx[1];
|
||||
motion.X1 = (short)(x + mvd[2]);
|
||||
motion.Y1 = (short)(y + mvd[3]);
|
||||
}
|
||||
}
|
||||
|
||||
// Inter prediction is the next step of the decoder: mid-grey for now.
|
||||
FillPlane(0, x0, y0, width, height, (ushort)(1 << (sps.BitDepthY - 1)));
|
||||
FillPlane(1, x0 >> 1, y0 >> 1, width >> 1, height >> 1, (ushort)(1 << (sps.BitDepthC - 1)));
|
||||
FillPlane(2, x0 >> 1, y0 >> 1, width >> 1, height >> 1, (ushort)(1 << (sps.BitDepthC - 1)));
|
||||
FillGrid(cur!.Motion, x0, y0, width, height, motion);
|
||||
PredictInter(x0, y0, width, height, motion);
|
||||
return merge;
|
||||
}
|
||||
|
||||
private void MvdCoding()
|
||||
/// <summary>mvd_coding() (§7.3.8.9): MvdLX, horizontal then vertical.</summary>
|
||||
private void MvdCoding(out int x, out int y)
|
||||
{
|
||||
var greater0X = cabac.Flag(CabacTables.AbsMvdGreater0Flag);
|
||||
var greater0Y = cabac.Flag(CabacTables.AbsMvdGreater0Flag);
|
||||
var greater1X = greater0X && cabac.Flag(CabacTables.AbsMvdGreater1Flag);
|
||||
var greater1Y = greater0Y && cabac.Flag(CabacTables.AbsMvdGreater1Flag);
|
||||
x = 0;
|
||||
y = 0;
|
||||
if (greater0X)
|
||||
{
|
||||
if (greater1X)
|
||||
x = greater1X ? ExpGolombBypass(1) + 2 : 1;
|
||||
if (cabac.Bypass() == 1)
|
||||
{
|
||||
ExpGolombBypass(1);
|
||||
x = -x;
|
||||
}
|
||||
|
||||
cabac.Bypass();
|
||||
}
|
||||
|
||||
if (greater0Y)
|
||||
{
|
||||
if (greater1Y)
|
||||
y = greater1Y ? ExpGolombBypass(1) + 2 : 1;
|
||||
if (cabac.Bypass() == 1)
|
||||
{
|
||||
ExpGolombBypass(1);
|
||||
y = -y;
|
||||
}
|
||||
|
||||
cabac.Bypass();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@ namespace Febe.Core.Codecs.H265;
|
||||
/// <summary>
|
||||
/// 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, deblocking and SAO. Intra pictures only for now: inter prediction is the next step,
|
||||
/// and a P or B slice raises an <see cref="H265Exception"/> (see <see cref="ParseInterSlices"/>). Not handled (an
|
||||
/// skip, sign data hiding, scaling lists, inter prediction (merge, AMVP, temporal motion vector prediction, weighted
|
||||
/// prediction), deblocking and SAO. Not handled (an
|
||||
/// <see cref="H265Exception"/>): 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.
|
||||
/// </summary>
|
||||
@@ -37,10 +37,13 @@ public sealed partial class H265Decoder
|
||||
/// <summary>The slices of the current picture are skipped (a RASL picture that cannot be decoded, no IRAP yet).</summary>
|
||||
private bool skipping;
|
||||
|
||||
/// <summary>The five lists of the reference picture set of the current picture (§8.3.2); null for "no reference picture".</summary>
|
||||
private readonly List<Picture?> refStCurrBefore = [];
|
||||
private readonly List<Picture?> refStCurrAfter = [];
|
||||
private readonly List<Picture?> refLtCurr = [];
|
||||
/// <summary>
|
||||
/// The three lists of the reference picture set that the current picture uses (§8.3.2), a generated picture in place
|
||||
/// of "no reference picture" (§8.3.3).
|
||||
/// </summary>
|
||||
private readonly List<Picture> refStCurrBefore = [];
|
||||
private readonly List<Picture> refStCurrAfter = [];
|
||||
private readonly List<Picture> refLtCurr = [];
|
||||
|
||||
/// <summary>Raised for each frame in output order (the bumping process of C.5.2.4), cropped.</summary>
|
||||
public event Action<H265Frame>? FrameOutput;
|
||||
@@ -48,12 +51,6 @@ public sealed partial class H265Decoder
|
||||
/// <summary>Raised for each picture once decoded and filtered, in decoding order (for the decoded picture hash).</summary>
|
||||
internal event Action<Picture>? PictureDecoded;
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the syntax of P and B slices (with every prediction unit predicted as mid-grey) instead of refusing them:
|
||||
/// only to check the parsing of the inter syntax before inter prediction exists. The pictures are not correct.
|
||||
/// </summary>
|
||||
internal bool ParseInterSlices { get; set; }
|
||||
|
||||
/// <summary>Coded pictures met so far, also those skipped.</summary>
|
||||
public long PicturesDecoded => codedPictures;
|
||||
|
||||
@@ -215,13 +212,13 @@ public sealed partial class H265Decoder
|
||||
throw new H265Exception("Parametri diversi fra le slice di un'immagine.");
|
||||
}
|
||||
|
||||
if (!header.IsIntra && !ParseInterSlices)
|
||||
{
|
||||
throw new H265Exception("La predizione inter HEVC non è ancora gestita.");
|
||||
}
|
||||
|
||||
if (!header.Dependent)
|
||||
{
|
||||
if (!header.IsIntra)
|
||||
{
|
||||
BuildReferencePictureLists(header);
|
||||
}
|
||||
|
||||
sliceHeader = header;
|
||||
slices.Add(header);
|
||||
}
|
||||
@@ -394,7 +391,7 @@ public sealed partial class H265Decoder
|
||||
|
||||
if (h.UsedByCurrPicLt[i])
|
||||
{
|
||||
refLtCurr.Add(found >= 0 ? dpb[found] : null);
|
||||
refLtCurr.Add(found >= 0 ? dpb[found] : MissingReference(s, pocLt));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -405,7 +402,7 @@ public sealed partial class H265Decoder
|
||||
var picture = FindShortTerm(poc + rps.DeltaPocS0[i], keep);
|
||||
if (rps.UsedS0[i])
|
||||
{
|
||||
refStCurrBefore.Add(picture);
|
||||
refStCurrBefore.Add(picture ?? MissingReference(s, poc + rps.DeltaPocS0[i]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -414,7 +411,7 @@ public sealed partial class H265Decoder
|
||||
var picture = FindShortTerm(poc + rps.DeltaPocS1[i], keep);
|
||||
if (rps.UsedS1[i])
|
||||
{
|
||||
refStCurrAfter.Add(picture);
|
||||
refStCurrAfter.Add(picture ?? MissingReference(s, poc + rps.DeltaPocS1[i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -429,6 +426,20 @@ public sealed partial class H265Decoder
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A picture for a reference that is not in the DPB (§8.3.3.2): every sample at the middle of its range, every block
|
||||
/// intra. It is not put in the DPB and never output; only damaged or cut streams need one.
|
||||
/// </summary>
|
||||
private static Picture MissingReference(Sps s, int poc)
|
||||
{
|
||||
var picture = new Picture(s) { Poc = poc, Generated = true };
|
||||
picture.Planes[0].AsSpan().Fill((ushort)(1 << (s.BitDepthY - 1)));
|
||||
picture.Planes[1].AsSpan().Fill((ushort)(1 << (s.BitDepthC - 1)));
|
||||
picture.Planes[2].AsSpan().Fill((ushort)(1 << (s.BitDepthC - 1)));
|
||||
picture.Motion.AsSpan().Fill(MvField.Intra);
|
||||
return picture;
|
||||
}
|
||||
|
||||
private Picture? FindShortTerm(int poc, Span<bool> keep)
|
||||
{
|
||||
for (var k = 0; k < dpb.Count; k++)
|
||||
|
||||
@@ -20,6 +20,7 @@ internal sealed class Picture
|
||||
new ushort[ChromaWidth * ChromaHeight],
|
||||
new ushort[ChromaWidth * ChromaHeight],
|
||||
];
|
||||
Motion = new MvField[((Width + 3) >> 2) * ((Height + 3) >> 2)];
|
||||
}
|
||||
|
||||
/// <summary>The SPS of the picture: a picture of the pool is reused for another SPS of the same size.</summary>
|
||||
@@ -58,6 +59,15 @@ internal sealed class Picture
|
||||
/// <summary>Every slice of the picture is an I slice: it does not depend on other pictures.</summary>
|
||||
internal bool IntraOnly;
|
||||
|
||||
/// <summary>The motion of every 4×4 luma block (§8.5.3), kept for the pictures that take this one as collocated (TMVP).</summary>
|
||||
internal MvField[] Motion { get; }
|
||||
|
||||
/// <summary>Index in <see cref="Slices"/> of the slice of each CTB (raster order), −1 where none was decoded.</summary>
|
||||
internal int[] CtbSlice = [];
|
||||
|
||||
/// <summary>The independent slice segment headers of the picture, with their reference picture lists.</summary>
|
||||
internal List<SliceHeader> Slices { get; } = [];
|
||||
|
||||
internal bool IsReference => ShortTerm || LongTerm;
|
||||
|
||||
internal int Stride(int cIdx) => cIdx == 0 ? Width : ChromaWidth;
|
||||
@@ -98,6 +108,26 @@ internal sealed class Picture
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The motion of a prediction block: a motion vector in quarter luma samples and a reference index for each list, the
|
||||
/// index −1 when the list is not used (both −1 for an intra block). An unused list always has a zero vector, so that
|
||||
/// equal motion means equal fields.
|
||||
/// </summary>
|
||||
internal struct MvField
|
||||
{
|
||||
internal static readonly MvField Intra = new() { Ref0 = -1, Ref1 = -1 };
|
||||
|
||||
internal short X0;
|
||||
internal short Y0;
|
||||
internal short X1;
|
||||
internal short Y1;
|
||||
internal sbyte Ref0;
|
||||
internal sbyte Ref1;
|
||||
|
||||
internal readonly bool SameAs(in MvField other) =>
|
||||
X0 == other.X0 && Y0 == other.Y0 && X1 == other.X1 && Y1 == other.Y1 && Ref0 == other.Ref0 && Ref1 == other.Ref1;
|
||||
}
|
||||
|
||||
/// <summary>A decoded HEVC frame, cropped to the conformance window, with one 16-bit value per sample.</summary>
|
||||
/// <param name="Width">Luma width after cropping.</param>
|
||||
/// <param name="Height">Luma height after cropping.</param>
|
||||
|
||||
@@ -68,6 +68,21 @@ internal sealed class SliceHeader
|
||||
internal int NumEntryPoints;
|
||||
internal int[] EntryPointOffsets = [];
|
||||
|
||||
/// <summary>RefPicList0 and RefPicList1 (§8.3.4) of the slice, by [list][refIdx].</summary>
|
||||
internal readonly Picture[][] RefPicList = [new Picture[16], new Picture[16]];
|
||||
|
||||
/// <summary>PicOrderCntVal of each entry of <see cref="RefPicList"/>, kept for the pictures that use this one as collocated.</summary>
|
||||
internal readonly int[][] RefPoc = [new int[16], new int[16]];
|
||||
|
||||
/// <summary>Whether each entry of <see cref="RefPicList"/> is a long-term reference picture (LongTermRefPic of §8.5.3.2.8).</summary>
|
||||
internal readonly bool[][] RefIsLongTerm = [new bool[16], new bool[16]];
|
||||
|
||||
/// <summary>ColPic (§8.5.3.2.8), when slice_temporal_mvp_enabled_flag is 1.</summary>
|
||||
internal Picture? ColPic;
|
||||
|
||||
/// <summary>NoBackwardPredFlag (§8.5.3.2.9): no reference picture follows the current one in output order.</summary>
|
||||
internal bool NoBackwardPred;
|
||||
|
||||
/// <summary>NumPicTotalCurr (7-55).</summary>
|
||||
internal int NumPicTotalCurr;
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
# Flussi di conformità H.265 (HEVC)
|
||||
|
||||
Questi flussi proveranno il decodificatore HEVC scritto in casa, che serve per i video HEVC e per le foto HEIC (profilo
|
||||
Main Still Picture). Il decodificatore **non c'è ancora**: le prove `H265ConformanceTests.FramesMatchTheReference`
|
||||
sono tutte inconcludenti finché non c'è, e lo restano per i flussi RExt finché Alberto non decide se servono. Già oggi
|
||||
si controllano i dati di riferimento e il lettore degli hash delle immagini decodificate (vedi sotto).
|
||||
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.
|
||||
|
||||
## Provenienza
|
||||
|
||||
@@ -72,7 +73,8 @@ C.5.2.3 (riordino, latenza, buffer pieno, `pic_output_flag`, RASL saltati dopo u
|
||||
sequenza, `no_output_of_prior_pics_flag`). Il conto coincide con i 15 YUV ufficiali e con il `readme` di
|
||||
`BUMPING_A_ericsson_1`, che elenca le 17 immagini che non escono. Per `NoOutPrior_A_Qualcomm_1` (40),
|
||||
`NoOutPrior_B_Qualcomm_1` (47) e `RAP_B_Bossen_2` (80), dove un IRAP scarta 3 immagini non ancora uscite, il numero è
|
||||
solo calcolato: lo confermerà il decodificatore. Anche `tutto` per i flussi senza YUV sarà verificato solo allora.
|
||||
stato prima calcolato; il decodificatore l'ha poi confermato, come `tutto` di ogni flusso senza YUV: i fotogrammi
|
||||
decodificati hanno esattamente quell'MD5.
|
||||
|
||||
## Che cosa copre ciascun flusso (Main, Main 10, Main Still Picture)
|
||||
|
||||
@@ -290,9 +292,7 @@ Le estensioni multistrato e 3D (MV-HEVC, SHVC, SCC) non sono nemmeno state guard
|
||||
|
||||
## Che cosa non è verificato
|
||||
|
||||
- Il numero di fotogrammi e `tutto` dei flussi senza YUV ufficiale: vengono dalla simulazione dell'uscita e dal file
|
||||
MD5 dello zip, e li confermerà solo il decodificatore. In particolare `NoOutPrior_A_Qualcomm_1`,
|
||||
`NoOutPrior_B_Qualcomm_1` e `RAP_B_Bossen_2`.
|
||||
- Quale dei due MD5 di uno zip sia quello del YUV, per i flussi senza YUV (la regola sopra).
|
||||
- La disposizione a 16 bit di `TSUNEQBD_A_MAIN10_Technicolor_2` (10 e 9 bit): è la stessa di ogni flusso oltre gli 8 bit,
|
||||
ma non c'è un YUV ufficiale per controllarla.
|
||||
- Il numero di fotogrammi e `tutto` dei flussi senza YUV ufficiale, quale dei due MD5 di uno zip sia quello del YUV e
|
||||
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.
|
||||
@@ -4,21 +4,14 @@ using Febe.Core.Codecs.H265;
|
||||
namespace Febe.Tests.Codecs.H265;
|
||||
|
||||
/// <summary>
|
||||
/// The streams of the ITU-T H.265.1 conformance set in Media/H265/Conformita (see LEGGIMI.md there). The decoder has no
|
||||
/// inter prediction yet: the streams with only I slices must match their YUV exactly, the others are inconclusive (their
|
||||
/// intra pictures are checked in <see cref="H265DecoderTests"/>), and 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 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.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class H265ConformanceTests
|
||||
{
|
||||
/// <summary>Streams the decoder is expected to reproduce exactly: those of Main, Main 10 and Main Still Picture made only of I slices.</summary>
|
||||
private static readonly HashSet<string> s_supported =
|
||||
[
|
||||
"IPRED_A_docomo_2", "IPRED_B_Nokia_3", "IPRED_C_Mitsubishi_3", "ipcm_A_NEC_3", "ipcm_B_NEC_3", "ipcm_C_NEC_3",
|
||||
"ipcm_D_NEC_3", "ipcm_E_NEC_2", "MAXBINS_A_TI_5", "POC_A_Bossen_3", "SAO_H_Parabola_1", "VPSSPSPPS_A_MainConcept_1",
|
||||
];
|
||||
|
||||
public static IEnumerable<object[]> Streams => H265ConformanceStream.Names().Select(n => new object[] { n });
|
||||
|
||||
[TestMethod]
|
||||
@@ -31,11 +24,6 @@ public sealed class H265ConformanceTests
|
||||
Assert.Inconclusive($"{name}: estensione di formato (RExt, {stream.Chroma} a {stream.LumaBitDepth} bit), da decodificare solo se Alberto la vuole.");
|
||||
}
|
||||
|
||||
if (!s_supported.Contains(name))
|
||||
{
|
||||
Assert.Inconclusive($"{name}: ha slice P o B, e la predizione inter HEVC non è ancora scritta.");
|
||||
}
|
||||
|
||||
var frames = new List<byte[]>();
|
||||
var decoder = new H265Decoder();
|
||||
decoder.FrameOutput += frame => frames.Add(frame.ToYuvFile());
|
||||
|
||||
@@ -4,9 +4,9 @@ using Febe.Core.Codecs.H265;
|
||||
namespace Febe.Tests.Codecs.H265;
|
||||
|
||||
/// <summary>
|
||||
/// The HEVC decoder beyond the intra-only streams of <see cref="H265ConformanceTests"/>: every picture made only of I
|
||||
/// slices, in every Main and Main 10 stream, against the MD5 its encoder wrote in the bitstream; the syntax of the P and
|
||||
/// B slices read to the end of every slice; length-prefixed samples; damaged streams.
|
||||
/// The HEVC decoder beyond the whole frames of <see cref="H265ConformanceTests"/>: 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
|
||||
/// picture is found where it first goes wrong, also when it is never output); length-prefixed samples; damaged streams.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class H265DecoderTests
|
||||
@@ -17,17 +17,14 @@ public sealed class H265DecoderTests
|
||||
|
||||
[TestMethod]
|
||||
[DynamicData(nameof(MainStreams))]
|
||||
public void IntraPicturesMatchTheirHashAndEverySliceIsReadToItsEnd(string name)
|
||||
public void EveryPictureMatchesItsHash(string name)
|
||||
{
|
||||
var stream = H265ConformanceStream.Load(name);
|
||||
var data = File.ReadAllBytes(stream.BitstreamPath);
|
||||
var hashes = H265PictureHashes.Read(data).ToDictionary(h => h.Picture);
|
||||
|
||||
// Inter prediction is not written: P and B slices are read with their prediction units mid-grey, so only the
|
||||
// pictures of I slices alone can be checked; reading every slice to its end_of_slice_segment_flag without an
|
||||
// error checks the inter syntax.
|
||||
var decoder = new H265Decoder { ParseInterSlices = true };
|
||||
int decoded = 0, hashed = 0, intra = 0;
|
||||
var decoder = new H265Decoder();
|
||||
int decoded = 0, hashed = 0;
|
||||
var wrong = new List<string>();
|
||||
decoder.PictureDecoded += picture =>
|
||||
{
|
||||
@@ -38,12 +35,6 @@ public sealed class H265DecoderTests
|
||||
}
|
||||
|
||||
hashed++;
|
||||
if (!picture.IntraOnly)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
intra++;
|
||||
for (var c = 0; c < hash.Planes.Length; c++)
|
||||
{
|
||||
var width = c == 0 ? picture.Width : picture.ChromaWidth;
|
||||
@@ -69,21 +60,30 @@ public sealed class H265DecoderTests
|
||||
}
|
||||
|
||||
Assert.AreEqual(stream.FrameCount, frames, $"{name}: fotogrammi in uscita");
|
||||
if (hashes.Count > 0)
|
||||
{
|
||||
Assert.IsGreaterThan(0, intra, $"{name}: nessuna immagine intra controllata");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InterSlicesAreRefusedByDefault()
|
||||
public void TheHashesCoverInterPictures()
|
||||
{
|
||||
// BUMPING_A begins with an IDR picture and goes on with P and B slices: the IDR comes out, then the refusal.
|
||||
var data = File.ReadAllBytes(H265ConformanceStream.Load("BUMPING_A_ericsson_1").BitstreamPath);
|
||||
var decoder = new H265Decoder();
|
||||
var error = Assert.ThrowsExactly<H265Exception>(() => decoder.DecodeAnnexB(data));
|
||||
StringAssert.Contains(error.Message, "inter");
|
||||
Assert.IsGreaterThanOrEqualTo(1, decoder.PicturesDecoded);
|
||||
// The check above is worth something for inter prediction only if the hashes cover P and B pictures: count
|
||||
// them in the streams that carry hashes, decoding a few streams whose names say they are about inter tools.
|
||||
string[] names = ["MERGE_A_TI_3", "TMVP_A_MS_3", "WP_A_Toshiba_3", "WP_B_Toshiba_3", "PMERGE_A_TI_3", "MVCLIP_A_qualcomm_3", "MVEDGE_A_qualcomm_3", "SAO_A_MediaTek_4", "RAP_B_Bossen_2"];
|
||||
var none = new List<string>();
|
||||
foreach (var name in names)
|
||||
{
|
||||
var data = File.ReadAllBytes(H265ConformanceStream.Load(name).BitstreamPath);
|
||||
var hashes = H265PictureHashes.Read(data).Select(h => h.Picture).ToHashSet();
|
||||
var inter = 0;
|
||||
var decoder = new H265Decoder();
|
||||
decoder.PictureDecoded += picture => inter += !picture.IntraOnly && hashes.Contains((int)picture.DecodeIndex) ? 1 : 0;
|
||||
decoder.DecodeAnnexB(data);
|
||||
if (inter == 0)
|
||||
{
|
||||
none.Add(name);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsEmpty(none, $"nessuna immagine inter con hash: {string.Join(", ", none)}");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -155,6 +155,10 @@ public sealed class H265DecoderTests
|
||||
[DataRow("WPP_C_ericsson_MAIN_2", 2708)]
|
||||
[DataRow("TILES_B_Cisco_1", 2709)]
|
||||
[DataRow("DSLICE_A_HHI_5", 2710)]
|
||||
[DataRow("MVEDGE_A_qualcomm_3", 2711)]
|
||||
[DataRow("WP_B_Toshiba_3", 2712)]
|
||||
[DataRow("TMVP_A_MS_3", 2713)]
|
||||
[DataRow("PMERGE_B_TI_3", 2714)]
|
||||
public void DamagedStreamsGiveFramesOrAnH265Exception(string name, int seed)
|
||||
{
|
||||
var data = File.ReadAllBytes(H265ConformanceStream.Load(name).BitstreamPath);
|
||||
@@ -186,7 +190,7 @@ public sealed class H265DecoderTests
|
||||
|
||||
try
|
||||
{
|
||||
var decoder = new H265Decoder { ParseInterSlices = true };
|
||||
var decoder = new H265Decoder();
|
||||
decoder.FrameOutput += _ => { };
|
||||
decoder.DecodeAnnexB(copy);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user