diff --git a/docs/decisioni.md b/docs/decisioni.md
index 3baebdb..2de6d0c 100644
--- a/docs/decisioni.md
+++ b/docs/decisioni.md
@@ -428,3 +428,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-18 | Lettori di contenitori più tolleranti: un blocco Matroska danneggiato o troncato, o oltre il limite dei campioni, ferma la lettura e i blocchi letti restano; una traccia MP4 con `tkhd`, `elst`, `mdhd`, `hdlr` o `esds` danneggiati si scarta e le altre restano; la durata AVI oltre 10⁹ secondi è ignota senza perdere la data; i tempi Matroska usano come unità il massimo comun divisore fra TimecodeScale e un secondo, così la scala dei tempi è esatta per ogni TimecodeScale; la sonda dei metadati legge su un thread del pool e controlla l'annullamento fra i frammenti, e senza campioni non copia le tabelle né conserva i campioni dei frammenti | Come per il lettore ISO già prima: un file con un solo punto rovinato dopo il primo secondo non deve restare senza miniatura né perdere la data. La divisione intera 10⁹ / TimecodeScale spostava i tempi dello 0,1% con 3 ms e sbagliava fotogramma oltre il secondo |
| 2026-11-18 | Ciò che il decodificatore dei fotogrammi offre ma la produzione non usa ancora: `AnalyseStillnessAsync` (video di un'immagine ferma) e `Mp4Writer` (rimpacchettare con moov in testa) sono pronti per una tappa successiva e oggi servono solo alle prove; la miniatura di un video passa ancora da un BMP decodificato da SkiaSharp (tappa C1: dare `VideoImage` direttamente al ridimensionamento e al codificatore JPEG scritti in casa, senza BMP) | La riga del 18 novembre sui video li descriveva come se fossero già usati. Il passaggio per BMP resta finché SkiaSharp è nel programma |
| 2026-11-18 | Per il decodificatore HEVC si tengono nel repository 146 flussi della serie di conformità ITU-T H.265.1 (136 Main, Main 10 e Main Still Picture, 10 RExt), circa 29 MB, in `tests/Febe.Tests/Media/H265/Conformita`: flusso, `readme` originale e `riferimento.md5` con l'MD5 di tutto il YUV ufficiale e, per i 15 flussi che hanno il YUV nello zip, di ogni fotogramma. Le prove di decodifica sono inconcludenti finché il decodificatore non c'è, e quelle RExt finché Alberto non decide se servono; gli hash SEI delle immagini si leggono già con un lettore scritto dalla norma (D.3.19) | Un riferimento ufficiale per ogni strumento di HEVC prima di scriverne il decodificatore, senza i YUV (centinaia di MB) e senza i flussi grandi già coperti da altri (elenco in LEGGIMI.md). Le 146 prove inconcludenti sono saltate per la CI, che oggi non ne ammette nessuna: il ramo non passa la verifica finché il decodificatore o una regola diversa non le toglie |
+| 2026-11-18 | Decodificatore HEVC (ITU-T H.265), prima parte, scritto in casa in `src/Febe.Core/Codecs/H265` accanto a quello H.264: unità NAL Annex B e `hvcC`, VPS/SPS/PPS con liste di scala, VUI e indicatori RExt, intestazione di slice, POC, RPS, DPB e uscita (C.5.2), CABAC con le tabelle d'inizio della norma, albero di codifica, unità di predizione, residui (sign data hiding, transform skip), predizione intra, trasformate, PCM, deblocking e SAO, tile, WPP e segmenti dipendenti. Riusa da H.264 `rangeTabLps`, `transIdxLps` e la lettura delle unità NAL. Le slice P e B si rifiutano con un'eccezione: la predizione inter è la tappa successiva; con un interruttore interno le prove ne leggono la sintassi fino a `end_of_slice_segment_flag`, con le unità di predizione grigie. Profili accettati: 4:2:0 fino a 12 bit senza strumenti RExt | I 12 flussi di sole slice I (Main, Main 10, Main Still Picture) coincidono col YUV ufficiale; nei 136 flussi Main e Main 10 ogni immagine di sole slice I coincide con l'MD5 SEI del codificatore, dove il flusso lo porta, e ogni slice P e B si legge fino in fondo: un primo controllo della sintassi inter, che senza predizione non si può confrontare con gli hash |
diff --git a/src/Febe.Core/Codecs/H265/BitReader.cs b/src/Febe.Core/Codecs/H265/BitReader.cs
new file mode 100644
index 0000000..9310df5
--- /dev/null
+++ b/src/Febe.Core/Codecs/H265/BitReader.cs
@@ -0,0 +1,174 @@
+using System.Buffers.Binary;
+using Febe.Core.Codecs.H264;
+
+namespace Febe.Core.Codecs.H265;
+
+/// A malformed or unsupported HEVC stream.
+public sealed class H265Exception(string message) : Exception(message);
+
+///
+/// Reads the bits of a raw byte sequence payload (ITU-T H.265 §7.2, §7.4.2): a NAL unit with its emulation prevention
+/// bytes removed. The buffer carries sixteen zero bytes past the end (see ), so reads never
+/// need a bounds check; reading past the payload gives zeros and is detected through .
+///
+internal sealed class BitReader
+{
+ private readonly byte[] data;
+ private readonly int length;
+ private int position;
+
+ /// The payload, followed by at least sixteen bytes of zero padding.
+ /// Bytes of payload.
+ /// First byte to read (after the two-byte NAL unit header).
+ internal BitReader(byte[] data, int length, int startByte)
+ {
+ this.data = data;
+ this.length = length;
+ position = startByte * 8;
+ }
+
+ internal byte[] Data => data;
+
+ internal int Length => length;
+
+ internal int Position
+ {
+ get => position;
+ set => position = value;
+ }
+
+ internal int BitsLeft => (length * 8) - position;
+
+ internal bool ByteAligned => (position & 7) == 0;
+
+ /// more_rbsp_data() (§7.2): true while bits remain before the rbsp_stop_one_bit.
+ internal bool MoreRbspData
+ {
+ get
+ {
+ var last = length - 1;
+ while (last >= 0 && data[last] == 0)
+ {
+ last--;
+ }
+
+ if (last < 0)
+ {
+ return false;
+ }
+
+ var stopBit = (last * 8) + 7 - System.Numerics.BitOperations.TrailingZeroCount(data[last]);
+ return position < stopBit;
+ }
+ }
+
+ internal uint Peek(int count)
+ {
+ var index = position >> 3;
+ if (index + 8 > data.Length)
+ {
+ throw new H265Exception("Flusso HEVC troncato.");
+ }
+
+ var word = BinaryPrimitives.ReadUInt64BigEndian(data.AsSpan(index, 8));
+ return (uint)((word << (position & 7)) >> (64 - count));
+ }
+
+ /// u(n), 0 to 32 bits.
+ internal uint Read(int count)
+ {
+ if (count == 0)
+ {
+ return 0;
+ }
+
+ var value = Peek(count);
+ position += count;
+ return value;
+ }
+
+ internal int ReadInt(int count) => (int)Read(count);
+
+ internal void Skip(int count) => position += count;
+
+ internal bool ReadFlag()
+ {
+ if ((position >> 3) >= data.Length)
+ {
+ throw new H265Exception("Flusso HEVC troncato.");
+ }
+
+ var bit = (data[position >> 3] >> (7 - (position & 7))) & 1;
+ position++;
+ return bit != 0;
+ }
+
+ /// ue(v): Exp-Golomb code (§9.2).
+ internal uint ReadUe()
+ {
+ var zeros = 0;
+ while (!ReadFlag())
+ {
+ if (++zeros > 31 || position > (length * 8) + 32)
+ {
+ throw new H265Exception("Codice Exp-Golomb non valido.");
+ }
+ }
+
+ return zeros == 0 ? 0 : (uint)(((1UL << zeros) - 1) + Read(zeros));
+ }
+
+ /// A ue(v) value that must not exceed .
+ internal int ReadUe(int max)
+ {
+ var value = ReadUe();
+ if (value > (uint)max)
+ {
+ throw new H265Exception("Valore fuori dall'intervallo ammesso.");
+ }
+
+ return (int)value;
+ }
+
+ /// se(v): signed Exp-Golomb code (§9.2.2).
+ internal int ReadSe()
+ {
+ var code = ReadUe();
+ var magnitude = (int)((code + 1) >> 1);
+ return (code & 1) != 0 ? magnitude : -magnitude;
+ }
+
+ /// A se(v) value inside [, ].
+ internal int ReadSe(int min, int max)
+ {
+ var value = ReadSe();
+ if (value < min || value > max)
+ {
+ throw new H265Exception("Valore fuori dall'intervallo ammesso.");
+ }
+
+ return value;
+ }
+
+ /// Moves to the next byte boundary (byte_alignment() and the alignment bits before PCM samples).
+ internal void AlignToByte() => position = (position + 7) & ~7;
+}
+
+/// One HEVC NAL unit, with its RBSP (the two-byte header included at its start).
+internal readonly record struct H265NalUnit(int Type, int LayerId, int TemporalId, byte[] Rbsp, int Length)
+{
+ /// A reader positioned after the two-byte NAL unit header (§7.3.1.2).
+ internal BitReader Reader() => new(Rbsp, Length, 2);
+
+ /// Removes the emulation prevention bytes of one NAL unit into , grown when needed.
+ internal static H265NalUnit Unescape(ReadOnlySpan nal, ref byte[]? buffer)
+ {
+ if (nal.Length < 2)
+ {
+ throw new H265Exception("Unità NAL HEVC troppo corta.");
+ }
+
+ var unit = NalUnits.Unescape(nal, ref buffer);
+ return new H265NalUnit((nal[0] >> 1) & 63, ((nal[0] & 1) << 5) | (nal[1] >> 3), (nal[1] & 7) - 1, unit.Rbsp, unit.Length);
+ }
+}
diff --git a/src/Febe.Core/Codecs/H265/CabacEngine.cs b/src/Febe.Core/Codecs/H265/CabacEngine.cs
new file mode 100644
index 0000000..d958c30
--- /dev/null
+++ b/src/Febe.Core/Codecs/H265/CabacEngine.cs
@@ -0,0 +1,201 @@
+using System.Buffers.Binary;
+using System.Numerics;
+using Lps = Febe.Core.Codecs.H264.CabacTables;
+
+namespace Febe.Core.Codecs.H265;
+
+///
+/// The arithmetic decoding engine of HEVC CABAC (ITU-T H.265 §9.3.4.3) with the context variables of the slice segment.
+/// Each context is one byte, (pStateIdx << 1) | valMps, so the storage and synchronisation of §9.3.2.3 and §9.3.2.4
+/// (wavefronts, dependent slice segments) are plain copies. The data is read through a 64-bit window and
+/// renormalisation shifts all its bits at once: the arithmetic is that of the Recommendation, bit for bit.
+///
+internal sealed class CabacEngine
+{
+ internal readonly byte[] Contexts = new byte[CabacTables.ContextCount];
+
+ private byte[] data = [];
+ private int range;
+ private int offset;
+ private ulong window;
+ private int bits;
+ private int next;
+ private int end;
+
+ /// Initialises every context variable for an initType and the slice QP (§9.3.2.2).
+ internal void InitContexts(int initType, int sliceQp)
+ {
+ var values = CabacTables.InitValues[initType];
+ var qp = Math.Clamp(sliceQp, 0, 51);
+ for (var i = 0; i < Contexts.Length; i++)
+ {
+ int initValue = values[i];
+ var m = ((initValue >> 4) * 5) - 45;
+ var n = ((initValue & 15) << 3) - 16;
+ var pre = Math.Clamp(((m * qp) >> 4) + n, 1, 126);
+ Contexts[i] = pre <= 63 ? (byte)((63 - pre) << 1) : (byte)(((pre - 64) << 1) | 1);
+ }
+ }
+
+ ///
+ /// Initialises the arithmetic decoder (§9.3.2.5) at a bit position of ; reading stops at
+ /// (the end of the slice segment data), past which the decoder sees zeros.
+ ///
+ internal void Start(byte[] source, int bitPosition, int endByte)
+ {
+ data = source;
+ end = endByte;
+ next = bitPosition >> 3;
+ window = 0;
+ bits = 0;
+ Refill();
+ var skip = bitPosition & 7;
+ window <<= skip;
+ bits -= skip;
+ range = 510;
+ offset = Take(9);
+ if (offset >= range)
+ {
+ throw new H265Exception("Dati CABAC non validi.");
+ }
+ }
+
+ /// The bit position right after the last bit the decoder has read (after a terminating bin equal to 1).
+ internal int BitPosition => (next * 8) - bits;
+
+ /// DecodeDecision (§9.3.4.3.2).
+ internal int Decision(int ctx)
+ {
+ int s = Contexts[ctx];
+ var p = s >> 1;
+ var mps = s & 1;
+ int lps = Lps.RangeLps[(p << 2) + ((range >> 6) & 3)];
+ range -= lps;
+ int bin;
+ if (offset >= range)
+ {
+ bin = mps ^ 1;
+ offset -= range;
+ range = lps;
+ if (p == 0)
+ {
+ mps ^= 1;
+ }
+
+ Contexts[ctx] = (byte)((Lps.NextStateLps[p] << 1) | mps);
+ }
+ else
+ {
+ bin = mps;
+ if (p < 62)
+ {
+ Contexts[ctx] = (byte)(s + 2);
+ }
+ }
+
+ if (range < 256)
+ {
+ var shift = BitOperations.LeadingZeroCount((uint)range) - 23;
+ range <<= shift;
+ offset = (offset << shift) | Take(shift);
+ }
+
+ return bin;
+ }
+
+ internal bool Flag(int ctx) => Decision(ctx) != 0;
+
+ /// DecodeBypass (§9.3.4.3.4).
+ internal int Bypass()
+ {
+ offset = (offset << 1) | Take(1);
+ if (offset >= range)
+ {
+ offset -= range;
+ return 1;
+ }
+
+ return 0;
+ }
+
+ /// bypass bins (at most 16), the first one in the most significant bit.
+ internal int BypassBits(int count)
+ {
+ var value = 0;
+ for (var i = 0; i < count; i++)
+ {
+ offset = (offset << 1) | Take(1);
+ value <<= 1;
+ if (offset >= range)
+ {
+ offset -= range;
+ value |= 1;
+ }
+ }
+
+ return value;
+ }
+
+ ///
+ /// DecodeTerminate (§9.3.4.3.5). After a bin equal to 1 (end of slice segment, of a substream, PCM samples) the last
+ /// bit read is the final bit of the encoder's flush and is where the bitstream goes on.
+ ///
+ internal int Terminate()
+ {
+ range -= 2;
+ if (offset >= range)
+ {
+ return 1;
+ }
+
+ if (range < 256)
+ {
+ range <<= 1;
+ offset = (offset << 1) | Take(1);
+ }
+
+ return 0;
+ }
+
+ private int Take(int count)
+ {
+ if (bits < count)
+ {
+ Refill();
+ }
+
+ var value = (int)(window >> (64 - count));
+ window <<= count;
+ bits -= count;
+ return value;
+ }
+
+ private void Refill()
+ {
+ while (bits <= 32)
+ {
+ uint word;
+ if (next + 4 <= end)
+ {
+ word = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(next, 4));
+ }
+ else
+ {
+ if (next > end + 64)
+ {
+ throw new H265Exception("Dati CABAC oltre la fine della slice.");
+ }
+
+ word = 0;
+ for (var k = 0; k < 4; k++)
+ {
+ word = (word << 8) | (next + k < end ? data[next + k] : 0u);
+ }
+ }
+
+ window |= (ulong)word << (32 - bits);
+ next += 4;
+ bits += 32;
+ }
+ }
+}
diff --git a/src/Febe.Core/Codecs/H265/CabacTables.cs b/src/Febe.Core/Codecs/H265/CabacTables.cs
new file mode 100644
index 0000000..506dafd
--- /dev/null
+++ b/src/Febe.Core/Codecs/H265/CabacTables.cs
@@ -0,0 +1,141 @@
+namespace Febe.Core.Codecs.H265;
+
+///
+/// The context variables of HEVC CABAC (ITU-T H.265 §9.3.2.2): where each syntax element's contexts start in the
+/// decoder's array and their initValue for the three initTypes (0 for I slices, 1 and 2 for P and B slices, swapped by
+/// cabac_init_flag), transcribed from the tables of 9.3.2.2 of the Recommendation. Contexts that a slice type never uses
+/// (for instance cu_skip_flag in I slices) have no value in the Recommendation and take 154 here, which is never read.
+/// rangeTabLps and transIdxLps (9.3.4.3.2) are those of H.264 ().
+///
+internal static class CabacTables
+{
+ internal const int SaoMergeFlag = 0;
+ internal const int SaoTypeIdx = SaoMergeFlag + 1;
+ internal const int SplitCuFlag = SaoTypeIdx + 1;
+ internal const int CuTransquantBypassFlag = SplitCuFlag + 3;
+ internal const int CuSkipFlag = CuTransquantBypassFlag + 1;
+ internal const int PredModeFlag = CuSkipFlag + 3;
+ internal const int PartMode = PredModeFlag + 1;
+ internal const int PrevIntraLumaPredFlag = PartMode + 4;
+ internal const int IntraChromaPredMode = PrevIntraLumaPredFlag + 1;
+ internal const int RqtRootCbf = IntraChromaPredMode + 1;
+ internal const int MergeFlag = RqtRootCbf + 1;
+ internal const int MergeIdx = MergeFlag + 1;
+ internal const int InterPredIdc = MergeIdx + 1;
+ internal const int RefIdx = InterPredIdc + 5;
+ internal const int MvpFlag = RefIdx + 2;
+ internal const int SplitTransformFlag = MvpFlag + 1;
+ internal const int CbfLuma = SplitTransformFlag + 3;
+ internal const int CbfChroma = CbfLuma + 2;
+ internal const int AbsMvdGreater0Flag = CbfChroma + 5;
+ internal const int AbsMvdGreater1Flag = AbsMvdGreater0Flag + 1;
+ internal const int CuQpDeltaAbs = AbsMvdGreater1Flag + 1;
+ internal const int TransformSkipFlag = CuQpDeltaAbs + 2;
+ internal const int LastSigCoeffXPrefix = TransformSkipFlag + 2;
+ internal const int LastSigCoeffYPrefix = LastSigCoeffXPrefix + 18;
+ internal const int CodedSubBlockFlag = LastSigCoeffYPrefix + 18;
+ internal const int SigCoeffFlag = CodedSubBlockFlag + 4;
+ internal const int CoeffAbsLevelGreater1Flag = SigCoeffFlag + 44;
+ internal const int CoeffAbsLevelGreater2Flag = CoeffAbsLevelGreater1Flag + 24;
+ internal const int ExplicitRdpcmFlag = CoeffAbsLevelGreater2Flag + 6;
+ internal const int ExplicitRdpcmDirFlag = ExplicitRdpcmFlag + 2;
+ internal const int Log2ResScaleAbsPlus1 = ExplicitRdpcmDirFlag + 2;
+ internal const int ResScaleSignFlag = Log2ResScaleAbsPlus1 + 8;
+ internal const int CuChromaQpOffsetFlag = ResScaleSignFlag + 2;
+ internal const int CuChromaQpOffsetIdx = CuChromaQpOffsetFlag + 1;
+
+ /// Number of context variables kept by the decoder.
+ internal const int ContextCount = CuChromaQpOffsetIdx + 1;
+
+ ///
+ /// The syntax elements in the order of the layout above, each with its initValues for initType 0, 1 and 2 (as many
+ /// values per initType as the element has contexts).
+ ///
+ internal static readonly (string Name, byte[] I, byte[] P, byte[] B)[] Elements =
+ [
+ ("sao_merge_left_flag", [153], [153], [153]),
+ ("sao_type_idx", [200], [185], [160]),
+ ("split_cu_flag", [139, 141, 157], [107, 139, 126], [107, 139, 126]),
+ ("cu_transquant_bypass_flag", [154], [154], [154]),
+ ("cu_skip_flag", [154, 154, 154], [197, 185, 201], [197, 185, 201]),
+ ("pred_mode_flag", [154], [149], [134]),
+ ("part_mode", [184, 154, 154, 154], [154, 139, 154, 154], [154, 139, 154, 154]),
+ ("prev_intra_luma_pred_flag", [184], [154], [183]),
+ ("intra_chroma_pred_mode", [63], [152], [152]),
+ ("rqt_root_cbf", [154], [79], [79]),
+ ("merge_flag", [154], [110], [154]),
+ ("merge_idx", [154], [122], [137]),
+ ("inter_pred_idc", [154, 154, 154, 154, 154], [95, 79, 63, 31, 31], [95, 79, 63, 31, 31]),
+ ("ref_idx", [154, 154], [153, 153], [153, 153]),
+ ("mvp_flag", [154], [168], [168]),
+ ("split_transform_flag", [153, 138, 138], [124, 138, 94], [224, 167, 122]),
+ ("cbf_luma", [111, 141], [153, 111], [153, 111]),
+ ("cbf_cb_cr", [94, 138, 182, 154, 154], [149, 107, 167, 154, 154], [149, 92, 167, 154, 154]),
+ ("abs_mvd_greater0_flag", [154], [140], [169]),
+ ("abs_mvd_greater1_flag", [154], [198], [198]),
+ ("cu_qp_delta_abs", [154, 154], [154, 154], [154, 154]),
+ ("transform_skip_flag", [139, 139], [139, 139], [139, 139]),
+ (
+ "last_sig_coeff_x_prefix",
+ [110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63],
+ [125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108],
+ [125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93]),
+ (
+ "last_sig_coeff_y_prefix",
+ [110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63],
+ [125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108],
+ [125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93]),
+ ("coded_sub_block_flag", [91, 171, 134, 141], [121, 140, 61, 154], [121, 140, 61, 154]),
+ (
+ "sig_coeff_flag", // the last two of each initType are those of transform_skip_context_enabled_flag
+ [
+ 111, 111, 125, 110, 110, 94, 124, 108, 124, 107, 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 107,
+ 125, 141, 179, 153, 125, 140, 139, 182, 182, 152, 136, 152, 136, 153, 136, 139, 111, 136, 139, 111, 141, 111,
+ ],
+ [
+ 155, 154, 139, 153, 139, 123, 123, 63, 153, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 166,
+ 183, 140, 136, 153, 154, 170, 153, 123, 123, 107, 121, 107, 121, 167, 151, 183, 140, 151, 183, 140, 140, 140,
+ ],
+ [
+ 170, 154, 139, 153, 139, 123, 123, 63, 124, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 166,
+ 183, 140, 136, 153, 154, 170, 153, 138, 138, 122, 121, 122, 121, 167, 151, 183, 140, 151, 183, 140, 140, 140,
+ ]),
+ (
+ "coeff_abs_level_greater1_flag",
+ [140, 92, 137, 138, 140, 152, 138, 139, 153, 74, 149, 92, 139, 107, 122, 152, 140, 179, 166, 182, 140, 227, 122, 197],
+ [154, 196, 196, 167, 154, 152, 167, 182, 182, 134, 149, 136, 153, 121, 136, 137, 169, 194, 166, 167, 154, 167, 137, 182],
+ [154, 196, 167, 167, 154, 152, 167, 182, 182, 134, 149, 136, 153, 121, 136, 122, 169, 208, 166, 167, 154, 152, 167, 182]),
+ ("coeff_abs_level_greater2_flag", [138, 153, 136, 167, 152, 152], [107, 167, 91, 122, 107, 167], [107, 167, 91, 107, 107, 167]),
+ ("explicit_rdpcm_flag", [139, 139], [139, 139], [139, 139]),
+ ("explicit_rdpcm_dir_flag", [139, 139], [139, 139], [139, 139]),
+ ("log2_res_scale_abs_plus1", [154, 154, 154, 154, 154, 154, 154, 154], [154, 154, 154, 154, 154, 154, 154, 154], [154, 154, 154, 154, 154, 154, 154, 154]),
+ ("res_scale_sign_flag", [154, 154], [154, 154], [154, 154]),
+ ("cu_chroma_qp_offset_flag", [154], [154], [154]),
+ ("cu_chroma_qp_offset_idx", [154], [154], [154]),
+ ];
+
+ /// initValue of every context by initType: InitValues[initType][ctx].
+ internal static readonly byte[][] InitValues = BuildInitValues();
+
+ private static byte[][] BuildInitValues()
+ {
+ var tables = new byte[3][];
+ for (var t = 0; t < 3; t++)
+ {
+ var values = new List(ContextCount);
+ foreach (var element in Elements)
+ {
+ values.AddRange(t == 0 ? element.I : t == 1 ? element.P : element.B);
+ }
+
+ if (values.Count != ContextCount)
+ {
+ throw new InvalidOperationException("Tabelle CABAC HEVC incoerenti.");
+ }
+
+ tables[t] = [.. values];
+ }
+
+ return tables;
+ }
+}
diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.Filters.cs b/src/Febe.Core/Codecs/H265/H265Decoder.Filters.cs
new file mode 100644
index 0000000..2207673
--- /dev/null
+++ b/src/Febe.Core/Codecs/H265/H265Decoder.Filters.cs
@@ -0,0 +1,479 @@
+namespace Febe.Core.Codecs.H265;
+
+/// The in-loop filters (§8.7): deblocking (§8.7.2) then sample adaptive offset (§8.7.3), on the whole picture.
+public sealed partial class H265Decoder
+{
+ private ushort[] saoSource = [];
+
+ /// The left and top edges of a coding block, unless filterEdgeFlag of §8.7.2.3 is 0 for them.
+ private void MarkCodingUnitEdges(int x0, int y0, int size)
+ {
+ if (x0 > 0 && FilterAcross(x0 - 1, y0))
+ {
+ MarkVertical(x0, y0, size, 2);
+ }
+
+ if (y0 > 0 && FilterAcross(x0, y0 - 1))
+ {
+ MarkHorizontal(x0, y0, size, 2);
+ }
+ }
+
+ /// Whether deblocking may cross into the block at (xN, yN) from the current one: slice and tile boundaries.
+ private bool FilterAcross(int xN, int yN)
+ {
+ var log2 = sps.Log2CtbSize;
+ var ctbN = ((yN >> log2) * widthInCtbs) + (xN >> log2);
+ if (ctbN == ctbAddrRs)
+ {
+ return true;
+ }
+
+ if (!pps.LoopFilterAcrossTilesEnabled && pps.TileIdRs[ctbN] != pps.TileIdRs[ctbAddrRs])
+ {
+ return false;
+ }
+
+ return slice.LoopFilterAcrossSlices || ctbSlice[ctbN] == sliceIdx;
+ }
+
+ /// The edges between the prediction blocks of an inter coding unit (§8.7.2.3).
+ private void MarkPredictionEdges(int x0, int y0, int size)
+ {
+ if (cuIntra)
+ {
+ return;
+ }
+
+ int half = size >> 1, quarter = size >> 2;
+ switch (cuPartMode)
+ {
+ case PartNx2N:
+ MarkVertical(x0 + half, y0, size, 1);
+ break;
+ case PartnLx2N:
+ MarkVertical(x0 + quarter, y0, size, 1);
+ break;
+ case PartnRx2N:
+ MarkVertical(x0 + size - quarter, y0, size, 1);
+ break;
+ case Part2NxN:
+ MarkHorizontal(x0, y0 + half, size, 1);
+ break;
+ case Part2NxnU:
+ MarkHorizontal(x0, y0 + quarter, size, 1);
+ break;
+ case Part2NxnD:
+ MarkHorizontal(x0, y0 + size - quarter, size, 1);
+ break;
+ case PartNxN:
+ MarkVertical(x0 + half, y0, size, 1);
+ MarkHorizontal(x0, y0 + half, size, 1);
+ break;
+ }
+ }
+
+ private void MarkVertical(int x, int y0, int length, byte kind)
+ {
+ if (slice.DeblockingDisabled || (x & 7) != 0)
+ {
+ return;
+ }
+
+ var gx = x >> 2;
+ var end = Math.Min((y0 + length) >> 2, h4);
+ for (var gy = y0 >> 2; gy < end; gy++)
+ {
+ ref var e = ref edgeV[(gy * w4) + gx];
+ e = Math.Max(e, kind);
+ }
+ }
+
+ private void MarkHorizontal(int x0, int y, int length, byte kind)
+ {
+ if (slice.DeblockingDisabled || (y & 7) != 0)
+ {
+ return;
+ }
+
+ var row = (y >> 2) * w4;
+ var end = Math.Min((x0 + length) >> 2, w4);
+ for (var gx = x0 >> 2; gx < end; gx++)
+ {
+ ref var e = ref edgeH[row + gx];
+ e = Math.Max(e, kind);
+ }
+ }
+
+ private void ApplyInLoopFilters(Picture picture)
+ {
+ Deblock(picture, true);
+ Deblock(picture, false);
+ foreach (var header in slices)
+ {
+ if (header.SaoLuma || header.SaoChroma)
+ {
+ ApplySao(picture);
+ break;
+ }
+ }
+ }
+
+ /// bS of §8.7.2.4 between the 4×4 blocks and of the grid.
+ private int BoundaryStrength(int p, int q, int kind)
+ {
+ if (predMode[p] == ModeIntra || predMode[q] == ModeIntra)
+ {
+ return 2;
+ }
+
+ if (kind == 2 && ((blockFlags[p] | blockFlags[q]) & FlagCoded) != 0)
+ {
+ return 1;
+ }
+
+ // The motion conditions need the motion data of inter prediction, which is not decoded yet.
+ return 0;
+ }
+
+ /// Filters every vertical (or horizontal) edge of the picture: luma on the 8×8 grid, chroma on the 16×16 one.
+ private void Deblock(Picture picture, bool vertical)
+ {
+ var edges = vertical ? edgeV : edgeH;
+ var luma = picture.Planes[0];
+ var stride = picture.Width;
+ var maxY = (1 << sps.BitDepthY) - 1;
+ var scaleY = 1 << (sps.BitDepthY - 8);
+ var log2Ctb = sps.Log2CtbSize;
+ var checkFlags = pictureHasUnfilteredBlocks;
+ for (var gy = 0; gy < h4; gy++)
+ {
+ for (var gx = 0; gx < w4; gx++)
+ {
+ var q = (gy * w4) + gx;
+ int kind = edges[q];
+ if (kind == 0)
+ {
+ continue;
+ }
+
+ var p = vertical ? q - 1 : q - w4;
+ var bS = BoundaryStrength(p, q, kind);
+ if (bS == 0)
+ {
+ continue;
+ }
+
+ var header = slices[ctbSlice[((gy << 2 >> log2Ctb) * widthInCtbs) + (gx << 2 >> log2Ctb)]];
+ int qpP = qpMap[p], qpQ = qpMap[q];
+ var qpL = (qpQ + qpP + 1) >> 1;
+ var beta = H265Tables.Beta[Math.Clamp(qpL + (header.BetaOffsetDiv2 * 2), 0, 51)] * scaleY;
+ var tc = H265Tables.Tc[Math.Clamp(qpL + (2 * (bS - 1)) + (header.TcOffsetDiv2 * 2), 0, 53)] * scaleY;
+ var noP = checkFlags && (blockFlags[p] & FlagNoFilter) != 0;
+ var noQ = checkFlags && (blockFlags[q] & FlagNoFilter) != 0;
+ var x = gx << 2;
+ var y = gy << 2;
+ var origin = (y * stride) + x;
+ if (tc > 0 || beta > 0)
+ {
+ FilterLuma(luma, origin, vertical ? 1 : stride, vertical ? stride : 1, beta, tc, noP, noQ, maxY);
+ }
+
+ // Chroma (§8.7.2.5.5): bS 2 only, edges on the chroma 8×8 grid; the segment of 4 chroma samples takes the
+ // values of the first luma segment of its 8 luma samples.
+ if (bS == 2 && (vertical ? (x & 15) == 0 && (y & 7) == 0 : (y & 15) == 0 && (x & 7) == 0))
+ {
+ FilterChromaEdge(picture, x >> 1, y >> 1, vertical, qpL, header.TcOffsetDiv2, noP, noQ);
+ }
+ }
+ }
+ }
+
+ private void FilterChromaEdge(Picture picture, int xc, int yc, bool vertical, int qpL, int tcOffsetDiv2, bool noP, bool noQ)
+ {
+ var stride = picture.ChromaWidth;
+ var max = (1 << sps.BitDepthC) - 1;
+ var scale = 1 << (sps.BitDepthC - 8);
+ var lines = Math.Min(4, vertical ? picture.ChromaHeight - yc : picture.ChromaWidth - xc);
+ for (var c = 1; c <= 2; c++)
+ {
+ var qPi = qpL + (c == 1 ? pps.CbQpOffset : pps.CrQpOffset);
+ var qpC = qPi < 30 ? qPi : qPi > 43 ? qPi - 6 : H265Tables.ChromaQp30To43[qPi - 30];
+ var tc = H265Tables.Tc[Math.Clamp(qpC + 2 + (tcOffsetDiv2 * 2), 0, 53)] * scale;
+ if (tc == 0)
+ {
+ continue;
+ }
+
+ var s = picture.Planes[c];
+ var across = vertical ? 1 : stride;
+ var along = vertical ? stride : 1;
+ var origin = (yc * stride) + xc;
+ for (var k = 0; k < lines; k++)
+ {
+ var q0At = origin + (k * along);
+ int p0 = s[q0At - across], p1 = s[q0At - (2 * across)], q0 = s[q0At], q1 = s[q0At + across];
+ var delta = Math.Clamp(((((q0 - p0) << 2) + p1 - q1 + 4) >> 3), -tc, tc);
+ if (!noP)
+ {
+ s[q0At - across] = (ushort)Math.Clamp(p0 + delta, 0, max);
+ }
+
+ if (!noQ)
+ {
+ s[q0At] = (ushort)Math.Clamp(q0 - delta, 0, max);
+ }
+ }
+ }
+ }
+
+ /// The luma decisions (§8.7.2.5.3, §8.7.2.5.6) and filtering (§8.7.2.5.7) of one 4-line edge segment.
+ private static void FilterLuma(ushort[] s, int origin, int across, int along, int beta, int tc, bool noP, bool noQ, int max)
+ {
+ var line3 = origin + (3 * along);
+ var dp0 = Math.Abs(s[origin - (3 * across)] - (2 * s[origin - (2 * across)]) + s[origin - across]);
+ var dp3 = Math.Abs(s[line3 - (3 * across)] - (2 * s[line3 - (2 * across)]) + s[line3 - across]);
+ var dq0 = Math.Abs(s[origin + (2 * across)] - (2 * s[origin + across]) + s[origin]);
+ var dq3 = Math.Abs(s[line3 + (2 * across)] - (2 * s[line3 + across]) + s[line3]);
+ var dpq0 = dp0 + dq0;
+ var dpq3 = dp3 + dq3;
+ var dp = dp0 + dp3;
+ var dq = dq0 + dq3;
+ if (dpq0 + dpq3 >= beta)
+ {
+ return;
+ }
+
+ var strong = StrongDecision(s, origin, across, 2 * dpq0, beta, tc) && StrongDecision(s, line3, across, 2 * dpq3, beta, tc);
+ var side = (beta + (beta >> 1)) >> 3;
+ var dEp = dp < side;
+ var dEq = dq < side;
+ for (var k = 0; k < 4; k++)
+ {
+ var at = origin + (k * along);
+ int p0 = s[at - across], p1 = s[at - (2 * across)], p2 = s[at - (3 * across)], p3 = s[at - (4 * across)];
+ int q0 = s[at], q1 = s[at + across], q2 = s[at + (2 * across)], q3 = s[at + (3 * across)];
+ if (strong)
+ {
+ var tc2 = 2 * tc;
+ if (!noP)
+ {
+ s[at - across] = (ushort)Math.Clamp((p2 + (2 * p1) + (2 * p0) + (2 * q0) + q1 + 4) >> 3, p0 - tc2, p0 + tc2);
+ s[at - (2 * across)] = (ushort)Math.Clamp((p2 + p1 + p0 + q0 + 2) >> 2, p1 - tc2, p1 + tc2);
+ s[at - (3 * across)] = (ushort)Math.Clamp(((2 * p3) + (3 * p2) + p1 + p0 + q0 + 4) >> 3, p2 - tc2, p2 + tc2);
+ }
+
+ if (!noQ)
+ {
+ s[at] = (ushort)Math.Clamp((p1 + (2 * p0) + (2 * q0) + (2 * q1) + q2 + 4) >> 3, q0 - tc2, q0 + tc2);
+ s[at + across] = (ushort)Math.Clamp((p0 + q0 + q1 + q2 + 2) >> 2, q1 - tc2, q1 + tc2);
+ s[at + (2 * across)] = (ushort)Math.Clamp((p0 + q0 + q1 + (3 * q2) + (2 * q3) + 4) >> 3, q2 - tc2, q2 + tc2);
+ }
+ }
+ else
+ {
+ var delta = ((9 * (q0 - p0)) - (3 * (q1 - p1)) + 8) >> 4;
+ if (Math.Abs(delta) >= tc * 10)
+ {
+ continue;
+ }
+
+ delta = Math.Clamp(delta, -tc, tc);
+ if (!noP)
+ {
+ s[at - across] = (ushort)Math.Clamp(p0 + delta, 0, max);
+ if (dEp)
+ {
+ var deltaP = Math.Clamp((((p2 + p0 + 1) >> 1) - p1 + delta) >> 1, -(tc >> 1), tc >> 1);
+ s[at - (2 * across)] = (ushort)Math.Clamp(p1 + deltaP, 0, max);
+ }
+ }
+
+ if (!noQ)
+ {
+ s[at] = (ushort)Math.Clamp(q0 - delta, 0, max);
+ if (dEq)
+ {
+ var deltaQ = Math.Clamp((((q2 + q0 + 1) >> 1) - q1 - delta) >> 1, -(tc >> 1), tc >> 1);
+ s[at + across] = (ushort)Math.Clamp(q1 + deltaQ, 0, max);
+ }
+ }
+ }
+ }
+ }
+
+ /// dSam of §8.7.2.5.6 for one line.
+ private static bool StrongDecision(ushort[] s, int at, int across, int dpq, int beta, int tc)
+ {
+ int p0 = s[at - across], p3 = s[at - (4 * across)], q0 = s[at], q3 = s[at + (3 * across)];
+ return dpq < (beta >> 2) && Math.Abs(p3 - p0) + Math.Abs(q0 - q3) < (beta >> 3) && Math.Abs(p0 - q0) < (((5 * tc) + 1) >> 1);
+ }
+
+ /// Sample adaptive offset (§8.7.3) of every CTB, from a copy of the deblocked picture.
+ private void ApplySao(Picture picture)
+ {
+ var log2Ctb = sps.Log2CtbSize;
+ var heightInCtbs = sps.HeightInCtbs;
+ Span neighbours = stackalloc bool[9];
+ for (var c = 0; c < 3; c++)
+ {
+ var plane = picture.Planes[c];
+ var width = c == 0 ? picture.Width : picture.ChromaWidth;
+ var height = c == 0 ? picture.Height : picture.ChromaHeight;
+ var shift = c == 0 ? 0 : 1;
+ var ctbSize = (1 << log2Ctb) >> shift;
+ var bitDepth = c == 0 ? sps.BitDepthY : sps.BitDepthC;
+ var max = (1 << bitDepth) - 1;
+ if (saoSource.Length < plane.Length)
+ {
+ saoSource = new ushort[plane.Length];
+ }
+
+ var copied = false;
+ for (var rs = 0; rs < sps.CtbCount; rs++)
+ {
+ var at = (rs * 3) + c;
+ int type = saoType[at];
+ if (type == 0 || ctbSlice[rs] < 0)
+ {
+ continue;
+ }
+
+ if (!copied)
+ {
+ plane.AsSpan().CopyTo(saoSource);
+ copied = true;
+ }
+
+ int cx = rs % widthInCtbs, cy = rs / widthInCtbs;
+ int x0 = cx * ctbSize, y0 = cy * ctbSize;
+ int x1 = Math.Min(x0 + ctbSize, width), y1 = Math.Min(y0 + ctbSize, height);
+ var offsets = saoOffset.AsSpan(at * 4, 4);
+ if (type == 1)
+ {
+ SaoBand(plane, width, x0, y0, x1, y1, saoClass[at], offsets, bitDepth, max, shift);
+ }
+ else
+ {
+ for (var dy = -1; dy <= 1; dy++)
+ {
+ for (var dx = -1; dx <= 1; dx++)
+ {
+ neighbours[((dy + 1) * 3) + dx + 1] = SaoNeighbourAvailable(rs, cx + dx, cy + dy, heightInCtbs);
+ }
+ }
+
+ SaoEdge(plane, width, x0, y0, x1, y1, saoClass[at], offsets, max, shift, neighbours);
+ }
+ }
+ }
+ }
+
+ /// Whether the samples of the CTB at (nx, ny) can be used by the edge offset of the CTB .
+ private bool SaoNeighbourAvailable(int rs, int nx, int ny, int heightInCtbs)
+ {
+ if (nx < 0 || ny < 0 || nx >= widthInCtbs || ny >= heightInCtbs)
+ {
+ return false;
+ }
+
+ var nb = (ny * widthInCtbs) + nx;
+ if (nb == rs)
+ {
+ return true;
+ }
+
+ int sliceN = ctbSlice[nb], sliceC = ctbSlice[rs];
+ if (sliceN < 0)
+ {
+ return false;
+ }
+
+ if (sliceN != sliceC)
+ {
+ // The flag of the slice that comes later in decoding order decides.
+ var later = sliceN > sliceC ? slices[sliceN] : slices[sliceC];
+ if (!later.LoopFilterAcrossSlices)
+ {
+ return false;
+ }
+ }
+
+ return pps.LoopFilterAcrossTilesEnabled || pps.TileIdRs[nb] == pps.TileIdRs[rs];
+ }
+
+ private void SaoBand(ushort[] plane, int stride, int x0, int y0, int x1, int y1, int position, ReadOnlySpan offsets, int bitDepth, int max, int shift)
+ {
+ Span table = stackalloc int[32];
+ for (var k = 0; k < 4; k++)
+ {
+ table[(k + position) & 31] = offsets[k];
+ }
+
+ var bandShift = bitDepth - 5;
+ var check = pictureHasUnfilteredBlocks;
+ for (var y = y0; y < y1; y++)
+ {
+ var row = y * stride;
+ for (var x = x0; x < x1; x++)
+ {
+ if (check && (blockFlags[Grid(x << shift, y << shift)] & FlagNoFilter) != 0)
+ {
+ continue;
+ }
+
+ int value = saoSource[row + x];
+ var offset = table[value >> bandShift];
+ if (offset != 0)
+ {
+ plane[row + x] = (ushort)Math.Clamp(value + offset, 0, max);
+ }
+ }
+ }
+ }
+
+ private void SaoEdge(ushort[] plane, int stride, int x0, int y0, int x1, int y1, int eoClass, ReadOnlySpan offsets, int max, int shift, ReadOnlySpan neighbours)
+ {
+ // hPos and vPos of table 8-14 (the second neighbour is the opposite of the first).
+ int dx = eoClass switch { 0 => -1, 1 => 0, 2 => -1, _ => 1 };
+ int dy = eoClass == 0 ? 0 : -1;
+ Span byEdge = [offsets[0], offsets[1], 0, offsets[2], offsets[3]];
+ var check = pictureHasUnfilteredBlocks;
+ var width = stride;
+ var height = plane.Length / stride;
+ for (var y = y0; y < y1; y++)
+ {
+ var row = y * stride;
+ int ya = y + dy, yb = y - dy;
+ var cellA = (ya < y0 ? 0 : ya >= y1 ? 2 : 1) * 3;
+ var cellB = (yb < y0 ? 0 : yb >= y1 ? 2 : 1) * 3;
+ var rowOutside = ya < 0 || yb < 0 || ya >= height || yb >= height;
+ for (var x = x0; x < x1; x++)
+ {
+ int xa = x + dx, xb = x - dx;
+ if (rowOutside || xa < 0 || xb < 0 || xa >= width || xb >= width)
+ {
+ continue;
+ }
+
+ if (!neighbours[cellA + (xa < x0 ? 0 : xa >= x1 ? 2 : 1)] || !neighbours[cellB + (xb < x0 ? 0 : xb >= x1 ? 2 : 1)])
+ {
+ continue;
+ }
+
+ if (check && (blockFlags[Grid(x << shift, y << shift)] & FlagNoFilter) != 0)
+ {
+ continue;
+ }
+
+ int value = saoSource[row + x];
+ var edge = 2 + Math.Sign(value - saoSource[(ya * stride) + xa]) + Math.Sign(value - saoSource[(yb * stride) + xb]);
+ var offset = byEdge[edge];
+ if (offset != 0)
+ {
+ plane[row + x] = (ushort)Math.Clamp(value + offset, 0, max);
+ }
+ }
+ }
+ }
+}
diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.Intra.cs b/src/Febe.Core/Codecs/H265/H265Decoder.Intra.cs
new file mode 100644
index 0000000..ae255e9
--- /dev/null
+++ b/src/Febe.Core/Codecs/H265/H265Decoder.Intra.cs
@@ -0,0 +1,269 @@
+namespace Febe.Core.Codecs.H265;
+
+/// Intra sample prediction (§8.4.4.2): reference samples, their substitution and filtering, planar, DC and angular.
+public sealed partial class H265Decoder
+{
+ ///
+ /// The reference samples of a block of size N as one line of 4N + 1 values, from p[−1][2N − 1] up to p[−1][−1] (at
+ /// index 2N) and on to p[2N − 1][−1]: the order of the substitution process of §8.4.4.2.2.
+ ///
+ private readonly int[] refLine = new int[(4 * 32) + 1];
+
+ private readonly int[] refFiltered = new int[(4 * 32) + 1];
+ private readonly bool[] refAvailable = new bool[(4 * 32) + 1];
+ private readonly int[] refMain = new int[(3 * 32) + 1];
+
+ /// Predicts a block of component at (, ) in its own samples.
+ private void PredictIntra(int cIdx, int x0, int y0, int log2, int mode)
+ {
+ var picture = cur!;
+ var plane = picture.Planes[cIdx];
+ var stride = picture.Stride(cIdx);
+ var bitDepth = cIdx == 0 ? sps.BitDepthY : sps.BitDepthC;
+ var n = 1 << log2;
+ var n2 = 2 * n;
+ var shift = cIdx == 0 ? 0 : 1; // 4:2:0
+ var unit = 4 >> shift;
+ int xL = x0 << shift, yL = y0 << shift;
+ var line = refLine.AsSpan(0, (4 * n) + 1);
+ var available = refAvailable.AsSpan(0, (4 * n) + 1);
+ var constrained = pps.ConstrainedIntraPred;
+ var any = false;
+
+ // Left and below-left, top to bottom.
+ for (var k = 0; k < n2; k += unit)
+ {
+ var ok = IntraNeighbour(xL, yL, (x0 - 1) << shift, (y0 + k) << shift, constrained);
+ for (var j = 0; j < unit; j++)
+ {
+ var index = n2 - 1 - (k + j);
+ available[index] = ok;
+ if (ok)
+ {
+ line[index] = plane[((y0 + k + j) * stride) + x0 - 1];
+ }
+ }
+
+ any |= ok;
+ }
+
+ var corner = IntraNeighbour(xL, yL, (x0 - 1) << shift, (y0 - 1) << shift, constrained);
+ available[n2] = corner;
+ if (corner)
+ {
+ line[n2] = plane[((y0 - 1) * stride) + x0 - 1];
+ any = true;
+ }
+
+ // Above and above-right, left to right.
+ for (var k = 0; k < n2; k += unit)
+ {
+ var ok = IntraNeighbour(xL, yL, (x0 + k) << shift, (y0 - 1) << shift, constrained);
+ if (ok)
+ {
+ plane.AsSpan(((y0 - 1) * stride) + x0 + k, unit).CopyTo(refRow);
+ for (var j = 0; j < unit; j++)
+ {
+ line[n2 + 1 + k + j] = refRow[j];
+ }
+ }
+
+ for (var j = 0; j < unit; j++)
+ {
+ available[n2 + 1 + k + j] = ok;
+ }
+
+ any |= ok;
+ }
+
+ // Substitution (§8.4.4.2.2).
+ if (!any)
+ {
+ line.Fill(1 << (bitDepth - 1));
+ }
+ else
+ {
+ if (!available[0])
+ {
+ for (var i = 1; i < line.Length; i++)
+ {
+ if (available[i])
+ {
+ line[0] = line[i];
+ break;
+ }
+ }
+ }
+
+ for (var i = 1; i < line.Length; i++)
+ {
+ if (!available[i])
+ {
+ line[i] = line[i - 1];
+ }
+ }
+ }
+
+ // Filtering (§8.4.4.2.3), luma only in 4:2:0.
+ Span p = line;
+ if (cIdx == 0 && mode != 1 && n != 4)
+ {
+ var minDistVerHor = Math.Min(Math.Abs(mode - 26), Math.Abs(mode - 10));
+ var threshold = n == 8 ? 7 : n == 16 ? 1 : 0;
+ if (minDistVerHor > threshold)
+ {
+ var filtered = refFiltered.AsSpan(0, line.Length);
+ var last = 4 * n;
+ var limit = 1 << (bitDepth - 5);
+ if (sps.StrongIntraSmoothing && n == 32
+ && Math.Abs(line[n2] + line[last] - (2 * line[n2 + n])) < limit
+ && Math.Abs(line[n2] + line[0] - (2 * line[n2 - n])) < limit)
+ {
+ filtered[0] = line[0];
+ filtered[n2] = line[n2];
+ filtered[last] = line[last];
+ for (var i = 0; i < 63; i++)
+ {
+ filtered[n2 - 1 - i] = (((63 - i) * line[n2]) + ((i + 1) * line[0]) + 32) >> 6;
+ filtered[n2 + 1 + i] = (((63 - i) * line[n2]) + ((i + 1) * line[last]) + 32) >> 6;
+ }
+ }
+ else
+ {
+ filtered[0] = line[0];
+ filtered[last] = line[last];
+ for (var i = 1; i < last; i++)
+ {
+ filtered[i] = (line[i - 1] + (2 * line[i]) + line[i + 1] + 2) >> 2;
+ }
+ }
+
+ p = filtered;
+ }
+ }
+
+ var max = (1 << bitDepth) - 1;
+ if (mode == 0)
+ {
+ // Planar (§8.4.4.2.5).
+ var topRight = p[n2 + 1 + n];
+ var bottomLeft = p[n2 - 1 - n];
+ for (var y = 0; y < n; y++)
+ {
+ var row = ((y0 + y) * stride) + x0;
+ var left = p[n2 - 1 - y];
+ for (var x = 0; x < n; x++)
+ {
+ plane[row + x] = (ushort)((((n - 1 - x) * left) + ((x + 1) * topRight) + ((n - 1 - y) * p[n2 + 1 + x]) + ((y + 1) * bottomLeft) + n) >> (log2 + 1));
+ }
+ }
+ }
+ else if (mode == 1)
+ {
+ // DC (§8.4.4.2.6), with the edge filter for luma blocks below 32×32.
+ var sum = n;
+ for (var i = 0; i < n; i++)
+ {
+ sum += p[n2 + 1 + i] + p[n2 - 1 - i];
+ }
+
+ var dc = sum >> (log2 + 1);
+ for (var y = 0; y < n; y++)
+ {
+ plane.AsSpan(((y0 + y) * stride) + x0, n).Fill((ushort)dc);
+ }
+
+ if (cIdx == 0 && n < 32)
+ {
+ plane[(y0 * stride) + x0] = (ushort)((p[n2 - 1] + (2 * dc) + p[n2 + 1] + 2) >> 2);
+ for (var x = 1; x < n; x++)
+ {
+ plane[(y0 * stride) + x0 + x] = (ushort)((p[n2 + 1 + x] + (3 * dc) + 2) >> 2);
+ }
+
+ for (var y = 1; y < n; y++)
+ {
+ plane[((y0 + y) * stride) + x0] = (ushort)((p[n2 - 1 - y] + (3 * dc) + 2) >> 2);
+ }
+ }
+ }
+ else
+ {
+ // Angular (§8.4.4.2.6): ref[x] for x from −N to 2N, at refMain[N + x].
+ int angle = H265Tables.IntraPredAngle[mode];
+ var refs = refMain.AsSpan(0, (3 * n) + 1);
+ var vertical = mode >= 18;
+ for (var x = 0; x <= n; x++)
+ {
+ refs[n + x] = vertical ? p[n2 + x] : p[n2 - x];
+ }
+
+ if (angle < 0)
+ {
+ var invAngle = H265Tables.InvAngle[mode - 11];
+ var lowest = (n * angle) >> 5;
+ if (lowest < -1)
+ {
+ for (var x = lowest; x <= -1; x++)
+ {
+ var offset = ((x * invAngle) + 128) >> 8;
+ refs[n + x] = vertical ? p[n2 - offset] : p[n2 + offset];
+ }
+ }
+ }
+ else
+ {
+ for (var x = n + 1; x <= n2; x++)
+ {
+ refs[n + x] = vertical ? p[n2 + x] : p[n2 - x];
+ }
+ }
+
+ for (var j = 0; j < n; j++)
+ {
+ var iIdx = ((j + 1) * angle) >> 5;
+ var iFact = ((j + 1) * angle) & 31;
+ for (var i = 0; i < n; i++)
+ {
+ var a = n + i + iIdx + 1;
+ var value = iFact != 0 ? (((32 - iFact) * refs[a]) + (iFact * refs[a + 1]) + 16) >> 5 : refs[a];
+
+ // For vertical modes j is the row and i the column; for horizontal ones the other way round.
+ var position = vertical ? ((y0 + j) * stride) + x0 + i : ((y0 + i) * stride) + x0 + j;
+ plane[position] = (ushort)value;
+ }
+ }
+
+ if (cIdx == 0 && n < 32)
+ {
+ if (mode == 26)
+ {
+ for (var y = 0; y < n; y++)
+ {
+ plane[((y0 + y) * stride) + x0] = (ushort)Math.Clamp(p[n2 + 1] + ((p[n2 - 1 - y] - p[n2]) >> 1), 0, max);
+ }
+ }
+ else if (mode == 10)
+ {
+ for (var x = 0; x < n; x++)
+ {
+ plane[(y0 * stride) + x0 + x] = (ushort)Math.Clamp(p[n2 - 1] + ((p[n2 + 1 + x] - p[n2]) >> 1), 0, max);
+ }
+ }
+ }
+ }
+ }
+
+ private readonly ushort[] refRow = new ushort[4];
+
+ /// Whether a neighbouring sample can be used for intra prediction (§8.4.4.2.2), in luma locations.
+ private bool IntraNeighbour(int xCur, int yCur, int xN, int yN, bool constrained)
+ {
+ if (!Available(xCur, yCur, xN, yN))
+ {
+ return false;
+ }
+
+ return !constrained || predMode[Grid(xN, yN)] == ModeIntra;
+ }
+}
diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.Residual.cs b/src/Febe.Core/Codecs/H265/H265Decoder.Residual.cs
new file mode 100644
index 0000000..bde9ba4
--- /dev/null
+++ b/src/Febe.Core/Codecs/H265/H265Decoder.Residual.cs
@@ -0,0 +1,449 @@
+namespace Febe.Core.Codecs.H265;
+
+/// residual_coding() (§7.3.8.11) and the scaling, transformation and reconstruction of §8.6.
+public sealed partial class H265Decoder
+{
+ /// ctxIdxMap of sig_coeff_flag in 4×4 blocks (9-55), by raster position.
+ private static readonly byte[] s_sigCtxMap4x4 = [0, 1, 4, 5, 2, 3, 4, 5, 6, 6, 8, 8, 7, 7, 8, 8];
+
+ /// TransCoeffLevel of the block being decoded, raster order (y << log2) + x; zero outside it.
+ private readonly int[] coefficients = new int[32 * 32];
+
+ /// Raster positions of the nonzero entries of .
+ private readonly short[] nonzero = new short[32 * 32];
+
+ private readonly int[] residual = new int[32 * 32];
+ private readonly int[] transformTemp = new int[32 * 32];
+ private readonly byte[] codedSubBlocks = new byte[64];
+
+ /// Decodes the residual of one transform block and adds it to the prediction in the picture.
+ /// Colour component.
+ /// Left of the block, in samples of the component.
+ /// Top of the block, in samples of the component.
+ /// Log2 of the block size.
+ /// The intra prediction mode of the block, −1 for inter.
+ private void Residual(int cIdx, int x0, int y0, int log2, int predModeIntra)
+ {
+ var count = ParseResidual(cIdx, log2, predModeIntra, out var transformSkip, out var maxX, out var maxY);
+ var size = 1 << log2;
+ var bitDepth = cIdx == 0 ? sps.BitDepthY : sps.BitDepthC;
+ var total = size * size;
+ if (cuTransquantBypass)
+ {
+ Array.Copy(coefficients, residual, total);
+ }
+ else
+ {
+ Dequantise(cIdx, log2, count, bitDepth);
+ if (transformSkip)
+ {
+ // §8.6.4.2: r = d << tsShift, then the same rounding as after a transform.
+ var tsShift = 5 + log2;
+ var bdShift = 20 - bitDepth;
+ var add = 1 << (bdShift - 1);
+ for (var i = 0; i < total; i++)
+ {
+ residual[i] = ((coefficients[i] << tsShift) + add) >> bdShift;
+ }
+ }
+ else if (count == 1 && nonzero[0] == 0 && !(cuIntra && cIdx == 0 && log2 == 2))
+ {
+ // Only the DC coefficient of a DCT: the two passes give one value everywhere.
+ var bdShift = 20 - bitDepth;
+ var first = Math.Clamp(((coefficients[0] * 64) + 64) >> 7, short.MinValue, short.MaxValue);
+ var value = ((first * 64) + (1 << (bdShift - 1))) >> bdShift;
+ residual.AsSpan(0, total).Fill(value);
+ }
+ else
+ {
+ Transform.Inverse(coefficients, residual, transformTemp, log2, cIdx == 0 && cuIntra && log2 == 2, maxX, maxY, bitDepth);
+ }
+ }
+
+ // Clear the coefficients for the next block.
+ for (var i = 0; i < count; i++)
+ {
+ coefficients[nonzero[i]] = 0;
+ }
+
+ var plane = cur!.Planes[cIdx];
+ var stride = cur.Stride(cIdx);
+ var max = (1 << bitDepth) - 1;
+ for (var y = 0; y < size; y++)
+ {
+ var row = ((y0 + y) * stride) + x0;
+ var r = y << log2;
+ for (var x = 0; x < size; x++)
+ {
+ plane[row + x] = (ushort)Math.Clamp(plane[row + x] + residual[r + x], 0, max);
+ }
+ }
+ }
+
+ /// The scaling process for transform coefficients (§8.6.3), on the nonzero coefficients.
+ private void Dequantise(int cIdx, int log2, int count, int bitDepth)
+ {
+ int qp;
+ if (cIdx == 0)
+ {
+ qp = qpY + sps.QpBdOffsetY;
+ }
+ else
+ {
+ var offset = cIdx == 1 ? pps.CbQpOffset + slice.CbQpOffset + cuQpOffsetCb : pps.CrQpOffset + slice.CrQpOffset + cuQpOffsetCr;
+ var qPi = Math.Clamp(qpY + offset, -sps.QpBdOffsetC, 57);
+ var qPc = qPi < 30 ? qPi : qPi > 43 ? qPi - 6 : H265Tables.ChromaQp30To43[qPi - 30];
+ qp = qPc + sps.QpBdOffsetC;
+ }
+
+ var bdShift = bitDepth + log2 - 5;
+ var add = 1L << (bdShift - 1);
+ var scale = (long)H265Tables.LevelScale[qp % 6] << (qp / 6);
+ var list = pps.ScalingList ?? sps.ScalingList;
+ byte[]? factors = null;
+ if (sps.ScalingListEnabled && list is not null)
+ {
+ factors = list.Factors[((log2 - 2) * 6) + (cuIntra ? 0 : 3) + cIdx];
+ }
+
+ for (var i = 0; i < count; i++)
+ {
+ int position = nonzero[i];
+ long m = factors is null ? 16 : factors[position];
+ var value = ((coefficients[position] * m * scale) + add) >> bdShift;
+ coefficients[position] = (int)Math.Clamp(value, short.MinValue, short.MaxValue);
+ }
+ }
+
+ ///
+ /// residual_coding(): fills and ; returns the number of nonzero
+ /// coefficients and the largest column and row that hold one.
+ ///
+ private int ParseResidual(int cIdx, int log2, int predModeIntra, out bool transformSkip, out int maxX, out int maxY)
+ {
+ transformSkip = false;
+ if (pps.TransformSkipEnabled && !cuTransquantBypass && log2 <= pps.Log2MaxTransformSkipSize)
+ {
+ transformSkip = cabac.Flag(CabacTables.TransformSkipFlag + (cIdx == 0 ? 0 : 1));
+ }
+
+ // last_sig_coeff_x_prefix, last_sig_coeff_y_prefix and their suffixes (§9.3.4.2.3).
+ int ctxOffset, ctxShift;
+ if (cIdx == 0)
+ {
+ ctxOffset = (3 * (log2 - 2)) + ((log2 - 1) >> 2);
+ ctxShift = (log2 + 1) >> 2;
+ }
+ else
+ {
+ ctxOffset = 15;
+ ctxShift = log2 - 2;
+ }
+
+ var cMax = (log2 << 1) - 1;
+ var prefixX = 0;
+ while (prefixX < cMax && cabac.Flag(CabacTables.LastSigCoeffXPrefix + ctxOffset + (prefixX >> ctxShift)))
+ {
+ prefixX++;
+ }
+
+ var prefixY = 0;
+ while (prefixY < cMax && cabac.Flag(CabacTables.LastSigCoeffYPrefix + ctxOffset + (prefixY >> ctxShift)))
+ {
+ prefixY++;
+ }
+
+ var lastX = prefixX;
+ if (prefixX > 3)
+ {
+ var bits = (prefixX >> 1) - 1;
+ lastX = ((2 + (prefixX & 1)) << bits) + cabac.BypassBits(bits);
+ }
+
+ var lastY = prefixY;
+ if (prefixY > 3)
+ {
+ var bits = (prefixY >> 1) - 1;
+ lastY = ((2 + (prefixY & 1)) << bits) + cabac.BypassBits(bits);
+ }
+
+ // scanIdx (§7.4.9.11): mode-dependent scans for intra 4×4 blocks and 8×8 luma blocks.
+ var scanIdx = 0;
+ if (predModeIntra >= 0 && (log2 == 2 || (log2 == 3 && cIdx == 0)))
+ {
+ if (predModeIntra is >= 6 and <= 14)
+ {
+ scanIdx = 2;
+ }
+ else if (predModeIntra is >= 22 and <= 30)
+ {
+ scanIdx = 1;
+ }
+ }
+
+ if (scanIdx == 2)
+ {
+ (lastX, lastY) = (lastY, lastX);
+ }
+
+ var size = 1 << log2;
+ if (lastX >= size || lastY >= size)
+ {
+ throw new H265Exception("Ultimo coefficiente fuori dal blocco.");
+ }
+
+ var log2Sb = log2 - 2;
+ var sbWidth = 1 << log2Sb;
+ var sbScan = H265Tables.ScanOrder[log2Sb][scanIdx];
+ var scan4 = H265Tables.ScanOrder[2][scanIdx];
+ var lastSubBlock = 0;
+ var lastPacked = (ushort)((lastX >> 2) | ((lastY >> 2) << 8));
+ for (var i = 0; i < sbScan.Length; i++)
+ {
+ if (sbScan[i] == lastPacked)
+ {
+ lastSubBlock = i;
+ break;
+ }
+ }
+
+ var lastScanPos = H265Tables.ScanPosition4x4[scanIdx][((lastY & 3) << 2) + (lastX & 3)];
+ codedSubBlocks.AsSpan(0, sbWidth * sbWidth).Clear();
+
+ var signHidingEnabled = pps.SignDataHidingEnabled && !cuTransquantBypass;
+ var greater1Ctx = 1;
+ var firstSubBlock = true;
+ var count = 0;
+ maxX = 0;
+ maxY = 0;
+ Span sigPositions = stackalloc int[16];
+ Span levels = stackalloc int[16];
+ var ctxBase = CabacTables.SigCoeffFlag + (cIdx == 0 ? 0 : 27);
+ for (var i = lastSubBlock; i >= 0; i--)
+ {
+ var xS = sbScan[i] & 0xFF;
+ var yS = sbScan[i] >> 8;
+ var inferSbDcSigCoeff = false;
+ bool coded;
+ if (i < lastSubBlock && i > 0)
+ {
+ var csbfCtx = 0;
+ if (xS < sbWidth - 1)
+ {
+ csbfCtx += codedSubBlocks[(yS * sbWidth) + xS + 1];
+ }
+
+ if (yS < sbWidth - 1)
+ {
+ csbfCtx += codedSubBlocks[((yS + 1) * sbWidth) + xS];
+ }
+
+ coded = cabac.Flag(CabacTables.CodedSubBlockFlag + Math.Min(csbfCtx, 1) + (cIdx == 0 ? 0 : 2));
+ inferSbDcSigCoeff = true;
+ }
+ else
+ {
+ coded = true;
+ }
+
+ codedSubBlocks[(yS * sbWidth) + xS] = (byte)(coded ? 1 : 0);
+
+ // prevCsbf for the contexts of sig_coeff_flag (§9.3.4.2.5).
+ var prevCsbf = 0;
+ if (xS < sbWidth - 1)
+ {
+ prevCsbf += codedSubBlocks[(yS * sbWidth) + xS + 1];
+ }
+
+ if (yS < sbWidth - 1)
+ {
+ prevCsbf += codedSubBlocks[((yS + 1) * sbWidth) + xS] << 1;
+ }
+
+ // Significant coefficients, from the last scan position of the sub-block down to 0.
+ var sigCount = 0;
+ var start = 15;
+ if (i == lastSubBlock)
+ {
+ start = lastScanPos - 1;
+ sigPositions[sigCount++] = lastScanPos;
+ }
+
+ if (coded)
+ {
+ for (var n = start; n >= 0; n--)
+ {
+ var xP = scan4[n] & 0xFF;
+ var yP = scan4[n] >> 8;
+ if (n > 0 || !inferSbDcSigCoeff)
+ {
+ int sigCtx;
+ if (log2 == 2)
+ {
+ sigCtx = s_sigCtxMap4x4[(yP << 2) + xP];
+ }
+ else if (xS == 0 && yS == 0 && xP == 0 && yP == 0)
+ {
+ sigCtx = 0;
+ }
+ else
+ {
+ sigCtx = prevCsbf switch
+ {
+ 0 => xP + yP == 0 ? 2 : xP + yP < 3 ? 1 : 0,
+ 1 => yP == 0 ? 2 : yP == 1 ? 1 : 0,
+ 2 => xP == 0 ? 2 : xP == 1 ? 1 : 0,
+ _ => 2,
+ };
+ if (cIdx == 0)
+ {
+ if (xS > 0 || yS > 0)
+ {
+ sigCtx += 3;
+ }
+
+ sigCtx += log2 == 3 ? (scanIdx == 0 ? 9 : 15) : 21;
+ }
+ else
+ {
+ sigCtx += log2 == 3 ? 9 : 12;
+ }
+ }
+
+ if (cabac.Flag(ctxBase + sigCtx))
+ {
+ sigPositions[sigCount++] = n;
+ inferSbDcSigCoeff = false;
+ }
+ }
+ else
+ {
+ // n == 0 with every other flag of a coded sub-block zero: the DC is inferred significant.
+ sigPositions[sigCount++] = 0;
+ }
+ }
+ }
+
+ if (sigCount == 0)
+ {
+ continue;
+ }
+
+ // coeff_abs_level_greater1_flag for the first 8, then greater2 for the first of them that is 1 (§9.3.4.2.6).
+ var ctxSet = i == 0 || cIdx > 0 ? 0 : 2;
+ if (!firstSubBlock && greater1Ctx == 0)
+ {
+ ctxSet++;
+ }
+
+ firstSubBlock = false;
+ greater1Ctx = 1;
+ var firstGreater1 = -1;
+ var g1Base = CabacTables.CoeffAbsLevelGreater1Flag + (cIdx == 0 ? 0 : 16);
+ var limit = Math.Min(sigCount, 8);
+ for (var k = 0; k < sigCount; k++)
+ {
+ levels[k] = 1;
+ }
+
+ for (var k = 0; k < limit; k++)
+ {
+ var flag = cabac.Flag(g1Base + (ctxSet * 4) + Math.Min(3, greater1Ctx));
+ if (flag)
+ {
+ levels[k] = 2;
+ greater1Ctx = 0;
+ if (firstGreater1 < 0)
+ {
+ firstGreater1 = k;
+ }
+ }
+ else if (greater1Ctx > 0)
+ {
+ greater1Ctx++;
+ }
+ }
+
+ if (firstGreater1 >= 0 && cabac.Flag(CabacTables.CoeffAbsLevelGreater2Flag + ctxSet + (cIdx == 0 ? 0 : 4)))
+ {
+ levels[firstGreater1] = 3;
+ }
+
+ var firstSigScanPos = sigPositions[sigCount - 1];
+ var lastSigScanPos = sigPositions[0];
+ var signHidden = signHidingEnabled && lastSigScanPos - firstSigScanPos > 3;
+ var signCount = signHidden ? sigCount - 1 : sigCount;
+ var signs = cabac.BypassBits(signCount) << (32 - signCount);
+ if (signCount == 0)
+ {
+ signs = 0;
+ }
+
+ // coeff_abs_level_remaining (§9.3.3.11) with the Rice parameter of §9.3.3.11 (v1: starts at 0, at most 4).
+ var rice = 0;
+ var sumAbs = 0;
+ for (var k = 0; k < sigCount; k++)
+ {
+ var baseLevel = levels[k];
+ var absolute = baseLevel;
+ if (baseLevel == (k < 8 ? (k == firstGreater1 ? 3 : 2) : 1))
+ {
+ var remaining = CoeffAbsLevelRemaining(rice);
+ absolute = baseLevel + remaining;
+ if (absolute > 3 * (1 << rice))
+ {
+ rice = Math.Min(rice + 1, 4);
+ }
+ }
+
+ var n = sigPositions[k];
+ var xC = (xS << 2) + (scan4[n] & 0xFF);
+ var yC = (yS << 2) + (scan4[n] >> 8);
+ var value = absolute;
+ if (k < signCount)
+ {
+ if (signs < 0)
+ {
+ value = -value;
+ }
+
+ signs <<= 1;
+ }
+
+ sumAbs += absolute;
+ if (signHidden && k == sigCount - 1 && (sumAbs & 1) == 1)
+ {
+ value = -value;
+ }
+
+ var position = (yC << log2) + xC;
+ coefficients[position] = value;
+ nonzero[count++] = (short)position;
+ maxX = Math.Max(maxX, xC);
+ maxY = Math.Max(maxY, yC);
+ }
+ }
+
+ return count;
+ }
+
+ private int CoeffAbsLevelRemaining(int rice)
+ {
+ var prefix = 0;
+ while (cabac.Bypass() == 1)
+ {
+ if (++prefix > 32)
+ {
+ throw new H265Exception("coeff_abs_level_remaining non valido.");
+ }
+ }
+
+ if (prefix <= 3)
+ {
+ return (prefix << rice) + (rice > 0 ? cabac.BypassBits(rice) : 0);
+ }
+
+ var bits = prefix - 3 + rice;
+ return (((1 << (prefix - 3)) + 3 - 1) << rice) + ReadBypass(bits);
+ }
+}
diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.Slice.cs b/src/Febe.Core/Codecs/H265/H265Decoder.Slice.cs
new file mode 100644
index 0000000..b36e0a7
--- /dev/null
+++ b/src/Febe.Core/Codecs/H265/H265Decoder.Slice.cs
@@ -0,0 +1,1169 @@
+namespace Febe.Core.Codecs.H265;
+
+/// Slice segment data (§7.3.8): coding tree units, coding quadtree, coding units, prediction units and transform tree.
+public sealed partial class H265Decoder
+{
+ private const byte ModeIntra = 1;
+ private const byte ModeInter = 2;
+ private const byte ModeSkip = 3;
+
+ /// Samples that no in-loop filter changes: PCM with pcm_loop_filter_disabled_flag, cu_transquant_bypass_flag.
+ private const byte FlagNoFilter = 1;
+
+ /// A luma transform block with coefficients (for the boundary strength of §8.7.2.4).
+ private const byte FlagCoded = 2;
+
+ private const byte FlagPcm = 4;
+
+ private const int Part2Nx2N = 0;
+ private const int Part2NxN = 1;
+ private const int PartNx2N = 2;
+ private const int PartNxN = 3;
+ private const int Part2NxnU = 4;
+ private const int Part2NxnD = 5;
+ private const int PartnLx2N = 6;
+ private const int PartnRx2N = 7;
+
+ /// Z-scan order of the 4×4 blocks of a CTB (up to 16×16 of them), by (y << 4) | x (§6.5.2).
+ private static readonly ushort[] s_zOrder = BuildZOrder();
+
+ private readonly CabacEngine cabac = new();
+ private readonly byte[] wppContexts = new byte[CabacTables.ContextCount];
+ private readonly byte[] dsContexts = new byte[CabacTables.ContextCount];
+ private readonly List slices = [];
+
+ private Picture? cur;
+ private Sps sps = null!;
+ private Pps pps = null!;
+ private SliceHeader? sliceHeader;
+
+ // Per picture, on the grid of 4×4 luma blocks.
+ private int w4;
+ private int h4;
+ private byte[] predMode = [];
+ private byte[] ctDepthMap = [];
+ private byte[] intraModeMap = [];
+ private sbyte[] qpMap = [];
+ private byte[] blockFlags = [];
+
+ /// Edges of §8.7.2 at the left (edgeV) and the top (edgeH) of each 4×4 block: 0 none, 1 prediction, 2 transform.
+ private byte[] edgeV = [];
+
+ private byte[] edgeH = [];
+
+ /// Index in of the slice of each CTB (raster order), −1 while not decoded.
+ private int[] ctbSlice = [];
+
+ /// SAO parameters by CTB and component: type (0 none, 1 band, 2 edge), class or band position, 4 offsets.
+ private byte[] saoType = [];
+
+ private byte[] saoClass = [];
+ private short[] saoOffset = [];
+ private bool pictureHasUnfilteredBlocks;
+
+ // The slice segment being decoded.
+ private SliceHeader slice = null!;
+ private int sliceIdx;
+ private byte[] data = [];
+ private int dataEnd;
+ private int ctbAddrRs;
+ private int ctbX;
+ private int ctbY;
+ private int widthInCtbs;
+
+ // Quantisation (§8.6.1).
+ private int log2MinCuQpDeltaSize;
+ private bool isCuQpDeltaCoded;
+ private int cuQpDeltaVal;
+ private int qpYPrev;
+ private int qpYPred;
+ private int qpY;
+ private bool resetQpPrev;
+ private bool isCuChromaQpOffsetCoded;
+ private int cuQpOffsetCb;
+ private int cuQpOffsetCr;
+
+ // The coding unit being decoded.
+ private int cuX;
+ private int cuY;
+ private int cuLog2;
+ private bool cuIntra;
+ private bool cuTransquantBypass;
+ private int cuPartMode;
+ private int cuIntraModeC;
+ private int cuMaxTrafoDepth;
+ private bool cuIntraSplit;
+
+ private void StartPictureData(Sps s, Pps p)
+ {
+ sps = s;
+ pps = p;
+ slices.Clear();
+ widthInCtbs = s.WidthInCtbs;
+ var nw = (s.Width + 3) >> 2;
+ var nh = (s.Height + 3) >> 2;
+ if (nw != w4 || nh != h4)
+ {
+ w4 = nw;
+ h4 = nh;
+ var count = nw * nh;
+ predMode = new byte[count];
+ ctDepthMap = new byte[count];
+ intraModeMap = new byte[count];
+ qpMap = new sbyte[count];
+ blockFlags = new byte[count];
+ edgeV = new byte[count];
+ edgeH = new byte[count];
+ }
+ else
+ {
+ Array.Clear(predMode);
+ Array.Clear(blockFlags);
+ Array.Clear(edgeV);
+ Array.Clear(edgeH);
+ }
+
+ var ctbs = s.CtbCount;
+ if (ctbSlice.Length != ctbs)
+ {
+ ctbSlice = new int[ctbs];
+ saoType = new byte[ctbs * 3];
+ saoClass = new byte[ctbs * 3];
+ saoOffset = new short[ctbs * 12];
+ }
+
+ Array.Fill(ctbSlice, -1);
+ Array.Clear(saoType);
+ pictureHasUnfilteredBlocks = false;
+ log2MinCuQpDeltaSize = s.Log2CtbSize - p.DiffCuQpDeltaDepth;
+ }
+
+ private void DecodeSliceData(H265NalUnit nal, SliceHeader h)
+ {
+ slice = h;
+ if (!h.Dependent)
+ {
+ sliceIdx = slices.Count - 1;
+ resetQpPrev = true;
+ }
+
+ data = nal.Rbsp;
+ dataEnd = nal.Length;
+ ctbAddrRs = h.SegmentAddress;
+ if (ctbSlice[ctbAddrRs] >= 0)
+ {
+ throw new H265Exception("Segmento di slice sovrapposto a uno già decodificato.");
+ }
+
+ var ctbAddrTs = pps.CtbAddrRsToTs[ctbAddrRs];
+ cabac.Start(data, h.DataOffset * 8, dataEnd);
+ var firstInSegment = true;
+ var initType = h.InitType;
+ while (true)
+ {
+ ctbX = ctbAddrRs % widthInCtbs;
+ ctbY = ctbAddrRs / widthInCtbs;
+ var tile = pps.TileIdRs[ctbAddrRs];
+ var colStart = pps.ColBd[tile % pps.NumTileColumns];
+ var rowStart = pps.RowBd[tile / pps.NumTileColumns];
+ var tileStart = ctbX == colStart && ctbY == rowStart;
+ var wppRowStart = pps.EntropyCodingSyncEnabled && ctbX == colStart;
+ if (firstInSegment || tileStart || wppRowStart)
+ {
+ // Initialisation of the context variables (§9.3.2.2 to §9.3.2.4).
+ if (tileStart)
+ {
+ cabac.InitContexts(initType, h.SliceQpY);
+ }
+ else if (wppRowStart)
+ {
+ var topRight = ctbAddrRs - widthInCtbs + 1;
+ var available = ctbY > 0 && ctbX + 1 < widthInCtbs && ctbSlice[topRight] == sliceIdx && pps.TileIdRs[topRight] == tile;
+ if (available)
+ {
+ wppContexts.CopyTo(cabac.Contexts, 0);
+ }
+ else
+ {
+ cabac.InitContexts(initType, h.SliceQpY);
+ }
+ }
+ else if (h.Dependent)
+ {
+ dsContexts.CopyTo(cabac.Contexts, 0);
+ }
+ else
+ {
+ cabac.InitContexts(initType, h.SliceQpY);
+ }
+ }
+
+ if (tileStart || wppRowStart)
+ {
+ resetQpPrev = true;
+ }
+
+ ctbSlice[ctbAddrRs] = sliceIdx;
+ CodingTreeUnit();
+ if (pps.EntropyCodingSyncEnabled && ctbX - colStart <= 1)
+ {
+ cabac.Contexts.CopyTo(wppContexts, 0);
+ }
+
+ var end = cabac.Terminate() == 1;
+ ctbAddrTs++;
+ if (end)
+ {
+ if (pps.DependentSliceSegmentsEnabled)
+ {
+ cabac.Contexts.CopyTo(dsContexts, 0);
+ }
+
+ return;
+ }
+
+ if (ctbAddrTs >= sps.CtbCount)
+ {
+ throw new H265Exception("Slice che continua oltre l'ultimo CTB.");
+ }
+
+ var nextRs = pps.CtbAddrTsToRs[ctbAddrTs];
+ var nextTile = pps.TileIdRs[nextRs];
+ var nextX = nextRs % widthInCtbs;
+ if ((pps.TilesEnabled && nextTile != tile)
+ || (pps.EntropyCodingSyncEnabled && nextX == pps.ColBd[nextTile % pps.NumTileColumns]))
+ {
+ // end_of_subset_one_bit, byte_alignment() and a new substream (§9.3.2.5).
+ if (cabac.Terminate() != 1)
+ {
+ throw new H265Exception("Fine di un sottoflusso CABAC non valida.");
+ }
+
+ var position = (cabac.BitPosition + 7) & ~7;
+ cabac.Start(data, position, dataEnd);
+ }
+
+ ctbAddrRs = nextRs;
+ firstInSegment = false;
+ }
+ }
+
+ private void CodingTreeUnit()
+ {
+ var log2 = sps.Log2CtbSize;
+ if (slice.SaoLuma || slice.SaoChroma)
+ {
+ ParseSao();
+ }
+
+ CodingQuadtree(ctbX << log2, ctbY << log2, log2, 0);
+ }
+
+ /// sao() (§7.3.8.3).
+ private void ParseSao()
+ {
+ var rs = ctbAddrRs;
+ var merge = -1;
+ if (ctbX > 0 && rs > slice.SliceAddress && pps.TileIdRs[rs] == pps.TileIdRs[rs - 1] && cabac.Flag(CabacTables.SaoMergeFlag))
+ {
+ merge = rs - 1;
+ }
+
+ if (merge < 0 && ctbY > 0 && rs - widthInCtbs >= slice.SliceAddress && pps.TileIdRs[rs] == pps.TileIdRs[rs - widthInCtbs]
+ && cabac.Flag(CabacTables.SaoMergeFlag))
+ {
+ merge = rs - widthInCtbs;
+ }
+
+ if (merge >= 0)
+ {
+ Array.Copy(saoType, merge * 3, saoType, rs * 3, 3);
+ Array.Copy(saoClass, merge * 3, saoClass, rs * 3, 3);
+ Array.Copy(saoOffset, merge * 12, saoOffset, rs * 12, 12);
+ return;
+ }
+
+ Span magnitude = stackalloc int[4];
+ for (var cIdx = 0; cIdx < 3; cIdx++)
+ {
+ var at = (rs * 3) + cIdx;
+ if (!(cIdx == 0 ? slice.SaoLuma : slice.SaoChroma))
+ {
+ saoType[at] = 0;
+ continue;
+ }
+
+ if (cIdx == 2)
+ {
+ saoType[at] = saoType[at - 1];
+ saoClass[at] = saoClass[at - 1];
+ }
+ else
+ {
+ // sao_type_idx: TR with cMax 2, the first bin with its context, the second bypass.
+ saoType[at] = (byte)(!cabac.Flag(CabacTables.SaoTypeIdx) ? 0 : cabac.Bypass() == 0 ? 1 : 2);
+ }
+
+ if (saoType[at] == 0)
+ {
+ continue;
+ }
+
+ var bitDepth = cIdx == 0 ? sps.BitDepthY : sps.BitDepthC;
+ var cMax = (1 << (Math.Min(bitDepth, 10) - 5)) - 1;
+ for (var i = 0; i < 4; i++)
+ {
+ var value = 0;
+ while (value < cMax && cabac.Bypass() == 1)
+ {
+ value++;
+ }
+
+ magnitude[i] = value;
+ }
+
+ var scale = cIdx == 0 ? pps.Log2SaoOffsetScaleLuma : pps.Log2SaoOffsetScaleChroma;
+ if (saoType[at] == 1)
+ {
+ for (var i = 0; i < 4; i++)
+ {
+ if (magnitude[i] != 0 && cabac.Bypass() == 1)
+ {
+ magnitude[i] = -magnitude[i];
+ }
+ }
+
+ saoClass[at] = (byte)cabac.BypassBits(5);
+ for (var i = 0; i < 4; i++)
+ {
+ saoOffset[(at * 4) + i] = (short)(magnitude[i] << scale);
+ }
+ }
+ else
+ {
+ if (cIdx < 2)
+ {
+ saoClass[at] = (byte)cabac.BypassBits(2);
+ }
+
+ // Edge offsets: the first two are positive, the last two negative.
+ saoOffset[(at * 4) + 0] = (short)(magnitude[0] << scale);
+ saoOffset[(at * 4) + 1] = (short)(magnitude[1] << scale);
+ saoOffset[(at * 4) + 2] = (short)(-(magnitude[2] << scale));
+ saoOffset[(at * 4) + 3] = (short)(-(magnitude[3] << scale));
+ }
+ }
+ }
+
+ private void CodingQuadtree(int x0, int y0, int log2, int depth)
+ {
+ var size = 1 << log2;
+ bool split;
+ if (x0 + size <= sps.Width && y0 + size <= sps.Height && log2 > sps.Log2MinCbSize)
+ {
+ var ctx = 0;
+ if (Available(x0, y0, x0 - 1, y0) && ctDepthMap[Grid(x0 - 1, y0)] > depth)
+ {
+ ctx++;
+ }
+
+ if (Available(x0, y0, x0, y0 - 1) && ctDepthMap[Grid(x0, y0 - 1)] > depth)
+ {
+ ctx++;
+ }
+
+ split = cabac.Flag(CabacTables.SplitCuFlag + ctx);
+ }
+ else
+ {
+ split = log2 > sps.Log2MinCbSize;
+ }
+
+ if (pps.CuQpDeltaEnabled && log2 >= log2MinCuQpDeltaSize)
+ {
+ isCuQpDeltaCoded = false;
+ cuQpDeltaVal = 0;
+ }
+
+ if (slice.CuChromaQpOffsetEnabled && log2 >= sps.Log2CtbSize - pps.DiffCuChromaQpOffsetDepth)
+ {
+ isCuChromaQpOffsetCoded = false;
+ }
+
+ if (split)
+ {
+ var half = size >> 1;
+ CodingQuadtree(x0, y0, log2 - 1, depth + 1);
+ if (x0 + half < sps.Width)
+ {
+ CodingQuadtree(x0 + half, y0, log2 - 1, depth + 1);
+ }
+
+ if (y0 + half < sps.Height)
+ {
+ CodingQuadtree(x0, y0 + half, log2 - 1, depth + 1);
+ }
+
+ if (x0 + half < sps.Width && y0 + half < sps.Height)
+ {
+ CodingQuadtree(x0 + half, y0 + half, log2 - 1, depth + 1);
+ }
+ }
+ else
+ {
+ CodingUnit(x0, y0, log2, depth);
+ }
+ }
+
+ private void CodingUnit(int x0, int y0, int log2, int depth)
+ {
+ var size = 1 << log2;
+ cuX = x0;
+ cuY = y0;
+ cuLog2 = log2;
+
+ // The predicted QP of a quantisation group (§8.6.1), at its first coding unit.
+ var qgMask = (1 << log2MinCuQpDeltaSize) - 1;
+ if ((x0 & qgMask) == 0 && (y0 & qgMask) == 0)
+ {
+ if (resetQpPrev)
+ {
+ qpYPrev = slice.SliceQpY;
+ resetQpPrev = false;
+ }
+
+ var ctbMask = ~((1 << sps.Log2CtbSize) - 1);
+ var qpA = (x0 & ~ctbMask) != 0 ? qpMap[Grid(x0 - 1, y0)] : qpYPrev;
+ var qpB = (y0 & ~ctbMask) != 0 ? qpMap[Grid(x0, y0 - 1)] : qpYPrev;
+ qpYPred = (qpA + qpB + 1) >> 1;
+ }
+
+ UpdateQpY();
+ cuTransquantBypass = pps.TransquantBypassEnabled && cabac.Flag(CabacTables.CuTransquantBypassFlag);
+ var skip = false;
+ if (!slice.IsIntra)
+ {
+ var ctx = 0;
+ if (Available(x0, y0, x0 - 1, y0) && predMode[Grid(x0 - 1, y0)] == ModeSkip)
+ {
+ ctx++;
+ }
+
+ if (Available(x0, y0, x0, y0 - 1) && predMode[Grid(x0, y0 - 1)] == ModeSkip)
+ {
+ ctx++;
+ }
+
+ skip = cabac.Flag(CabacTables.CuSkipFlag + ctx);
+ }
+
+ FillGrid(ctDepthMap, x0, y0, size, size, (byte)depth);
+ var pcm = false;
+ cuPartMode = Part2Nx2N;
+ cuIntraSplit = false;
+ if (skip)
+ {
+ cuIntra = false;
+ FillGrid(predMode, x0, y0, size, size, ModeSkip);
+ PredictionUnit(x0, y0, size, size, true, depth);
+ }
+ else
+ {
+ cuIntra = slice.IsIntra || cabac.Flag(CabacTables.PredModeFlag);
+ FillGrid(predMode, x0, y0, size, size, cuIntra ? ModeIntra : ModeInter);
+ if (!cuIntra || log2 == sps.Log2MinCbSize)
+ {
+ cuPartMode = ParsePartMode(log2);
+ }
+
+ var mergeFirst = false;
+ if (cuIntra)
+ {
+ cuIntraSplit = cuPartMode == PartNxN;
+ if (cuPartMode == Part2Nx2N && sps.PcmEnabled && log2 >= sps.Log2MinPcmCbSize && log2 <= sps.Log2MaxPcmCbSize)
+ {
+ pcm = cabac.Terminate() == 1;
+ }
+
+ if (pcm)
+ {
+ PcmSamples(x0, y0, log2);
+ }
+ else
+ {
+ ParseIntraModes(x0, y0, log2);
+ }
+ }
+ else
+ {
+ mergeFirst = PredictionUnits(x0, y0, size, depth);
+ }
+
+ if (!pcm)
+ {
+ var rqtRootCbf = true;
+ if (!cuIntra && !(cuPartMode == Part2Nx2N && mergeFirst))
+ {
+ rqtRootCbf = cabac.Flag(CabacTables.RqtRootCbf);
+ }
+
+ MarkPredictionEdges(x0, y0, size);
+ if (rqtRootCbf)
+ {
+ cuMaxTrafoDepth = cuIntra ? sps.MaxTransformHierarchyDepthIntra + (cuIntraSplit ? 1 : 0) : sps.MaxTransformHierarchyDepthInter;
+ TransformTree(x0, y0, x0, y0, log2, 0, 0, false, false);
+ }
+ }
+ }
+
+ // QpY of the coding unit (for the prediction of the next ones and for deblocking), and its flags.
+ FillGrid(qpMap, x0, y0, size, size, (sbyte)qpY);
+ qpYPrev = qpY;
+ var flags = (byte)((pcm ? FlagPcm : 0) | ((pcm && sps.PcmLoopFilterDisabled) || cuTransquantBypass ? FlagNoFilter : 0));
+ if (flags != 0)
+ {
+ OrGrid(blockFlags, x0, y0, size, size, flags);
+ pictureHasUnfilteredBlocks |= (flags & FlagNoFilter) != 0;
+ }
+
+ MarkCodingUnitEdges(x0, y0, size);
+ }
+
+ /// QpY from the predicted QP and CuQpDeltaVal (8-283).
+ private void UpdateQpY()
+ {
+ var offset = sps.QpBdOffsetY;
+ qpY = ((qpYPred + cuQpDeltaVal + 52 + (2 * offset)) % (52 + offset)) - offset;
+ }
+
+ /// part_mode (§9.3.3.7): bins 0 and 1 with contexts 0 and 1, then context 2 or 3, then bypass.
+ private int ParsePartMode(int log2)
+ {
+ if (cabac.Flag(CabacTables.PartMode))
+ {
+ return Part2Nx2N;
+ }
+
+ if (cuIntra)
+ {
+ return PartNxN;
+ }
+
+ if (log2 == sps.Log2MinCbSize)
+ {
+ if (cabac.Flag(CabacTables.PartMode + 1))
+ {
+ return Part2NxN;
+ }
+
+ if (log2 == 3)
+ {
+ return PartNx2N;
+ }
+
+ return cabac.Flag(CabacTables.PartMode + 2) ? PartNx2N : PartNxN;
+ }
+
+ var horizontal = cabac.Flag(CabacTables.PartMode + 1);
+ if (!sps.AmpEnabled)
+ {
+ return horizontal ? Part2NxN : PartNx2N;
+ }
+
+ if (cabac.Flag(CabacTables.PartMode + 3))
+ {
+ return horizontal ? Part2NxN : PartNx2N;
+ }
+
+ var second = cabac.Bypass() == 1;
+ return horizontal ? (second ? Part2NxnD : Part2NxnU) : (second ? PartnRx2N : PartnLx2N);
+ }
+
+ /// The intra prediction modes of a coding unit (§7.3.8.5, §8.4.2, §8.4.3).
+ private void ParseIntraModes(int x0, int y0, int log2)
+ {
+ var count = cuIntraSplit ? 4 : 1;
+ var pbSize = cuIntraSplit ? 1 << (log2 - 1) : 1 << log2;
+ Span prev = stackalloc bool[4];
+ Span list = stackalloc int[3];
+ for (var i = 0; i < count; i++)
+ {
+ prev[i] = cabac.Flag(CabacTables.PrevIntraLumaPredFlag);
+ }
+
+ var firstMode = 0;
+ for (var i = 0; i < count; i++)
+ {
+ var xPb = x0 + ((i & 1) * pbSize);
+ var yPb = y0 + ((i >> 1) * pbSize);
+ var candA = NeighbourIntraMode(xPb, yPb, xPb - 1, yPb, false);
+ var candB = NeighbourIntraMode(xPb, yPb, xPb, yPb - 1, true);
+ if (candA == candB)
+ {
+ if (candA < 2)
+ {
+ list[0] = 0;
+ list[1] = 1;
+ list[2] = 26;
+ }
+ else
+ {
+ list[0] = candA;
+ list[1] = 2 + ((candA + 29) % 32);
+ list[2] = 2 + ((candA - 2 + 1) % 32);
+ }
+ }
+ else
+ {
+ list[0] = candA;
+ list[1] = candB;
+ list[2] = candA != 0 && candB != 0 ? 0 : candA != 1 && candB != 1 ? 1 : 26;
+ }
+
+ int mode;
+ if (prev[i])
+ {
+ // mpm_idx: TR with cMax 2, bypass.
+ var mpm = cabac.Bypass() == 0 ? 0 : cabac.Bypass() == 0 ? 1 : 2;
+ mode = list[mpm];
+ }
+ else
+ {
+ mode = cabac.BypassBits(5);
+ list.Sort();
+ for (var k = 0; k < 3; k++)
+ {
+ if (mode >= list[k])
+ {
+ mode++;
+ }
+ }
+ }
+
+ FillGrid(intraModeMap, xPb, yPb, pbSize, pbSize, (byte)mode);
+ if (i == 0)
+ {
+ firstMode = mode;
+ }
+ }
+
+ // intra_chroma_pred_mode (table 8-2 for ChromaArrayType 1): 4 is the luma mode, 0 to 3 are planar, vertical,
+ // horizontal and DC, replaced by mode 34 when they equal the luma mode.
+ var chroma = !cabac.Flag(CabacTables.IntraChromaPredMode) ? 4 : cabac.BypassBits(2);
+ cuIntraModeC = chroma switch
+ {
+ 0 => firstMode == 0 ? 34 : 0,
+ 1 => firstMode == 26 ? 34 : 26,
+ 2 => firstMode == 10 ? 34 : 10,
+ 3 => firstMode == 1 ? 34 : 1,
+ _ => firstMode,
+ };
+ }
+
+ /// candIntraPredModeX of §8.4.2.
+ private int NeighbourIntraMode(int xPb, int yPb, int xN, int yN, bool above)
+ {
+ if (!Available(xPb, yPb, xN, yN))
+ {
+ return 1;
+ }
+
+ var g = Grid(xN, yN);
+ if (predMode[g] != ModeIntra || (blockFlags[g] & FlagPcm) != 0)
+ {
+ return 1;
+ }
+
+ if (above && yN < ((yPb >> sps.Log2CtbSize) << sps.Log2CtbSize))
+ {
+ return 1;
+ }
+
+ return intraModeMap[g];
+ }
+
+ /// pcm_sample() (§7.3.8.7) and its reconstruction (§8.4.4.1): the CABAC engine restarts after the samples.
+ private void PcmSamples(int x0, int y0, int log2)
+ {
+ var reader = new BitReader(data, dataEnd, 0) { Position = (cabac.BitPosition + 7) & ~7 };
+ var size = 1 << log2;
+ var plane = cur!.Planes[0];
+ var stride = cur.Width;
+ int shift = sps.BitDepthY - sps.PcmBitDepthY, bits = sps.PcmBitDepthY;
+ for (var y = 0; y < size; y++)
+ {
+ for (var x = 0; x < size; x++)
+ {
+ plane[((y0 + y) * stride) + x0 + x] = (ushort)(reader.Read(bits) << shift);
+ }
+ }
+
+ var chromaSize = size >> 1;
+ shift = sps.BitDepthC - sps.PcmBitDepthC;
+ bits = sps.PcmBitDepthC;
+ for (var c = 1; c <= 2; c++)
+ {
+ plane = cur.Planes[c];
+ stride = cur.ChromaWidth;
+ for (var y = 0; y < chromaSize; y++)
+ {
+ for (var x = 0; x < chromaSize; x++)
+ {
+ plane[(((y0 >> 1) + y) * stride) + (x0 >> 1) + x] = (ushort)(reader.Read(bits) << shift);
+ }
+ }
+ }
+
+ if (reader.BitsLeft < 0)
+ {
+ throw new H265Exception("Campioni PCM troncati.");
+ }
+
+ cabac.Start(data, reader.Position, dataEnd);
+ }
+
+ /// The prediction units of an inter coding unit by part_mode; true when the first one is merged.
+ private bool PredictionUnits(int x0, int y0, int size, int depth)
+ {
+ int half = size >> 1, quarter = size >> 2;
+ switch (cuPartMode)
+ {
+ case Part2Nx2N:
+ return PredictionUnit(x0, y0, size, size, false, depth);
+ case Part2NxN:
+ {
+ var merge = PredictionUnit(x0, y0, size, half, false, depth);
+ PredictionUnit(x0, y0 + half, size, half, false, depth);
+ return merge;
+ }
+
+ case PartNx2N:
+ {
+ var merge = PredictionUnit(x0, y0, half, size, false, depth);
+ PredictionUnit(x0 + half, y0, half, size, false, depth);
+ return merge;
+ }
+
+ case Part2NxnU:
+ {
+ var merge = PredictionUnit(x0, y0, size, quarter, false, depth);
+ PredictionUnit(x0, y0 + quarter, size, size - quarter, false, depth);
+ return merge;
+ }
+
+ case Part2NxnD:
+ {
+ var merge = PredictionUnit(x0, y0, size, size - quarter, false, depth);
+ PredictionUnit(x0, y0 + size - quarter, size, quarter, false, depth);
+ return merge;
+ }
+
+ case PartnLx2N:
+ {
+ var merge = PredictionUnit(x0, y0, quarter, size, false, depth);
+ PredictionUnit(x0 + quarter, y0, size - quarter, size, false, depth);
+ return merge;
+ }
+
+ case PartnRx2N:
+ {
+ var merge = PredictionUnit(x0, y0, size - quarter, size, false, depth);
+ PredictionUnit(x0 + size - quarter, y0, quarter, size, false, depth);
+ return merge;
+ }
+
+ default:
+ {
+ var merge = PredictionUnit(x0, y0, half, half, false, depth);
+ PredictionUnit(x0 + half, y0, half, half, false, depth);
+ PredictionUnit(x0, y0 + half, half, half, false, depth);
+ PredictionUnit(x0 + half, y0 + half, half, half, false, depth);
+ return merge;
+ }
+ }
+ }
+
+ ///
+ /// prediction_unit() (§7.3.8.6) and mvd_coding() (§7.3.8.9). The motion data is read but not used yet: the samples of
+ /// the unit are mid-grey (only with ).
+ ///
+ private bool PredictionUnit(int x0, int y0, int width, int height, bool skip, int depth)
+ {
+ var merge = skip || cabac.Flag(CabacTables.MergeFlag);
+ if (merge)
+ {
+ if (slice.MaxNumMergeCand > 1 && cabac.Flag(CabacTables.MergeIdx))
+ {
+ var index = 1;
+ while (index < slice.MaxNumMergeCand - 1 && cabac.Bypass() == 1)
+ {
+ index++;
+ }
+ }
+ }
+ else
+ {
+ var interPredIdc = 0; // PRED_L0
+ if (slice.Type == SliceType.B)
+ {
+ if (width + height != 12 && cabac.Flag(CabacTables.InterPredIdc + depth))
+ {
+ interPredIdc = 2; // PRED_BI
+ }
+ else
+ {
+ interPredIdc = cabac.Flag(CabacTables.InterPredIdc + 4) ? 1 : 0;
+ }
+ }
+
+ for (var list = 0; list < 2; list++)
+ {
+ if (interPredIdc == 1 - list)
+ {
+ continue;
+ }
+
+ var count = slice.NumRefIdxActive[list];
+ if (count > 1)
+ {
+ var refIdx = 0;
+ while (refIdx < count - 1 && (refIdx >= 2 ? cabac.Bypass() == 1 : cabac.Flag(CabacTables.RefIdx + refIdx)))
+ {
+ refIdx++;
+ }
+ }
+
+ if (!(list == 1 && slice.MvdL1Zero && interPredIdc == 2))
+ {
+ MvdCoding();
+ }
+
+ cabac.Flag(CabacTables.MvpFlag);
+ }
+ }
+
+ // Inter prediction is the next step of the decoder: mid-grey for now.
+ FillPlane(0, x0, y0, width, height, (ushort)(1 << (sps.BitDepthY - 1)));
+ FillPlane(1, x0 >> 1, y0 >> 1, width >> 1, height >> 1, (ushort)(1 << (sps.BitDepthC - 1)));
+ FillPlane(2, x0 >> 1, y0 >> 1, width >> 1, height >> 1, (ushort)(1 << (sps.BitDepthC - 1)));
+ return merge;
+ }
+
+ private void MvdCoding()
+ {
+ var greater0X = cabac.Flag(CabacTables.AbsMvdGreater0Flag);
+ var greater0Y = cabac.Flag(CabacTables.AbsMvdGreater0Flag);
+ var greater1X = greater0X && cabac.Flag(CabacTables.AbsMvdGreater1Flag);
+ var greater1Y = greater0Y && cabac.Flag(CabacTables.AbsMvdGreater1Flag);
+ if (greater0X)
+ {
+ if (greater1X)
+ {
+ ExpGolombBypass(1);
+ }
+
+ cabac.Bypass();
+ }
+
+ if (greater0Y)
+ {
+ if (greater1Y)
+ {
+ ExpGolombBypass(1);
+ }
+
+ cabac.Bypass();
+ }
+ }
+
+ /// A k-th order Exp-Golomb value in bypass bins (§9.3.3.3).
+ private int ExpGolombBypass(int k)
+ {
+ var value = 0;
+ while (cabac.Bypass() == 1)
+ {
+ value += 1 << k;
+ k++;
+ if (k > 31)
+ {
+ throw new H265Exception("Codice Exp-Golomb CABAC non valido.");
+ }
+ }
+
+ return k > 0 ? value + ReadBypass(k) : value;
+ }
+
+ private int ReadBypass(int count)
+ {
+ var value = 0;
+ while (count > 16)
+ {
+ value = (value << 16) | cabac.BypassBits(16);
+ count -= 16;
+ }
+
+ return (value << count) | cabac.BypassBits(count);
+ }
+
+ private void TransformTree(int x0, int y0, int xBase, int yBase, int log2, int depth, int blkIdx, bool parentCbfCb, bool parentCbfCr)
+ {
+ bool split;
+ var interSplit = sps.MaxTransformHierarchyDepthInter == 0 && !cuIntra && cuPartMode != Part2Nx2N && depth == 0;
+ if (log2 <= sps.Log2MaxTbSize && log2 > sps.Log2MinTbSize && depth < cuMaxTrafoDepth && !(cuIntraSplit && depth == 0))
+ {
+ split = cabac.Flag(CabacTables.SplitTransformFlag + 5 - log2);
+ }
+ else
+ {
+ split = log2 > sps.Log2MaxTbSize || (cuIntraSplit && depth == 0) || interSplit;
+ }
+
+ bool cbfCb, cbfCr;
+ if (log2 > 2)
+ {
+ cbfCb = (depth == 0 || parentCbfCb) && cabac.Flag(CabacTables.CbfChroma + depth);
+ cbfCr = (depth == 0 || parentCbfCr) && cabac.Flag(CabacTables.CbfChroma + depth);
+ }
+ else
+ {
+ // 4×4 luma blocks: the chroma of the four is coded once, with the parent's flags (§7.4.9.8).
+ cbfCb = parentCbfCb;
+ cbfCr = parentCbfCr;
+ }
+
+ if (split)
+ {
+ var half = 1 << (log2 - 1);
+ TransformTree(x0, y0, x0, y0, log2 - 1, depth + 1, 0, cbfCb, cbfCr);
+ TransformTree(x0 + half, y0, x0, y0, log2 - 1, depth + 1, 1, cbfCb, cbfCr);
+ TransformTree(x0, y0 + half, x0, y0, log2 - 1, depth + 1, 2, cbfCb, cbfCr);
+ TransformTree(x0 + half, y0 + half, x0, y0, log2 - 1, depth + 1, 3, cbfCb, cbfCr);
+ return;
+ }
+
+ var cbfLuma = true;
+ if (cuIntra || depth != 0 || cbfCb || cbfCr)
+ {
+ cbfLuma = cabac.Flag(CabacTables.CbfLuma + (depth == 0 ? 1 : 0));
+ }
+
+ TransformUnit(x0, y0, xBase, yBase, log2, blkIdx, cbfLuma, cbfCb, cbfCr);
+ }
+
+ private void TransformUnit(int x0, int y0, int xBase, int yBase, int log2, int blkIdx, bool cbfLuma, bool cbfCb, bool cbfCr)
+ {
+ var size = 1 << log2;
+ var cbfChroma = cbfCb || cbfCr;
+ if (cbfLuma || cbfChroma)
+ {
+ if (pps.CuQpDeltaEnabled && !isCuQpDeltaCoded)
+ {
+ // cu_qp_delta_abs: TR prefix of up to 5 bins (the first with context 0, the others with context 1),
+ // then an EG0 suffix in bypass; cu_qp_delta_sign_flag in bypass.
+ var prefix = 0;
+ while (prefix < 5 && cabac.Flag(CabacTables.CuQpDeltaAbs + (prefix == 0 ? 0 : 1)))
+ {
+ prefix++;
+ }
+
+ var value = prefix == 5 ? 5 + ExpGolombBypass(0) : prefix;
+ if (value != 0 && cabac.Bypass() == 1)
+ {
+ value = -value;
+ }
+
+ var offset = sps.QpBdOffsetY;
+ if (value < -(26 + (offset / 2)) || value > 25 + (offset / 2))
+ {
+ throw new H265Exception("cu_qp_delta fuori dall'intervallo.");
+ }
+
+ isCuQpDeltaCoded = true;
+ cuQpDeltaVal = value;
+ UpdateQpY();
+ }
+
+ if (slice.CuChromaQpOffsetEnabled && cbfChroma && !cuTransquantBypass && !isCuChromaQpOffsetCoded)
+ {
+ var on = cabac.Flag(CabacTables.CuChromaQpOffsetFlag);
+ var index = 0;
+ if (on && pps.ChromaQpOffsetListLength > 1)
+ {
+ while (index < pps.ChromaQpOffsetListLength - 1 && cabac.Flag(CabacTables.CuChromaQpOffsetIdx))
+ {
+ index++;
+ }
+ }
+
+ cuQpOffsetCb = on ? pps.CbQpOffsetList[index] : 0;
+ cuQpOffsetCr = on ? pps.CrQpOffsetList[index] : 0;
+ isCuChromaQpOffsetCoded = true;
+ }
+ }
+
+ var lumaMode = cuIntra ? intraModeMap[Grid(x0, y0)] : -1;
+ var chromaMode = cuIntra ? cuIntraModeC : -1;
+ if (cuIntra)
+ {
+ PredictIntra(0, x0, y0, log2, lumaMode);
+ }
+
+ if (cbfLuma)
+ {
+ Residual(0, x0, y0, log2, lumaMode);
+ FillGrid(blockFlags, x0, y0, size, size, FlagCoded, true);
+ }
+
+ if (x0 > cuX)
+ {
+ MarkVertical(x0, y0, size, 2);
+ }
+
+ if (y0 > cuY)
+ {
+ MarkHorizontal(x0, y0, size, 2);
+ }
+
+ if (log2 > 2)
+ {
+ int xc = x0 >> 1, yc = y0 >> 1;
+ if (cuIntra)
+ {
+ PredictIntra(1, xc, yc, log2 - 1, cuIntraModeC);
+ }
+
+ if (cbfCb)
+ {
+ Residual(1, xc, yc, log2 - 1, chromaMode);
+ }
+
+ if (cuIntra)
+ {
+ PredictIntra(2, xc, yc, log2 - 1, cuIntraModeC);
+ }
+
+ if (cbfCr)
+ {
+ Residual(2, xc, yc, log2 - 1, chromaMode);
+ }
+ }
+ else if (blkIdx == 3)
+ {
+ int xc = xBase >> 1, yc = yBase >> 1;
+ if (cuIntra)
+ {
+ PredictIntra(1, xc, yc, 2, cuIntraModeC);
+ }
+
+ if (cbfCb)
+ {
+ Residual(1, xc, yc, 2, chromaMode);
+ }
+
+ if (cuIntra)
+ {
+ PredictIntra(2, xc, yc, 2, cuIntraModeC);
+ }
+
+ if (cbfCr)
+ {
+ Residual(2, xc, yc, 2, chromaMode);
+ }
+ }
+ }
+
+ ///
+ /// availableN of the z-scan order (§6.4.1), for luma locations: inside the picture, already decoded, in the same
+ /// slice and the same tile.
+ ///
+ private bool Available(int xCur, int yCur, int xN, int yN)
+ {
+ if (xN < 0 || yN < 0 || xN >= sps.Width || yN >= sps.Height)
+ {
+ return false;
+ }
+
+ var log2 = sps.Log2CtbSize;
+ var ctbN = ((yN >> log2) * widthInCtbs) + (xN >> log2);
+ var ctbC = ((yCur >> log2) * widthInCtbs) + (xCur >> log2);
+ if (ctbN != ctbC)
+ {
+ return ctbSlice[ctbN] == sliceIdx && pps.TileIdRs[ctbN] == pps.TileIdRs[ctbC];
+ }
+
+ var mask = (1 << log2) - 1;
+ return s_zOrder[(((yN & mask) >> 2) << 4) | ((xN & mask) >> 2)] < s_zOrder[(((yCur & mask) >> 2) << 4) | ((xCur & mask) >> 2)];
+ }
+
+ private int Grid(int x, int y) => ((y >> 2) * w4) + (x >> 2);
+
+ private void FillGrid(T[] grid, int x0, int y0, int width, int height, T value)
+ {
+ int gx = x0 >> 2, gy = y0 >> 2;
+ int gw = Math.Min((width + 3) >> 2, w4 - gx), gh = Math.Min((height + 3) >> 2, h4 - gy);
+ for (var y = 0; y < gh; y++)
+ {
+ grid.AsSpan(((gy + y) * w4) + gx, gw).Fill(value);
+ }
+ }
+
+ private void FillGrid(byte[] grid, int x0, int y0, int width, int height, byte bits, bool or)
+ {
+ if (or)
+ {
+ OrGrid(grid, x0, y0, width, height, bits);
+ }
+ else
+ {
+ FillGrid(grid, x0, y0, width, height, bits);
+ }
+ }
+
+ private void OrGrid(byte[] grid, int x0, int y0, int width, int height, byte bits)
+ {
+ int gx = x0 >> 2, gy = y0 >> 2;
+ int gw = Math.Min((width + 3) >> 2, w4 - gx), gh = Math.Min((height + 3) >> 2, h4 - gy);
+ for (var y = 0; y < gh; y++)
+ {
+ var row = ((gy + y) * w4) + gx;
+ for (var x = 0; x < gw; x++)
+ {
+ grid[row + x] |= bits;
+ }
+ }
+ }
+
+ private void FillPlane(int cIdx, int x0, int y0, int width, int height, ushort value)
+ {
+ var plane = cur!.Planes[cIdx];
+ var stride = cur.Stride(cIdx);
+ var rows = cIdx == 0 ? cur.Height : cur.ChromaHeight;
+ width = Math.Min(width, stride - x0);
+ height = Math.Min(height, rows - y0);
+ for (var y = 0; y < height; y++)
+ {
+ plane.AsSpan(((y0 + y) * stride) + x0, width).Fill(value);
+ }
+ }
+
+ private static ushort[] BuildZOrder()
+ {
+ var table = new ushort[256];
+ for (var y = 0; y < 16; y++)
+ {
+ for (var x = 0; x < 16; x++)
+ {
+ var z = 0;
+ for (var b = 0; b < 4; b++)
+ {
+ z |= ((x >> b) & 1) << (2 * b);
+ z |= ((y >> b) & 1) << ((2 * b) + 1);
+ }
+
+ table[(y << 4) | x] = (ushort)z;
+ }
+ }
+
+ return table;
+ }
+}
diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.cs b/src/Febe.Core/Codecs/H265/H265Decoder.cs
new file mode 100644
index 0000000..7cba68d
--- /dev/null
+++ b/src/Febe.Core/Codecs/H265/H265Decoder.cs
@@ -0,0 +1,571 @@
+using Febe.Core.Codecs.H264;
+
+namespace Febe.Core.Codecs.H265;
+
+///
+/// An HEVC (ITU-T H.265 | ISO/IEC 23008-2) decoder written from the Recommendation, for the Main, Main 10 and Main Still
+/// Picture profiles: 4:2:0 at 8 to 10 bits (up to 12 accepted), tiles, wavefronts, dependent slice segments, PCM, transform
+/// skip, sign data hiding, scaling lists, deblocking and SAO. Intra pictures only for now: inter prediction is the next step,
+/// and a P or B slice raises an (see ). Not handled (an
+/// ): the range extensions (4:0:0, 4:2:2, 4:4:4 and their coding tools), separate colour planes
+/// and the layers above 0 of scalable and multiview streams, which are ignored.
+///
+public sealed partial class H265Decoder
+{
+ private readonly Sps?[] spss = new Sps?[16];
+ private readonly Pps?[] ppss = new Pps?[64];
+ private readonly List dpb = [];
+ private readonly Stack pool = new();
+ private byte[]? rbsp;
+
+ /// No picture decoded yet: the next IRAP picture is "picture 0" of C.5.2.2.
+ private bool firstPicture = true;
+
+ /// At the start of the bitstream or after an end of sequence: the next CRA picture has NoRaslOutputFlag 1.
+ private bool afterEndOfSequence = true;
+
+ private bool seenIrap;
+
+ /// NoRaslOutputFlag of the IRAP picture the current pictures are associated with.
+ private bool irapNoRaslOutput;
+
+ /// PicOrderCntVal of prevTid0Pic (§8.3.1).
+ private int prevTid0Poc;
+
+ private long codedPictures;
+
+ /// The slices of the current picture are skipped (a RASL picture that cannot be decoded, no IRAP yet).
+ private bool skipping;
+
+ /// The five lists of the reference picture set of the current picture (§8.3.2); null for "no reference picture".
+ private readonly List refStCurrBefore = [];
+ private readonly List refStCurrAfter = [];
+ private readonly List refLtCurr = [];
+
+ /// Raised for each frame in output order (the bumping process of C.5.2.4), cropped.
+ public event Action? FrameOutput;
+
+ /// Raised for each picture once decoded and filtered, in decoding order (for the decoded picture hash).
+ internal event Action? PictureDecoded;
+
+ ///
+ /// Decodes the syntax of P and B slices (with every prediction unit predicted as mid-grey) instead of refusing them:
+ /// only to check the parsing of the inter syntax before inter prediction exists. The pictures are not correct.
+ ///
+ internal bool ParseInterSlices { get; set; }
+
+ /// Coded pictures met so far, also those skipped.
+ public long PicturesDecoded => codedPictures;
+
+ /// Decodes a whole Annex B byte stream, then outputs every picture left.
+ public void DecodeAnnexB(ReadOnlySpan stream)
+ {
+ var position = 0;
+ while (NalUnits.NextAnnexB(stream, ref position, out var unit))
+ {
+ Decode(stream[unit]);
+ }
+
+ Flush();
+ }
+
+ ///
+ /// Reads the parameter sets of an hvcC box (HEVCDecoderConfigurationRecord, ISO/IEC 14496-15 §8.3.3); returns
+ /// the size of the NAL length fields of the samples.
+ ///
+ public int ConfigureHvcC(ReadOnlySpan hvcC)
+ {
+ if (hvcC.Length < 23 || hvcC[0] != 1)
+ {
+ throw new H265Exception("Configurazione hvcC non valida.");
+ }
+
+ var lengthSize = (hvcC[21] & 3) + 1;
+ var arrays = hvcC[22];
+ var offset = 23;
+ for (var a = 0; a < arrays; a++)
+ {
+ if (offset + 3 > hvcC.Length)
+ {
+ throw new H265Exception("Configurazione hvcC troncata.");
+ }
+
+ var count = (hvcC[offset + 1] << 8) | hvcC[offset + 2];
+ offset += 3;
+ for (var i = 0; i < count; i++)
+ {
+ if (offset + 2 > hvcC.Length)
+ {
+ throw new H265Exception("Configurazione hvcC troncata.");
+ }
+
+ var size = (hvcC[offset] << 8) | hvcC[offset + 1];
+ offset += 2;
+ if (size == 0 || offset + size > hvcC.Length)
+ {
+ throw new H265Exception("Configurazione hvcC troncata.");
+ }
+
+ Decode(hvcC.Slice(offset, size));
+ offset += size;
+ }
+ }
+
+ return lengthSize;
+ }
+
+ /// Decodes one access unit stored with length prefixes (an MP4 or Matroska sample) and finishes its picture.
+ public void DecodeSample(ReadOnlySpan sample, int lengthSize)
+ {
+ var position = 0;
+ while (NalUnits.NextLengthPrefixed(sample, lengthSize, ref position, out var unit))
+ {
+ Decode(sample[unit]);
+ }
+
+ FinishPicture();
+ }
+
+ /// Finishes the picture being decoded and outputs every picture still waiting, in output order.
+ public void Flush()
+ {
+ FinishPicture();
+ while (Bump())
+ {
+ }
+ }
+
+ private void Decode(ReadOnlySpan bytes)
+ {
+ if (bytes.Length < 2 || (bytes[0] & 0x80) != 0)
+ {
+ return;
+ }
+
+ var type = (bytes[0] >> 1) & 63;
+ var layer = ((bytes[0] & 1) << 5) | (bytes[1] >> 3);
+ if (layer != 0)
+ {
+ return;
+ }
+
+ try
+ {
+ switch (type)
+ {
+ case <= 9:
+ case >= 16 and <= 21:
+ DecodeSlice(H265NalUnit.Unescape(bytes, ref rbsp));
+ break;
+ case 33:
+ {
+ var sps = Sps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader());
+ spss[sps.Id] = sps;
+ break;
+ }
+
+ case 34:
+ {
+ var pps = Pps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader());
+ ppss[pps.Id] = pps;
+ break;
+ }
+
+ case 35: // access unit delimiter
+ FinishPicture();
+ break;
+ case 36: // end of sequence
+ case 37: // end of bitstream
+ FinishPicture();
+ afterEndOfSequence = true;
+ break;
+ }
+ }
+ catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException)
+ {
+ throw new H265Exception("Flusso HEVC troncato o danneggiato.");
+ }
+ }
+
+ private void DecodeSlice(H265NalUnit nal)
+ {
+ var first = (nal.Rbsp[2] & 0x80) != 0;
+ if (first)
+ {
+ FinishPicture();
+ }
+ else if (skipping || cur is null)
+ {
+ // A segment of a picture that is skipped, or whose first segment is missing.
+ return;
+ }
+
+ var reader = nal.Reader();
+ var header = SliceHeader.Parse(reader, nal.Type, spss, ppss, first ? null : sliceHeader, out var s, out var p);
+ if (first)
+ {
+ StartPicture(nal, header, s, p);
+ if (skipping)
+ {
+ return;
+ }
+ }
+ else if (!ReferenceEquals(s, sps) || !ReferenceEquals(p, pps))
+ {
+ throw new H265Exception("Parametri diversi fra le slice di un'immagine.");
+ }
+
+ if (!header.IsIntra && !ParseInterSlices)
+ {
+ throw new H265Exception("La predizione inter HEVC non è ancora gestita.");
+ }
+
+ if (!header.Dependent)
+ {
+ sliceHeader = header;
+ slices.Add(header);
+ }
+
+ DecodeSliceData(nal, header);
+ }
+
+ private void StartPicture(H265NalUnit nal, SliceHeader h, Sps s, Pps p)
+ {
+ var index = codedPictures++;
+ var type = nal.Type;
+ var irap = type is >= 16 and <= 23;
+ var idr = type is 19 or 20;
+ skipping = false;
+ sliceHeader = null;
+ var noRaslOutput = false;
+ if (irap)
+ {
+ noRaslOutput = idr || type <= 18 || afterEndOfSequence;
+ irapNoRaslOutput = noRaslOutput;
+ seenIrap = true;
+ }
+ else if (!seenIrap || (type is 8 or 9 && irapNoRaslOutput))
+ {
+ // Decoding cannot start here, or a RASL picture of a CRA that starts the sequence (§8.1.3): not decoded.
+ skipping = true;
+ return;
+ }
+
+ if (s.ChromaArrayType != 1 || s.BitDepthY > 12 || s.BitDepthC > 12)
+ {
+ throw new H265Exception("Solo video HEVC 4:2:0 fino a 12 bit.");
+ }
+
+ if (s.UsesRangeExtensionTools || p.UsesRangeExtensionTools)
+ {
+ throw new H265Exception("Gli strumenti delle estensioni di formato HEVC non sono gestiti.");
+ }
+
+ p.Activate(s);
+
+ // Picture order count (§8.3.1).
+ var maxLsb = 1 << s.Log2MaxPocLsb;
+ int msb;
+ if (irap && noRaslOutput)
+ {
+ msb = 0;
+ }
+ else
+ {
+ var prevLsb = prevTid0Poc & (maxLsb - 1);
+ var prevMsb = prevTid0Poc - prevLsb;
+ if (h.PocLsb < prevLsb && prevLsb - h.PocLsb >= maxLsb / 2)
+ {
+ msb = prevMsb + maxLsb;
+ }
+ else if (h.PocLsb > prevLsb && h.PocLsb - prevLsb > maxLsb / 2)
+ {
+ msb = prevMsb - maxLsb;
+ }
+ else
+ {
+ msb = prevMsb;
+ }
+ }
+
+ var poc = msb + h.PocLsb;
+ var subLayerNonReference = type <= 14 && type % 2 == 0;
+ if (nal.TemporalId == 0 && type is not (>= 6 and <= 9) && !subLayerNonReference)
+ {
+ prevTid0Poc = poc;
+ }
+
+ ApplyReferencePictureSet(h, s, poc, irap && noRaslOutput, idr);
+
+ // Removal of pictures from the DPB before the current one is decoded (C.5.2.2).
+ if (irap && noRaslOutput && !firstPicture)
+ {
+ var noOutputOfPriorPics = type == 21 || h.NoOutputOfPriorPics;
+ if (!noOutputOfPriorPics)
+ {
+ while (Bump())
+ {
+ }
+ }
+
+ foreach (var picture in dpb)
+ {
+ pool.Push(picture);
+ }
+
+ dpb.Clear();
+ }
+ else
+ {
+ RemoveUnused();
+ var t = s.HighestTid;
+ while (OutputWanted(s, t) || dpb.Count >= s.MaxDecPicBufferingMinus1[t] + 1)
+ {
+ if (!Bump())
+ {
+ break;
+ }
+ }
+ }
+
+ firstPicture = false;
+ afterEndOfSequence = false;
+ cur = NewPicture(s);
+ cur.Poc = poc;
+ cur.DecodeIndex = index;
+ cur.OutputFlag = h.PicOutputFlag;
+ StartPictureData(s, p);
+ }
+
+ /// The decoding process for the reference picture set (§8.3.2), and the marking of the DPB it implies.
+ private void ApplyReferencePictureSet(SliceHeader h, Sps s, int poc, bool irapNoRasl, bool idr)
+ {
+ refStCurrBefore.Clear();
+ refStCurrAfter.Clear();
+ refLtCurr.Clear();
+ if (irapNoRasl)
+ {
+ foreach (var picture in dpb)
+ {
+ picture.ShortTerm = picture.LongTerm = false;
+ }
+ }
+
+ if (idr)
+ {
+ foreach (var picture in dpb)
+ {
+ picture.ShortTerm = picture.LongTerm = false;
+ }
+
+ return;
+ }
+
+ var maxLsb = 1 << s.Log2MaxPocLsb;
+ Span keep = stackalloc bool[dpb.Count];
+
+ // Long-term pictures first: a picture they take is no longer a short-term candidate.
+ var total = h.PocLsbLt.Length;
+ for (var i = 0; i < total; i++)
+ {
+ var pocLt = h.PocLsbLt[i];
+ if (h.DeltaPocMsbPresent[i])
+ {
+ pocLt += poc - (h.DeltaPocMsbCycleLt[i] * maxLsb) - (poc & (maxLsb - 1));
+ }
+
+ var found = -1;
+ for (var k = 0; k < dpb.Count; k++)
+ {
+ var candidate = dpb[k];
+ if (candidate.IsReference && (h.DeltaPocMsbPresent[i] ? candidate.Poc == pocLt : (candidate.Poc & (maxLsb - 1)) == pocLt))
+ {
+ found = k;
+ break;
+ }
+ }
+
+ if (found >= 0)
+ {
+ keep[found] = true;
+ dpb[found].LongTerm = true;
+ dpb[found].ShortTerm = false;
+ }
+
+ if (h.UsedByCurrPicLt[i])
+ {
+ refLtCurr.Add(found >= 0 ? dpb[found] : null);
+ }
+ }
+
+ if (h.StRps is { } rps)
+ {
+ for (var i = 0; i < rps.NumNegative; i++)
+ {
+ var picture = FindShortTerm(poc + rps.DeltaPocS0[i], keep);
+ if (rps.UsedS0[i])
+ {
+ refStCurrBefore.Add(picture);
+ }
+ }
+
+ for (var i = 0; i < rps.NumPositive; i++)
+ {
+ var picture = FindShortTerm(poc + rps.DeltaPocS1[i], keep);
+ if (rps.UsedS1[i])
+ {
+ refStCurrAfter.Add(picture);
+ }
+ }
+ }
+
+ // Every reference picture that is in none of the five lists is no longer used for reference.
+ for (var k = 0; k < dpb.Count; k++)
+ {
+ if (!keep[k])
+ {
+ dpb[k].ShortTerm = dpb[k].LongTerm = false;
+ }
+ }
+ }
+
+ private Picture? FindShortTerm(int poc, Span keep)
+ {
+ for (var k = 0; k < dpb.Count; k++)
+ {
+ if (dpb[k].ShortTerm && !dpb[k].LongTerm && dpb[k].Poc == poc)
+ {
+ keep[k] = true;
+ return dpb[k];
+ }
+ }
+
+ return null;
+ }
+
+ /// The conditions of C.5.2.2 and C.5.2.3 on the pictures waiting for output.
+ private bool OutputWanted(Sps s, int t)
+ {
+ var waiting = 0;
+ var late = false;
+ var maxLatency = s.MaxNumReorderPics[t] + (long)s.MaxLatencyIncreasePlus1[t] - 1;
+ foreach (var picture in dpb)
+ {
+ if (picture.NeededForOutput)
+ {
+ waiting++;
+ late |= s.MaxLatencyIncreasePlus1[t] != 0 && picture.LatencyCount >= maxLatency;
+ }
+ }
+
+ return waiting > s.MaxNumReorderPics[t] || late;
+ }
+
+ private void RemoveUnused()
+ {
+ for (var k = dpb.Count - 1; k >= 0; k--)
+ {
+ if (!dpb[k].NeededForOutput && !dpb[k].IsReference)
+ {
+ pool.Push(dpb[k]);
+ dpb.RemoveAt(k);
+ }
+ }
+ }
+
+ /// The bumping process (C.5.2.4): outputs the waiting picture with the smallest POC; false when none waits.
+ private bool Bump()
+ {
+ Picture? best = null;
+ foreach (var picture in dpb)
+ {
+ if (picture.NeededForOutput && (best is null || picture.Poc < best.Poc))
+ {
+ best = picture;
+ }
+ }
+
+ if (best is null)
+ {
+ return false;
+ }
+
+ best.NeededForOutput = false;
+ FrameOutput?.Invoke(best.ToFrame());
+ if (!best.IsReference)
+ {
+ dpb.Remove(best);
+ pool.Push(best);
+ }
+
+ return true;
+ }
+
+ private Picture NewPicture(Sps s)
+ {
+ while (pool.Count > 0)
+ {
+ var picture = pool.Pop();
+ if (picture.Fits(s))
+ {
+ picture.Sps = s;
+ picture.ShortTerm = picture.LongTerm = picture.NeededForOutput = picture.Generated = false;
+ picture.LatencyCount = 0;
+ return picture;
+ }
+ }
+
+ return new Picture(s);
+ }
+
+ ///
+ /// Finishes the current picture: in-loop filters, then the marking and the "additional bumping" of C.5.2.3. A damaged
+ /// picture whose filtering fails raises an and is dropped.
+ ///
+ private void FinishPicture()
+ {
+ if (cur is null)
+ {
+ return;
+ }
+
+ var picture = cur;
+ cur = null;
+ picture.IntraOnly = true;
+ foreach (var header in slices)
+ {
+ picture.IntraOnly &= header.IsIntra;
+ }
+
+ try
+ {
+ ApplyInLoopFilters(picture);
+ }
+ catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException)
+ {
+ throw new H265Exception("Flusso HEVC troncato o danneggiato.");
+ }
+
+ PictureDecoded?.Invoke(picture);
+ foreach (var other in dpb)
+ {
+ if (other.NeededForOutput)
+ {
+ other.LatencyCount++;
+ }
+ }
+
+ picture.NeededForOutput = picture.OutputFlag;
+ picture.LatencyCount = 0;
+ picture.ShortTerm = true;
+ dpb.Add(picture);
+ var s = picture.Sps;
+ while (OutputWanted(s, s.HighestTid))
+ {
+ if (!Bump())
+ {
+ break;
+ }
+ }
+ }
+}
diff --git a/src/Febe.Core/Codecs/H265/H265Tables.cs b/src/Febe.Core/Codecs/H265/H265Tables.cs
new file mode 100644
index 0000000..8de4390
--- /dev/null
+++ b/src/Febe.Core/Codecs/H265/H265Tables.cs
@@ -0,0 +1,175 @@
+namespace Febe.Core.Codecs.H265;
+
+///
+/// Constant tables of ITU-T H.265, transcribed from the text of the Recommendation: scan orders (§6.5.3–6.5.5), default
+/// scaling lists (table 7-6), intra prediction angles (tables 8-4 and 8-5), the chroma QP mapping (table 8-10), the
+/// thresholds of the deblocking filter (table 8-12) and the transform matrices (§8.6.4.2).
+///
+internal static class H265Tables
+{
+ /// intraPredAngle by intra prediction mode (table 8-4); modes 0 (planar) and 1 (DC) have none.
+ internal static readonly sbyte[] IntraPredAngle =
+ [
+ 0, 0, 32, 26, 21, 17, 13, 9, 5, 2, 0, -2, -5, -9, -13, -17, -21, -26,
+ -32, -26, -21, -17, -13, -9, -5, -2, 0, 2, 5, 9, 13, 17, 21, 26, 32,
+ ];
+
+ /// invAngle of the modes 11 to 25 (table 8-5), indexed by mode − 11.
+ internal static readonly short[] InvAngle = [-4096, -1638, -910, -630, -482, -390, -315, -256, -315, -390, -482, -630, -910, -1638, -4096];
+
+ /// QpC as a function of qPi for ChromaArrayType 1 (table 8-10), for qPi from 30 to 43.
+ internal static readonly byte[] ChromaQp30To43 = [29, 30, 31, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37];
+
+ /// β′ for Q from 0 to 51 (table 8-12).
+ internal static readonly byte[] Beta =
+ [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24,
+ 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64,
+ ];
+
+ /// tC′ for Q from 0 to 53 (table 8-12).
+ internal static readonly byte[] Tc =
+ [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3,
+ 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24,
+ ];
+
+ /// levelScale[qP % 6] of the scaling process (§8.6.3).
+ internal static readonly int[] LevelScale = [40, 45, 51, 57, 64, 72];
+
+ /// Default values of ScalingList[1..3][0..2] (intra), in up-right diagonal order (table 7-6).
+ internal static readonly byte[] DefaultScalingIntra =
+ [
+ 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 16, 17, 16, 17, 18, 17, 18, 18, 17, 18, 21, 19, 20, 21, 20, 19, 21, 24, 22, 22, 24,
+ 24, 22, 22, 24, 25, 25, 27, 30, 27, 25, 25, 29, 31, 35, 35, 31, 29, 36, 41, 44, 41, 36, 47, 54, 54, 47, 65, 70, 65, 88, 88, 115,
+ ];
+
+ /// Default values of ScalingList[1..3][3..5] (inter), in up-right diagonal order (table 7-6).
+ internal static readonly byte[] DefaultScalingInter =
+ [
+ 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 20, 20, 20, 20, 20, 20, 20, 24, 24, 24, 24,
+ 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 28, 28, 28, 28, 28, 28, 33, 33, 33, 33, 33, 41, 41, 41, 41, 54, 54, 54, 71, 71, 91,
+ ];
+
+ ///
+ /// Scan orders of blocks from 1×1 to 32×32 (index log2 size, 0 to 5) for scanIdx 0 (up-right diagonal, §6.5.3), 1
+ /// (horizontal, §6.5.4) and 2 (vertical, §6.5.5): each entry is x | (y << 8).
+ ///
+ internal static readonly ushort[][][] ScanOrder = BuildScans();
+
+ /// For the 4×4 scans: position in scan order of each raster position (y * 4 + x), by scanIdx.
+ internal static readonly byte[][] ScanPosition4x4 = BuildInverse4x4();
+
+ ///
+ /// Magnitudes of the coefficients of the 32-point DCT of §8.6.4.2 by angle index a (cos(aπ/64) scaled), for a from 0 to
+ /// 32: the odd rows of the 32-point matrix are 90, 90, 88, 85, …, 4, the odd rows of the 16-point one 90, 87, 80, …, 9,
+ /// those of the 8-point one 89, 75, 50, 18 and of the 4-point one 83, 36.
+ ///
+ internal static readonly byte[] DctCosines =
+ [
+ 64, 90, 90, 90, 89, 88, 87, 85, 83, 82, 80, 78, 75, 73, 70, 67, 64, 61, 57, 54, 50, 46, 43, 38, 36, 31, 25, 22, 18, 13, 9, 4, 0,
+ ];
+
+ ///
+ /// The 32×32 inverse DCT matrix of §8.6.4.2, as transMatrix[k][n] = DctMatrix[k * 32 + n] with k the frequency and n
+ /// the sample: the 4-, 8- and 16-point matrices are its rows 32/N·k and first N columns.
+ ///
+ internal static readonly short[] DctMatrix = BuildDct();
+
+ /// The 4×4 DST matrix of §8.6.4.2 (trType 1), transMatrix[k][n] = DstMatrix[k * 4 + n].
+ internal static readonly short[] DstMatrix = [29, 55, 74, 84, 74, 74, 0, -74, 84, -29, -74, 55, 55, -84, 74, -29];
+
+ private static short[] BuildDct()
+ {
+ var m = new short[32 * 32];
+ for (var k = 0; k < 32; k++)
+ {
+ for (var n = 0; n < 32; n++)
+ {
+ if (k == 0)
+ {
+ m[n] = 64;
+ continue;
+ }
+
+ // The entry is cos((2n + 1)kπ/64) on the scale of the table: fold the angle into the first quadrant.
+ var a = ((2 * n) + 1) * k % 128;
+ int value = a switch
+ {
+ <= 32 => DctCosines[a],
+ <= 64 => -DctCosines[64 - a],
+ <= 96 => -DctCosines[a - 64],
+ _ => DctCosines[128 - a],
+ };
+ m[(k * 32) + n] = (short)value;
+ }
+ }
+
+ return m;
+ }
+
+ private static ushort[][][] BuildScans()
+ {
+ var scans = new ushort[6][][];
+ for (var log2 = 0; log2 < 6; log2++)
+ {
+ var size = 1 << log2;
+ var diagonal = new ushort[size * size];
+ int i = 0, x = 0, y = 0;
+ var stop = false;
+ while (!stop)
+ {
+ while (y >= 0)
+ {
+ if (x < size && y < size)
+ {
+ diagonal[i++] = (ushort)(x | (y << 8));
+ }
+
+ y--;
+ x++;
+ }
+
+ y = x;
+ x = 0;
+ if (i >= size * size)
+ {
+ stop = true;
+ }
+ }
+
+ var horizontal = new ushort[size * size];
+ var vertical = new ushort[size * size];
+ i = 0;
+ for (y = 0; y < size; y++)
+ {
+ for (x = 0; x < size; x++)
+ {
+ horizontal[i] = (ushort)(x | (y << 8));
+ vertical[i] = (ushort)(y | (x << 8));
+ i++;
+ }
+ }
+
+ scans[log2] = [diagonal, horizontal, vertical];
+ }
+
+ return scans;
+ }
+
+ private static byte[][] BuildInverse4x4()
+ {
+ var inverse = new byte[3][];
+ for (var s = 0; s < 3; s++)
+ {
+ inverse[s] = new byte[16];
+ for (var n = 0; n < 16; n++)
+ {
+ var p = ScanOrder[2][s][n];
+ inverse[s][((p >> 8) * 4) + (p & 0xFF)] = (byte)n;
+ }
+ }
+
+ return inverse;
+ }
+}
diff --git a/src/Febe.Core/Codecs/H265/ParameterSets.cs b/src/Febe.Core/Codecs/H265/ParameterSets.cs
new file mode 100644
index 0000000..591d3ab
--- /dev/null
+++ b/src/Febe.Core/Codecs/H265/ParameterSets.cs
@@ -0,0 +1,972 @@
+namespace Febe.Core.Codecs.H265;
+
+/// A short-term reference picture set (§7.3.7, §7.4.8): the POC deltas of the negative and positive pictures.
+internal sealed class ShortTermRps
+{
+ /// At most sps_max_dec_pic_buffering_minus1 + 1 ≤ 16 pictures in each half.
+ internal const int MaxPictures = 16;
+
+ internal int NumNegative;
+ internal int NumPositive;
+ internal readonly int[] DeltaPocS0 = new int[MaxPictures];
+ internal readonly int[] DeltaPocS1 = new int[MaxPictures];
+ internal readonly bool[] UsedS0 = new bool[MaxPictures];
+ internal readonly bool[] UsedS1 = new bool[MaxPictures];
+
+ internal int NumDeltaPocs => NumNegative + NumPositive;
+
+ ///
+ /// st_ref_pic_set(stRpsIdx): is stRpsIdx, the sets already read
+ /// from the SPS (all of them when the set is in a slice header, where equals their number).
+ ///
+ internal static ShortTermRps Parse(BitReader r, int index, int spsCount, IReadOnlyList spsSets)
+ {
+ var rps = new ShortTermRps();
+ var interPrediction = index != 0 && r.ReadFlag();
+ if (interPrediction)
+ {
+ var deltaIdx = index == spsCount ? r.ReadUe(index - 1) + 1 : 1;
+ var reference = spsSets[index - deltaIdx];
+ var sign = r.ReadFlag();
+ var deltaRps = (r.ReadUe(32767) + 1) * (sign ? -1 : 1);
+ var count = reference.NumDeltaPocs;
+ Span used = stackalloc bool[(MaxPictures * 2) + 1];
+ Span useDelta = stackalloc bool[(MaxPictures * 2) + 1];
+ for (var j = 0; j <= count; j++)
+ {
+ used[j] = r.ReadFlag();
+ useDelta[j] = used[j] || r.ReadFlag();
+ }
+
+ // (7-61) and (7-62).
+ var i = 0;
+ for (var j = reference.NumPositive - 1; j >= 0; j--)
+ {
+ var dPoc = reference.DeltaPocS1[j] + deltaRps;
+ if (dPoc < 0 && useDelta[reference.NumNegative + j])
+ {
+ rps.Add0(ref i, dPoc, used[reference.NumNegative + j]);
+ }
+ }
+
+ if (deltaRps < 0 && useDelta[count])
+ {
+ rps.Add0(ref i, deltaRps, used[count]);
+ }
+
+ for (var j = 0; j < reference.NumNegative; j++)
+ {
+ var dPoc = reference.DeltaPocS0[j] + deltaRps;
+ if (dPoc < 0 && useDelta[j])
+ {
+ rps.Add0(ref i, dPoc, used[j]);
+ }
+ }
+
+ rps.NumNegative = i;
+ i = 0;
+ for (var j = reference.NumNegative - 1; j >= 0; j--)
+ {
+ var dPoc = reference.DeltaPocS0[j] + deltaRps;
+ if (dPoc > 0 && useDelta[j])
+ {
+ rps.Add1(ref i, dPoc, used[j]);
+ }
+ }
+
+ if (deltaRps > 0 && useDelta[count])
+ {
+ rps.Add1(ref i, deltaRps, used[count]);
+ }
+
+ for (var j = 0; j < reference.NumPositive; j++)
+ {
+ var dPoc = reference.DeltaPocS1[j] + deltaRps;
+ if (dPoc > 0 && useDelta[reference.NumNegative + j])
+ {
+ rps.Add1(ref i, dPoc, used[reference.NumNegative + j]);
+ }
+ }
+
+ rps.NumPositive = i;
+ }
+ else
+ {
+ rps.NumNegative = r.ReadUe(MaxPictures);
+ rps.NumPositive = r.ReadUe(MaxPictures);
+ if (rps.NumDeltaPocs > MaxPictures)
+ {
+ throw new H265Exception("Insieme di riferimento con troppe immagini.");
+ }
+
+ var poc = 0;
+ for (var i = 0; i < rps.NumNegative; i++)
+ {
+ poc -= r.ReadUe(32767) + 1;
+ rps.DeltaPocS0[i] = poc;
+ rps.UsedS0[i] = r.ReadFlag();
+ }
+
+ poc = 0;
+ for (var i = 0; i < rps.NumPositive; i++)
+ {
+ poc += r.ReadUe(32767) + 1;
+ rps.DeltaPocS1[i] = poc;
+ rps.UsedS1[i] = r.ReadFlag();
+ }
+ }
+
+ return rps;
+ }
+
+ private void Add0(ref int i, int dPoc, bool used)
+ {
+ if (i >= MaxPictures)
+ {
+ throw new H265Exception("Insieme di riferimento con troppe immagini.");
+ }
+
+ DeltaPocS0[i] = dPoc;
+ UsedS0[i++] = used;
+ }
+
+ private void Add1(ref int i, int dPoc, bool used)
+ {
+ if (i >= MaxPictures)
+ {
+ throw new H265Exception("Insieme di riferimento con troppe immagini.");
+ }
+
+ DeltaPocS1[i] = dPoc;
+ UsedS1[i++] = used;
+ }
+}
+
+///
+/// Scaling factors (§7.3.4, §7.4.5): ScalingFactor[sizeId][matrixId] as raster arrays (y * size + x), sizeId 0 to 3 for
+/// 4×4 to 32×32 and matrixId 0 to 5 (intra Y, Cb, Cr, then inter Y, Cb, Cr).
+///
+internal sealed class ScalingList
+{
+ private ScalingList()
+ {
+ }
+
+ /// Factors[sizeId * 6 + matrixId].
+ internal byte[][] Factors { get; } = new byte[24][];
+
+ /// The lists when scaling_list_enabled_flag is 1 and no list is sent: table 7-5 and table 7-6.
+ internal static ScalingList Default()
+ {
+ var lists = new byte[24][];
+ var dc = new int[24];
+ for (var sizeId = 0; sizeId < 4; sizeId++)
+ {
+ for (var matrixId = 0; matrixId < 6; matrixId++)
+ {
+ SetDefault(lists, dc, sizeId, matrixId);
+ }
+ }
+
+ return Build(lists, dc);
+ }
+
+ /// scaling_list_data().
+ internal static ScalingList Parse(BitReader r)
+ {
+ var lists = new byte[24][];
+ var dc = new int[24];
+ for (var sizeId = 0; sizeId < 4; sizeId++)
+ {
+ var coefNum = Math.Min(64, 1 << (4 + (sizeId << 1)));
+ for (var matrixId = 0; matrixId < 6; matrixId += sizeId == 3 ? 3 : 1)
+ {
+ var id = (sizeId * 6) + matrixId;
+ if (!r.ReadFlag())
+ {
+ // scaling_list_pred_matrix_id_delta: 0 is the default list, otherwise a copy of an earlier one.
+ var step = sizeId == 3 ? 3 : 1;
+ var delta = r.ReadUe(matrixId / step);
+ if (delta == 0)
+ {
+ SetDefault(lists, dc, sizeId, matrixId);
+ }
+ else
+ {
+ var reference = (sizeId * 6) + matrixId - (delta * step);
+ lists[id] = lists[reference];
+ dc[id] = dc[reference];
+ }
+ }
+ else
+ {
+ var list = new byte[coefNum];
+ var nextCoef = 8;
+ if (sizeId > 1)
+ {
+ nextCoef = r.ReadSe(-7, 247) + 8;
+ dc[id] = nextCoef;
+ }
+
+ for (var i = 0; i < coefNum; i++)
+ {
+ var delta = r.ReadSe(-128, 127);
+ nextCoef = (nextCoef + delta + 256) % 256;
+ list[i] = (byte)nextCoef;
+ }
+
+ lists[id] = list;
+ if (sizeId <= 1)
+ {
+ dc[id] = list[0];
+ }
+ }
+ }
+ }
+
+ // 32×32 chroma lists exist only for ChromaArrayType 3 (§7.3.4): they are those of the 16×16 ones.
+ foreach (var matrixId in (ReadOnlySpan)[1, 2, 4, 5])
+ {
+ lists[18 + matrixId] = lists[12 + matrixId];
+ dc[18 + matrixId] = dc[12 + matrixId];
+ }
+
+ return Build(lists, dc);
+ }
+
+ private static void SetDefault(byte[][] lists, int[] dc, int sizeId, int matrixId)
+ {
+ var id = (sizeId * 6) + matrixId;
+ if (sizeId == 0)
+ {
+ lists[id] = [16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16];
+ }
+ else
+ {
+ lists[id] = matrixId < 3 ? H265Tables.DefaultScalingIntra : H265Tables.DefaultScalingInter;
+ }
+
+ dc[id] = 16;
+ }
+
+ /// ScalingFactor from the lists (7-40 to 7-44): lists in diagonal order, upsampled beyond 8×8, with the DC.
+ private static ScalingList Build(byte[][] lists, int[] dc)
+ {
+ var result = new ScalingList();
+ for (var sizeId = 0; sizeId < 4; sizeId++)
+ {
+ var size = 4 << sizeId;
+ var scan = sizeId == 0 ? H265Tables.ScanOrder[2][0] : H265Tables.ScanOrder[3][0];
+ var ratio = sizeId <= 1 ? 1 : size / 8;
+ for (var matrixId = 0; matrixId < 6; matrixId++)
+ {
+ var id = (sizeId * 6) + matrixId;
+ var list = lists[id];
+ var factors = new byte[size * size];
+ for (var i = 0; i < list.Length; i++)
+ {
+ var x = scan[i] & 0xFF;
+ var y = scan[i] >> 8;
+ for (var j = 0; j < ratio; j++)
+ {
+ for (var k = 0; k < ratio; k++)
+ {
+ factors[((y * ratio) + j) * size + (x * ratio) + k] = list[i];
+ }
+ }
+ }
+
+ if (sizeId >= 2)
+ {
+ factors[0] = (byte)dc[id];
+ }
+
+ result.Factors[id] = factors;
+ }
+ }
+
+ return result;
+ }
+}
+
+/// A sequence parameter set (§7.3.2.2), with what decoding needs.
+internal sealed class Sps
+{
+ /// MaxLumaPs of level 6.2 (table A.8): the largest picture of any level.
+ internal const int MaxLumaPs = 35_651_584;
+
+ /// Largest width or height of any level: Sqrt(MaxLumaPs × 8).
+ internal const int MaxDimension = 16_888;
+
+ internal int Id;
+ internal int MaxSubLayersMinus1;
+ internal int ProfileIdc;
+ internal int ChromaFormatIdc;
+ internal bool SeparateColourPlane;
+ internal int Width;
+ internal int Height;
+ internal int ConfLeft, ConfRight, ConfTop, ConfBottom;
+ internal int BitDepthY;
+ internal int BitDepthC;
+ internal int Log2MaxPocLsb;
+ internal readonly int[] MaxDecPicBufferingMinus1 = new int[8];
+ internal readonly int[] MaxNumReorderPics = new int[8];
+ internal readonly int[] MaxLatencyIncreasePlus1 = new int[8];
+ internal int Log2MinCbSize;
+ internal int Log2CtbSize;
+ internal int Log2MinTbSize;
+ internal int Log2MaxTbSize;
+ internal int MaxTransformHierarchyDepthInter;
+ internal int MaxTransformHierarchyDepthIntra;
+ internal bool ScalingListEnabled;
+ internal ScalingList? ScalingList;
+ internal bool AmpEnabled;
+ internal bool SaoEnabled;
+ internal bool PcmEnabled;
+ internal int PcmBitDepthY;
+ internal int PcmBitDepthC;
+ internal int Log2MinPcmCbSize;
+ internal int Log2MaxPcmCbSize;
+ internal bool PcmLoopFilterDisabled;
+ internal readonly List ShortTermRpsList = [];
+ internal bool LongTermRefsPresent;
+ internal int NumLongTermRefPicsSps;
+ internal readonly int[] LtRefPicPocLsbSps = new int[32];
+ internal readonly bool[] UsedByCurrPicLtSps = new bool[32];
+ internal bool TemporalMvpEnabled;
+ internal bool StrongIntraSmoothing;
+
+ // Range extension (§7.3.2.2.2): parsed; streams that use these tools are refused for now.
+ internal bool TransformSkipRotationEnabled;
+ internal bool TransformSkipContextEnabled;
+ internal bool ImplicitRdpcmEnabled;
+ internal bool ExplicitRdpcmEnabled;
+ internal bool ExtendedPrecisionProcessing;
+ internal bool IntraSmoothingDisabled;
+ internal bool HighPrecisionOffsetsEnabled;
+ internal bool PersistentRiceAdaptationEnabled;
+ internal bool CabacBypassAlignmentEnabled;
+
+ /// VUI colour description: matrix_coeffs (2 = unspecified) and video_full_range_flag.
+ internal int MatrixCoefficients = 2;
+
+ internal bool FullRange;
+
+ internal int ChromaArrayType => SeparateColourPlane ? 0 : ChromaFormatIdc;
+
+ internal int SubWidthC => ChromaFormatIdc is 1 or 2 ? 2 : 1;
+
+ internal int SubHeightC => ChromaFormatIdc == 1 ? 2 : 1;
+
+ internal int CtbSize => 1 << Log2CtbSize;
+
+ internal int WidthInCtbs => (Width + CtbSize - 1) >> Log2CtbSize;
+
+ internal int HeightInCtbs => (Height + CtbSize - 1) >> Log2CtbSize;
+
+ internal int CtbCount => WidthInCtbs * HeightInCtbs;
+
+ internal int QpBdOffsetY => 6 * (BitDepthY - 8);
+
+ internal int QpBdOffsetC => 6 * (BitDepthC - 8);
+
+ internal int HighestTid => MaxSubLayersMinus1;
+
+ internal bool UsesRangeExtensionTools =>
+ TransformSkipRotationEnabled || TransformSkipContextEnabled || ImplicitRdpcmEnabled || ExplicitRdpcmEnabled
+ || ExtendedPrecisionProcessing || IntraSmoothingDisabled || HighPrecisionOffsetsEnabled
+ || PersistentRiceAdaptationEnabled || CabacBypassAlignmentEnabled;
+
+ internal static Sps Parse(BitReader r)
+ {
+ var s = new Sps();
+ r.Skip(4); // sps_video_parameter_set_id
+ s.MaxSubLayersMinus1 = r.ReadInt(3);
+ if (s.MaxSubLayersMinus1 > 6)
+ {
+ throw new H265Exception("SPS con troppi sottolivelli temporali.");
+ }
+
+ r.Skip(1); // sps_temporal_id_nesting_flag
+ s.ProfileIdc = ProfileTierLevel.Skip(r, true, s.MaxSubLayersMinus1);
+ s.Id = r.ReadUe(15);
+ s.ChromaFormatIdc = r.ReadUe(3);
+ if (s.ChromaFormatIdc == 3)
+ {
+ s.SeparateColourPlane = r.ReadFlag();
+ }
+
+ s.Width = r.ReadUe(MaxDimension);
+ s.Height = r.ReadUe(MaxDimension);
+ if (s.Width == 0 || s.Height == 0 || (long)s.Width * s.Height > MaxLumaPs)
+ {
+ throw new H265Exception("Dimensioni dell'immagine HEVC non valide.");
+ }
+
+ if (r.ReadFlag())
+ {
+ s.ConfLeft = r.ReadUe(MaxDimension) * s.SubWidthC;
+ s.ConfRight = r.ReadUe(MaxDimension) * s.SubWidthC;
+ s.ConfTop = r.ReadUe(MaxDimension) * s.SubHeightC;
+ s.ConfBottom = r.ReadUe(MaxDimension) * s.SubHeightC;
+ if (s.ConfLeft + s.ConfRight >= s.Width || s.ConfTop + s.ConfBottom >= s.Height)
+ {
+ throw new H265Exception("Finestra di conformità che non lascia immagine.");
+ }
+ }
+
+ s.BitDepthY = r.ReadUe(8) + 8;
+ s.BitDepthC = r.ReadUe(8) + 8;
+ s.Log2MaxPocLsb = r.ReadUe(12) + 4;
+ var orderingInfo = r.ReadFlag();
+ for (var i = orderingInfo ? 0 : s.MaxSubLayersMinus1; i <= s.MaxSubLayersMinus1; i++)
+ {
+ s.MaxDecPicBufferingMinus1[i] = r.ReadUe(15);
+ s.MaxNumReorderPics[i] = r.ReadUe(s.MaxDecPicBufferingMinus1[i]);
+ s.MaxLatencyIncreasePlus1[i] = (int)Math.Min(r.ReadUe(), int.MaxValue);
+ }
+
+ if (!orderingInfo)
+ {
+ for (var i = 0; i < s.MaxSubLayersMinus1; i++)
+ {
+ s.MaxDecPicBufferingMinus1[i] = s.MaxDecPicBufferingMinus1[s.MaxSubLayersMinus1];
+ s.MaxNumReorderPics[i] = s.MaxNumReorderPics[s.MaxSubLayersMinus1];
+ s.MaxLatencyIncreasePlus1[i] = s.MaxLatencyIncreasePlus1[s.MaxSubLayersMinus1];
+ }
+ }
+
+ s.Log2MinCbSize = r.ReadUe(3) + 3;
+ s.Log2CtbSize = s.Log2MinCbSize + r.ReadUe(3);
+ s.Log2MinTbSize = r.ReadUe(3) + 2;
+ s.Log2MaxTbSize = s.Log2MinTbSize + r.ReadUe(3);
+ if (s.Log2CtbSize > 6 || s.Log2CtbSize < 4 || s.Log2MinTbSize >= s.Log2MinCbSize || s.Log2MaxTbSize > Math.Min(s.Log2CtbSize, 5)
+ || s.Width % (1 << s.Log2MinCbSize) != 0 || s.Height % (1 << s.Log2MinCbSize) != 0)
+ {
+ throw new H265Exception("Dimensioni dei blocchi HEVC non valide.");
+ }
+
+ s.MaxTransformHierarchyDepthInter = r.ReadUe(s.Log2CtbSize - s.Log2MinTbSize);
+ s.MaxTransformHierarchyDepthIntra = r.ReadUe(s.Log2CtbSize - s.Log2MinTbSize);
+ s.ScalingListEnabled = r.ReadFlag();
+ if (s.ScalingListEnabled)
+ {
+ s.ScalingList = r.ReadFlag() ? ScalingList.Parse(r) : ScalingList.Default();
+ }
+
+ s.AmpEnabled = r.ReadFlag();
+ s.SaoEnabled = r.ReadFlag();
+ s.PcmEnabled = r.ReadFlag();
+ if (s.PcmEnabled)
+ {
+ s.PcmBitDepthY = r.ReadInt(4) + 1;
+ s.PcmBitDepthC = r.ReadInt(4) + 1;
+ s.Log2MinPcmCbSize = r.ReadUe(2) + 3;
+ s.Log2MaxPcmCbSize = s.Log2MinPcmCbSize + r.ReadUe(2);
+ s.PcmLoopFilterDisabled = r.ReadFlag();
+ if (s.PcmBitDepthY > s.BitDepthY || s.PcmBitDepthC > s.BitDepthC || s.Log2MaxPcmCbSize > Math.Min(s.Log2CtbSize, 5))
+ {
+ throw new H265Exception("Parametri PCM non validi.");
+ }
+ }
+
+ var count = r.ReadUe(64);
+ for (var i = 0; i < count; i++)
+ {
+ s.ShortTermRpsList.Add(ShortTermRps.Parse(r, i, count, s.ShortTermRpsList));
+ }
+
+ s.LongTermRefsPresent = r.ReadFlag();
+ if (s.LongTermRefsPresent)
+ {
+ s.NumLongTermRefPicsSps = r.ReadUe(32);
+ for (var i = 0; i < s.NumLongTermRefPicsSps; i++)
+ {
+ s.LtRefPicPocLsbSps[i] = r.ReadInt(s.Log2MaxPocLsb);
+ s.UsedByCurrPicLtSps[i] = r.ReadFlag();
+ }
+ }
+
+ s.TemporalMvpEnabled = r.ReadFlag();
+ s.StrongIntraSmoothing = r.ReadFlag();
+ if (r.ReadFlag())
+ {
+ Vui.Parse(r, s);
+ }
+
+ if (r.ReadFlag())
+ {
+ var range = r.ReadFlag();
+ r.Skip(7); // sps_multilayer_extension_flag, sps_3d_extension_flag, sps_scc_extension_flag, sps_extension_4bits
+ if (range)
+ {
+ s.TransformSkipRotationEnabled = r.ReadFlag();
+ s.TransformSkipContextEnabled = r.ReadFlag();
+ s.ImplicitRdpcmEnabled = r.ReadFlag();
+ s.ExplicitRdpcmEnabled = r.ReadFlag();
+ s.ExtendedPrecisionProcessing = r.ReadFlag();
+ s.IntraSmoothingDisabled = r.ReadFlag();
+ s.HighPrecisionOffsetsEnabled = r.ReadFlag();
+ s.PersistentRiceAdaptationEnabled = r.ReadFlag();
+ s.CabacBypassAlignmentEnabled = r.ReadFlag();
+ }
+
+ // Other extensions (multilayer, 3D, screen content) are not decoded: their data is ignored.
+ }
+
+ return s;
+ }
+}
+
+/// profile_tier_level() (§7.3.3): skipped, except general_profile_idc.
+internal static class ProfileTierLevel
+{
+ internal static int Skip(BitReader r, bool profilePresent, int maxSubLayersMinus1)
+ {
+ var profileIdc = 0;
+ if (profilePresent)
+ {
+ r.Skip(3); // general_profile_space, general_tier_flag
+ profileIdc = r.ReadInt(5);
+ r.Skip(32 + 48); // compatibility flags, constraint flags
+ }
+
+ r.Skip(8); // general_level_idc
+ Span profile = stackalloc bool[8];
+ Span level = stackalloc bool[8];
+ for (var i = 0; i < maxSubLayersMinus1; i++)
+ {
+ profile[i] = r.ReadFlag();
+ level[i] = r.ReadFlag();
+ }
+
+ if (maxSubLayersMinus1 > 0)
+ {
+ r.Skip(2 * (8 - maxSubLayersMinus1));
+ }
+
+ for (var i = 0; i < maxSubLayersMinus1; i++)
+ {
+ if (profile[i])
+ {
+ r.Skip(88);
+ }
+
+ if (level[i])
+ {
+ r.Skip(8);
+ }
+ }
+
+ return profileIdc;
+ }
+}
+
+/// vui_parameters() (Annex E): only the colour description is kept.
+internal static class Vui
+{
+ internal static void Parse(BitReader r, Sps s)
+ {
+ if (r.ReadFlag() && r.ReadInt(8) == 255)
+ {
+ r.Skip(32); // sar_width, sar_height
+ }
+
+ if (r.ReadFlag())
+ {
+ r.Skip(1); // overscan_appropriate_flag
+ }
+
+ if (r.ReadFlag())
+ {
+ r.Skip(3); // video_format
+ s.FullRange = r.ReadFlag();
+ if (r.ReadFlag())
+ {
+ r.Skip(16); // colour_primaries, transfer_characteristics
+ s.MatrixCoefficients = r.ReadInt(8);
+ }
+ }
+
+ if (r.ReadFlag())
+ {
+ r.ReadUe();
+ r.ReadUe();
+ }
+
+ r.Skip(3); // neutral_chroma_indication_flag, field_seq_flag, frame_field_info_present_flag
+ if (r.ReadFlag())
+ {
+ for (var i = 0; i < 4; i++)
+ {
+ r.ReadUe(); // default display window
+ }
+ }
+
+ if (r.ReadFlag())
+ {
+ r.Skip(64); // vui_num_units_in_tick, vui_time_scale
+ if (r.ReadFlag())
+ {
+ r.ReadUe(); // vui_num_ticks_poc_diff_one_minus1
+ }
+
+ if (r.ReadFlag())
+ {
+ Hrd(r, true, s.MaxSubLayersMinus1);
+ }
+ }
+
+ if (r.ReadFlag())
+ {
+ r.Skip(3); // tiles_fixed_structure_flag, motion_vectors_over_pic_boundaries_flag, restricted_ref_pic_lists_flag
+ for (var i = 0; i < 5; i++)
+ {
+ r.ReadUe();
+ }
+ }
+ }
+
+ /// hrd_parameters() (E.2.2), skipped.
+ internal static void Hrd(BitReader r, bool commonInfo, int maxSubLayersMinus1)
+ {
+ bool nal = false, vcl = false, subPic = false;
+ if (commonInfo)
+ {
+ nal = r.ReadFlag();
+ vcl = r.ReadFlag();
+ if (nal || vcl)
+ {
+ subPic = r.ReadFlag();
+ if (subPic)
+ {
+ r.Skip(8 + 5 + 1 + 5);
+ }
+
+ r.Skip(8); // bit_rate_scale, cpb_size_scale
+ if (subPic)
+ {
+ r.Skip(4);
+ }
+
+ r.Skip(15);
+ }
+ }
+
+ for (var i = 0; i <= maxSubLayersMinus1; i++)
+ {
+ var fixedGeneral = r.ReadFlag();
+ var fixedWithinCvs = fixedGeneral || r.ReadFlag();
+ var lowDelay = false;
+ if (fixedWithinCvs)
+ {
+ r.ReadUe();
+ }
+ else
+ {
+ lowDelay = r.ReadFlag();
+ }
+
+ var cpbCount = lowDelay ? 1 : r.ReadUe(31) + 1;
+ for (var k = (nal ? 1 : 0) + (vcl ? 1 : 0); k > 0; k--)
+ {
+ for (var j = 0; j < cpbCount; j++)
+ {
+ r.ReadUe();
+ r.ReadUe();
+ if (subPic)
+ {
+ r.ReadUe();
+ r.ReadUe();
+ }
+
+ r.Skip(1);
+ }
+ }
+ }
+ }
+}
+
+/// A picture parameter set (§7.3.2.3), with what decoding needs.
+internal sealed class Pps
+{
+ internal int Id;
+ internal int SpsId;
+ internal bool DependentSliceSegmentsEnabled;
+ internal bool OutputFlagPresent;
+ internal int NumExtraSliceHeaderBits;
+ internal bool SignDataHidingEnabled;
+ internal bool CabacInitPresent;
+ internal int NumRefIdxL0DefaultActive;
+ internal int NumRefIdxL1DefaultActive;
+ internal int InitQp;
+ internal bool ConstrainedIntraPred;
+ internal bool TransformSkipEnabled;
+ internal bool CuQpDeltaEnabled;
+ internal int DiffCuQpDeltaDepth;
+ internal int CbQpOffset;
+ internal int CrQpOffset;
+ internal bool SliceChromaQpOffsetsPresent;
+ internal bool WeightedPred;
+ internal bool WeightedBipred;
+ internal bool TransquantBypassEnabled;
+ internal bool TilesEnabled;
+ internal bool EntropyCodingSyncEnabled;
+ internal int NumTileColumns = 1;
+ internal int NumTileRows = 1;
+ internal bool UniformSpacing = true;
+ internal int[] ColumnWidths = [];
+ internal int[] RowHeights = [];
+ internal bool LoopFilterAcrossTilesEnabled = true;
+ internal bool LoopFilterAcrossSlicesEnabled;
+ internal bool DeblockingFilterOverrideEnabled;
+ internal bool DeblockingFilterDisabled;
+ internal int BetaOffsetDiv2;
+ internal int TcOffsetDiv2;
+ internal ScalingList? ScalingList;
+ internal bool ListsModificationPresent;
+ internal int Log2ParallelMergeLevel;
+ internal bool SliceSegmentHeaderExtensionPresent;
+
+ // Range extension (§7.3.2.3.2).
+ internal int Log2MaxTransformSkipSize = 2;
+ internal bool CrossComponentPredictionEnabled;
+ internal bool ChromaQpOffsetListEnabled;
+ internal int DiffCuChromaQpOffsetDepth;
+ internal int ChromaQpOffsetListLength;
+ internal readonly int[] CbQpOffsetList = new int[6];
+ internal readonly int[] CrQpOffsetList = new int[6];
+ internal int Log2SaoOffsetScaleLuma;
+ internal int Log2SaoOffsetScaleChroma;
+
+ /// The tile layout of the SPS the arrays below were computed for.
+ private Sps? layoutSps;
+
+ /// CtbAddrRsToTs, CtbAddrTsToRs and TileId (by raster address) of §6.5.1.
+ internal int[] CtbAddrRsToTs = [];
+
+ internal int[] CtbAddrTsToRs = [];
+ internal int[] TileIdRs = [];
+
+ /// colBd and rowBd: the first CTB column and row of each tile, with one more entry for the end.
+ internal int[] ColBd = [];
+
+ internal int[] RowBd = [];
+
+ internal bool UsesRangeExtensionTools => CrossComponentPredictionEnabled || ChromaQpOffsetListEnabled
+ || Log2SaoOffsetScaleLuma != 0 || Log2SaoOffsetScaleChroma != 0 || Log2MaxTransformSkipSize != 2;
+
+ internal static Pps Parse(BitReader r)
+ {
+ var p = new Pps
+ {
+ Id = r.ReadUe(63),
+ SpsId = r.ReadUe(15),
+ DependentSliceSegmentsEnabled = r.ReadFlag(),
+ OutputFlagPresent = r.ReadFlag(),
+ NumExtraSliceHeaderBits = r.ReadInt(3),
+ SignDataHidingEnabled = r.ReadFlag(),
+ CabacInitPresent = r.ReadFlag(),
+ NumRefIdxL0DefaultActive = r.ReadUe(14) + 1,
+ NumRefIdxL1DefaultActive = r.ReadUe(14) + 1,
+ InitQp = 26 + r.ReadSe(-26 - 36, 25),
+ ConstrainedIntraPred = r.ReadFlag(),
+ TransformSkipEnabled = r.ReadFlag(),
+ CuQpDeltaEnabled = r.ReadFlag(),
+ };
+ if (p.CuQpDeltaEnabled)
+ {
+ p.DiffCuQpDeltaDepth = r.ReadUe(3);
+ }
+
+ p.CbQpOffset = r.ReadSe(-12, 12);
+ p.CrQpOffset = r.ReadSe(-12, 12);
+ p.SliceChromaQpOffsetsPresent = r.ReadFlag();
+ p.WeightedPred = r.ReadFlag();
+ p.WeightedBipred = r.ReadFlag();
+ p.TransquantBypassEnabled = r.ReadFlag();
+ p.TilesEnabled = r.ReadFlag();
+ p.EntropyCodingSyncEnabled = r.ReadFlag();
+ if (p.TilesEnabled)
+ {
+ p.NumTileColumns = r.ReadUe(1055) + 1;
+ p.NumTileRows = r.ReadUe(1055) + 1;
+ p.UniformSpacing = r.ReadFlag();
+ if (!p.UniformSpacing)
+ {
+ p.ColumnWidths = new int[p.NumTileColumns];
+ p.RowHeights = new int[p.NumTileRows];
+ for (var i = 0; i < p.NumTileColumns - 1; i++)
+ {
+ p.ColumnWidths[i] = r.ReadUe(1055) + 1;
+ }
+
+ for (var i = 0; i < p.NumTileRows - 1; i++)
+ {
+ p.RowHeights[i] = r.ReadUe(1055) + 1;
+ }
+ }
+
+ p.LoopFilterAcrossTilesEnabled = r.ReadFlag();
+ }
+
+ p.LoopFilterAcrossSlicesEnabled = r.ReadFlag();
+ if (r.ReadFlag())
+ {
+ p.DeblockingFilterOverrideEnabled = r.ReadFlag();
+ p.DeblockingFilterDisabled = r.ReadFlag();
+ if (!p.DeblockingFilterDisabled)
+ {
+ p.BetaOffsetDiv2 = r.ReadSe(-6, 6);
+ p.TcOffsetDiv2 = r.ReadSe(-6, 6);
+ }
+ }
+
+ if (r.ReadFlag())
+ {
+ p.ScalingList = ScalingList.Parse(r);
+ }
+
+ p.ListsModificationPresent = r.ReadFlag();
+ p.Log2ParallelMergeLevel = r.ReadUe(4) + 2;
+ p.SliceSegmentHeaderExtensionPresent = r.ReadFlag();
+ if (r.ReadFlag())
+ {
+ var range = r.ReadFlag();
+ r.Skip(7); // pps_multilayer_extension_flag, pps_3d_extension_flag, pps_scc_extension_flag, pps_extension_4bits
+ if (range)
+ {
+ if (p.TransformSkipEnabled)
+ {
+ p.Log2MaxTransformSkipSize = r.ReadUe(3) + 2;
+ }
+
+ p.CrossComponentPredictionEnabled = r.ReadFlag();
+ p.ChromaQpOffsetListEnabled = r.ReadFlag();
+ if (p.ChromaQpOffsetListEnabled)
+ {
+ p.DiffCuChromaQpOffsetDepth = r.ReadUe(3);
+ p.ChromaQpOffsetListLength = r.ReadUe(5) + 1;
+ for (var i = 0; i < p.ChromaQpOffsetListLength; i++)
+ {
+ p.CbQpOffsetList[i] = r.ReadSe(-12, 12);
+ p.CrQpOffsetList[i] = r.ReadSe(-12, 12);
+ }
+ }
+
+ p.Log2SaoOffsetScaleLuma = r.ReadUe(6);
+ p.Log2SaoOffsetScaleChroma = r.ReadUe(6);
+ }
+ }
+
+ return p;
+ }
+
+ /// Computes the tile layout and the scan conversions of §6.5.1 for , once.
+ internal void Activate(Sps sps)
+ {
+ if (ReferenceEquals(layoutSps, sps))
+ {
+ return;
+ }
+
+ int w = sps.WidthInCtbs, h = sps.HeightInCtbs;
+ if (NumTileColumns > w || NumTileRows > h)
+ {
+ throw new H265Exception("Più tile che CTB.");
+ }
+
+ var colWidth = new int[NumTileColumns];
+ var rowHeight = new int[NumTileRows];
+ if (UniformSpacing)
+ {
+ for (var i = 0; i < NumTileColumns; i++)
+ {
+ colWidth[i] = ((i + 1) * w / NumTileColumns) - (i * w / NumTileColumns);
+ }
+
+ for (var j = 0; j < NumTileRows; j++)
+ {
+ rowHeight[j] = ((j + 1) * h / NumTileRows) - (j * h / NumTileRows);
+ }
+ }
+ else
+ {
+ var rest = w;
+ for (var i = 0; i < NumTileColumns - 1; i++)
+ {
+ colWidth[i] = ColumnWidths[i];
+ rest -= colWidth[i];
+ }
+
+ colWidth[NumTileColumns - 1] = rest;
+ rest = h;
+ for (var j = 0; j < NumTileRows - 1; j++)
+ {
+ rowHeight[j] = RowHeights[j];
+ rest -= rowHeight[j];
+ }
+
+ rowHeight[NumTileRows - 1] = rest;
+ if (colWidth[NumTileColumns - 1] <= 0 || rowHeight[NumTileRows - 1] <= 0)
+ {
+ throw new H265Exception("Tile più larghe dell'immagine.");
+ }
+ }
+
+ ColBd = new int[NumTileColumns + 1];
+ RowBd = new int[NumTileRows + 1];
+ for (var i = 0; i < NumTileColumns; i++)
+ {
+ ColBd[i + 1] = ColBd[i] + colWidth[i];
+ }
+
+ for (var j = 0; j < NumTileRows; j++)
+ {
+ RowBd[j + 1] = RowBd[j] + rowHeight[j];
+ }
+
+ var count = w * h;
+ CtbAddrRsToTs = new int[count];
+ CtbAddrTsToRs = new int[count];
+ TileIdRs = new int[count];
+ for (var rs = 0; rs < count; rs++)
+ {
+ int tbX = rs % w, tbY = rs / w;
+ int tileX = 0, tileY = 0;
+ for (var i = 0; i < NumTileColumns; i++)
+ {
+ if (tbX >= ColBd[i])
+ {
+ tileX = i;
+ }
+ }
+
+ for (var j = 0; j < NumTileRows; j++)
+ {
+ if (tbY >= RowBd[j])
+ {
+ tileY = j;
+ }
+ }
+
+ var v = 0;
+ for (var i = 0; i < tileX; i++)
+ {
+ v += rowHeight[tileY] * colWidth[i];
+ }
+
+ for (var j = 0; j < tileY; j++)
+ {
+ v += w * rowHeight[j];
+ }
+
+ v += ((tbY - RowBd[tileY]) * colWidth[tileX]) + tbX - ColBd[tileX];
+ CtbAddrRsToTs[rs] = v;
+ CtbAddrTsToRs[v] = rs;
+ TileIdRs[rs] = (tileY * NumTileColumns) + tileX;
+ }
+
+ layoutSps = sps;
+ }
+}
diff --git a/src/Febe.Core/Codecs/H265/Picture.cs b/src/Febe.Core/Codecs/H265/Picture.cs
new file mode 100644
index 0000000..636dad3
--- /dev/null
+++ b/src/Febe.Core/Codecs/H265/Picture.cs
@@ -0,0 +1,159 @@
+namespace Febe.Core.Codecs.H265;
+
+///
+/// A decoded HEVC picture in the decoded picture buffer: its sample arrays at full size (pic_width_in_luma_samples ×
+/// pic_height_in_luma_samples, before the conformance window), one 16-bit value per sample whatever the bit depth, and
+/// its state for reference and output (§8.3.2, C.5.2).
+///
+internal sealed class Picture
+{
+ internal Picture(Sps sps)
+ {
+ Sps = sps;
+ Width = sps.Width;
+ Height = sps.Height;
+ ChromaWidth = sps.ChromaArrayType == 0 ? 0 : Width / sps.SubWidthC;
+ ChromaHeight = sps.ChromaArrayType == 0 ? 0 : Height / sps.SubHeightC;
+ Planes =
+ [
+ new ushort[Width * Height],
+ new ushort[ChromaWidth * ChromaHeight],
+ new ushort[ChromaWidth * ChromaHeight],
+ ];
+ }
+
+ /// The SPS of the picture: a picture of the pool is reused for another SPS of the same size.
+ internal Sps Sps { get; set; }
+
+ internal int Width { get; }
+
+ internal int Height { get; }
+
+ internal int ChromaWidth { get; }
+
+ internal int ChromaHeight { get; }
+
+ /// Y, Cb and Cr; the chroma arrays are empty for 4:0:0.
+ internal ushort[][] Planes { get; }
+
+ internal int Poc;
+
+ internal bool ShortTerm;
+
+ internal bool LongTerm;
+
+ /// Marked "needed for output" (C.5.2).
+ internal bool NeededForOutput;
+
+ internal bool OutputFlag;
+
+ internal int LatencyCount;
+
+ /// Position of the coded picture in decoding order, counting the pictures that are skipped too.
+ internal long DecodeIndex;
+
+ /// A picture generated for a missing reference (§8.3.3): never output, its samples are not meaningful.
+ internal bool Generated;
+
+ /// Every slice of the picture is an I slice: it does not depend on other pictures.
+ internal bool IntraOnly;
+
+ internal bool IsReference => ShortTerm || LongTerm;
+
+ internal int Stride(int cIdx) => cIdx == 0 ? Width : ChromaWidth;
+
+ internal int BitDepth(int cIdx) => cIdx == 0 ? Sps.BitDepthY : Sps.BitDepthC;
+
+ internal bool Fits(Sps sps) => Width == sps.Width && Height == sps.Height && ChromaWidth == (sps.ChromaArrayType == 0 ? 0 : sps.Width / sps.SubWidthC)
+ && ChromaHeight == (sps.ChromaArrayType == 0 ? 0 : sps.Height / sps.SubHeightC);
+
+ /// The picture cropped to the conformance window.
+ internal H265Frame ToFrame()
+ {
+ var s = Sps;
+ var width = Width - s.ConfLeft - s.ConfRight;
+ var height = Height - s.ConfTop - s.ConfBottom;
+ var y = Crop(Planes[0], Width, s.ConfLeft, s.ConfTop, width, height);
+ ushort[] cb = [], cr = [];
+ if (s.ChromaArrayType != 0)
+ {
+ int cx = s.ConfLeft / s.SubWidthC, cy = s.ConfTop / s.SubHeightC;
+ int cw = width / s.SubWidthC, ch = height / s.SubHeightC;
+ cb = Crop(Planes[1], ChromaWidth, cx, cy, cw, ch);
+ cr = Crop(Planes[2], ChromaWidth, cx, cy, cw, ch);
+ }
+
+ return new H265Frame(width, height, s.ChromaArrayType, s.BitDepthY, s.BitDepthC, y, cb, cr, Poc, DecodeIndex, s.MatrixCoefficients, s.FullRange);
+ }
+
+ private static ushort[] Crop(ushort[] plane, int stride, int x0, int y0, int width, int height)
+ {
+ var result = new ushort[width * height];
+ for (var y = 0; y < height; y++)
+ {
+ plane.AsSpan(((y0 + y) * stride) + x0, width).CopyTo(result.AsSpan(y * width, width));
+ }
+
+ return result;
+ }
+}
+
+/// A decoded HEVC frame, cropped to the conformance window, with one 16-bit value per sample.
+/// Luma width after cropping.
+/// Luma height after cropping.
+/// ChromaArrayType: 0 (only luma), 1 (4:2:0), 2 (4:2:2), 3 (4:4:4).
+/// Bits per luma sample.
+/// Bits per chroma sample.
+/// Luma, × .
+/// Blue-difference chroma (empty for 4:0:0).
+/// Red-difference chroma, same size as .
+/// Picture order count.
+/// Position of the coded picture in decoding order.
+/// matrix_coeffs of the VUI (1 = BT.709, 5 and 6 = BT.601, 2 = unspecified).
+/// video_full_range_flag of the VUI.
+public sealed record H265Frame(
+ int Width,
+ int Height,
+ int ChromaFormat,
+ int BitDepthLuma,
+ int BitDepthChroma,
+ ushort[] Y,
+ ushort[] Cb,
+ ushort[] Cr,
+ int Poc,
+ long DecodeIndex,
+ int MatrixCoefficients,
+ bool FullRange)
+{
+ ///
+ /// The frame as reference decoders write it: Y, Cb and Cr one after the other, one byte per sample up to 8 bits,
+ /// otherwise two bytes (the low one first) for every plane.
+ ///
+ public byte[] ToYuvFile()
+ {
+ var wide = Math.Max(BitDepthLuma, BitDepthChroma) > 8;
+ var count = Y.Length + Cb.Length + Cr.Length;
+ var buffer = new byte[wide ? count * 2 : count];
+ var position = 0;
+ foreach (var plane in (ReadOnlySpan)[Y, Cb, Cr])
+ {
+ if (wide)
+ {
+ foreach (var sample in plane)
+ {
+ buffer[position++] = (byte)sample;
+ buffer[position++] = (byte)(sample >> 8);
+ }
+ }
+ else
+ {
+ foreach (var sample in plane)
+ {
+ buffer[position++] = (byte)sample;
+ }
+ }
+ }
+
+ return buffer;
+ }
+}
diff --git a/src/Febe.Core/Codecs/H265/SliceHeader.cs b/src/Febe.Core/Codecs/H265/SliceHeader.cs
new file mode 100644
index 0000000..c8bbfa2
--- /dev/null
+++ b/src/Febe.Core/Codecs/H265/SliceHeader.cs
@@ -0,0 +1,480 @@
+namespace Febe.Core.Codecs.H265;
+
+/// slice_type (§7.4.7.1).
+internal enum SliceType
+{
+ B = 0,
+ P = 1,
+ I = 2,
+}
+
+///
+/// A slice segment header (§7.3.6). A dependent slice segment starts as a copy of the header of the independent slice
+/// segment before it (§7.4.7.1) and only reads its own address and entry points.
+///
+internal sealed class SliceHeader
+{
+ internal bool FirstSliceSegmentInPic;
+ internal bool NoOutputOfPriorPics;
+ internal int PpsId;
+ internal bool Dependent;
+ internal int SegmentAddress;
+
+ /// SliceAddrRs: the address of the first CTB of the slice (of its independent slice segment).
+ internal int SliceAddress;
+
+ internal SliceType Type;
+ internal bool PicOutputFlag = true;
+ internal int ColourPlaneId;
+ internal int PocLsb;
+ internal ShortTermRps? StRps;
+ internal int NumLongTermSps;
+ internal int NumLongTermPics;
+ internal int[] PocLsbLt = [];
+ internal bool[] UsedByCurrPicLt = [];
+ internal bool[] DeltaPocMsbPresent = [];
+ internal int[] DeltaPocMsbCycleLt = [];
+ internal bool TemporalMvpEnabled;
+ internal bool SaoLuma;
+ internal bool SaoChroma;
+ internal readonly int[] NumRefIdxActive = new int[2];
+ internal readonly bool[] ListModification = new bool[2];
+ internal readonly int[][] ListEntry = [new int[16], new int[16]];
+ internal bool MvdL1Zero;
+ internal bool CabacInit;
+ internal bool CollocatedFromL0 = true;
+ internal int CollocatedRefIdx;
+ internal int LumaLog2WeightDenom;
+ internal int ChromaLog2WeightDenom;
+
+ /// LumaWeightLX and luma_offset_lX by [list][refIdx] (§7.4.7.3).
+ internal readonly int[][] LumaWeight = [new int[16], new int[16]];
+
+ internal readonly int[][] LumaOffset = [new int[16], new int[16]];
+
+ /// ChromaWeightLX and ChromaOffsetLX by [list][refIdx * 2 + (cIdx − 1)].
+ internal readonly int[][] ChromaWeight = [new int[32], new int[32]];
+
+ internal readonly int[][] ChromaOffset = [new int[32], new int[32]];
+ internal int MaxNumMergeCand = 5;
+ internal int SliceQpY;
+ internal int CbQpOffset;
+ internal int CrQpOffset;
+ internal bool CuChromaQpOffsetEnabled;
+ internal bool DeblockingDisabled;
+ internal int BetaOffsetDiv2;
+ internal int TcOffsetDiv2;
+ internal bool LoopFilterAcrossSlices;
+ internal int NumEntryPoints;
+ internal int[] EntryPointOffsets = [];
+
+ /// NumPicTotalCurr (7-55).
+ internal int NumPicTotalCurr;
+
+ /// The byte where slice_segment_data() starts in the RBSP.
+ internal int DataOffset;
+
+ internal bool IsIntra => Type == SliceType.I;
+
+ internal int InitType => Type switch
+ {
+ SliceType.I => 0,
+ SliceType.P => CabacInit ? 2 : 1,
+ _ => CabacInit ? 1 : 2,
+ };
+
+ ///
+ /// Reads a slice segment header. is the header of the last independent slice segment of
+ /// the current picture (for a dependent one); and are those it refers to.
+ ///
+ internal static SliceHeader Parse(
+ BitReader r, int nalType, Sps?[] spss, Pps?[] ppss, SliceHeader? previous, out Sps sps, out Pps pps)
+ {
+ var first = r.ReadFlag();
+ var noOutputOfPriorPics = nalType is >= 16 and <= 23 && r.ReadFlag();
+ var ppsId = r.ReadUe(63);
+ pps = ppss[ppsId] ?? throw new H265Exception("Slice con un PPS sconosciuto.");
+ sps = spss[pps.SpsId] ?? throw new H265Exception("PPS con un SPS sconosciuto.");
+ var dependent = false;
+ var address = 0;
+ if (!first)
+ {
+ if (pps.DependentSliceSegmentsEnabled)
+ {
+ dependent = r.ReadFlag();
+ }
+
+ var bits = CeilLog2(sps.CtbCount);
+ address = r.ReadInt(bits);
+ if (address >= sps.CtbCount)
+ {
+ throw new H265Exception("Indirizzo di slice fuori dall'immagine.");
+ }
+ }
+
+ SliceHeader h;
+ if (dependent)
+ {
+ if (previous is null || previous.PpsId != ppsId)
+ {
+ throw new H265Exception("Segmento di slice dipendente senza la sua slice.");
+ }
+
+ h = previous.CloneForDependent();
+ h.Dependent = true;
+ h.FirstSliceSegmentInPic = false;
+ h.SegmentAddress = address;
+ }
+ else
+ {
+ h = new SliceHeader
+ {
+ FirstSliceSegmentInPic = first,
+ NoOutputOfPriorPics = noOutputOfPriorPics,
+ PpsId = ppsId,
+ SegmentAddress = address,
+ SliceAddress = address,
+ };
+ h.ParseIndependent(r, nalType, sps, pps);
+ }
+
+ h.NumEntryPoints = 0;
+ h.EntryPointOffsets = [];
+ if (pps.TilesEnabled || pps.EntropyCodingSyncEnabled)
+ {
+ h.NumEntryPoints = r.ReadUe(sps.CtbCount);
+ if (h.NumEntryPoints > 0)
+ {
+ var length = r.ReadUe(31) + 1;
+ h.EntryPointOffsets = new int[h.NumEntryPoints];
+ for (var i = 0; i < h.NumEntryPoints; i++)
+ {
+ h.EntryPointOffsets[i] = (int)Math.Min(r.Read(length) + 1L, int.MaxValue);
+ }
+ }
+ }
+
+ if (pps.SliceSegmentHeaderExtensionPresent)
+ {
+ var length = r.ReadUe(256);
+ r.Skip(length * 8);
+ }
+
+ // byte_alignment(): a one, then zeros up to the byte boundary.
+ if (!r.ReadFlag())
+ {
+ throw new H265Exception("Allineamento dell'intestazione di slice non valido.");
+ }
+
+ r.AlignToByte();
+ if (r.BitsLeft <= 0)
+ {
+ throw new H265Exception("Slice senza dati.");
+ }
+
+ h.DataOffset = r.Position >> 3;
+ return h;
+ }
+
+ private static int CeilLog2(int value)
+ {
+ var bits = 0;
+ while ((1 << bits) < value)
+ {
+ bits++;
+ }
+
+ return bits;
+ }
+
+ private SliceHeader CloneForDependent() => (SliceHeader)MemberwiseClone();
+
+ private void ParseIndependent(BitReader r, int nalType, Sps sps, Pps pps)
+ {
+ r.Skip(pps.NumExtraSliceHeaderBits);
+ var type = r.ReadUe(2);
+ Type = (SliceType)type;
+ if (pps.OutputFlagPresent)
+ {
+ PicOutputFlag = r.ReadFlag();
+ }
+
+ if (sps.SeparateColourPlane)
+ {
+ ColourPlaneId = r.ReadInt(2);
+ }
+
+ if (nalType != 19 && nalType != 20)
+ {
+ PocLsb = r.ReadInt(sps.Log2MaxPocLsb);
+ var count = sps.ShortTermRpsList.Count;
+ if (!r.ReadFlag())
+ {
+ StRps = ShortTermRps.Parse(r, count, count, sps.ShortTermRpsList);
+ }
+ else
+ {
+ if (count == 0)
+ {
+ throw new H265Exception("Insieme di riferimento dell'SPS che non c'è.");
+ }
+
+ var index = count > 1 ? r.ReadInt(CeilLog2(count)) : 0;
+ if (index >= count)
+ {
+ throw new H265Exception("Insieme di riferimento dell'SPS che non c'è.");
+ }
+
+ StRps = sps.ShortTermRpsList[index];
+ }
+
+ if (sps.LongTermRefsPresent)
+ {
+ if (sps.NumLongTermRefPicsSps > 0)
+ {
+ NumLongTermSps = r.ReadUe(sps.NumLongTermRefPicsSps);
+ }
+
+ NumLongTermPics = r.ReadUe(32);
+ var total = NumLongTermSps + NumLongTermPics;
+ if (total > 32)
+ {
+ throw new H265Exception("Troppi riferimenti a lungo termine.");
+ }
+
+ PocLsbLt = new int[total];
+ UsedByCurrPicLt = new bool[total];
+ DeltaPocMsbPresent = new bool[total];
+ DeltaPocMsbCycleLt = new int[total];
+ for (var i = 0; i < total; i++)
+ {
+ if (i < NumLongTermSps)
+ {
+ var index = sps.NumLongTermRefPicsSps > 1 ? r.ReadInt(CeilLog2(sps.NumLongTermRefPicsSps)) : 0;
+ if (index >= sps.NumLongTermRefPicsSps)
+ {
+ throw new H265Exception("Riferimento a lungo termine dell'SPS che non c'è.");
+ }
+
+ PocLsbLt[i] = sps.LtRefPicPocLsbSps[index];
+ UsedByCurrPicLt[i] = sps.UsedByCurrPicLtSps[index];
+ }
+ else
+ {
+ PocLsbLt[i] = r.ReadInt(sps.Log2MaxPocLsb);
+ UsedByCurrPicLt[i] = r.ReadFlag();
+ }
+
+ DeltaPocMsbPresent[i] = r.ReadFlag();
+ var cycle = DeltaPocMsbPresent[i] ? (int)Math.Min(r.ReadUe(), 1u << 24) : 0;
+
+ // (7-52): the cycles accumulate, separately for the SPS candidates and the others.
+ DeltaPocMsbCycleLt[i] = i == 0 || i == NumLongTermSps ? cycle : cycle + DeltaPocMsbCycleLt[i - 1];
+ }
+ }
+
+ if (sps.TemporalMvpEnabled)
+ {
+ TemporalMvpEnabled = r.ReadFlag();
+ }
+ }
+
+ if (sps.SaoEnabled)
+ {
+ SaoLuma = r.ReadFlag();
+ if (sps.ChromaArrayType != 0)
+ {
+ SaoChroma = r.ReadFlag();
+ }
+ }
+
+ NumPicTotalCurr = 0;
+ if (StRps is { } rps)
+ {
+ for (var i = 0; i < rps.NumNegative; i++)
+ {
+ NumPicTotalCurr += rps.UsedS0[i] ? 1 : 0;
+ }
+
+ for (var i = 0; i < rps.NumPositive; i++)
+ {
+ NumPicTotalCurr += rps.UsedS1[i] ? 1 : 0;
+ }
+ }
+
+ foreach (var used in UsedByCurrPicLt)
+ {
+ NumPicTotalCurr += used ? 1 : 0;
+ }
+
+ if (Type != SliceType.I)
+ {
+ NumRefIdxActive[0] = pps.NumRefIdxL0DefaultActive;
+ NumRefIdxActive[1] = Type == SliceType.B ? pps.NumRefIdxL1DefaultActive : 0;
+ if (r.ReadFlag())
+ {
+ NumRefIdxActive[0] = r.ReadUe(14) + 1;
+ if (Type == SliceType.B)
+ {
+ NumRefIdxActive[1] = r.ReadUe(14) + 1;
+ }
+ }
+
+ if (NumPicTotalCurr == 0)
+ {
+ throw new H265Exception("Slice P o B senza immagini di riferimento.");
+ }
+
+ if (pps.ListsModificationPresent && NumPicTotalCurr > 1)
+ {
+ var bits = CeilLog2(NumPicTotalCurr);
+ for (var list = 0; list < (Type == SliceType.B ? 2 : 1); list++)
+ {
+ ListModification[list] = r.ReadFlag();
+ if (ListModification[list])
+ {
+ for (var i = 0; i < NumRefIdxActive[list]; i++)
+ {
+ ListEntry[list][i] = r.ReadInt(bits);
+ if (ListEntry[list][i] >= NumPicTotalCurr)
+ {
+ throw new H265Exception("Modifica della lista di riferimento non valida.");
+ }
+ }
+ }
+ }
+ }
+
+ if (Type == SliceType.B)
+ {
+ MvdL1Zero = r.ReadFlag();
+ }
+
+ if (pps.CabacInitPresent)
+ {
+ CabacInit = r.ReadFlag();
+ }
+
+ if (TemporalMvpEnabled)
+ {
+ if (Type == SliceType.B)
+ {
+ CollocatedFromL0 = r.ReadFlag();
+ }
+
+ if (NumRefIdxActive[CollocatedFromL0 ? 0 : 1] > 1)
+ {
+ CollocatedRefIdx = r.ReadUe(NumRefIdxActive[CollocatedFromL0 ? 0 : 1] - 1);
+ }
+ }
+
+ if ((pps.WeightedPred && Type == SliceType.P) || (pps.WeightedBipred && Type == SliceType.B))
+ {
+ ParsePredWeightTable(r, sps);
+ }
+
+ MaxNumMergeCand = 5 - r.ReadUe(4);
+ }
+
+ SliceQpY = pps.InitQp + r.ReadSe(-87, 51);
+ if (SliceQpY < -sps.QpBdOffsetY || SliceQpY > 51)
+ {
+ throw new H265Exception("QP di slice fuori dall'intervallo.");
+ }
+
+ if (pps.SliceChromaQpOffsetsPresent)
+ {
+ CbQpOffset = r.ReadSe(-12, 12);
+ CrQpOffset = r.ReadSe(-12, 12);
+ }
+
+ if (pps.ChromaQpOffsetListEnabled)
+ {
+ CuChromaQpOffsetEnabled = r.ReadFlag();
+ }
+
+ var overrideDeblocking = pps.DeblockingFilterOverrideEnabled && r.ReadFlag();
+ DeblockingDisabled = pps.DeblockingFilterDisabled;
+ BetaOffsetDiv2 = pps.BetaOffsetDiv2;
+ TcOffsetDiv2 = pps.TcOffsetDiv2;
+ if (overrideDeblocking)
+ {
+ DeblockingDisabled = r.ReadFlag();
+ if (!DeblockingDisabled)
+ {
+ BetaOffsetDiv2 = r.ReadSe(-6, 6);
+ TcOffsetDiv2 = r.ReadSe(-6, 6);
+ }
+ }
+
+ LoopFilterAcrossSlices = pps.LoopFilterAcrossSlicesEnabled;
+ if (pps.LoopFilterAcrossSlicesEnabled && (SaoLuma || SaoChroma || !DeblockingDisabled))
+ {
+ LoopFilterAcrossSlices = r.ReadFlag();
+ }
+ }
+
+ /// pred_weight_table() (§7.3.6.3), as the weights and offsets of §7.4.7.3.
+ private void ParsePredWeightTable(BitReader r, Sps sps)
+ {
+ LumaLog2WeightDenom = r.ReadUe(7);
+ var chroma = sps.ChromaArrayType != 0;
+ if (chroma)
+ {
+ ChromaLog2WeightDenom = LumaLog2WeightDenom + r.ReadSe(-LumaLog2WeightDenom, 7 - LumaLog2WeightDenom);
+ }
+
+ var offsetShift = sps.HighPrecisionOffsetsEnabled ? 0 : sps.BitDepthY - 8;
+ var offsetShiftC = sps.HighPrecisionOffsetsEnabled ? 0 : sps.BitDepthC - 8;
+ var wpOffsetHalfC = 1 << (sps.HighPrecisionOffsetsEnabled ? sps.BitDepthC - 1 : 7);
+ Span lumaFlags = stackalloc bool[16];
+ Span chromaFlags = stackalloc bool[16];
+ for (var list = 0; list < (Type == SliceType.B ? 2 : 1); list++)
+ {
+ var count = NumRefIdxActive[list];
+ for (var i = 0; i < count; i++)
+ {
+ lumaFlags[i] = r.ReadFlag();
+ }
+
+ for (var i = 0; i < count; i++)
+ {
+ chromaFlags[i] = chroma && r.ReadFlag();
+ }
+
+ for (var i = 0; i < count; i++)
+ {
+ LumaWeight[list][i] = 1 << LumaLog2WeightDenom;
+ LumaOffset[list][i] = 0;
+ if (lumaFlags[i])
+ {
+ LumaWeight[list][i] += r.ReadSe(-128, 127);
+ LumaOffset[list][i] = r.ReadSe(-128, 127) << offsetShift;
+ }
+
+ for (var j = 0; j < 2; j++)
+ {
+ ChromaWeight[list][(i * 2) + j] = 1 << ChromaLog2WeightDenom;
+ ChromaOffset[list][(i * 2) + j] = 0;
+ }
+
+ if (chromaFlags[i])
+ {
+ for (var j = 0; j < 2; j++)
+ {
+ var weight = (1 << ChromaLog2WeightDenom) + r.ReadSe(-128, 127);
+ var deltaOffset = r.ReadSe(-4 * wpOffsetHalfC, (4 * wpOffsetHalfC) - 1);
+
+ // (7-56): the offset is predicted from the weight.
+ var offset = Math.Clamp(
+ (wpOffsetHalfC - ((wpOffsetHalfC * weight) >> ChromaLog2WeightDenom)) + deltaOffset,
+ -wpOffsetHalfC,
+ wpOffsetHalfC - 1);
+ ChromaWeight[list][(i * 2) + j] = weight;
+ ChromaOffset[list][(i * 2) + j] = offset << offsetShiftC;
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/Febe.Core/Codecs/H265/Transform.cs b/src/Febe.Core/Codecs/H265/Transform.cs
new file mode 100644
index 0000000..48209bc
--- /dev/null
+++ b/src/Febe.Core/Codecs/H265/Transform.cs
@@ -0,0 +1,58 @@
+namespace Febe.Core.Codecs.H265;
+
+///
+/// The two-stage inverse transform of §8.6.4.2: columns first, clipped to 16 bits after a 7-bit shift, then rows, with
+/// the final shift of 20 − BitDepth. Columns and rows past the last nonzero coefficient are not computed, since their
+/// contribution is zero.
+///
+internal static class Transform
+{
+ /// Scaled coefficients d, raster (y << log2) + x.
+ /// Residual samples, raster.
+ /// Intermediate values, at least the block size.
+ /// Log2 of the block size.
+ /// trType 1: the 4×4 DST of intra luma blocks.
+ /// Largest column with a nonzero coefficient.
+ /// Largest row with a nonzero coefficient.
+ /// Bit depth of the component.
+ internal static void Inverse(int[] coefficients, int[] output, int[] temp, int log2, bool dst, int maxX, int maxY, int bitDepth)
+ {
+ var size = 1 << log2;
+ ReadOnlySpan matrix = dst ? H265Tables.DstMatrix : H265Tables.DctMatrix;
+ var rowStep = dst ? 4 : 32 << (5 - log2); // matrix row of frequency k: k * rowStep
+
+ // First stage: each column x up to maxX, e[x][y] = Σk transMatrix[k][y] · d[x][k].
+ for (var x = 0; x <= maxX; x++)
+ {
+ for (var y = 0; y < size; y++)
+ {
+ // At most 32 products of a 16-bit coefficient and a matrix entry below 91: no overflow in 32 bits.
+ var sum = 0;
+ for (var k = 0; k <= maxY; k++)
+ {
+ sum += matrix[(k * rowStep) + y] * coefficients[(k << log2) + x];
+ }
+
+ temp[(y << log2) + x] = Math.Clamp((sum + 64) >> 7, short.MinValue, short.MaxValue);
+ }
+ }
+
+ // Second stage: each row y, r[x][y] = Σk transMatrix[k][x] · g[k][y], then the bdShift of §8.6.2.
+ var bdShift = 20 - bitDepth;
+ var add = 1 << (bdShift - 1);
+ for (var y = 0; y < size; y++)
+ {
+ var row = y << log2;
+ for (var x = 0; x < size; x++)
+ {
+ var sum = 0;
+ for (var k = 0; k <= maxX; k++)
+ {
+ sum += matrix[(k * rowStep) + x] * temp[row + k];
+ }
+
+ output[row + x] = (sum + add) >> bdShift;
+ }
+ }
+ }
+}
diff --git a/tests/Febe.Tests/Media/H265/H265ConformanceTests.cs b/tests/Febe.Tests/Media/H265/H265ConformanceTests.cs
index 512ac4f..ffbe54d 100644
--- a/tests/Febe.Tests/Media/H265/H265ConformanceTests.cs
+++ b/tests/Febe.Tests/Media/H265/H265ConformanceTests.cs
@@ -1,18 +1,23 @@
using System.Security.Cryptography;
+using Febe.Core.Codecs.H265;
namespace Febe.Tests.Codecs.H265;
///
-/// The streams of the ITU-T H.265.1 conformance set in Media/H265/Conformita (see LEGGIMI.md there). There is no HEVC
-/// decoder yet: every stream is inconclusive until it exists, and the range extension streams (4:0:0, 4:2:2, 4:4:4,
-/// 12 bits, RExt tools) stay inconclusive until Alberto says whether «HEVC» covers them. The reference data and the
-/// reader of the decoded picture hashes are checked now.
+/// The streams of the ITU-T H.265.1 conformance set in Media/H265/Conformita (see LEGGIMI.md there). The decoder has no
+/// inter prediction yet: the streams with only I slices must match their YUV exactly, the others are inconclusive (their
+/// intra pictures are checked in ), and the range extension streams (4:0:0, 4:2:2,
+/// 4:4:4, 12 bits, RExt tools) stay inconclusive until Alberto says whether «HEVC» covers them.
///
[TestClass]
public sealed class H265ConformanceTests
{
- /// Streams the decoder is expected to reproduce exactly; empty while the decoder is not written.
- private static readonly HashSet s_supported = [];
+ /// Streams the decoder is expected to reproduce exactly: those of Main, Main 10 and Main Still Picture made only of I slices.
+ private static readonly HashSet s_supported =
+ [
+ "IPRED_A_docomo_2", "IPRED_B_Nokia_3", "IPRED_C_Mitsubishi_3", "ipcm_A_NEC_3", "ipcm_B_NEC_3", "ipcm_C_NEC_3",
+ "ipcm_D_NEC_3", "ipcm_E_NEC_2", "MAXBINS_A_TI_5", "POC_A_Bossen_3", "SAO_H_Parabola_1", "VPSSPSPPS_A_MainConcept_1",
+ ];
public static IEnumerable