Decodificatore H.264 per gli strumenti di Baseline ed Extended: FMO, ASO, slice ridondanti, partizionamento dei dati, slice SP e SI (#58)
Il decodificatore rifiutava i flussi con gruppi di slice e con slice SP o SI, e non leggeva le partizioni A, B e C: ora li gestisce tutti, perché sono parte di Baseline ed Extended e un file della libreria può usarli. - Gruppi di slice dal PPS, tipi da 0 a 6, con il cambio per immagine di slice_group_change_cycle; il macroblocco successivo segue il gruppo (§8.2.2). - Slice in ordine qualunque: la disponibilità dei vicini era già per slice, il deblocking a fine immagine. - Slice SP e SI con QS (§8.6): predizione trasformata e riquantizzata in QS, anche per P_Skip; sp_for_switch_flag e macroblocchi SI; nel deblocking contano come intra. - Partizionamento: A con intestazione e dati di categoria 2, B con il residuo intra (e gli I_PCM), C con quello inter; la regola del nN a zero con la predizione intra vincolata (§9.2.1). Una partizione che manca lascia a zero il suo residuo e, da lì in poi, quello della partizione che ne dipende. I cinque flussi FMO, ASO e SP della serie ITU-T (FM2_SVA_C, FM1_FT_E, FM1_BT_B, sp1_bt_a, sp2_bt_b) passano fra i verificati e coincidono fotogramma per fotogramma. Partizionamento, slice ridondanti e ASO si provano riscrivendo flussi verificati senza toccare i bit dei macroblocchi (StreamRewriter) e chiedendo di nuovo il riferimento ufficiale; le SI con un flusso sintetico calcolato a mano. Anche i flussi nuovi e quelli partizionati sono provati rovinati. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9c626f67ec
commit
8d03ca23de
19 files changed
+1738
-169
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 | Ciò che il decodificatore dei fotogrammi offre ma la produzione non usa ancora: `AnalyseStillnessAsync` (video di un'immagine ferma) e `Mp4Writer` (rimpacchettare con moov in testa) sono pronti per una tappa successiva e oggi servono solo alle prove; la miniatura di un video passa ancora da un BMP decodificato da SkiaSharp (tappa C1: dare `VideoImage` direttamente al ridimensionamento e al codificatore JPEG scritti in casa, senza BMP) | La riga del 18 novembre sui video li descriveva come se fossero già usati. Il passaggio per BMP resta finché SkiaSharp è nel programma |
|
||||||
| 2026-11-18 | Flussi di conformità ITU-T H.264.1 anche per le parti che il decodificatore non gestisce ancora (campi, PAFF, MBAFF, FMO e ASO, slice SP, 4:2:2 a 8 e 10 bit, 4:0:0, SVC, MVC), 37 in tutto e 8,3 MB, in `tests/Febe.Tests/Media/H264/Conformita` con il loro `riferimento.md5`: la prova è inconclusiva («da fare: …») finché la parte manca e fallisce apposta quando un flusso coincide senza essere passato fra i verificati. L'MD5 è quello dei campioni come stanno nel file YUV ufficiale (due byte little-endian oltre gli 8 bit, 4:2:2 com'è, il 4:0:0 con i piani a 128 del file); per SVC uno per lo strato più alto e uno per lo strato base, che si prova già; per MVC la serie non ha ricostruzioni e il file lo dice. Restano fuori partizionamento dei dati, slice ridondanti e SI (nessun flusso della serie li usa), High 10 in 4:2:0, 4:2:2 Intra e 4:4:4 con piani separati e senza perdita (i flussi non hanno la ricostruzione e pesano da 2 a 113 MB) | Alberto ha permesso il 18 novembre di scaricare i flussi ufficiali di conformità: il vuoto del decodificatore deve vedersi nella serie di prove senza farla diventare rossa, e chi scrive una parte ha già pronto il riferimento ufficiale. Le ricostruzioni restano fuori dal repository (sono decine di MB); i flussi sono stati scelti piccoli, uno o due per parte. Il dettaglio di che cosa copre ciascun flusso e di che cosa manca è in `LEGGIMI.md` della cartella. Il riepilogo delle prove della CI (`riepilogo-prove.sh`) conta e elenca a parte le inconclusive «da fare: …» e non le somma alle saltate, che restano a zero ammesse: senza, la verifica sarebbe rossa per 37 prove che segnano parti mancanti, non un ambiente rotto |
|
| 2026-11-18 | Flussi di conformità ITU-T H.264.1 anche per le parti che il decodificatore non gestisce ancora (campi, PAFF, MBAFF, FMO e ASO, slice SP, 4:2:2 a 8 e 10 bit, 4:0:0, SVC, MVC), 37 in tutto e 8,3 MB, in `tests/Febe.Tests/Media/H264/Conformita` con il loro `riferimento.md5`: la prova è inconclusiva («da fare: …») finché la parte manca e fallisce apposta quando un flusso coincide senza essere passato fra i verificati. L'MD5 è quello dei campioni come stanno nel file YUV ufficiale (due byte little-endian oltre gli 8 bit, 4:2:2 com'è, il 4:0:0 con i piani a 128 del file); per SVC uno per lo strato più alto e uno per lo strato base, che si prova già; per MVC la serie non ha ricostruzioni e il file lo dice. Restano fuori partizionamento dei dati, slice ridondanti e SI (nessun flusso della serie li usa), High 10 in 4:2:0, 4:2:2 Intra e 4:4:4 con piani separati e senza perdita (i flussi non hanno la ricostruzione e pesano da 2 a 113 MB) | Alberto ha permesso il 18 novembre di scaricare i flussi ufficiali di conformità: il vuoto del decodificatore deve vedersi nella serie di prove senza farla diventare rossa, e chi scrive una parte ha già pronto il riferimento ufficiale. Le ricostruzioni restano fuori dal repository (sono decine di MB); i flussi sono stati scelti piccoli, uno o due per parte. Il dettaglio di che cosa copre ciascun flusso e di che cosa manca è in `LEGGIMI.md` della cartella. Il riepilogo delle prove della CI (`riepilogo-prove.sh`) conta e elenca a parte le inconclusive «da fare: …» e non le somma alle saltate, che restano a zero ammesse: senza, la verifica sarebbe rossa per 37 prove che segnano parti mancanti, non un ambiente rotto |
|
||||||
| 2026-11-18 | Il decodificatore H.264 gestisce le immagini interlacciate (campi, PAFF, MBAFF) su una sola griglia di fotogramma: un campo è l'insieme delle sue righe pari o dispari, e ogni macroblocco ricostruisce con un'origine e un passo (doppio per i macroblocchi di campo) invece di copiare i campi in piani separati; liste dei riferimenti e marcatura per campi secondo §8.2.4 e §8.2.5, vicini MBAFF secondo la tabella 6-4, filtro di deblocking per i campi e per le coppie MBAFF come lo fa il decodificatore di riferimento dell'ITU-T (il bordo superiore di un macroblocco di fotogramma sotto una coppia di campi filtrato due volte, il bordo sinistro misto riga per riga). Due campi fanno un fotogramma se hanno parità opposte, lo stesso `frame_num` e sono entrambi di riferimento o entrambi no; un campo rimasto solo esce come fotogramma con le righe dell'altro campo a 128 | I 17 flussi interlacciati della serie di conformità coincidono così con la ricostruzione ufficiale fotogramma per fotogramma, e i flussi a immagini intere non rallentano (la griglia unica evita copie e doppi percorsi). Il grigio per il campo mancante non inventa righe che il flusso non ha |
|
| 2026-11-18 | Il decodificatore H.264 gestisce le immagini interlacciate (campi, PAFF, MBAFF) su una sola griglia di fotogramma: un campo è l'insieme delle sue righe pari o dispari, e ogni macroblocco ricostruisce con un'origine e un passo (doppio per i macroblocchi di campo) invece di copiare i campi in piani separati; liste dei riferimenti e marcatura per campi secondo §8.2.4 e §8.2.5, vicini MBAFF secondo la tabella 6-4, filtro di deblocking per i campi e per le coppie MBAFF come lo fa il decodificatore di riferimento dell'ITU-T (il bordo superiore di un macroblocco di fotogramma sotto una coppia di campi filtrato due volte, il bordo sinistro misto riga per riga). Due campi fanno un fotogramma se hanno parità opposte, lo stesso `frame_num` e sono entrambi di riferimento o entrambi no; un campo rimasto solo esce come fotogramma con le righe dell'altro campo a 128 | I 17 flussi interlacciati della serie di conformità coincidono così con la ricostruzione ufficiale fotogramma per fotogramma, e i flussi a immagini intere non rallentano (la griglia unica evita copie e doppi percorsi). Il grigio per il campo mancante non inventa righe che il flusso non ha |
|
||||||
|
| 2026-11-18 | Il decodificatore H.264 gestisce gli strumenti di Baseline ed Extended: gruppi di slice (FMO, tipi da 0 a 6 e cambio con `slice_group_change_cycle`), slice in ordine qualunque (ASO), slice ridondanti (si decodifica la primaria, le ridondanti si saltano), partizionamento dei dati (NAL 2, 3 e 4, solo CAVLC come vuole lo standard) e slice SP e SI con QS (§8.6). Una partizione B o C che manca lascia a zero il residuo che porta e, da quel macroblocco in poi, anche quello della partizione che ne dipende (il nC delle due partizioni conta i coefficienti dei vicini dell'altra, tranne che con la predizione intra vincolata). I macroblocchi delle slice SP e SI contano come intra per il filtro di deblocking. Dove la serie ITU-T non ha flussi (partizionamento, slice ridondanti, SI, `sp_for_switch_flag`) la prova riscrive flussi verificati lasciando intatti i bit dei macroblocchi (`StreamRewriter`) e chiede di nuovo il riferimento ufficiale; le SI con un flusso sintetico i cui valori sono calcolati a mano | I cinque flussi FMO, ASO e SP della serie coincidono ora fotogramma per fotogramma con la ricostruzione ufficiale. Riscrivere flussi già verificati dà un riferimento vero anche alle parti che nessun flusso ufficiale usa, senza inventare formati né scaricare altro; restano senza riferimento ufficiale le slice SI, `sp_for_switch_flag` a 1 e il ripiego per le partizioni mancanti, che segue la dipendenza dello standard invece di un decodificatore di riferimento |
|
||||||
@@ -341,7 +341,7 @@ public sealed partial class H264Decoder
|
|||||||
private int BoundaryStrength(Picture picture, int pm, int pb, int qm, int qb, bool mbEdge, bool vertical)
|
private int BoundaryStrength(Picture picture, int pm, int pb, int qm, int qb, bool mbEdge, bool vertical)
|
||||||
{
|
{
|
||||||
bool fieldP = picture.MbField[pm], fieldQ = picture.MbField[qm];
|
bool fieldP = picture.MbField[pm], fieldQ = picture.MbField[qm];
|
||||||
if (picture.MbIntra[pm] || picture.MbIntra[qm])
|
if (picture.MbIntra[pm] || picture.MbIntra[qm] || (anySwitching && (sliceSwitching[mbSlice[pm]] || sliceSwitching[mbSlice[qm]])))
|
||||||
{
|
{
|
||||||
return mbEdge && (vertical || (!fieldP && !fieldQ)) ? 4 : 3;
|
return mbEdge && (vertical || (!fieldP && !fieldQ)) ? 4 : 3;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,18 +24,16 @@ public sealed partial class H264Decoder
|
|||||||
switch (sh.Type)
|
switch (sh.Type)
|
||||||
{
|
{
|
||||||
case SliceType.I:
|
case SliceType.I:
|
||||||
|
return ReadIntraSliceMbType();
|
||||||
|
case SliceType.SI:
|
||||||
{
|
{
|
||||||
var inc = (mbA >= 0 && mbKind[mbA] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0)
|
// The prefix says SI or not (ctxIdx 0–2), then an I slice mb_type follows (§9.3.2.5).
|
||||||
+ (mbB >= 0 && mbKind[mbB] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0);
|
var inc = (mbA >= 0 && mbKind[mbA] != MbKind.SI ? 1 : 0) + (mbB >= 0 && mbKind[mbB] != MbKind.SI ? 1 : 0);
|
||||||
if (cabac.Decision(3 + inc) == 0)
|
return cabac.Decision(inc) == 0 ? 0 : 1 + ReadIntraSliceMbType();
|
||||||
{
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
return IntraMbTypeSuffix(3, intraSlice: true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
case SliceType.P:
|
case SliceType.P:
|
||||||
|
case SliceType.SP:
|
||||||
if (cabac.Decision(14) == 0)
|
if (cabac.Decision(14) == 0)
|
||||||
{
|
{
|
||||||
if (cabac.Decision(15) == 0)
|
if (cabac.Decision(15) == 0)
|
||||||
@@ -91,6 +89,19 @@ public sealed partial class H264Decoder
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>mb_type of an I slice (ctxIdxOffset 3).</summary>
|
||||||
|
private int ReadIntraSliceMbType()
|
||||||
|
{
|
||||||
|
var inc = (mbA >= 0 && mbKind[mbA] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0)
|
||||||
|
+ (mbB >= 0 && mbKind[mbB] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0);
|
||||||
|
if (cabac.Decision(3 + inc) == 0)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return IntraMbTypeSuffix(3, intraSlice: true);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The part of an intra mb_type after its first bin (which said «not I_NxN»): I_PCM or one of the I_16x16 types.
|
/// The part of an intra mb_type after its first bin (which said «not I_NxN»): I_PCM or one of the I_16x16 types.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -557,6 +568,12 @@ public sealed partial class H264Decoder
|
|||||||
return total;
|
return total;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// §9.2.1: in a partitioned slice with constrained_intra_pred_flag, an inter neighbour of an intra macroblock counts
|
||||||
|
/// as available with nN = 0 (its residual is in partition C, which the intra macroblock must not depend on).
|
||||||
|
/// </summary>
|
||||||
|
private bool HiddenByPartitioning(int n) => partitioned && pps.ConstrainedIntraPred && !IsIntra(n) && IsIntra(mb);
|
||||||
|
|
||||||
/// <summary>nC of a luma 4×4 block (raster index) from the blocks to its left and above (§9.2.1).</summary>
|
/// <summary>nC of a luma 4×4 block (raster index) from the blocks to its left and above (§9.2.1).</summary>
|
||||||
private int LumaNc(int raster)
|
private int LumaNc(int raster)
|
||||||
{
|
{
|
||||||
@@ -569,7 +586,7 @@ public sealed partial class H264Decoder
|
|||||||
}
|
}
|
||||||
else if (Locate(-1, by * 4, 16, out var yM) is var a and >= 0)
|
else if (Locate(-1, by * 4, 16, out var yM) is var a and >= 0)
|
||||||
{
|
{
|
||||||
nA = nz[(a * 24) + (((yM & 15) >> 2) * 4) + 3];
|
nA = HiddenByPartitioning(a) ? 0 : nz[(a * 24) + (((yM & 15) >> 2) * 4) + 3];
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -582,7 +599,7 @@ public sealed partial class H264Decoder
|
|||||||
}
|
}
|
||||||
else if (Locate(bx * 4, -1, 16, out _) is var b and >= 0)
|
else if (Locate(bx * 4, -1, 16, out _) is var b and >= 0)
|
||||||
{
|
{
|
||||||
nB = nz[(b * 24) + 12 + bx];
|
nB = HiddenByPartitioning(b) ? 0 : nz[(b * 24) + 12 + bx];
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -604,7 +621,7 @@ public sealed partial class H264Decoder
|
|||||||
}
|
}
|
||||||
else if (Locate(-1, by * 4, 8, out var yM) is var a and >= 0)
|
else if (Locate(-1, by * 4, 8, out var yM) is var a and >= 0)
|
||||||
{
|
{
|
||||||
nA = nz[(a * 24) + baseIndex + (((yM & 7) >> 2) * 2) + 1];
|
nA = HiddenByPartitioning(a) ? 0 : nz[(a * 24) + baseIndex + (((yM & 7) >> 2) * 2) + 1];
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -617,7 +634,7 @@ public sealed partial class H264Decoder
|
|||||||
}
|
}
|
||||||
else if (Locate(bx * 4, -1, 8, out _) is var n and >= 0)
|
else if (Locate(bx * 4, -1, 8, out _) is var n and >= 0)
|
||||||
{
|
{
|
||||||
nB = nz[(n * 24) + baseIndex + 2 + bx];
|
nB = HiddenByPartitioning(n) ? 0 : nz[(n * 24) + baseIndex + 2 + bx];
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -483,7 +483,7 @@ public sealed partial class H264Decoder
|
|||||||
|
|
||||||
private void PrepareWeights()
|
private void PrepareWeights()
|
||||||
{
|
{
|
||||||
weightMode = sh.Type == SliceType.P ? (pps.WeightedPred ? 1 : 0) : sh.IsB ? pps.WeightedBipredIdc : 0;
|
weightMode = sh.IsP ? (pps.WeightedPred ? 1 : 0) : sh.IsB ? pps.WeightedBipredIdc : 0;
|
||||||
if (weightMode != 2)
|
if (weightMode != 2)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -0,0 +1,158 @@
|
|||||||
|
namespace Febe.Core.Codecs.H264;
|
||||||
|
|
||||||
|
public sealed partial class H264Decoder
|
||||||
|
{
|
||||||
|
// Slice data partitioning (§7.3.2.9, §7.3.2.10, §7.4.2.9): partition A (NAL unit 2) holds the slice header and the
|
||||||
|
// category 2 syntax elements (macroblock types, prediction, coded_block_pattern, mb_qp_delta), partition B (3) the
|
||||||
|
// residual of the intra macroblocks (category 3), partition C (4) the residual of the inter ones (category 4). The
|
||||||
|
// three NAL units come one after the other: A is kept until its B and C have arrived, then the slice is decoded with
|
||||||
|
// one reader per partition.
|
||||||
|
|
||||||
|
/// <summary>A partition A is waiting for its partitions B and C.</summary>
|
||||||
|
private bool partitionPending;
|
||||||
|
|
||||||
|
private byte[] partitionA = [];
|
||||||
|
private byte[] partitionB = [];
|
||||||
|
private byte[] partitionC = [];
|
||||||
|
private NalUnit pendingNal;
|
||||||
|
private RbspReader? pendingReader;
|
||||||
|
private SliceHeader? pendingHeader;
|
||||||
|
private Sps? pendingSps;
|
||||||
|
private Pps? pendingPps;
|
||||||
|
private int pendingSliceId;
|
||||||
|
private RbspReader? pendingB;
|
||||||
|
private RbspReader? pendingC;
|
||||||
|
|
||||||
|
/// <summary>The slice being decoded is partitioned: the residual comes from <see cref="intraResidual"/> and <see cref="interResidual"/>.</summary>
|
||||||
|
private bool partitioned;
|
||||||
|
|
||||||
|
/// <summary>Partition B of the slice being decoded, null when it is missing.</summary>
|
||||||
|
private RbspReader? intraResidual;
|
||||||
|
|
||||||
|
/// <summary>Partition C of the slice being decoded, null when it is missing.</summary>
|
||||||
|
private RbspReader? interResidual;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// For the tests: called after the residual (or the I_PCM samples) of a macroblock has been read, with its first and
|
||||||
|
/// past-the-end bit in the RBSP of the slice, whether the macroblock is intra and whether it is I_PCM.
|
||||||
|
/// </summary>
|
||||||
|
internal Action<int, int, bool, bool>? ResidualRead { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Partition A (§7.3.2.9): the slice header and slice_id, kept until partitions B and C have arrived.</summary>
|
||||||
|
private void StorePartitionA(NalUnit nal)
|
||||||
|
{
|
||||||
|
var copy = Keep(nal, ref partitionA);
|
||||||
|
var reader = copy.Reader();
|
||||||
|
var header = ParseSliceHeader(reader, copy, out var sps, out var pps);
|
||||||
|
if (pps.Cabac)
|
||||||
|
{
|
||||||
|
throw new H264Exception("Partizionamento dei dati con CABAC: combinazione non ammessa.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var sliceId = reader.ReadUe(Sps.MaxFrameMbs - 1);
|
||||||
|
if (header.RedundantPicCnt > 0)
|
||||||
|
{
|
||||||
|
return; // a redundant picture, skipped with its partitions B and C (no partition is pending for them)
|
||||||
|
}
|
||||||
|
|
||||||
|
pendingNal = copy;
|
||||||
|
pendingReader = reader;
|
||||||
|
pendingHeader = header;
|
||||||
|
pendingSps = sps;
|
||||||
|
pendingPps = pps;
|
||||||
|
pendingSliceId = sliceId;
|
||||||
|
pendingB = pendingC = null;
|
||||||
|
partitionPending = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Partition B or C (§7.3.2.10) of the slice waiting in partition A; one of another slice is ignored.</summary>
|
||||||
|
private void StorePartition(NalUnit nal)
|
||||||
|
{
|
||||||
|
if (!partitionPending)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var copy = nal.Type == 3 ? Keep(nal, ref partitionB) : Keep(nal, ref partitionC);
|
||||||
|
var reader = copy.Reader();
|
||||||
|
var sliceId = reader.ReadUe(Sps.MaxFrameMbs - 1);
|
||||||
|
var redundant = pendingPps!.RedundantPicCntPresent ? reader.ReadUe(127) : 0;
|
||||||
|
if (sliceId != pendingSliceId || redundant != 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nal.Type == 3)
|
||||||
|
{
|
||||||
|
pendingB = reader;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
pendingC = reader;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Decodes the slice of the partitions received; a missing B or C leaves the residual it carries at zero.</summary>
|
||||||
|
private void DecodePartitionedSlice()
|
||||||
|
{
|
||||||
|
partitionPending = false;
|
||||||
|
partitioned = true;
|
||||||
|
intraResidual = pendingB;
|
||||||
|
interResidual = pendingC;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
DecodeParsedSlice(pendingNal, pendingReader!, pendingHeader!, pendingSps!, pendingPps!);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
partitioned = false;
|
||||||
|
intraResidual = interResidual = null;
|
||||||
|
pendingB = pendingC = null;
|
||||||
|
pendingReader = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A copy of the RBSP of a partition, which must outlive the shared buffer of the stream.</summary>
|
||||||
|
private static NalUnit Keep(NalUnit nal, ref byte[] buffer)
|
||||||
|
{
|
||||||
|
if (buffer.Length < nal.Length + NalUnits.Padding)
|
||||||
|
{
|
||||||
|
buffer = new byte[nal.Length + NalUnits.Padding];
|
||||||
|
}
|
||||||
|
|
||||||
|
nal.Rbsp.AsSpan(0, nal.Length + NalUnits.Padding).CopyTo(buffer);
|
||||||
|
return nal with { Rbsp = buffer };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The reader of the residual of the current macroblock: the slice data, or the partition B (intra) or C (inter) of a
|
||||||
|
/// partitioned slice — null when that partition is missing.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Asked only for a macroblock that has residual. When its partition is missing, the other one can no longer be read
|
||||||
|
/// from here on: the nC of an inter block counts the coefficients of its intra neighbours, and the nC of an intra
|
||||||
|
/// block those of its inter neighbours unless constrained_intra_pred makes them count as empty (§9.2.1).
|
||||||
|
/// </remarks>
|
||||||
|
private RbspReader? ResidualReader(bool intra)
|
||||||
|
{
|
||||||
|
if (!partitioned)
|
||||||
|
{
|
||||||
|
return rd;
|
||||||
|
}
|
||||||
|
|
||||||
|
var source = intra ? intraResidual : interResidual;
|
||||||
|
if (source is null)
|
||||||
|
{
|
||||||
|
if (intra)
|
||||||
|
{
|
||||||
|
interResidual = null;
|
||||||
|
}
|
||||||
|
else if (!pps.ConstrainedIntraPred)
|
||||||
|
{
|
||||||
|
intraResidual = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,9 @@ public sealed partial class H264Decoder
|
|||||||
BDirect,
|
BDirect,
|
||||||
PInter,
|
PInter,
|
||||||
BInter,
|
BInter,
|
||||||
|
|
||||||
|
/// <summary>The SI macroblock of SI slices: Intra_4x4 prediction, reconstructed in QS (§8.6.2).</summary>
|
||||||
|
SI,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shapes of inter macroblocks and sub-macroblocks.
|
// Shapes of inter macroblocks and sub-macroblocks.
|
||||||
@@ -107,6 +110,18 @@ public sealed partial class H264Decoder
|
|||||||
private readonly bool[] lumaHas = new bool[16];
|
private readonly bool[] lumaHas = new bool[16];
|
||||||
private readonly int[] chromaCoef = new int[2 * 4 * 16];
|
private readonly int[] chromaCoef = new int[2 * 4 * 16];
|
||||||
private readonly bool[] chromaHas = new bool[8];
|
private readonly bool[] chromaHas = new bool[8];
|
||||||
|
|
||||||
|
/// <summary>The chroma DC levels as parsed (component × 4), for the macroblocks reconstructed in QS.</summary>
|
||||||
|
private readonly int[] chromaDcLevels = new int[8];
|
||||||
|
|
||||||
|
/// <summary>The residual being parsed is kept as levels, not scaled: P macroblocks of SP slices and SI macroblocks.</summary>
|
||||||
|
private bool rawLevels;
|
||||||
|
|
||||||
|
/// <summary>Per slice of the picture: an SP or SI slice, whose macroblocks the deblocking filter treats as intra (§8.7.2.1).</summary>
|
||||||
|
private readonly List<bool> sliceSwitching = [];
|
||||||
|
|
||||||
|
/// <summary>Some slice of the picture is an SP or SI slice.</summary>
|
||||||
|
private bool anySwitching;
|
||||||
private readonly int[] levels = new int[64];
|
private readonly int[] levels = new int[64];
|
||||||
private readonly int[] levels4 = new int[64];
|
private readonly int[] levels4 = new int[64];
|
||||||
private readonly int[] subType = new int[4];
|
private readonly int[] subType = new int[4];
|
||||||
@@ -133,7 +148,13 @@ public sealed partial class H264Decoder
|
|||||||
subDirect = new bool[mbCount * 4];
|
subDirect = new bool[mbCount * 4];
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool IsIntra(int m) => mbKind[m] is MbKind.I4x4 or MbKind.I8x8 or MbKind.I16x16 or MbKind.IPcm;
|
private bool IsIntra(int m) => mbKind[m] is MbKind.I4x4 or MbKind.I8x8 or MbKind.I16x16 or MbKind.IPcm or MbKind.SI;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A neighbour whose samples intra prediction may use under constrained_intra_pred_flag: an intra macroblock, but not
|
||||||
|
/// an SI one for a macroblock that is not SI (§8.3.1.2).
|
||||||
|
/// </summary>
|
||||||
|
private bool IntraUsable(int m) => IsIntra(m) && (mbKind[m] != MbKind.SI || mbKind[mb] == MbKind.SI);
|
||||||
|
|
||||||
private bool IsSkip(int m) => mbKind[m] is MbKind.PSkip or MbKind.BSkip;
|
private bool IsSkip(int m) => mbKind[m] is MbKind.PSkip or MbKind.BSkip;
|
||||||
|
|
||||||
@@ -150,6 +171,12 @@ public sealed partial class H264Decoder
|
|||||||
mbaff = s.MbAdaptiveFrameField && !header.FieldPic;
|
mbaff = s.MbAdaptiveFrameField && !header.FieldPic;
|
||||||
sliceNum = sliceCounter++;
|
sliceNum = sliceCounter++;
|
||||||
sliceFilters.Add((header.DisableDeblocking, header.AlphaOffset, header.BetaOffset));
|
sliceFilters.Add((header.DisableDeblocking, header.AlphaOffset, header.BetaOffset));
|
||||||
|
sliceSwitching.Add(header.IsSwitching);
|
||||||
|
anySwitching |= header.IsSwitching;
|
||||||
|
if (header.IsSwitching && p.Transform8x8Mode)
|
||||||
|
{
|
||||||
|
throw new H264Exception("Slice SP o SI con la trasformata 8×8: combinazione non ammessa.");
|
||||||
|
}
|
||||||
qp = p.PicInitQp + header.QpDelta;
|
qp = p.PicInitQp + header.QpDelta;
|
||||||
if (qp is < 0 or > 51)
|
if (qp is < 0 or > 51)
|
||||||
{
|
{
|
||||||
@@ -187,7 +214,8 @@ public sealed partial class H264Decoder
|
|||||||
cabac.Start(rd);
|
cabac.Start(rd);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Macroblock addresses of the slice: those of the field, or of the pairs (two per pair) in an MBAFF frame.
|
// Macroblock addresses of the slice: those of the field, or of the pairs (two per pair) in an MBAFF frame; with
|
||||||
|
// slice groups only those of the group of the first one, in order.
|
||||||
var total = fieldPic ? mbCount / 2 : mbCount;
|
var total = fieldPic ? mbCount / 2 : mbCount;
|
||||||
var addr = header.FirstMb * (mbaff ? 2 : 1);
|
var addr = header.FirstMb * (mbaff ? 2 : 1);
|
||||||
if (addr >= total)
|
if (addr >= total)
|
||||||
@@ -195,6 +223,8 @@ public sealed partial class H264Decoder
|
|||||||
throw new H264Exception("Primo macroblocco fuori dall'immagine.");
|
throw new H264Exception("Primo macroblocco fuori dall'immagine.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
PrepareSliceGroups(header, s, p);
|
||||||
|
|
||||||
if (!mbaff)
|
if (!mbaff)
|
||||||
{
|
{
|
||||||
DecodeMacroblocks(addr, total);
|
DecodeMacroblocks(addr, total);
|
||||||
@@ -224,7 +254,13 @@ public sealed partial class H264Decoder
|
|||||||
|
|
||||||
for (var i = 0; i < (int)run; i++)
|
for (var i = 0; i < (int)run; i++)
|
||||||
{
|
{
|
||||||
BeginMacroblock(addr++);
|
if (addr >= total)
|
||||||
|
{
|
||||||
|
throw new H264Exception("mb_skip_run fuori dal gruppo di slice.");
|
||||||
|
}
|
||||||
|
|
||||||
|
BeginMacroblock(addr);
|
||||||
|
addr = NextAddress(addr);
|
||||||
DecodeSkip();
|
DecodeSkip();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -234,7 +270,8 @@ public sealed partial class H264Decoder
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
BeginMacroblock(addr++);
|
BeginMacroblock(addr);
|
||||||
|
addr = NextAddress(addr);
|
||||||
if (!isIntraSlice && cabacMode && ReadMbSkip() != 0)
|
if (!isIntraSlice && cabacMode && ReadMbSkip() != 0)
|
||||||
{
|
{
|
||||||
DecodeSkip();
|
DecodeSkip();
|
||||||
@@ -272,6 +309,11 @@ public sealed partial class H264Decoder
|
|||||||
|
|
||||||
for (var i = 0; i < (int)run; i++)
|
for (var i = 0; i < (int)run; i++)
|
||||||
{
|
{
|
||||||
|
if (addr >= total)
|
||||||
|
{
|
||||||
|
throw new H264Exception("mb_skip_run fuori dal gruppo di slice.");
|
||||||
|
}
|
||||||
|
|
||||||
if ((addr & 1) == 0)
|
if ((addr & 1) == 0)
|
||||||
{
|
{
|
||||||
SetPairField(addr, InferPairField(addr));
|
SetPairField(addr, InferPairField(addr));
|
||||||
@@ -281,7 +323,8 @@ public sealed partial class H264Decoder
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
BeginMacroblock(addr++);
|
BeginMacroblock(addr);
|
||||||
|
addr = NextAddress(addr);
|
||||||
DecodeSkip();
|
DecodeSkip();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -296,7 +339,8 @@ public sealed partial class H264Decoder
|
|||||||
SetPairField(addr, rd.ReadFlag());
|
SetPairField(addr, rd.ReadFlag());
|
||||||
}
|
}
|
||||||
|
|
||||||
BeginMacroblock(addr++);
|
BeginMacroblock(addr);
|
||||||
|
addr = NextAddress(addr);
|
||||||
DecodeMacroblock();
|
DecodeMacroblock();
|
||||||
if (!rd.MoreRbspData)
|
if (!rd.MoreRbspData)
|
||||||
{
|
{
|
||||||
@@ -348,7 +392,8 @@ public sealed partial class H264Decoder
|
|||||||
bottomSkipKnown = false;
|
bottomSkipKnown = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
BeginMacroblock(addr++);
|
BeginMacroblock(addr);
|
||||||
|
addr = NextAddress(addr);
|
||||||
if (skip)
|
if (skip)
|
||||||
{
|
{
|
||||||
DecodeSkip();
|
DecodeSkip();
|
||||||
@@ -612,7 +657,17 @@ public sealed partial class H264Decoder
|
|||||||
{
|
{
|
||||||
intraType = type;
|
intraType = type;
|
||||||
}
|
}
|
||||||
else if (sh.Type == SliceType.P)
|
else if (sh.Type == SliceType.SI)
|
||||||
|
{
|
||||||
|
if (type == 0)
|
||||||
|
{
|
||||||
|
DecodeSi();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
intraType = type - 1;
|
||||||
|
}
|
||||||
|
else if (sh.IsP)
|
||||||
{
|
{
|
||||||
intraType = type >= 5 ? type - 5 : -1;
|
intraType = type >= 5 ? type - 5 : -1;
|
||||||
}
|
}
|
||||||
@@ -652,6 +707,12 @@ public sealed partial class H264Decoder
|
|||||||
{
|
{
|
||||||
PredictPSkip();
|
PredictPSkip();
|
||||||
MotionCompensate(0, 0, 16, 16);
|
MotionCompensate(0, 0, 16, 16);
|
||||||
|
if (sh.Type == SliceType.SP)
|
||||||
|
{
|
||||||
|
// Even without residual the prediction of an SP slice is quantised in QS (§8.6.1).
|
||||||
|
ClearResidual();
|
||||||
|
ReconstructSwitchingInter();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -703,7 +764,7 @@ public sealed partial class H264Decoder
|
|||||||
if (cbp != 0 || intra16)
|
if (cbp != 0 || intra16)
|
||||||
{
|
{
|
||||||
ApplyQpDelta(ReadQpDelta());
|
ApplyQpDelta(ReadQpDelta());
|
||||||
ParseResidual(intra16, cbp, intra: true);
|
ReadResidual(intra16, cbp, intra: true);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -715,6 +776,38 @@ public sealed partial class H264Decoder
|
|||||||
ReconstructIntra(predMode16);
|
ReconstructIntra(predMode16);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>The SI macroblock (mb_type 0 of an SI slice): Intra_4x4 prediction, levels in QS (§7.4.5, §8.6.2).</summary>
|
||||||
|
private void DecodeSi()
|
||||||
|
{
|
||||||
|
cur!.MbIntra[mb] = true;
|
||||||
|
mbKind[mb] = MbKind.SI;
|
||||||
|
ReadIntraModes(false);
|
||||||
|
chromaModes[mb] = (byte)ReadChromaPredMode();
|
||||||
|
if (chromaModes[mb] > 3)
|
||||||
|
{
|
||||||
|
throw new H264Exception("Modo di predizione della crominanza non valido.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var cbp = ReadCbp(intra: true);
|
||||||
|
mbCbp[mb] = (byte)cbp;
|
||||||
|
ClearResidual();
|
||||||
|
if (cbp != 0)
|
||||||
|
{
|
||||||
|
ApplyQpDelta(ReadQpDelta());
|
||||||
|
rawLevels = true;
|
||||||
|
ReadResidual(false, cbp, intra: true);
|
||||||
|
rawLevels = false;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
lastQpDelta = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
mbQp[mb] = (byte)qp;
|
||||||
|
SetChromaQp();
|
||||||
|
ReconstructIntra(0);
|
||||||
|
}
|
||||||
|
|
||||||
private void ApplyQpDelta(int delta)
|
private void ApplyQpDelta(int delta)
|
||||||
{
|
{
|
||||||
if (delta is < -26 or > 25)
|
if (delta is < -26 or > 25)
|
||||||
@@ -776,7 +869,7 @@ public sealed partial class H264Decoder
|
|||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
modeA = mbKind[a] is MbKind.I4x4 or MbKind.I8x8 ? intraModes[(a * 16) + (((yM & 15) >> 2) * 4) + 3] : 2;
|
modeA = mbKind[a] is MbKind.I4x4 or MbKind.I8x8 or MbKind.SI ? intraModes[(a * 16) + (((yM & 15) >> 2) * 4) + 3] : 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (by > 0)
|
if (by > 0)
|
||||||
@@ -791,7 +884,7 @@ public sealed partial class H264Decoder
|
|||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
modeB = mbKind[b] is MbKind.I4x4 or MbKind.I8x8 ? intraModes[(b * 16) + 12 + bx] : 2;
|
modeB = mbKind[b] is MbKind.I4x4 or MbKind.I8x8 or MbKind.SI ? intraModes[(b * 16) + 12 + bx] : 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
return Math.Min(modeA, modeB);
|
return Math.Min(modeA, modeB);
|
||||||
@@ -801,30 +894,55 @@ public sealed partial class H264Decoder
|
|||||||
{
|
{
|
||||||
mbKind[mb] = MbKind.IPcm;
|
mbKind[mb] = MbKind.IPcm;
|
||||||
|
|
||||||
// With CABAC the arithmetic decoder has read exactly up to the end of its flush (§9.3.1.2).
|
// The samples are category 3: in partition B of a partitioned slice (grey when it is missing).
|
||||||
while (!rd.ByteAligned)
|
var main = rd;
|
||||||
{
|
var source = ResidualReader(intra: true);
|
||||||
rd.Skip(1); // pcm_alignment_zero_bit
|
|
||||||
}
|
|
||||||
|
|
||||||
var picture = cur!;
|
var picture = cur!;
|
||||||
for (var y = 0; y < 16; y++)
|
if (source is not null)
|
||||||
{
|
{
|
||||||
for (var x = 0; x < 16; x++)
|
rd = source;
|
||||||
{
|
var start = rd.Position;
|
||||||
picture.Y[lumaO + (y * lumaStride) + x] = (byte)rd.Read(8);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (var c = 0; c < 2; c++)
|
// With CABAC the arithmetic decoder has read exactly up to the end of its flush (§9.3.1.2).
|
||||||
|
while (!rd.ByteAligned)
|
||||||
|
{
|
||||||
|
rd.Skip(1); // pcm_alignment_zero_bit
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var y = 0; y < 16; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < 16; x++)
|
||||||
|
{
|
||||||
|
picture.Y[lumaO + (y * lumaStride) + x] = (byte)rd.Read(8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var c = 0; c < 2; c++)
|
||||||
|
{
|
||||||
|
var plane = c == 0 ? picture.Cb : picture.Cr;
|
||||||
|
for (var y = 0; y < 8; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < 8; x++)
|
||||||
|
{
|
||||||
|
plane[chromaO + (y * chromaStride) + x] = (byte)rd.Read(8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ResidualRead?.Invoke(start, rd.Position, true, true);
|
||||||
|
rd = main;
|
||||||
|
}
|
||||||
|
else
|
||||||
{
|
{
|
||||||
var plane = c == 0 ? picture.Cb : picture.Cr;
|
for (var y = 0; y < 16; y++)
|
||||||
|
{
|
||||||
|
picture.Y.AsSpan(lumaO + (y * lumaStride), 16).Fill(128);
|
||||||
|
}
|
||||||
|
|
||||||
for (var y = 0; y < 8; y++)
|
for (var y = 0; y < 8; y++)
|
||||||
{
|
{
|
||||||
for (var x = 0; x < 8; x++)
|
picture.Cb.AsSpan(chromaO + (y * chromaStride), 8).Fill(128);
|
||||||
{
|
picture.Cr.AsSpan(chromaO + (y * chromaStride), 8).Fill(128);
|
||||||
plane[chromaO + (y * chromaStride) + x] = (byte)rd.Read(8);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -981,10 +1099,13 @@ public sealed partial class H264Decoder
|
|||||||
}
|
}
|
||||||
|
|
||||||
ClearResidual();
|
ClearResidual();
|
||||||
|
var switching = sh.Type == SliceType.SP;
|
||||||
if (cbp != 0)
|
if (cbp != 0)
|
||||||
{
|
{
|
||||||
ApplyQpDelta(ReadQpDelta());
|
ApplyQpDelta(ReadQpDelta());
|
||||||
ParseResidual(false, cbp, intra: false);
|
rawLevels = switching;
|
||||||
|
ReadResidual(false, cbp, intra: false);
|
||||||
|
rawLevels = false;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -1069,7 +1190,14 @@ public sealed partial class H264Decoder
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
AddInterResidual();
|
if (switching)
|
||||||
|
{
|
||||||
|
ReconstructSwitchingInter();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
AddInterResidual();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void Partition(int part, out int px, out int py, out int w, out int h)
|
private void Partition(int part, out int px, out int py, out int w, out int h)
|
||||||
@@ -1189,6 +1317,27 @@ public sealed partial class H264Decoder
|
|||||||
Array.Clear(lumaHas);
|
Array.Clear(lumaHas);
|
||||||
Array.Clear(chromaCoef);
|
Array.Clear(chromaCoef);
|
||||||
Array.Clear(chromaHas);
|
Array.Clear(chromaHas);
|
||||||
|
Array.Clear(chromaDcLevels);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The residual of the macroblock, from the slice data or from its partition (§7.3.2.10): a missing partition leaves
|
||||||
|
/// it at zero.
|
||||||
|
/// </summary>
|
||||||
|
private void ReadResidual(bool intra16, int cbp, bool intra)
|
||||||
|
{
|
||||||
|
var source = ResidualReader(intra);
|
||||||
|
if (source is null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var main = rd;
|
||||||
|
rd = source;
|
||||||
|
var start = rd.Position;
|
||||||
|
ParseResidual(intra16, cbp, intra);
|
||||||
|
ResidualRead?.Invoke(start, rd.Position, intra, false);
|
||||||
|
rd = main;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>residual() of §7.3.5.3, with the scaling of §8.5 applied as the levels are read.</summary>
|
/// <summary>residual() of §7.3.5.3, with the scaling of §8.5 applied as the levels are read.</summary>
|
||||||
@@ -1295,7 +1444,7 @@ public sealed partial class H264Decoder
|
|||||||
if (level != 0)
|
if (level != 0)
|
||||||
{
|
{
|
||||||
var pos = scan4[k];
|
var pos = scan4[k];
|
||||||
lumaCoef[(raster * 16) + pos] = Scale4(level, scale4[(qpMod * 16) + pos], qpDiv);
|
lumaCoef[(raster * 16) + pos] = rawLevels ? level : Scale4(level, scale4[(qpMod * 16) + pos], qpDiv);
|
||||||
lumaHas[raster] = true;
|
lumaHas[raster] = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1320,6 +1469,12 @@ public sealed partial class H264Decoder
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (rawLevels)
|
||||||
|
{
|
||||||
|
levels.AsSpan(0, 4).CopyTo(chromaDcLevels.AsSpan(c * 4, 4));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
var qpc = H264Tables.ChromaQp[Math.Clamp(qp + (c == 0 ? pps.ChromaQpIndexOffset : pps.SecondChromaQpIndexOffset), 0, 51)];
|
var qpc = H264Tables.ChromaQp[Math.Clamp(qp + (c == 0 ? pps.ChromaQpIndexOffset : pps.SecondChromaQpIndexOffset), 0, 51)];
|
||||||
var ls = ls4[(intra ? 1 : 4) + c][(qpc % 6) * 16];
|
var ls = ls4[(intra ? 1 : 4) + c][(qpc % 6) * 16];
|
||||||
int c0 = levels[0], c1 = levels[1], c2 = levels[2], c3 = levels[3];
|
int c0 = levels[0], c1 = levels[1], c2 = levels[2], c3 = levels[3];
|
||||||
@@ -1355,7 +1510,7 @@ public sealed partial class H264Decoder
|
|||||||
if (level != 0)
|
if (level != 0)
|
||||||
{
|
{
|
||||||
var pos = scan4[k + 1];
|
var pos = scan4[k + 1];
|
||||||
chromaCoef[(((c * 4) + b) * 16) + pos] = Scale4(level, scale[((qpc % 6) * 16) + pos], qpc / 6);
|
chromaCoef[(((c * 4) + b) * 16) + pos] = rawLevels ? level : Scale4(level, scale[((qpc % 6) * 16) + pos], qpc / 6);
|
||||||
chromaHas[(c * 4) + b] = true;
|
chromaHas[(c * 4) + b] = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1405,7 +1560,7 @@ public sealed partial class H264Decoder
|
|||||||
var all = (1 << maxH) - 1;
|
var all = (1 << maxH) - 1;
|
||||||
if (!mbaff)
|
if (!mbaff)
|
||||||
{
|
{
|
||||||
return mbA >= 0 && (!constrained || IsIntra(mbA)) ? all : 0;
|
return mbA >= 0 && (!constrained || IntraUsable(mbA)) ? all : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pairA < 0)
|
if (pairA < 0)
|
||||||
@@ -1422,9 +1577,10 @@ public sealed partial class H264Decoder
|
|||||||
for (var r = 0; r < maxH; r++)
|
for (var r = 0; r < maxH; r++)
|
||||||
{
|
{
|
||||||
var n = Locate(-1, r, maxH, out _);
|
var n = Locate(-1, r, maxH, out _);
|
||||||
if (n >= 0 && IsIntra(n))
|
if (n >= 0 && IntraUsable(n))
|
||||||
{
|
{
|
||||||
mask |= 1 << r;
|
mask |= 1 << r;
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1441,14 +1597,16 @@ public sealed partial class H264Decoder
|
|||||||
var nB = Locate(0, -1, 16, out _);
|
var nB = Locate(0, -1, 16, out _);
|
||||||
var nC = Locate(16, -1, 16, out _);
|
var nC = Locate(16, -1, 16, out _);
|
||||||
var nD = Locate(-1, -1, 16, out _);
|
var nD = Locate(-1, -1, 16, out _);
|
||||||
var b = nB >= 0 && (!constrained || IsIntra(nB));
|
var b = nB >= 0 && (!constrained || IntraUsable(nB));
|
||||||
var c = nC >= 0 && (!constrained || IsIntra(nC));
|
var c = nC >= 0 && (!constrained || IntraUsable(nC));
|
||||||
var d = nD >= 0 && (!constrained || IsIntra(nD));
|
var d = nD >= 0 && (!constrained || IntraUsable(nD));
|
||||||
|
var si = mbKind[mb] == MbKind.SI;
|
||||||
var left = LeftRows(16, constrained);
|
var left = LeftRows(16, constrained);
|
||||||
Span<int> block = stackalloc int[64];
|
Span<int> block = stackalloc int[64];
|
||||||
switch (mbKind[mb])
|
switch (mbKind[mb])
|
||||||
{
|
{
|
||||||
case MbKind.I4x4:
|
case MbKind.I4x4:
|
||||||
|
case MbKind.SI:
|
||||||
for (var i = 0; i < 16; i++)
|
for (var i = 0; i < 16; i++)
|
||||||
{
|
{
|
||||||
var raster = H264Tables.BlockToRaster[i];
|
var raster = H264Tables.BlockToRaster[i];
|
||||||
@@ -1468,7 +1626,11 @@ public sealed partial class H264Decoder
|
|||||||
|
|
||||||
var o = LumaOffset(bx * 4, by * 4);
|
var o = LumaOffset(bx * 4, by * 4);
|
||||||
IntraPrediction.Predict4x4(picture.Y, o, stride, intraModes[(mb * 16) + raster], hasLeft, top, topRight, topLeft);
|
IntraPrediction.Predict4x4(picture.Y, o, stride, intraModes[(mb * 16) + raster], hasLeft, top, topRight, topLeft);
|
||||||
if (lumaHas[raster])
|
if (si)
|
||||||
|
{
|
||||||
|
SwitchingTransform.Luma4x4(picture.Y, o, stride, lumaCoef.AsSpan(raster * 16, 16), sh.Qs, sh.Qs, levelInQs: true);
|
||||||
|
}
|
||||||
|
else if (lumaHas[raster])
|
||||||
{
|
{
|
||||||
lumaCoef.AsSpan(raster * 16, 16).CopyTo(block);
|
lumaCoef.AsSpan(raster * 16, 16).CopyTo(block);
|
||||||
Transform.Add4x4(block[..16], picture.Y, o, stride);
|
Transform.Add4x4(block[..16], picture.Y, o, stride);
|
||||||
@@ -1516,7 +1678,38 @@ public sealed partial class H264Decoder
|
|||||||
bool upper = Rows(chromaLeft, 0, 4), lower = Rows(chromaLeft, 4, 4);
|
bool upper = Rows(chromaLeft, 0, 4), lower = Rows(chromaLeft, 4, 4);
|
||||||
IntraPrediction.PredictChroma(picture.Cb, chromaO, chromaStride, chromaModes[mb], upper, lower, b, d);
|
IntraPrediction.PredictChroma(picture.Cb, chromaO, chromaStride, chromaModes[mb], upper, lower, b, d);
|
||||||
IntraPrediction.PredictChroma(picture.Cr, chromaO, chromaStride, chromaModes[mb], upper, lower, b, d);
|
IntraPrediction.PredictChroma(picture.Cr, chromaO, chromaStride, chromaModes[mb], upper, lower, b, d);
|
||||||
AddChromaResidual();
|
if (si)
|
||||||
|
{
|
||||||
|
SwitchingChroma(levelInQs: true);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
AddChromaResidual();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A P macroblock of an SP slice, its prediction in place: every block is rebuilt in QS (§8.6.1).</summary>
|
||||||
|
private void ReconstructSwitchingInter()
|
||||||
|
{
|
||||||
|
var picture = cur!;
|
||||||
|
for (var raster = 0; raster < 16; raster++)
|
||||||
|
{
|
||||||
|
SwitchingTransform.Luma4x4(picture.Y, LumaOffset((raster & 3) * 4, (raster >> 2) * 4), lumaStride, lumaCoef.AsSpan(raster * 16, 16), mbQp[mb], sh.Qs, sh.SpForSwitch);
|
||||||
|
}
|
||||||
|
|
||||||
|
SwitchingChroma(sh.SpForSwitch);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The chroma of a macroblock rebuilt in QS: QPc from the QP of the macroblock, QSc from QS (§8.6.1, §8.6.2).</summary>
|
||||||
|
private void SwitchingChroma(bool levelInQs)
|
||||||
|
{
|
||||||
|
var picture = cur!;
|
||||||
|
for (var c = 0; c < 2; c++)
|
||||||
|
{
|
||||||
|
var offset = c == 0 ? pps.ChromaQpIndexOffset : pps.SecondChromaQpIndexOffset;
|
||||||
|
var qsc = H264Tables.ChromaQp[Math.Clamp(sh.Qs + offset, 0, 51)];
|
||||||
|
SwitchingTransform.Chroma(c == 0 ? picture.Cb : picture.Cr, chromaO, chromaStride, chromaCoef.AsSpan(c * 64, 64), chromaDcLevels.AsSpan(c * 4, 4), mbQpC[(mb * 2) + c], qsc, levelInQs);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void AddInterResidual()
|
private void AddInterResidual()
|
||||||
|
|||||||
@@ -0,0 +1,245 @@
|
|||||||
|
namespace Febe.Core.Codecs.H264;
|
||||||
|
|
||||||
|
public sealed partial class H264Decoder
|
||||||
|
{
|
||||||
|
/// <summary>The picture has more than one slice group (FMO): a slice walks the macroblocks of its group only.</summary>
|
||||||
|
private bool fmo;
|
||||||
|
|
||||||
|
/// <summary>The slice group of each map unit (mapUnitToSliceGroupMap, §8.2.2.1–§8.2.2.7).</summary>
|
||||||
|
private int[] mapUnitGroup = [];
|
||||||
|
|
||||||
|
/// <summary>The slice group of each macroblock address of the picture (mbToSliceGroupMap, §8.2.2.8).</summary>
|
||||||
|
private byte[] mbGroup = [];
|
||||||
|
|
||||||
|
/// <summary>NextMbAddress (§8.2.2): the next address of the same slice group, the picture size after the last one.</summary>
|
||||||
|
private int[] nextMb = [];
|
||||||
|
|
||||||
|
// What the map in the arrays above was computed for.
|
||||||
|
private Pps? mapPps;
|
||||||
|
private Sps? mapSps;
|
||||||
|
private int mapCycle = -1;
|
||||||
|
private int mapLayout = -1;
|
||||||
|
|
||||||
|
/// <summary>The address after <paramref name="addr"/> in the slice (§7.3.4).</summary>
|
||||||
|
private int NextAddress(int addr) => fmo ? nextMb[addr] : addr + 1;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The slice group map of the slice about to be decoded (§8.2.2), computed again only when the parameter sets,
|
||||||
|
/// slice_group_change_cycle or the kind of picture (frame, field, MBAFF frame) change.
|
||||||
|
/// </summary>
|
||||||
|
private void PrepareSliceGroups(SliceHeader h, Sps s, Pps p)
|
||||||
|
{
|
||||||
|
fmo = p.NumSliceGroups > 1;
|
||||||
|
if (!fmo)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 0 frame of frame macroblocks only or a field, 1 MBAFF frame, 2 frame of a stream with fields but no MBAFF.
|
||||||
|
var layout = s.FrameMbsOnly || h.FieldPic ? 0 : s.MbAdaptiveFrameField ? 1 : 2;
|
||||||
|
var cycle = p.SliceGroupMapType is >= 3 and <= 5 ? h.SliceGroupChangeCycle : -1;
|
||||||
|
if (ReferenceEquals(mapPps, p) && ReferenceEquals(mapSps, s) && mapCycle == cycle && mapLayout == layout)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var w = s.WidthInMbs;
|
||||||
|
var mapHeight = s.HeightInMapUnits;
|
||||||
|
var units = w * mapHeight;
|
||||||
|
if (mapUnitGroup.Length != units)
|
||||||
|
{
|
||||||
|
mapUnitGroup = new int[units];
|
||||||
|
}
|
||||||
|
|
||||||
|
BuildMapUnits(p, w, mapHeight, Math.Min(Math.Max(cycle, 0) * p.SliceGroupChangeRate, units));
|
||||||
|
|
||||||
|
var total = h.FieldPic ? s.WidthInMbs * s.HeightInMbs / 2 : s.WidthInMbs * s.HeightInMbs;
|
||||||
|
if (mbGroup.Length != total)
|
||||||
|
{
|
||||||
|
mbGroup = new byte[total];
|
||||||
|
nextMb = new int[total];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < total; i++)
|
||||||
|
{
|
||||||
|
var unit = layout switch
|
||||||
|
{
|
||||||
|
0 => i,
|
||||||
|
1 => i >> 1,
|
||||||
|
_ => ((i / (2 * w)) * w) + (i % w),
|
||||||
|
};
|
||||||
|
mbGroup[i] = (byte)mapUnitGroup[unit];
|
||||||
|
}
|
||||||
|
|
||||||
|
Span<int> last = stackalloc int[8];
|
||||||
|
last.Fill(total);
|
||||||
|
for (var i = total - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
var g = mbGroup[i];
|
||||||
|
nextMb[i] = last[g];
|
||||||
|
last[g] = i;
|
||||||
|
}
|
||||||
|
|
||||||
|
mapPps = p;
|
||||||
|
mapSps = s;
|
||||||
|
mapCycle = cycle;
|
||||||
|
mapLayout = layout;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>mapUnitToSliceGroupMap for the map type of the PPS (§8.2.2.1–§8.2.2.7).</summary>
|
||||||
|
private void BuildMapUnits(Pps p, int w, int h, int unitsInGroup0)
|
||||||
|
{
|
||||||
|
var map = mapUnitGroup;
|
||||||
|
var units = map.Length;
|
||||||
|
var groups = p.NumSliceGroups;
|
||||||
|
var direction = p.SliceGroupChangeDirection ? 1 : 0;
|
||||||
|
switch (p.SliceGroupMapType)
|
||||||
|
{
|
||||||
|
case 0:
|
||||||
|
{
|
||||||
|
// Interleaved: runs of each group in turn.
|
||||||
|
var i = 0;
|
||||||
|
do
|
||||||
|
{
|
||||||
|
for (var g = 0; g < groups && i < units; i += p.RunLength[g++])
|
||||||
|
{
|
||||||
|
for (var j = 0; j < p.RunLength[g] && i + j < units; j++)
|
||||||
|
{
|
||||||
|
map[i + j] = g;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (i < units);
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 1:
|
||||||
|
// Dispersed.
|
||||||
|
for (var i = 0; i < units; i++)
|
||||||
|
{
|
||||||
|
map[i] = ((i % w) + (((i / w) * groups) / 2)) % groups;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
// Foreground rectangles, the last group taking what is left.
|
||||||
|
Array.Fill(map, groups - 1);
|
||||||
|
for (var g = groups - 2; g >= 0; g--)
|
||||||
|
{
|
||||||
|
int topLeft = p.TopLeft[g], bottomRight = p.BottomRight[g];
|
||||||
|
if (bottomRight >= units || topLeft > bottomRight || topLeft % w > bottomRight % w)
|
||||||
|
{
|
||||||
|
throw new H264Exception("Rettangolo di un gruppo di slice fuori dall'immagine.");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var y = topLeft / w; y <= bottomRight / w; y++)
|
||||||
|
{
|
||||||
|
for (var x = topLeft % w; x <= bottomRight % w; x++)
|
||||||
|
{
|
||||||
|
map[(y * w) + x] = g;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case 3:
|
||||||
|
BoxOut(map, w, h, direction, unitsInGroup0);
|
||||||
|
break;
|
||||||
|
case 4:
|
||||||
|
{
|
||||||
|
// Raster scan.
|
||||||
|
var upperLeft = direction != 0 ? units - unitsInGroup0 : unitsInGroup0;
|
||||||
|
for (var i = 0; i < units; i++)
|
||||||
|
{
|
||||||
|
map[i] = i < upperLeft ? direction : 1 - direction;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 5:
|
||||||
|
{
|
||||||
|
// Wipe: column by column.
|
||||||
|
var upperLeft = direction != 0 ? units - unitsInGroup0 : unitsInGroup0;
|
||||||
|
var k = 0;
|
||||||
|
for (var x = 0; x < w; x++)
|
||||||
|
{
|
||||||
|
for (var y = 0; y < h; y++)
|
||||||
|
{
|
||||||
|
map[(y * w) + x] = k++ < upperLeft ? direction : 1 - direction;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
// Explicit.
|
||||||
|
if (p.SliceGroupIds.Length != units)
|
||||||
|
{
|
||||||
|
throw new H264Exception("Mappa esplicita dei gruppi di slice di dimensione sbagliata.");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < units; i++)
|
||||||
|
{
|
||||||
|
map[i] = p.SliceGroupIds[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Box-out (§8.2.2.4): group 0 grows as a spiral from the centre, clockwise or counter-clockwise.</summary>
|
||||||
|
private static void BoxOut(int[] map, int w, int h, int direction, int unitsInGroup0)
|
||||||
|
{
|
||||||
|
Array.Fill(map, 1);
|
||||||
|
var x = (w - direction) / 2;
|
||||||
|
var y = (h - direction) / 2;
|
||||||
|
int left = x, top = y, right = x, bottom = y;
|
||||||
|
int xDir = direction - 1, yDir = direction;
|
||||||
|
for (var k = 0; k < unitsInGroup0;)
|
||||||
|
{
|
||||||
|
var vacant = map[(y * w) + x] == 1;
|
||||||
|
if (vacant)
|
||||||
|
{
|
||||||
|
map[(y * w) + x] = 0;
|
||||||
|
k++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (xDir == -1 && x == left)
|
||||||
|
{
|
||||||
|
left = Math.Max(left - 1, 0);
|
||||||
|
x = left;
|
||||||
|
xDir = 0;
|
||||||
|
yDir = (2 * direction) - 1;
|
||||||
|
}
|
||||||
|
else if (xDir == 1 && x == right)
|
||||||
|
{
|
||||||
|
right = Math.Min(right + 1, w - 1);
|
||||||
|
x = right;
|
||||||
|
xDir = 0;
|
||||||
|
yDir = 1 - (2 * direction);
|
||||||
|
}
|
||||||
|
else if (yDir == -1 && y == top)
|
||||||
|
{
|
||||||
|
top = Math.Max(top - 1, 0);
|
||||||
|
y = top;
|
||||||
|
xDir = 1 - (2 * direction);
|
||||||
|
yDir = 0;
|
||||||
|
}
|
||||||
|
else if (yDir == 1 && y == bottom)
|
||||||
|
{
|
||||||
|
bottom = Math.Min(bottom + 1, h - 1);
|
||||||
|
y = bottom;
|
||||||
|
xDir = (2 * direction) - 1;
|
||||||
|
yDir = 0;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
x += xDir;
|
||||||
|
y += yDir;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,14 +14,17 @@ public enum H264AccessPoint
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Main and High profiles in
|
/// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Extended, Main and High
|
||||||
/// 4:2:0 with 8-bit samples — CAVLC and CABAC, I, P and B slices, 8×8 transform and scaling matrices, spatial and
|
/// profiles in 4:2:0 with 8-bit samples — CAVLC and CABAC, I, P and B slices, 8×8 transform and scaling matrices, spatial
|
||||||
/// temporal direct prediction, list modification, memory management operations and long-term references, deblocking —
|
/// and temporal direct prediction, list modification, memory management operations and long-term references,
|
||||||
/// for progressive frames and for interlaced video: field pictures, frames and fields mixed picture by picture (PAFF),
|
/// deblocking — for progressive frames and for interlaced video: field pictures, frames and fields mixed picture by
|
||||||
/// frames of frame and field macroblock pairs (MBAFF). Frames come out whole: the two fields of a pair are interleaved.
|
/// picture (PAFF), frames of frame and field macroblock pairs (MBAFF). Frames come out whole: the two fields of a pair are
|
||||||
/// Written from the standard but not yet checked against a conformance stream: explicit and implicit weighted
|
/// interleaved. The tools of Baseline and Extended: slice groups (FMO, map types 0–6), slices in any order (ASO), SP and
|
||||||
/// prediction, gaps in frame_num, I_PCM. Not handled (an <see cref="H264Exception"/>): slice groups, SP/SI slices, data
|
/// SI slices (switching pictures), slice data partitioning (NAL units 2–4); redundant coded pictures are skipped, the
|
||||||
/// partitioning, 4:2:2/4:4:4 and depths above 8 bits. Redundant coded pictures are skipped.
|
/// primary one is decoded. Written from the standard but not yet checked against a conformance stream: explicit and
|
||||||
|
/// implicit weighted prediction, gaps in frame_num, I_PCM, SI macroblocks and sp_for_switch_flag, data partitioning
|
||||||
|
/// (checked only on conformance streams split into partitions). Not handled (an <see cref="H264Exception"/>):
|
||||||
|
/// 4:2:2/4:4:4 and depths above 8 bits.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed partial class H264Decoder
|
public sealed partial class H264Decoder
|
||||||
{
|
{
|
||||||
@@ -174,12 +177,13 @@ public sealed partial class H264Decoder
|
|||||||
case 5:
|
case 5:
|
||||||
return H264AccessPoint.Idr;
|
return H264AccessPoint.Idr;
|
||||||
case 1:
|
case 1:
|
||||||
|
case 2: // partition A starts like a slice
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// first_mb_in_slice and slice_type: a few bytes of the header are enough.
|
// first_mb_in_slice and slice_type: a few bytes of the header are enough.
|
||||||
var reader = NalUnits.Parse(nal[..Math.Min(nal.Length, 16)]).Reader();
|
var reader = NalUnits.Parse(nal[..Math.Min(nal.Length, 16)]).Reader();
|
||||||
_ = reader.ReadUe();
|
_ = reader.ReadUe();
|
||||||
return reader.ReadUe(9) % 5 == (int)SliceType.I ? H264AccessPoint.IntraPicture : H264AccessPoint.None;
|
return (SliceType)(reader.ReadUe(9) % 5) is SliceType.I or SliceType.SI ? H264AccessPoint.IntraPicture : H264AccessPoint.None;
|
||||||
}
|
}
|
||||||
catch (H264Exception)
|
catch (H264Exception)
|
||||||
{
|
{
|
||||||
@@ -217,6 +221,11 @@ public sealed partial class H264Decoder
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
if (partitionPending)
|
||||||
|
{
|
||||||
|
DecodePartitionedSlice();
|
||||||
|
}
|
||||||
|
|
||||||
CompletePicture();
|
CompletePicture();
|
||||||
}
|
}
|
||||||
catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException or NullReferenceException)
|
catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException or NullReferenceException)
|
||||||
@@ -228,10 +237,19 @@ public sealed partial class H264Decoder
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Decodes one NAL unit (with its header, without start code) and leaves the picture open: for the tests.</summary>
|
||||||
|
internal void DecodeUnit(ReadOnlySpan<byte> nal) => Decode(NalUnits.Unescape(nal, ref rbsp));
|
||||||
|
|
||||||
private void Decode(NalUnit nal)
|
private void Decode(NalUnit nal)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
// The partitions B and C of a slice follow its partition A: anything else completes it.
|
||||||
|
if (partitionPending && nal.Type is not (3 or 4))
|
||||||
|
{
|
||||||
|
DecodePartitionedSlice();
|
||||||
|
}
|
||||||
|
|
||||||
switch (nal.Type)
|
switch (nal.Type)
|
||||||
{
|
{
|
||||||
case 1:
|
case 1:
|
||||||
@@ -239,9 +257,12 @@ public sealed partial class H264Decoder
|
|||||||
DecodeSlice(nal);
|
DecodeSlice(nal);
|
||||||
break;
|
break;
|
||||||
case 2:
|
case 2:
|
||||||
|
StorePartitionA(nal);
|
||||||
|
break;
|
||||||
case 3:
|
case 3:
|
||||||
case 4:
|
case 4:
|
||||||
throw new H264Exception("Il partizionamento dei dati non è gestito.");
|
StorePartition(nal);
|
||||||
|
break;
|
||||||
case 7:
|
case 7:
|
||||||
{
|
{
|
||||||
var sps = Sps.Parse(nal.Reader());
|
var sps = Sps.Parse(nal.Reader());
|
||||||
@@ -270,7 +291,20 @@ public sealed partial class H264Decoder
|
|||||||
private void DecodeSlice(NalUnit nal)
|
private void DecodeSlice(NalUnit nal)
|
||||||
{
|
{
|
||||||
var reader = nal.Reader();
|
var reader = nal.Reader();
|
||||||
var header = SliceHeader.Parse(reader, nal, sequences, pictures, out var sps, out var pps);
|
var header = ParseSliceHeader(reader, nal, out var sps, out var pps);
|
||||||
|
|
||||||
|
// A redundant coded picture (§7.4.3) repeats the primary one, which is decoded: it is skipped.
|
||||||
|
if (header.RedundantPicCnt > 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
DecodeParsedSlice(nal, reader, header, sps, pps);
|
||||||
|
}
|
||||||
|
|
||||||
|
private SliceHeader ParseSliceHeader(RbspReader reader, NalUnit nal, out Sps sps, out Pps pps)
|
||||||
|
{
|
||||||
|
var header = SliceHeader.Parse(reader, nal, sequences, pictures, out sps, out pps);
|
||||||
if (sps.ChromaFormatIdc != 1 || sps.BitDepthLuma != 8 || sps.BitDepthChroma != 8)
|
if (sps.ChromaFormatIdc != 1 || sps.BitDepthLuma != 8 || sps.BitDepthChroma != 8)
|
||||||
{
|
{
|
||||||
throw new H264Exception("Solo video 4:2:0 a 8 bit.");
|
throw new H264Exception("Solo video 4:2:0 a 8 bit.");
|
||||||
@@ -281,12 +315,12 @@ public sealed partial class H264Decoder
|
|||||||
throw new H264Exception("La codifica senza perdita non è gestita.");
|
throw new H264Exception("La codifica senza perdita non è gestita.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// A redundant coded picture (§7.4.3) repeats the primary one, which is decoded: it is skipped.
|
return header;
|
||||||
if (header.RedundantPicCnt > 0)
|
}
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
/// <summary>A slice whose header is read: the picture it belongs to, then its macroblocks.</summary>
|
||||||
|
private void DecodeParsedSlice(NalUnit nal, RbspReader reader, SliceHeader header, Sps sps, Pps pps)
|
||||||
|
{
|
||||||
if (cur is null || picHeader is null || StartsNewPicture(header, nal) || FirstMacroblockDone(header, sps))
|
if (cur is null || picHeader is null || StartsNewPicture(header, nal) || FirstMacroblockDone(header, sps))
|
||||||
{
|
{
|
||||||
FinishPicture();
|
FinishPicture();
|
||||||
@@ -444,6 +478,8 @@ public sealed partial class H264Decoder
|
|||||||
picture.Decoded |= structure == 0 ? 3 : structure;
|
picture.Decoded |= structure == 0 ? 3 : structure;
|
||||||
sliceCounter = 0;
|
sliceCounter = 0;
|
||||||
sliceFilters.Clear();
|
sliceFilters.Clear();
|
||||||
|
sliceSwitching.Clear();
|
||||||
|
anySwitching = false;
|
||||||
Array.Fill(mbSlice, -1);
|
Array.Fill(mbSlice, -1);
|
||||||
|
|
||||||
// A picture nobody refers to and nobody wants: its header has set the state above, its slices are not decoded.
|
// A picture nobody refers to and nobody wants: its header has set the state above, its slices are not decoded.
|
||||||
@@ -1165,7 +1201,7 @@ public sealed partial class H264Decoder
|
|||||||
|
|
||||||
longTerm.Sort((a, b) => a.LongTermPicNum.CompareTo(b.LongTermPicNum));
|
longTerm.Sort((a, b) => a.LongTermPicNum.CompareTo(b.LongTermPicNum));
|
||||||
List<RefEntry> init0 = [], init1 = [];
|
List<RefEntry> init0 = [], init1 = [];
|
||||||
if (h.Type == SliceType.P)
|
if (h.IsP)
|
||||||
{
|
{
|
||||||
shortTerm.Sort((a, b) => b.PicNum.CompareTo(a.PicNum));
|
shortTerm.Sort((a, b) => b.PicNum.CompareTo(a.PicNum));
|
||||||
foreach (var p in shortTerm)
|
foreach (var p in shortTerm)
|
||||||
@@ -1223,7 +1259,7 @@ public sealed partial class H264Decoder
|
|||||||
|
|
||||||
longTerm.Sort((a, b) => a.LongTermFrameIdx.CompareTo(b.LongTermFrameIdx));
|
longTerm.Sort((a, b) => a.LongTermFrameIdx.CompareTo(b.LongTermFrameIdx));
|
||||||
List<RefEntry> init0 = [], init1 = [];
|
List<RefEntry> init0 = [], init1 = [];
|
||||||
if (h.Type == SliceType.P)
|
if (h.IsP)
|
||||||
{
|
{
|
||||||
shortTerm.Sort((a, b) => b.FrameNumWrap.CompareTo(a.FrameNumWrap));
|
shortTerm.Sort((a, b) => b.FrameNumWrap.CompareTo(a.FrameNumWrap));
|
||||||
Alternate(shortTerm, parity, longTerm: false, init0);
|
Alternate(shortTerm, parity, longTerm: false, init0);
|
||||||
|
|||||||
@@ -181,6 +181,31 @@ internal sealed class Pps
|
|||||||
internal bool WeightedPred;
|
internal bool WeightedPred;
|
||||||
internal int WeightedBipredIdc;
|
internal int WeightedBipredIdc;
|
||||||
internal int PicInitQp;
|
internal int PicInitQp;
|
||||||
|
|
||||||
|
/// <summary>26 + pic_init_qs_minus26: the starting QS of SP and SI slices.</summary>
|
||||||
|
internal int PicInitQs;
|
||||||
|
|
||||||
|
/// <summary>num_slice_groups_minus1 + 1: more than one is FMO (§8.2.2).</summary>
|
||||||
|
internal int NumSliceGroups = 1;
|
||||||
|
|
||||||
|
internal int SliceGroupMapType;
|
||||||
|
|
||||||
|
/// <summary>run_length_minus1 + 1 of each slice group (map type 0).</summary>
|
||||||
|
internal int[] RunLength = [];
|
||||||
|
|
||||||
|
/// <summary>top_left and bottom_right of the rectangles of the slice groups but the last (map type 2).</summary>
|
||||||
|
internal int[] TopLeft = [];
|
||||||
|
|
||||||
|
internal int[] BottomRight = [];
|
||||||
|
|
||||||
|
internal bool SliceGroupChangeDirection;
|
||||||
|
|
||||||
|
/// <summary>slice_group_change_rate_minus1 + 1 (map types 3–5).</summary>
|
||||||
|
internal int SliceGroupChangeRate;
|
||||||
|
|
||||||
|
/// <summary>slice_group_id of each map unit (map type 6).</summary>
|
||||||
|
internal byte[] SliceGroupIds = [];
|
||||||
|
|
||||||
internal int ChromaQpIndexOffset;
|
internal int ChromaQpIndexOffset;
|
||||||
internal int SecondChromaQpIndexOffset;
|
internal int SecondChromaQpIndexOffset;
|
||||||
internal bool DeblockingFilterControlPresent;
|
internal bool DeblockingFilterControlPresent;
|
||||||
@@ -196,9 +221,10 @@ internal sealed class Pps
|
|||||||
var p = new Pps { Id = r.ReadUe(255), SpsId = r.ReadUe(31) };
|
var p = new Pps { Id = r.ReadUe(255), SpsId = r.ReadUe(31) };
|
||||||
p.Cabac = r.ReadFlag();
|
p.Cabac = r.ReadFlag();
|
||||||
p.BottomFieldPicOrderInFramePresent = r.ReadFlag();
|
p.BottomFieldPicOrderInFramePresent = r.ReadFlag();
|
||||||
if (r.ReadUe(7) > 0)
|
p.NumSliceGroups = r.ReadUe(7) + 1;
|
||||||
|
if (p.NumSliceGroups > 1)
|
||||||
{
|
{
|
||||||
throw new H264Exception("I gruppi di slice (FMO) non sono gestiti.");
|
ParseSliceGroups(r, p);
|
||||||
}
|
}
|
||||||
|
|
||||||
p.NumRefIdxL0DefaultActive = r.ReadUe(31) + 1;
|
p.NumRefIdxL0DefaultActive = r.ReadUe(31) + 1;
|
||||||
@@ -206,7 +232,12 @@ internal sealed class Pps
|
|||||||
p.WeightedPred = r.ReadFlag();
|
p.WeightedPred = r.ReadFlag();
|
||||||
p.WeightedBipredIdc = (int)r.Read(2);
|
p.WeightedBipredIdc = (int)r.Read(2);
|
||||||
p.PicInitQp = 26 + r.ReadSe();
|
p.PicInitQp = 26 + r.ReadSe();
|
||||||
r.ReadSe(); // pic_init_qs_minus26
|
p.PicInitQs = 26 + r.ReadSe();
|
||||||
|
if (p.PicInitQs is < 0 or > 51)
|
||||||
|
{
|
||||||
|
throw new H264Exception("QS iniziale del PPS non valido.");
|
||||||
|
}
|
||||||
|
|
||||||
p.ChromaQpIndexOffset = r.ReadSe();
|
p.ChromaQpIndexOffset = r.ReadSe();
|
||||||
p.DeblockingFilterControlPresent = r.ReadFlag();
|
p.DeblockingFilterControlPresent = r.ReadFlag();
|
||||||
p.ConstrainedIntraPred = r.ReadFlag();
|
p.ConstrainedIntraPred = r.ReadFlag();
|
||||||
@@ -227,6 +258,58 @@ internal sealed class Pps
|
|||||||
|
|
||||||
return p;
|
return p;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>The slice group map of §7.3.2.2 (num_slice_groups_minus1 above 0), checked against the picture later.</summary>
|
||||||
|
private static void ParseSliceGroups(RbspReader r, Pps p)
|
||||||
|
{
|
||||||
|
p.SliceGroupMapType = r.ReadUe(6);
|
||||||
|
var groups = p.NumSliceGroups;
|
||||||
|
switch (p.SliceGroupMapType)
|
||||||
|
{
|
||||||
|
case 0:
|
||||||
|
p.RunLength = new int[groups];
|
||||||
|
for (var i = 0; i < groups; i++)
|
||||||
|
{
|
||||||
|
p.RunLength[i] = r.ReadUe(Sps.MaxFrameMbs - 1) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
p.TopLeft = new int[groups - 1];
|
||||||
|
p.BottomRight = new int[groups - 1];
|
||||||
|
for (var i = 0; i < groups - 1; i++)
|
||||||
|
{
|
||||||
|
p.TopLeft[i] = r.ReadUe(Sps.MaxFrameMbs - 1);
|
||||||
|
p.BottomRight[i] = r.ReadUe(Sps.MaxFrameMbs - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case 3:
|
||||||
|
case 4:
|
||||||
|
case 5:
|
||||||
|
p.SliceGroupChangeDirection = r.ReadFlag();
|
||||||
|
p.SliceGroupChangeRate = r.ReadUe(Sps.MaxFrameMbs - 1) + 1;
|
||||||
|
break;
|
||||||
|
case 6:
|
||||||
|
{
|
||||||
|
var size = r.ReadUe(Sps.MaxFrameMbs - 1) + 1;
|
||||||
|
var bits = 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)(groups - 1));
|
||||||
|
p.SliceGroupIds = new byte[size];
|
||||||
|
for (var i = 0; i < size; i++)
|
||||||
|
{
|
||||||
|
var id = (int)r.Read(bits);
|
||||||
|
if (id >= groups || r.BitsLeft < 0)
|
||||||
|
{
|
||||||
|
throw new H264Exception("slice_group_id non valido.");
|
||||||
|
}
|
||||||
|
|
||||||
|
p.SliceGroupIds[i] = (byte)id;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Scaling lists (§7.3.2.1.1.1, tables 7-2 to 7-4) and the scale factors derived from them (§8.5.9).</summary>
|
/// <summary>Scaling lists (§7.3.2.1.1.1, tables 7-2 to 7-4) and the scale factors derived from them (§8.5.9).</summary>
|
||||||
|
|||||||
@@ -56,8 +56,23 @@ internal sealed class SliceHeader
|
|||||||
internal int AlphaOffset;
|
internal int AlphaOffset;
|
||||||
internal int BetaOffset;
|
internal int BetaOffset;
|
||||||
|
|
||||||
|
/// <summary>sp_for_switch_flag of an SP slice: its P macroblocks decode as those of a switching picture (§8.6.1).</summary>
|
||||||
|
internal bool SpForSwitch;
|
||||||
|
|
||||||
|
/// <summary>QS_Y of an SP or SI slice: pic_init_qs_minus26 + 26 + slice_qs_delta.</summary>
|
||||||
|
internal int Qs;
|
||||||
|
|
||||||
|
/// <summary>slice_group_change_cycle (map types 3–5 of FMO).</summary>
|
||||||
|
internal int SliceGroupChangeCycle;
|
||||||
|
|
||||||
internal bool IsIntra => Type is SliceType.I or SliceType.SI;
|
internal bool IsIntra => Type is SliceType.I or SliceType.SI;
|
||||||
|
|
||||||
|
/// <summary>A P or SP slice: both are parsed and predicted alike (an SP slice differs in the reconstruction).</summary>
|
||||||
|
internal bool IsP => Type is SliceType.P or SliceType.SP;
|
||||||
|
|
||||||
|
/// <summary>An SP or SI slice: switching pictures (§8.6).</summary>
|
||||||
|
internal bool IsSwitching => Type is SliceType.SP or SliceType.SI;
|
||||||
|
|
||||||
internal bool IsB => Type == SliceType.B;
|
internal bool IsB => Type == SliceType.B;
|
||||||
|
|
||||||
/// <summary>0 frame, 1 top field, 2 bottom field.</summary>
|
/// <summary>0 frame, 1 top field, 2 bottom field.</summary>
|
||||||
@@ -74,11 +89,6 @@ internal sealed class SliceHeader
|
|||||||
throw new H264Exception("Slice senza i suoi insiemi di parametri.");
|
throw new H264Exception("Slice senza i suoi insiemi di parametri.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (h.Type is SliceType.SP or SliceType.SI)
|
|
||||||
{
|
|
||||||
throw new H264Exception("Le slice SP e SI non sono gestite.");
|
|
||||||
}
|
|
||||||
|
|
||||||
h.FrameNum = (int)r.Read(sps.Log2MaxFrameNum);
|
h.FrameNum = (int)r.Read(sps.Log2MaxFrameNum);
|
||||||
if (!sps.FrameMbsOnly)
|
if (!sps.FrameMbsOnly)
|
||||||
{
|
{
|
||||||
@@ -151,7 +161,7 @@ internal sealed class SliceHeader
|
|||||||
h.NumRefIdxActiveL0 = 0;
|
h.NumRefIdxActiveL0 = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((pps.WeightedPred && h.Type == SliceType.P) || (pps.WeightedBipredIdc == 1 && h.IsB))
|
if ((pps.WeightedPred && h.IsP) || (pps.WeightedBipredIdc == 1 && h.IsB))
|
||||||
{
|
{
|
||||||
ParseWeights(r, h, sps);
|
ParseWeights(r, h, sps);
|
||||||
}
|
}
|
||||||
@@ -205,6 +215,20 @@ internal sealed class SliceHeader
|
|||||||
}
|
}
|
||||||
|
|
||||||
h.QpDelta = r.ReadSe();
|
h.QpDelta = r.ReadSe();
|
||||||
|
if (h.Type is SliceType.SP or SliceType.SI)
|
||||||
|
{
|
||||||
|
if (h.Type == SliceType.SP)
|
||||||
|
{
|
||||||
|
h.SpForSwitch = r.ReadFlag();
|
||||||
|
}
|
||||||
|
|
||||||
|
h.Qs = pps.PicInitQs + r.ReadSe();
|
||||||
|
if (h.Qs is < 0 or > 51)
|
||||||
|
{
|
||||||
|
throw new H264Exception("QS della slice non valido.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (pps.DeblockingFilterControlPresent)
|
if (pps.DeblockingFilterControlPresent)
|
||||||
{
|
{
|
||||||
h.DisableDeblocking = r.ReadUe(2);
|
h.DisableDeblocking = r.ReadUe(2);
|
||||||
@@ -215,6 +239,15 @@ internal sealed class SliceHeader
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (pps.NumSliceGroups > 1 && pps.SliceGroupMapType is >= 3 and <= 5)
|
||||||
|
{
|
||||||
|
// Ceil(Log2(PicSizeInMapUnits ÷ SliceGroupChangeRate + 1)) bits (§7.4.3).
|
||||||
|
var size = sps.WidthInMbs * sps.HeightInMapUnits;
|
||||||
|
var units = (size + pps.SliceGroupChangeRate - 1) / pps.SliceGroupChangeRate;
|
||||||
|
var bits = 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)units);
|
||||||
|
h.SliceGroupChangeCycle = (int)r.Read(bits);
|
||||||
|
}
|
||||||
|
|
||||||
return h;
|
return h;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,161 @@
|
|||||||
|
namespace Febe.Core.Codecs.H264;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The reconstruction of the P macroblocks of SP slices and of the SI macroblocks (§8.6): the prediction is transformed
|
||||||
|
/// and quantised with QS together with the received levels, so that a switching picture rebuilds exactly the same
|
||||||
|
/// samples whichever stream it was reached from. The block is then decoded with QS as usual, and the result replaces the
|
||||||
|
/// prediction instead of being added to it.
|
||||||
|
/// </summary>
|
||||||
|
internal static class SwitchingTransform
|
||||||
|
{
|
||||||
|
/// <summary>Quantisation factors (the inverse of normAdjust4x4) by QS % 6 and class of position (0 even-even, 1 odd-odd, 2 others).</summary>
|
||||||
|
private static readonly int[,] Quant =
|
||||||
|
{
|
||||||
|
{ 13107, 5243, 8066 }, { 11916, 4660, 7490 }, { 10082, 4194, 6554 }, { 9362, 3647, 5825 }, { 8192, 3355, 5243 }, { 7282, 2893, 4559 },
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>A<sub>ij</sub> of §8.6.1 by class of position.</summary>
|
||||||
|
private static readonly int[] Norm = [16, 25, 20];
|
||||||
|
|
||||||
|
/// <summary>The class of each raster position of a 4×4 block (0 even row and column, 1 both odd, 2 the others).</summary>
|
||||||
|
private static readonly byte[] Class = [0, 2, 0, 2, 2, 1, 2, 1, 0, 2, 0, 2, 2, 1, 2, 1];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A luma 4×4 block: the prediction at <paramref name="o"/> is replaced by the reconstruction from it and the levels
|
||||||
|
/// (raster order, not scaled). <paramref name="levelInQs"/> is set for SI macroblocks and for SP slices with
|
||||||
|
/// sp_for_switch_flag: the levels are then added to the quantised prediction (§8.6.2) instead of the scaled ones to the
|
||||||
|
/// transformed prediction (§8.6.1).
|
||||||
|
/// </summary>
|
||||||
|
internal static void Luma4x4(byte[] plane, int o, int stride, ReadOnlySpan<int> levels, int qp, int qs, bool levelInQs)
|
||||||
|
{
|
||||||
|
Span<int> c = stackalloc int[16];
|
||||||
|
Forward(plane, o, stride, c);
|
||||||
|
int qpMod = qp % 6, qpDiv = qp / 6, qsMod = qs % 6, qsDiv = qs / 6;
|
||||||
|
for (var pos = 0; pos < 16; pos++)
|
||||||
|
{
|
||||||
|
var cls = Class[pos];
|
||||||
|
var level = Requantise(c[pos], levels[pos], cls, qpMod, qpDiv, qsMod, qsDiv, levelInQs, dc: false);
|
||||||
|
c[pos] = (level * H264Tables.NormAdjust4x4[qsMod, cls]) << qsDiv;
|
||||||
|
}
|
||||||
|
|
||||||
|
Store4x4(c, plane, o, stride);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One chroma component (four 4×4 blocks): <paramref name="ac"/> holds the AC levels of the four blocks (block × 16
|
||||||
|
/// + raster position; position 0 is ignored), <paramref name="dc"/> the four DC levels in the order they are parsed.
|
||||||
|
/// </summary>
|
||||||
|
internal static void Chroma(byte[] plane, int o, int stride, ReadOnlySpan<int> ac, ReadOnlySpan<int> dc, int qpc, int qsc, bool levelInQs)
|
||||||
|
{
|
||||||
|
Span<int> c = stackalloc int[64];
|
||||||
|
for (var b = 0; b < 4; b++)
|
||||||
|
{
|
||||||
|
Forward(plane, BlockOffset(o, stride, b), stride, c.Slice(b * 16, 16));
|
||||||
|
}
|
||||||
|
|
||||||
|
int qpMod = qpc % 6, qpDiv = qpc / 6, qsMod = qsc % 6, qsDiv = qsc / 6;
|
||||||
|
|
||||||
|
// The DC terms of the prediction through the 2×2 transform, combined with the levels, back through it (§8.6.1).
|
||||||
|
int p0 = c[0], p1 = c[16], p2 = c[32], p3 = c[48];
|
||||||
|
Span<int> q = [p0 + p1 + p2 + p3, p0 - p1 + p2 - p3, p0 + p1 - p2 - p3, p0 - p1 - p2 + p3];
|
||||||
|
for (var k = 0; k < 4; k++)
|
||||||
|
{
|
||||||
|
q[k] = Requantise(q[k], dc[k], 0, qpMod, qpDiv, qsMod, qsDiv, levelInQs, dc: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
int f0 = q[0] + q[1] + q[2] + q[3], f1 = q[0] - q[1] + q[2] - q[3], f2 = q[0] + q[1] - q[2] - q[3], f3 = q[0] - q[1] - q[2] + q[3];
|
||||||
|
var scaleDc = 16 * H264Tables.NormAdjust4x4[qsMod, 0];
|
||||||
|
c[0] = ((f0 * scaleDc) << qsDiv) >> 5;
|
||||||
|
c[16] = ((f1 * scaleDc) << qsDiv) >> 5;
|
||||||
|
c[32] = ((f2 * scaleDc) << qsDiv) >> 5;
|
||||||
|
c[48] = ((f3 * scaleDc) << qsDiv) >> 5;
|
||||||
|
|
||||||
|
for (var b = 0; b < 4; b++)
|
||||||
|
{
|
||||||
|
var block = c.Slice(b * 16, 16);
|
||||||
|
for (var pos = 1; pos < 16; pos++)
|
||||||
|
{
|
||||||
|
var cls = Class[pos];
|
||||||
|
var level = Requantise(block[pos], ac[(b * 16) + pos], cls, qpMod, qpDiv, qsMod, qsDiv, levelInQs, dc: false);
|
||||||
|
block[pos] = (level * H264Tables.NormAdjust4x4[qsMod, cls]) << qsDiv;
|
||||||
|
}
|
||||||
|
|
||||||
|
Store4x4(block, plane, BlockOffset(o, stride, b), stride);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The level in QS of one coefficient from the transformed prediction <paramref name="predicted"/> and the received
|
||||||
|
/// level: equations 8-401 to 8-404 of §8.6.1 (with QP), or 8-410 to 8-411 of §8.6.2 (in QS). The DC terms of
|
||||||
|
/// chroma carry one bit more of scaling.
|
||||||
|
/// </summary>
|
||||||
|
private static int Requantise(int predicted, int level, int cls, int qpMod, int qpDiv, int qsMod, int qsDiv, bool levelInQs, bool dc)
|
||||||
|
{
|
||||||
|
var extra = dc ? 1 : 0;
|
||||||
|
var shift = 15 + qsDiv + extra;
|
||||||
|
var round = 1L << (shift - 1);
|
||||||
|
var quant = Quant[qsMod, cls];
|
||||||
|
if (levelInQs)
|
||||||
|
{
|
||||||
|
var magnitude = (int)(((Math.Abs((long)predicted) * quant) + round) >> shift);
|
||||||
|
return level + (predicted < 0 ? -magnitude : magnitude);
|
||||||
|
}
|
||||||
|
|
||||||
|
var sum = predicted + ((((long)level * H264Tables.NormAdjust4x4[qpMod, cls] * Norm[cls]) << qpDiv) >> (6 - extra));
|
||||||
|
var result = (int)Math.Min(((Math.Abs(sum) * quant) + round) >> shift, int.MaxValue / 64);
|
||||||
|
return sum < 0 ? -result : result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int BlockOffset(int o, int stride, int b) => o + ((b >> 1) * 4 * stride) + ((b & 1) * 4);
|
||||||
|
|
||||||
|
/// <summary>The forward 4×4 core transform of the samples at <paramref name="o"/> (§8.6.1, c<sup>p</sup>), raster order.</summary>
|
||||||
|
private static void Forward(byte[] plane, int o, int stride, Span<int> c)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < 4; i++)
|
||||||
|
{
|
||||||
|
var row = o + (i * stride);
|
||||||
|
int x0 = plane[row], x1 = plane[row + 1], x2 = plane[row + 2], x3 = plane[row + 3];
|
||||||
|
int a = x0 + x3, b = x1 + x2, d = x1 - x2, e = x0 - x3;
|
||||||
|
c[i * 4] = a + b;
|
||||||
|
c[(i * 4) + 1] = (2 * e) + d;
|
||||||
|
c[(i * 4) + 2] = a - b;
|
||||||
|
c[(i * 4) + 3] = e - (2 * d);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var j = 0; j < 4; j++)
|
||||||
|
{
|
||||||
|
int x0 = c[j], x1 = c[4 + j], x2 = c[8 + j], x3 = c[12 + j];
|
||||||
|
int a = x0 + x3, b = x1 + x2, d = x1 - x2, e = x0 - x3;
|
||||||
|
c[j] = a + b;
|
||||||
|
c[4 + j] = (2 * e) + d;
|
||||||
|
c[8 + j] = a - b;
|
||||||
|
c[12 + j] = e - (2 * d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The inverse 4×4 transform of scaled coefficients (§8.5.12), stored at <paramref name="o"/> in place of the prediction.</summary>
|
||||||
|
private static void Store4x4(Span<int> d, byte[] plane, int o, int stride)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < 4; i++)
|
||||||
|
{
|
||||||
|
var r = d.Slice(i * 4, 4);
|
||||||
|
int e0 = r[0] + r[2], e1 = r[0] - r[2], e2 = (r[1] >> 1) - r[3], e3 = r[1] + (r[3] >> 1);
|
||||||
|
r[0] = e0 + e3;
|
||||||
|
r[1] = e1 + e2;
|
||||||
|
r[2] = e1 - e2;
|
||||||
|
r[3] = e0 - e3;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var j = 0; j < 4; j++)
|
||||||
|
{
|
||||||
|
int f0 = d[j], f1 = d[4 + j], f2 = d[8 + j], f3 = d[12 + j];
|
||||||
|
int g0 = f0 + f2, g1 = f0 - f2, g2 = (f1 >> 1) - f3, g3 = f1 + (f3 >> 1);
|
||||||
|
plane[o + j] = Clip((g0 + g3 + 32) >> 6);
|
||||||
|
plane[o + stride + j] = Clip((g1 + g2 + 32) >> 6);
|
||||||
|
plane[o + (2 * stride) + j] = Clip((g1 - g2 + 32) >> 6);
|
||||||
|
plane[o + (3 * stride) + j] = Clip((g0 - g3 + 32) >> 6);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte Clip(int v) => (byte)(v < 0 ? 0 : v > 255 ? 255 : v);
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
namespace Febe.Tests.Codecs.H264;
|
||||||
|
|
||||||
|
/// <summary>The bits of an RBSP written one by one (§7.2): fixed-length fields, Exp-Golomb codes, bits copied from another RBSP.</summary>
|
||||||
|
internal sealed class BitWriter
|
||||||
|
{
|
||||||
|
private readonly List<bool> bits = [];
|
||||||
|
|
||||||
|
/// <summary>Bits written so far.</summary>
|
||||||
|
public int Count => bits.Count;
|
||||||
|
|
||||||
|
public void Bits(uint value, int count)
|
||||||
|
{
|
||||||
|
for (var i = count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
bits.Add(((value >> i) & 1) != 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Ue(uint value)
|
||||||
|
{
|
||||||
|
var code = value + 1;
|
||||||
|
var length = 32 - System.Numerics.BitOperations.LeadingZeroCount(code);
|
||||||
|
Bits(0, length - 1);
|
||||||
|
Bits(code, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Se(int value) => Ue(value <= 0 ? (uint)(-2 * value) : (uint)((2 * value) - 1));
|
||||||
|
|
||||||
|
/// <summary>Zero bits up to the next byte.</summary>
|
||||||
|
public void Align()
|
||||||
|
{
|
||||||
|
while (bits.Count % 8 != 0)
|
||||||
|
{
|
||||||
|
bits.Add(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One bits up to the next byte (cabac_alignment_one_bit).</summary>
|
||||||
|
public void AlignWithOnes()
|
||||||
|
{
|
||||||
|
while (bits.Count % 8 != 0)
|
||||||
|
{
|
||||||
|
bits.Add(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Bits <paramref name="from"/> (included) to <paramref name="to"/> (excluded) of <paramref name="data"/>, most significant first.</summary>
|
||||||
|
public void Copy(byte[] data, int from, int to)
|
||||||
|
{
|
||||||
|
for (var i = from; i < to; i++)
|
||||||
|
{
|
||||||
|
bits.Add(((data[i >> 3] >> (7 - (i & 7))) & 1) != 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>rbsp_trailing_bits(): the stop bit and zeros up to the byte.</summary>
|
||||||
|
public void Trailing()
|
||||||
|
{
|
||||||
|
bits.Add(true);
|
||||||
|
Align();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The bytes, padded with zeros to the byte, with emulation prevention (§7.4.1).</summary>
|
||||||
|
public byte[] ToArray()
|
||||||
|
{
|
||||||
|
var bytes = new byte[(bits.Count + 7) / 8];
|
||||||
|
for (var i = 0; i < bits.Count; i++)
|
||||||
|
{
|
||||||
|
if (bits[i])
|
||||||
|
{
|
||||||
|
bytes[i / 8] |= (byte)(0x80 >> (i % 8));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Emulation prevention (§7.4.1): never two zero bytes followed by a byte up to 3.
|
||||||
|
var output = new List<byte>(bytes.Length + 16);
|
||||||
|
var zeros = 0;
|
||||||
|
foreach (var b in bytes)
|
||||||
|
{
|
||||||
|
if (zeros >= 2 && b <= 3)
|
||||||
|
{
|
||||||
|
output.Add(3);
|
||||||
|
zeros = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
output.Add(b);
|
||||||
|
zeros = b == 0 ? zeros + 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [.. output];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -80,8 +80,31 @@ rimasto senza il suo compagno esce da solo, con le righe dell'altro campo grigie
|
|||||||
| `MR6_BT_B` | Extended, 192×128, 60 | campi, CAVLC, POC di tipo 1, MMCO, riordino, numero di slice variabile |
|
| `MR6_BT_B` | Extended, 192×128, 60 | campi, CAVLC, POC di tipo 1, MMCO, riordino, numero di slice variabile |
|
||||||
| `MR9_BT_B` | Main, 192×128, 58 | MBAFF e PAFF, CABAC, slice B, POC di tipo 1, MMCO, riordino |
|
| `MR9_BT_B` | Main, 192×128, 58 | MBAFF e PAFF, CABAC, slice B, POC di tipo 1, MMCO, riordino |
|
||||||
|
|
||||||
|
Strumenti di Baseline ed Extended, QCIF 4:2:0 a 8 bit:
|
||||||
|
|
||||||
|
| Flusso | Profilo, formato | Che cosa prova |
|
||||||
|
|---|---|---|
|
||||||
|
| `FM2_SVA_C` | Baseline, 17 | FMO con 3 gruppi di slice di tipo 0, ASO, POC di tipo 1 |
|
||||||
|
| `FM1_FT_E` | Baseline, 300 | FMO di tipo 1, 2, 3 e 4 che cambiano lungo il flusso (11 PPS), POC di tipo 2, SEI di recupero graduale |
|
||||||
|
| `FM1_BT_B` | Baseline, 400 | FMO di tutti i tipi da 0 a 6, ASO (lo zip non ha `readme`) |
|
||||||
|
| `sp1_bt_a` | Extended, 400 | slice SP (39 immagini) con QS diverso da QP e deblocking spento, POC di tipo 1 (lo zip non ha `readme`) |
|
||||||
|
| `sp2_bt_b` | Extended, 400 | slice SP con deblocking attivo (lo zip non ha `readme`) |
|
||||||
|
|
||||||
Nessuno di questi flussi usa la predizione pesata, i salti di `frame_num` o gli I_PCM: quelle parti del decodificatore
|
Nessuno di questi flussi usa la predizione pesata, i salti di `frame_num` o gli I_PCM: quelle parti del decodificatore
|
||||||
non hanno qui un riferimento ufficiale.
|
non hanno qui un riferimento ufficiale. Le slice SP dei due flussi hanno tutte `sp_for_switch_flag` a 0.
|
||||||
|
|
||||||
|
Per gli strumenti che nessun flusso della serie usa, `H264ExtendedToolsTests` riscrive flussi verificati con
|
||||||
|
`StreamRewriter`, lasciando intatti i bit dei macroblocchi, e chiede di nuovo il riferimento ufficiale:
|
||||||
|
|
||||||
|
- **partizionamento dei dati**: ogni slice P, B, SP o I non IDR divisa nelle partizioni A, B e C (`BA3_SVA_C`,
|
||||||
|
`sp1_bt_a`, `FM1_FT_E`, `MR6_BT_B`, `CVMAQP3_Sony_D`, `SVA_BA1_B`); senza B o senza C il flusso si decodifica ancora,
|
||||||
|
senza il residuo che mancava;
|
||||||
|
- **slice ridondanti**: dopo ogni immagine una copia ridondante con dati a caso, che il decodificatore deve saltare
|
||||||
|
(CAVLC, CABAC, campi, MBAFF, FMO, SP, e anche partizionate);
|
||||||
|
- **ASO**: le slice di ogni immagine in ordine inverso (`BASQP1_Sony_C`, `FM1_FT_E`, `CAMASL3_Sony_B`).
|
||||||
|
|
||||||
|
Le slice SI e `sp_for_switch_flag` a 1 non hanno flussi: le prova un flusso sintetico di
|
||||||
|
`H264SyntheticStreamTests`, con i valori calcolati a mano dalle equazioni di §8.6.2.
|
||||||
|
|
||||||
`H264ConformanceTests.SvcBaseLayerMatchesTheReference`: lo strato base dei tre flussi SVC qui sotto, con
|
`H264ConformanceTests.SvcBaseLayerMatchesTheReference`: lo strato base dei tre flussi SVC qui sotto, con
|
||||||
`riferimento-base.md5`.
|
`riferimento-base.md5`.
|
||||||
@@ -93,16 +116,6 @@ e MVC, dà solo lo strato o la vista base), e la prova è **inconclusiva** con i
|
|||||||
resta verde e il vuoto si vede. Quando una di queste coincide con il riferimento la prova **fallisce** apposta, per
|
resta verde e il vuoto si vede. Quando una di queste coincide con il riferimento la prova **fallisce** apposta, per
|
||||||
ricordare di spostarla fra i flussi verificati.
|
ricordare di spostarla fra i flussi verificati.
|
||||||
|
|
||||||
**Strumenti di Baseline ed Extended**, QCIF 4:2:0 a 8 bit:
|
|
||||||
|
|
||||||
| Flusso | Profilo, formato | Che cosa prova |
|
|
||||||
|---|---|---|
|
|
||||||
| `FM2_SVA_C` | Baseline, 17 | FMO con 3 gruppi di slice di tipo 0, ASO, POC di tipo 1 |
|
|
||||||
| `FM1_FT_E` | Baseline, 300 | FMO di tipo 1, 2, 3 e 4 che cambiano lungo il flusso (11 PPS), POC di tipo 2, SEI di recupero graduale |
|
|
||||||
| `FM1_BT_B` | Baseline, 400 | FMO di tutti i tipi da 0 a 6, ASO (lo zip non ha `readme`) |
|
|
||||||
| `sp1_bt_a` | Extended, 400 | slice SP (39 immagini), POC di tipo 1 (lo zip non ha `readme`) |
|
|
||||||
| `sp2_bt_b` | Extended, 400 | slice SP (lo zip non ha `readme`) |
|
|
||||||
|
|
||||||
**4:2:2, 8 e 10 bit** (High 4:2:2), CIF, 5 fotogrammi ciascuno:
|
**4:2:2, 8 e 10 bit** (High 4:2:2), CIF, 5 fotogrammi ciascuno:
|
||||||
|
|
||||||
| Flusso | Che cosa prova |
|
| Flusso | Che cosa prova |
|
||||||
@@ -136,7 +149,7 @@ senza riferimento.
|
|||||||
i flussi di tutti gli zip di `AVCv1` e `FRExt` (tranne `FREH10-1` e `FREH10-2`, High 10, profilo che quegli strumenti
|
i flussi di tutti gli zip di `AVCv1` e `FRExt` (tranne `FREH10-1` e `FREH10-2`, High 10, profilo che quegli strumenti
|
||||||
non li ammette): nessuna unità NAL di tipo 2, 3 o 4, nessun PPS con
|
non li ammette): nessuna unità NAL di tipo 2, 3 o 4, nessun PPS con
|
||||||
`redundant_pic_cnt_present_flag`, nessuna slice SI. I soli flussi Extended sono `BA3_SVA_C`, `sp1_bt_a`, `sp2_bt_b` e
|
`redundant_pic_cnt_present_flag`, nessuna slice SI. I soli flussi Extended sono `BA3_SVA_C`, `sp1_bt_a`, `sp2_bt_b` e
|
||||||
`MR6_BT_B`, `MR7_BT_B`, `MR8_BT_B`.
|
`MR6_BT_B`, `MR7_BT_B`, `MR8_BT_B`. Si provano riscrivendo i flussi verificati (vedi sopra).
|
||||||
- **High 10 in 4:2:0**: `FREH10-1` e `FREH10-2` (1920×1088, flussi da 98 e 34 MB) e `PPH10I1`–`PPH10I7` (High 10 Intra)
|
- **High 10 in 4:2:0**: `FREH10-1` e `FREH10-2` (1920×1088, flussi da 98 e 34 MB) e `PPH10I1`–`PPH10I7` (High 10 Intra)
|
||||||
non hanno la ricostruzione. I 10 bit si provano con `Hi422FR13`–`Hi422FR15`.
|
non hanno la ricostruzione. I 10 bit si provano con `Hi422FR13`–`Hi422FR15`.
|
||||||
- **High 4:2:2 Intra e altri 4:2:2**: `PPH422I1`–`PPH422I7`, `Hi422FR1`–`Hi422FR9` e `Hi422FREXT16`–`Hi422FREXT19` non
|
- **High 4:2:2 Intra e altri 4:2:2**: `PPH422I1`–`PPH422I7`, `Hi422FR1`–`Hi422FR9` e `Hi422FREXT16`–`Hi422FREXT19` non
|
||||||
|
|||||||
@@ -8,12 +8,15 @@ namespace Febe.Tests.Codecs.H264;
|
|||||||
/// The decoder against streams of the ITU-T H.264.1 conformance suite: every output frame, in output order, must have the
|
/// The decoder against streams of the ITU-T H.264.1 conformance suite: every output frame, in output order, must have the
|
||||||
/// MD5 of the corresponding frame of the official reconstruction (see Conformita/LEGGIMI.md). The verified streams include
|
/// MD5 of the corresponding frame of the official reconstruction (see Conformita/LEGGIMI.md). The verified streams include
|
||||||
/// interlaced video — field pictures, PAFF, MBAFF, both together — with memory management operations, long-term
|
/// interlaced video — field pictures, PAFF, MBAFF, both together — with memory management operations, long-term
|
||||||
/// references and POC type 1 on fields (MR6_BT_B, MR9_BT_B). None of them uses weighted prediction, gaps in frame_num or
|
/// references and POC type 1 on fields (MR6_BT_B, MR9_BT_B), slice groups of every map type with slices in any order
|
||||||
/// I_PCM: those parts of the decoder have no reference MD5 here (some are reached by <see cref="H264SyntheticStreamTests"/>,
|
/// (FM1_BT_B, FM1_FT_E, FM2_SVA_C) and SP slices (sp1_bt_a, sp2_bt_b; sp2 with the deblocking filter on). None of them
|
||||||
/// without an official reference). The streams of the parts the decoder does not handle yet (FMO and ASO, SP slices,
|
/// uses weighted prediction, gaps in frame_num, I_PCM, SI slices, sp_for_switch_flag, data partitioning or redundant
|
||||||
/// 4:2:2, more than 8 bits, 4:0:0, SVC, MVC) are in
|
/// slices: data partitioning, redundant slices and other slice orders are checked on conformance streams rewritten by
|
||||||
/// <see cref="FeaturesStillToDo"/>: they are inconclusive until the feature is written, and fail as soon as one of them
|
/// <see cref="StreamRewriter"/> (<see cref="H264ExtendedToolsTests"/>), SI slices and the rest by
|
||||||
/// matches its reference without having been moved among the verified ones.
|
/// <see cref="H264SyntheticStreamTests"/>, without an official reference. The streams of the parts the decoder does not
|
||||||
|
/// handle yet (4:2:2, more than 8 bits, 4:0:0, SVC, MVC) are in <see cref="FeaturesStillToDo"/>: they are inconclusive
|
||||||
|
/// until the feature is written, and fail as soon as one of them matches its reference without having been moved among
|
||||||
|
/// the verified ones.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[TestClass]
|
[TestClass]
|
||||||
public sealed class H264ConformanceTests
|
public sealed class H264ConformanceTests
|
||||||
@@ -48,6 +51,11 @@ public sealed class H264ConformanceTests
|
|||||||
[DataRow("FRExt4_Panasonic_B")]
|
[DataRow("FRExt4_Panasonic_B")]
|
||||||
[DataRow("MR6_BT_B")]
|
[DataRow("MR6_BT_B")]
|
||||||
[DataRow("MR9_BT_B")]
|
[DataRow("MR9_BT_B")]
|
||||||
|
[DataRow("FM2_SVA_C")]
|
||||||
|
[DataRow("FM1_FT_E")]
|
||||||
|
[DataRow("FM1_BT_B")]
|
||||||
|
[DataRow("sp1_bt_a")]
|
||||||
|
[DataRow("sp2_bt_b")]
|
||||||
public void FramesMatchTheReference(string name) => AssertMatches(name, "riferimento.md5");
|
public void FramesMatchTheReference(string name) => AssertMatches(name, "riferimento.md5");
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
@@ -62,11 +70,6 @@ public sealed class H264ConformanceTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
[DataRow("FM2_SVA_C", "FMO (gruppi di slice di tipo 0) e ASO")]
|
|
||||||
[DataRow("FM1_FT_E", "FMO (gruppi di slice di tipo 1, 2, 3 e 4)")]
|
|
||||||
[DataRow("FM1_BT_B", "FMO (gruppi di slice di tipo 0-6) e ASO")]
|
|
||||||
[DataRow("sp1_bt_a", "slice SP (Extended)")]
|
|
||||||
[DataRow("sp2_bt_b", "slice SP (Extended)")]
|
|
||||||
[DataRow("Hi422FR10_SONY_A", "4:2:2 a 8 bit, solo slice I (CABAC)")]
|
[DataRow("Hi422FR10_SONY_A", "4:2:2 a 8 bit, solo slice I (CABAC)")]
|
||||||
[DataRow("Hi422FR11_SONY_A", "4:2:2 a 8 bit con slice P (CABAC)")]
|
[DataRow("Hi422FR11_SONY_A", "4:2:2 a 8 bit con slice P (CABAC)")]
|
||||||
[DataRow("Hi422FR12_SONY_A", "4:2:2 a 8 bit con slice B (CABAC)")]
|
[DataRow("Hi422FR12_SONY_A", "4:2:2 a 8 bit con slice B (CABAC)")]
|
||||||
@@ -162,7 +165,14 @@ public sealed class H264ConformanceTests
|
|||||||
internal static string StreamFile(string folder) =>
|
internal static string StreamFile(string folder) =>
|
||||||
Directory.EnumerateFiles(folder).Single(f => Path.GetExtension(f).ToLowerInvariant() is ".264" or ".jsv" or ".avc" or ".h264" or ".jvt");
|
Directory.EnumerateFiles(folder).Single(f => Path.GetExtension(f).ToLowerInvariant() is ".264" or ".jsv" or ".avc" or ".h264" or ".jvt");
|
||||||
|
|
||||||
private static void AssertMatches(string name, string reference)
|
private static void AssertMatches(string name, string reference) =>
|
||||||
|
AssertStreamMatches(name, File.ReadAllBytes(StreamFile(Folder(name))), reference);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <paramref name="stream"/> (the conformance stream <paramref name="name"/>, possibly rewritten) must give every frame
|
||||||
|
/// of the official reconstruction.
|
||||||
|
/// </summary>
|
||||||
|
internal static void AssertStreamMatches(string name, byte[] stream, string reference = "riferimento.md5")
|
||||||
{
|
{
|
||||||
var folder = Folder(name);
|
var folder = Folder(name);
|
||||||
var expected = ReadReference(Path.Combine(folder, reference), out var declared);
|
var expected = ReadReference(Path.Combine(folder, reference), out var declared);
|
||||||
@@ -171,7 +181,7 @@ public sealed class H264ConformanceTests
|
|||||||
var frames = new List<H264Frame>();
|
var frames = new List<H264Frame>();
|
||||||
var decoder = new H264Decoder();
|
var decoder = new H264Decoder();
|
||||||
decoder.FrameDecoded += frames.Add;
|
decoder.FrameDecoded += frames.Add;
|
||||||
decoder.DecodeAnnexB(File.ReadAllBytes(StreamFile(folder)));
|
decoder.DecodeAnnexB(stream);
|
||||||
|
|
||||||
var ordered = OutputOrder(frames);
|
var ordered = OutputOrder(frames);
|
||||||
var actual = ordered.Select(Md5).ToList();
|
var actual = ordered.Select(Md5).ToList();
|
||||||
@@ -187,6 +197,19 @@ public sealed class H264ConformanceTests
|
|||||||
Assert.AreEqual(expected.Count, actual.Count, $"{name}: numero di fotogrammi");
|
Assert.AreEqual(expected.Count, actual.Count, $"{name}: numero di fotogrammi");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>The frame MD5s of a riferimento.md5, in output order.</summary>
|
||||||
|
internal static List<string> ReferenceFrames(string name) => ReadReference(Path.Combine(Folder(name), "riferimento.md5"), out _);
|
||||||
|
|
||||||
|
/// <summary>The MD5 of each frame of a stream, in output order.</summary>
|
||||||
|
internal static List<string> FrameMd5s(byte[] stream)
|
||||||
|
{
|
||||||
|
var frames = new List<H264Frame>();
|
||||||
|
var decoder = new H264Decoder();
|
||||||
|
decoder.FrameDecoded += frames.Add;
|
||||||
|
decoder.DecodeAnnexB(stream);
|
||||||
|
return OutputOrder(frames).Select(Md5).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
private static List<string> Decode(string stream)
|
private static List<string> Decode(string stream)
|
||||||
{
|
{
|
||||||
var frames = new List<H264Frame>();
|
var frames = new List<H264Frame>();
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
using Febe.Core.Codecs.H264;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Codecs.H264;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Tools of the Baseline and Extended profiles that no stream of the ITU-T series uses — slice data partitioning,
|
||||||
|
/// redundant slices — and slices in another order than the one of the series, on conformance streams rewritten by
|
||||||
|
/// <see cref="StreamRewriter"/>: the macroblocks keep their bits, so every frame must still be the official one.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class H264ExtendedToolsTests
|
||||||
|
{
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow("BA3_SVA_C")] // Extended, B slices
|
||||||
|
[DataRow("sp1_bt_a")] // SP slices
|
||||||
|
[DataRow("FM1_FT_E")] // slice groups of types 1–4
|
||||||
|
[DataRow("MR6_BT_B")] // Extended, field pictures
|
||||||
|
[DataRow("CVMAQP3_Sony_D")] // MBAFF
|
||||||
|
[DataRow("SVA_BA1_B")] // non-IDR I slices: residual in partition B only
|
||||||
|
public void DataPartitionsGiveTheOfficialFrames(string name)
|
||||||
|
{
|
||||||
|
var stream = StreamRewriter.Partition(Original(name));
|
||||||
|
var types = NalTypes(stream);
|
||||||
|
Assert.IsFalse(types.Contains(1), "restano slice non partizionate");
|
||||||
|
Assert.IsTrue(types.Contains(2), "manca la partizione A");
|
||||||
|
Assert.IsTrue(types.Contains(3) || types.Contains(4), "mancano le partizioni B e C");
|
||||||
|
H264ConformanceTests.AssertStreamMatches(name, stream);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow(false, true)]
|
||||||
|
[DataRow(true, false)]
|
||||||
|
[DataRow(false, false)]
|
||||||
|
public void MissingPartitionsLeaveTheirResidualOut(bool keepB, bool keepC)
|
||||||
|
{
|
||||||
|
// Without partition B or C a slice still decodes, without the residual of its intra or inter macroblocks: every
|
||||||
|
// picture comes out, and the IDR picture (never partitioned) is still the official one.
|
||||||
|
var name = "BA3_SVA_C";
|
||||||
|
var complete = H264ConformanceTests.FrameMd5s(StreamRewriter.Partition(Original(name)));
|
||||||
|
var partial = H264ConformanceTests.FrameMd5s(StreamRewriter.Partition(Original(name), keepB, keepC));
|
||||||
|
var expected = H264ConformanceTests.ReferenceFrames(name);
|
||||||
|
Assert.HasCount(expected.Count, partial);
|
||||||
|
Assert.AreEqual(expected[0], partial[0], "l'immagine IDR");
|
||||||
|
Assert.IsTrue(partial.Where((md5, i) => md5 != complete[i]).Any(), "togliere una partizione cambia qualcosa");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow("BA3_SVA_C", 4101)] // CAVLC
|
||||||
|
[DataRow("CABA3_SVA_B", 4102)] // CABAC
|
||||||
|
[DataRow("MR6_BT_B", 4103)] // fields, POC type 1
|
||||||
|
[DataRow("CAPAMA3_Sand_F", 4104)] // CABAC, MBAFF and fields
|
||||||
|
[DataRow("FM1_FT_E", 4105)] // slice groups, several PPS
|
||||||
|
[DataRow("sp1_bt_a", 4106)] // SP slices
|
||||||
|
public void RedundantSlicesAreSkipped(string name, int seed)
|
||||||
|
{
|
||||||
|
var stream = StreamRewriter.AddRedundantSlices(Original(name), seed);
|
||||||
|
Assert.IsGreaterThan(Original(name).Length, stream.Length);
|
||||||
|
H264ConformanceTests.AssertStreamMatches(name, stream);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void RedundantSlicesAreSkippedAlsoWhenPartitioned()
|
||||||
|
{
|
||||||
|
// The redundant slices become partitions A (header and random bits) with slice_id and redundant_pic_cnt.
|
||||||
|
var name = "BA3_SVA_C";
|
||||||
|
H264ConformanceTests.AssertStreamMatches(name, StreamRewriter.Partition(StreamRewriter.AddRedundantSlices(Original(name), 4107)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow("BASQP1_Sony_C")] // twenty slices per picture
|
||||||
|
[DataRow("FM1_FT_E")] // slice groups
|
||||||
|
[DataRow("CAMASL3_Sony_B")] // CABAC, MBAFF, four slices per picture
|
||||||
|
public void SlicesInReverseOrderGiveTheOfficialFrames(string name)
|
||||||
|
{
|
||||||
|
var original = Original(name);
|
||||||
|
var stream = StreamRewriter.ReverseSlices(original);
|
||||||
|
CollectionAssert.AreNotEqual(original, stream, "il flusso ha più slice per immagine");
|
||||||
|
H264ConformanceTests.AssertStreamMatches(name, stream);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow("FM1_FT_E", 4201)]
|
||||||
|
[DataRow("sp2_bt_b", 4202)]
|
||||||
|
[DataRow("BA3_SVA_C", 4203)]
|
||||||
|
public void DamagedPartitionedStreamsGiveFramesOrAnH264Exception(string name, int seed)
|
||||||
|
{
|
||||||
|
H264RobustnessTests.AssertDamagedCopiesDecode(name, StreamRewriter.Partition(Original(name)), seed, trials: 30);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] Original(string name) => File.ReadAllBytes(H264ConformanceTests.StreamFile(H264ConformanceTests.Folder(name)));
|
||||||
|
|
||||||
|
private static HashSet<int> NalTypes(byte[] stream) => StreamRewriter.Units(stream).Select(u => u[0] & 0x1F).ToHashSet();
|
||||||
|
}
|
||||||
@@ -29,11 +29,22 @@ public sealed class H264RobustnessTests
|
|||||||
[DataRow("MR6_BT_B", 2657)]
|
[DataRow("MR6_BT_B", 2657)]
|
||||||
[DataRow("MR9_BT_B", 2658)]
|
[DataRow("MR9_BT_B", 2658)]
|
||||||
[DataRow("CAPAMA3_Sand_F", 2659)]
|
[DataRow("CAPAMA3_Sand_F", 2659)]
|
||||||
public void DamagedStreamsGiveFramesOrAnH264Exception(string name, int seed)
|
[DataRow("FM2_SVA_C", 2660)]
|
||||||
|
[DataRow("FM1_FT_E", 2661)]
|
||||||
|
[DataRow("FM1_BT_B", 2662)]
|
||||||
|
[DataRow("sp1_bt_a", 2663)]
|
||||||
|
[DataRow("sp2_bt_b", 2664)]
|
||||||
|
public void DamagedStreamsGiveFramesOrAnH264Exception(string name, int seed) =>
|
||||||
|
AssertDamagedCopiesDecode(name, File.ReadAllBytes(H264ConformanceTests.StreamFile(H264ConformanceTests.Folder(name))), seed, trials: 60);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Copies of <paramref name="data"/> with a few bytes changed (and some cut short), from a fixed seed: each must give
|
||||||
|
/// frames or an <see cref="H264Exception"/>, never another exception.
|
||||||
|
/// </summary>
|
||||||
|
internal static void AssertDamagedCopiesDecode(string name, byte[] data, int seed, int trials)
|
||||||
{
|
{
|
||||||
var data = File.ReadAllBytes(H264ConformanceTests.StreamFile(H264ConformanceTests.Folder(name)));
|
|
||||||
var random = new Random(seed);
|
var random = new Random(seed);
|
||||||
for (var trial = 0; trial < 60; trial++)
|
for (var trial = 0; trial < trials; trial++)
|
||||||
{
|
{
|
||||||
var copy = (byte[])data.Clone();
|
var copy = (byte[])data.Clone();
|
||||||
var changes = 1 + random.Next(20);
|
var changes = 1 + random.Next(20);
|
||||||
|
|||||||
@@ -49,6 +49,38 @@ public sealed class H264SyntheticStreamTests
|
|||||||
Assert.IsTrue(frames[0].Y.All(v => v == 100), "il fotogramma è quello primario");
|
Assert.IsTrue(frames[0].Y.All(v => v == 100), "il fotogramma è quello primario");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow(0, 127, 49, 128)]
|
||||||
|
[DataRow(12, 130, 52, 126)]
|
||||||
|
public void AnSiPictureIsRebuiltInQs(int qsDelta, int first, int third, int chroma)
|
||||||
|
{
|
||||||
|
// Three macroblocks: SI, I_PCM (luma 50), SI; the SI ones without residual, every block predicted in DC mode. Each
|
||||||
|
// 4×4 block of an SI macroblock is its prediction transformed, quantised in QS and decoded in QS (§8.6.2), so a
|
||||||
|
// flat block of 128 comes back as 127 with QS 26 (DC 2048 → level 39 → 8112 → 127) and as 130 with QS 38; next to
|
||||||
|
// the I_PCM samples (50) the blocks give 49 and 52. Chroma: the DC of the four blocks through the 2×2 transform
|
||||||
|
// (8192 → level 79 with QSc 26, 28 with QSc 35), back to 128 and 126. Worked out by hand from the equations.
|
||||||
|
var s = new SequenceSettings(WidthInMbs: 3);
|
||||||
|
var frames = Decode([.. Sps(s), .. Pps(), .. SiIdr(s, qsDelta, pcm: [1], pcmLuma: 50)]);
|
||||||
|
Assert.HasCount(1, frames);
|
||||||
|
var f = frames[0];
|
||||||
|
for (var y = 0; y < 16; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < 48; x++)
|
||||||
|
{
|
||||||
|
var expected = x < 16 ? first : x < 32 ? 50 : third;
|
||||||
|
Assert.AreEqual(expected, f.Y[(y * 48) + x], $"luma ({x}, {y})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < f.Cb.Length; i++)
|
||||||
|
{
|
||||||
|
var x = i % 24;
|
||||||
|
var expected = x is >= 8 and < 16 ? 128 : chroma;
|
||||||
|
Assert.AreEqual(expected, f.Cb[i], $"Cb {i}");
|
||||||
|
Assert.AreEqual(expected, f.Cr[i], $"Cr {i}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void APSliceWithNothingToPredictFromIsRefused()
|
public void APSliceWithNothingToPredictFromIsRefused()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,383 @@
|
|||||||
|
using Febe.Core.Codecs.H264;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Codecs.H264;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Conformance streams rewritten with the tools of the Extended and Baseline profiles that no stream of the ITU-T series
|
||||||
|
/// uses: the same pictures split into data partitions, with redundant slices, with the slices of each picture in another
|
||||||
|
/// order. The macroblocks and their bits do not change, so the official reconstruction stays the expected result.
|
||||||
|
/// </summary>
|
||||||
|
internal static class StreamRewriter
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Every non-IDR slice (NAL unit 1) as partitions A, B and C (§7.3.2.8–§7.3.2.10): the decoder reads the original
|
||||||
|
/// stream and says where the residual of each macroblock lies; A keeps the header and everything else, B the residual
|
||||||
|
/// of the intra macroblocks, C that of the inter ones. A partition with nothing in it is left out, as are those that
|
||||||
|
/// <paramref name="keepB"/> and <paramref name="keepC"/> drop. Only CAVLC without constrained intra prediction and
|
||||||
|
/// without I_PCM: with them the bits would not stay the same (§9.2.1, pcm_alignment_zero_bit).
|
||||||
|
/// </summary>
|
||||||
|
internal static byte[] Partition(byte[] stream, bool keepB = true, bool keepC = true)
|
||||||
|
{
|
||||||
|
var decoder = new H264Decoder();
|
||||||
|
var residual = new List<(int Start, int End, bool Intra, bool Pcm)>();
|
||||||
|
decoder.ResidualRead = (start, end, intra, pcm) => residual.Add((start, end, intra, pcm));
|
||||||
|
var sequences = new Dictionary<int, Sps>();
|
||||||
|
var pictures = new Dictionary<int, Pps>();
|
||||||
|
var output = new List<byte[]>();
|
||||||
|
var sliceId = 0;
|
||||||
|
foreach (var unit in Units(stream))
|
||||||
|
{
|
||||||
|
var nal = NalUnits.Parse(unit);
|
||||||
|
Remember(nal, sequences, pictures);
|
||||||
|
residual.Clear();
|
||||||
|
decoder.DecodeUnit(unit);
|
||||||
|
if (nal.Type != 1)
|
||||||
|
{
|
||||||
|
output.Add(unit);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var reader = nal.Reader();
|
||||||
|
var header = SliceHeader.Parse(reader, nal, sequences, pictures, out _, out var pps);
|
||||||
|
if (pps.Cabac || pps.ConstrainedIntraPred || residual.Exists(r => r.Pcm))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Flusso non adatto: CABAC, predizione intra vincolata o I_PCM.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// slice_id: 0 for the first slice of each picture, then one more per slice (the streams are in order).
|
||||||
|
sliceId = header.FirstMb == 0 ? 0 : sliceId + 1;
|
||||||
|
var a = new BitWriter();
|
||||||
|
a.Copy(nal.Rbsp, 8, reader.Position);
|
||||||
|
a.Ue((uint)sliceId);
|
||||||
|
var b = PartitionStart(sliceId, pps, header);
|
||||||
|
var c = PartitionStart(sliceId, pps, header);
|
||||||
|
var position = reader.Position;
|
||||||
|
foreach (var (start, end, intra, _) in residual)
|
||||||
|
{
|
||||||
|
a.Copy(nal.Rbsp, position, start);
|
||||||
|
(intra ? b : c).Copy(nal.Rbsp, start, end);
|
||||||
|
position = end;
|
||||||
|
}
|
||||||
|
|
||||||
|
a.Copy(nal.Rbsp, position, StopBit(nal));
|
||||||
|
var refIdc = (byte)(nal.RefIdc << 5);
|
||||||
|
output.Add(Unit((byte)(refIdc | 2), a));
|
||||||
|
if (keepB && residual.Exists(r => r.Intra))
|
||||||
|
{
|
||||||
|
output.Add(Unit((byte)(refIdc | 3), b));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (keepC && residual.Exists(r => !r.Intra))
|
||||||
|
{
|
||||||
|
output.Add(Unit((byte)(refIdc | 4), c));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Join(output);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The same stream with redundant_pic_cnt_present_flag set in every PPS (§7.3.2.2) and, after the slices of each
|
||||||
|
/// picture, a redundant copy of them (redundant_pic_cnt 1) whose header is the primary one and whose data are random
|
||||||
|
/// bits: a decoder that decodes a redundant slice cannot give the official reconstruction.
|
||||||
|
/// </summary>
|
||||||
|
internal static byte[] AddRedundantSlices(byte[] stream, int seed)
|
||||||
|
{
|
||||||
|
var random = new Random(seed);
|
||||||
|
var sequences = new Dictionary<int, Sps>();
|
||||||
|
var pictures = new Dictionary<int, Pps>();
|
||||||
|
var output = new List<byte[]>();
|
||||||
|
var redundant = new List<byte[]>();
|
||||||
|
foreach (var unit in Units(stream))
|
||||||
|
{
|
||||||
|
var nal = NalUnits.Parse(unit);
|
||||||
|
var slice = nal.Type is 1 or 5;
|
||||||
|
var header = slice ? SliceHeader.Parse(nal.Reader(), nal, sequences, pictures, out _, out _) : null;
|
||||||
|
if (!slice || header!.FirstMb == 0)
|
||||||
|
{
|
||||||
|
output.AddRange(redundant);
|
||||||
|
redundant.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nal.Type == 8)
|
||||||
|
{
|
||||||
|
Remember(nal, sequences, pictures);
|
||||||
|
output.Add(SetRedundantFlag(nal));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
Remember(nal, sequences, pictures);
|
||||||
|
if (!slice)
|
||||||
|
{
|
||||||
|
output.Add(unit);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var reader = nal.Reader();
|
||||||
|
SliceHeader.Parse(reader, nal, sequences, pictures, out var sps, out var pps);
|
||||||
|
var headerEnd = reader.Position;
|
||||||
|
var insert = RedundantPicCntPosition(nal, sps, pps);
|
||||||
|
output.Add(WithRedundantPicCnt(nal, insert, headerEnd, pps.Cabac, 0, null));
|
||||||
|
var garbage = new byte[16 + random.Next(48)];
|
||||||
|
random.NextBytes(garbage);
|
||||||
|
redundant.Add(WithRedundantPicCnt(nal, insert, headerEnd, pps.Cabac, 1, garbage));
|
||||||
|
}
|
||||||
|
|
||||||
|
output.AddRange(redundant);
|
||||||
|
return Join(output);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The slices of each picture in reverse order (arbitrary slice order, §7.4.3: Baseline and Extended). A picture ends
|
||||||
|
/// at a NAL unit that is not a slice or at a slice whose header differs as in §7.4.1.2.4: the source may already send
|
||||||
|
/// its slices out of order.
|
||||||
|
/// </summary>
|
||||||
|
internal static byte[] ReverseSlices(byte[] stream)
|
||||||
|
{
|
||||||
|
var sequences = new Dictionary<int, Sps>();
|
||||||
|
var pictures = new Dictionary<int, Pps>();
|
||||||
|
var output = new List<byte[]>();
|
||||||
|
var picture = new List<byte[]>();
|
||||||
|
var current = "";
|
||||||
|
foreach (var unit in Units(stream))
|
||||||
|
{
|
||||||
|
var nal = NalUnits.Parse(unit);
|
||||||
|
Remember(nal, sequences, pictures);
|
||||||
|
var slice = nal.Type is 1 or 5;
|
||||||
|
var key = "";
|
||||||
|
if (slice)
|
||||||
|
{
|
||||||
|
var h = SliceHeader.Parse(nal.Reader(), nal, sequences, pictures, out _, out _);
|
||||||
|
key = $"{h.FrameNum} {h.PpsId} {h.Structure} {nal.RefIdc == 0} {nal.Type} {h.IdrPicId} {h.PocLsb} {h.DeltaPocBottom} {h.DeltaPoc0} {h.DeltaPoc1}";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!slice || key != current)
|
||||||
|
{
|
||||||
|
current = key;
|
||||||
|
picture.Reverse();
|
||||||
|
output.AddRange(picture);
|
||||||
|
picture.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (slice)
|
||||||
|
{
|
||||||
|
picture.Add(unit);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
output.Add(unit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
picture.Reverse();
|
||||||
|
output.AddRange(picture);
|
||||||
|
return Join(output);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The NAL units of an Annex B stream, each with its header and without start code.</summary>
|
||||||
|
internal static List<byte[]> Units(byte[] stream)
|
||||||
|
{
|
||||||
|
var units = new List<byte[]>();
|
||||||
|
var position = 0;
|
||||||
|
while (NalUnits.NextAnnexB(stream, ref position, out var range))
|
||||||
|
{
|
||||||
|
units.Add(stream[range]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return units;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static byte[] Join(IEnumerable<byte[]> units)
|
||||||
|
{
|
||||||
|
var output = new List<byte>();
|
||||||
|
foreach (var unit in units)
|
||||||
|
{
|
||||||
|
output.AddRange((byte[])[0, 0, 0, 1]);
|
||||||
|
output.AddRange(unit);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [.. output];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Remember(NalUnit nal, Dictionary<int, Sps> sequences, Dictionary<int, Pps> pictures)
|
||||||
|
{
|
||||||
|
if (nal.Type == 7)
|
||||||
|
{
|
||||||
|
var sps = Sps.Parse(nal.Reader());
|
||||||
|
sequences[sps.Id] = sps;
|
||||||
|
}
|
||||||
|
else if (nal.Type == 8)
|
||||||
|
{
|
||||||
|
var pps = Pps.Parse(nal.Reader(), sequences);
|
||||||
|
pictures[pps.Id] = pps;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>slice_id, then redundant_pic_cnt when the PPS has it (§7.3.2.10).</summary>
|
||||||
|
private static BitWriter PartitionStart(int sliceId, Pps pps, SliceHeader header)
|
||||||
|
{
|
||||||
|
var bits = new BitWriter();
|
||||||
|
bits.Ue((uint)sliceId);
|
||||||
|
if (pps.RedundantPicCntPresent)
|
||||||
|
{
|
||||||
|
bits.Ue((uint)header.RedundantPicCnt);
|
||||||
|
}
|
||||||
|
|
||||||
|
return bits;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] Unit(byte header, BitWriter bits)
|
||||||
|
{
|
||||||
|
bits.Trailing();
|
||||||
|
return [header, .. bits.ToArray()];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The position of the rbsp_stop_one_bit: the last bit set of the payload.</summary>
|
||||||
|
private static int StopBit(NalUnit nal)
|
||||||
|
{
|
||||||
|
var last = nal.Length - 1;
|
||||||
|
while (nal.Rbsp[last] == 0)
|
||||||
|
{
|
||||||
|
last--;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (last * 8) + 7 - System.Numerics.BitOperations.TrailingZeroCount(nal.Rbsp[last]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Where redundant_pic_cnt goes in a slice header: after the picture order count fields (§7.3.3).</summary>
|
||||||
|
private static int RedundantPicCntPosition(NalUnit nal, Sps sps, Pps pps)
|
||||||
|
{
|
||||||
|
var r = nal.Reader();
|
||||||
|
r.ReadUe(); // first_mb_in_slice
|
||||||
|
r.ReadUe(); // slice_type
|
||||||
|
r.ReadUe(); // pic_parameter_set_id
|
||||||
|
r.Read(sps.Log2MaxFrameNum);
|
||||||
|
var field = false;
|
||||||
|
if (!sps.FrameMbsOnly && (field = r.ReadFlag()))
|
||||||
|
{
|
||||||
|
r.ReadFlag(); // bottom_field_flag
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nal.Type == 5)
|
||||||
|
{
|
||||||
|
r.ReadUe(); // idr_pic_id
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sps.PocType == 0)
|
||||||
|
{
|
||||||
|
r.Read(sps.Log2MaxPocLsb);
|
||||||
|
if (pps.BottomFieldPicOrderInFramePresent && !field)
|
||||||
|
{
|
||||||
|
r.ReadSe();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (sps.PocType == 1 && !sps.DeltaPicOrderAlwaysZero)
|
||||||
|
{
|
||||||
|
r.ReadSe();
|
||||||
|
if (pps.BottomFieldPicOrderInFramePresent && !field)
|
||||||
|
{
|
||||||
|
r.ReadSe();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return r.Position;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The slice with redundant_pic_cnt inserted at <paramref name="insert"/>; with <paramref name="garbage"/> its slice
|
||||||
|
/// data are those bytes instead of the original ones (CABAC data start again at a byte, after cabac_alignment_one_bit).
|
||||||
|
/// </summary>
|
||||||
|
private static byte[] WithRedundantPicCnt(NalUnit nal, int insert, int headerEnd, bool cabac, int count, byte[]? garbage)
|
||||||
|
{
|
||||||
|
var bits = new BitWriter();
|
||||||
|
bits.Copy(nal.Rbsp, 8, insert);
|
||||||
|
bits.Ue((uint)count);
|
||||||
|
bits.Copy(nal.Rbsp, insert, headerEnd);
|
||||||
|
if (cabac)
|
||||||
|
{
|
||||||
|
bits.AlignWithOnes();
|
||||||
|
if (garbage is null)
|
||||||
|
{
|
||||||
|
bits.Copy(nal.Rbsp, (headerEnd + 7) / 8 * 8, nal.Length * 8);
|
||||||
|
return [nal.Rbsp[0], .. bits.ToArray()];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (garbage is null)
|
||||||
|
{
|
||||||
|
bits.Copy(nal.Rbsp, headerEnd, StopBit(nal));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
bits.Copy(garbage, 0, garbage.Length * 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
bits.Trailing();
|
||||||
|
return [nal.Rbsp[0], .. bits.ToArray()];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The PPS with redundant_pic_cnt_present_flag set: the fields before it read again (§7.3.2.2).</summary>
|
||||||
|
private static byte[] SetRedundantFlag(NalUnit nal)
|
||||||
|
{
|
||||||
|
var r = nal.Reader();
|
||||||
|
r.ReadUe(); // pic_parameter_set_id
|
||||||
|
r.ReadUe(); // seq_parameter_set_id
|
||||||
|
r.ReadFlag(); // entropy_coding_mode_flag
|
||||||
|
r.ReadFlag(); // bottom_field_pic_order_in_frame_present_flag
|
||||||
|
var groups = (int)r.ReadUe() + 1;
|
||||||
|
if (groups > 1)
|
||||||
|
{
|
||||||
|
var type = r.ReadUe();
|
||||||
|
switch (type)
|
||||||
|
{
|
||||||
|
case 0:
|
||||||
|
for (var i = 0; i < groups; i++)
|
||||||
|
{
|
||||||
|
r.ReadUe();
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
for (var i = 0; i < 2 * (groups - 1); i++)
|
||||||
|
{
|
||||||
|
r.ReadUe();
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case 3 or 4 or 5:
|
||||||
|
r.ReadFlag();
|
||||||
|
r.ReadUe();
|
||||||
|
break;
|
||||||
|
case 6:
|
||||||
|
{
|
||||||
|
var size = (int)r.ReadUe() + 1;
|
||||||
|
var bitsPerId = 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)(groups - 1));
|
||||||
|
r.Skip(size * bitsPerId);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
r.ReadUe(); // num_ref_idx_l0_default_active_minus1
|
||||||
|
r.ReadUe(); // num_ref_idx_l1_default_active_minus1
|
||||||
|
r.ReadFlag(); // weighted_pred_flag
|
||||||
|
r.Read(2); // weighted_bipred_idc
|
||||||
|
r.ReadSe(); // pic_init_qp_minus26
|
||||||
|
r.ReadSe(); // pic_init_qs_minus26
|
||||||
|
r.ReadSe(); // chroma_qp_index_offset
|
||||||
|
r.ReadFlag(); // deblocking_filter_control_present_flag
|
||||||
|
r.ReadFlag(); // constrained_intra_pred_flag
|
||||||
|
var flag = r.Position;
|
||||||
|
if (r.ReadFlag())
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Il PPS ha già redundant_pic_cnt_present_flag.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var bits = new BitWriter();
|
||||||
|
bits.Copy(nal.Rbsp, 8, flag);
|
||||||
|
bits.Bits(1, 1);
|
||||||
|
bits.Copy(nal.Rbsp, flag + 1, StopBit(nal));
|
||||||
|
bits.Trailing();
|
||||||
|
return [nal.Rbsp[0], .. bits.ToArray()];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -148,69 +148,64 @@ internal static class SyntheticStreams
|
|||||||
return Nal(reference ? (byte)0x41 : (byte)0x01, bits);
|
return Nal(reference ? (byte)0x41 : (byte)0x01, bits);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// An IDR picture of one SI slice (§7.3.3, §7.3.5) with QS = 26 + <paramref name="qsDelta"/>: every macroblock is an SI
|
||||||
|
/// macroblock without residual (Intra_4x4, every block with the predicted mode, chroma DC), except those listed in
|
||||||
|
/// <paramref name="pcm"/>, which are I_PCM (mb_type 26 in an SI slice) with luma <paramref name="pcmLuma"/> and chroma 128.
|
||||||
|
/// </summary>
|
||||||
|
internal static byte[] SiIdr(SequenceSettings s, int qsDelta, int[] pcm, byte pcmLuma)
|
||||||
|
{
|
||||||
|
var bits = new BitWriter();
|
||||||
|
bits.Ue(0); // first_mb_in_slice
|
||||||
|
bits.Ue(9); // slice_type: SI (all slices of the picture)
|
||||||
|
bits.Ue(0); // pic_parameter_set_id
|
||||||
|
bits.Bits(0, s.Log2MaxFrameNum); // frame_num
|
||||||
|
bits.Ue(0); // idr_pic_id
|
||||||
|
if (s.PocType == 0)
|
||||||
|
{
|
||||||
|
bits.Bits(0, 8); // pic_order_cnt_lsb
|
||||||
|
}
|
||||||
|
|
||||||
|
bits.Bits(0, 1); // no_output_of_prior_pics_flag
|
||||||
|
bits.Bits(0, 1); // long_term_reference_flag
|
||||||
|
bits.Se(0); // slice_qp_delta
|
||||||
|
bits.Se(qsDelta); // slice_qs_delta
|
||||||
|
bits.Ue(1); // disable_deblocking_filter_idc: off
|
||||||
|
for (var m = 0; m < s.WidthInMbs * s.HeightInMbs; m++)
|
||||||
|
{
|
||||||
|
if (Array.IndexOf(pcm, m) >= 0)
|
||||||
|
{
|
||||||
|
bits.Ue(26); // mb_type: I_PCM (25 + 1 in an SI slice)
|
||||||
|
bits.Align(); // pcm_alignment_zero_bit
|
||||||
|
for (var i = 0; i < 256; i++)
|
||||||
|
{
|
||||||
|
bits.Bits(pcmLuma, 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < 128; i++)
|
||||||
|
{
|
||||||
|
bits.Bits(128, 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
bits.Ue(0); // mb_type: SI
|
||||||
|
for (var i = 0; i < 16; i++)
|
||||||
|
{
|
||||||
|
bits.Bits(1, 1); // prev_intra4x4_pred_mode_flag
|
||||||
|
}
|
||||||
|
|
||||||
|
bits.Ue(0); // intra_chroma_pred_mode: DC
|
||||||
|
bits.Ue(3); // coded_block_pattern: codeNum 3 is 0 for intra prediction modes (table 9-4)
|
||||||
|
}
|
||||||
|
|
||||||
|
return Nal(0x65, bits);
|
||||||
|
}
|
||||||
|
|
||||||
private static byte[] Nal(byte header, BitWriter bits)
|
private static byte[] Nal(byte header, BitWriter bits)
|
||||||
{
|
{
|
||||||
bits.Bits(1, 1); // rbsp_stop_one_bit
|
bits.Bits(1, 1); // rbsp_stop_one_bit
|
||||||
return [0, 0, 0, 1, header, .. bits.ToArray()];
|
return [0, 0, 0, 1, header, .. bits.ToArray()];
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed class BitWriter
|
|
||||||
{
|
|
||||||
private readonly List<bool> bits = [];
|
|
||||||
|
|
||||||
public void Bits(uint value, int count)
|
|
||||||
{
|
|
||||||
for (var i = count - 1; i >= 0; i--)
|
|
||||||
{
|
|
||||||
bits.Add(((value >> i) & 1) != 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Ue(uint value)
|
|
||||||
{
|
|
||||||
var code = value + 1;
|
|
||||||
var length = 32 - System.Numerics.BitOperations.LeadingZeroCount(code);
|
|
||||||
Bits(0, length - 1);
|
|
||||||
Bits(code, length);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Se(int value) => Ue(value <= 0 ? (uint)(-2 * value) : (uint)((2 * value) - 1));
|
|
||||||
|
|
||||||
public void Align()
|
|
||||||
{
|
|
||||||
while (bits.Count % 8 != 0)
|
|
||||||
{
|
|
||||||
bits.Add(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public byte[] ToArray()
|
|
||||||
{
|
|
||||||
var bytes = new byte[(bits.Count + 7) / 8];
|
|
||||||
for (var i = 0; i < bits.Count; i++)
|
|
||||||
{
|
|
||||||
if (bits[i])
|
|
||||||
{
|
|
||||||
bytes[i / 8] |= (byte)(0x80 >> (i % 8));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Emulation prevention (§7.4.1): never two zero bytes followed by a byte up to 3.
|
|
||||||
var output = new List<byte>();
|
|
||||||
var zeros = 0;
|
|
||||||
foreach (var b in bytes)
|
|
||||||
{
|
|
||||||
if (zeros >= 2 && b <= 3)
|
|
||||||
{
|
|
||||||
output.Add(3);
|
|
||||||
zeros = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
output.Add(b);
|
|
||||||
zeros = b == 0 ? zeros + 1 : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
return [.. output];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user