Decodificatore HEVC scritto in casa, prima parte: le immagini intra coincidono coi flussi di conformità (#58)

Per leggere i video HEVC senza ffmpeg serve un decodificatore nostro, scritto dalla
norma ITU-T H.265. Questa prima parte copre tutto ciò che serve alle immagini intra:
unità NAL Annex B e hvcC, VPS/SPS/PPS (liste di scala, VUI, indicatori RExt),
intestazione di slice, POC, RPS, DPB con uscita e bumping (C.5.2), CABAC con tutte
le tabelle d'inizio, albero di codifica, unità di predizione, residui con sign data
hiding e transform skip, predizione intra, DCT/DST e dequantizzazione, PCM,
deblocking e SAO, tile, WPP e segmenti dipendenti.

I 12 flussi di sole slice I dei profili Main, Main 10 e 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. Le slice P e B si
rifiutano finché manca la predizione inter (tappa successiva). Le prove ne leggono
comunque la sintassi fino alla fine di ogni slice, con le unità di predizione grigie.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 15:39:56 +01:00
1 parent 6274c4ee03
commit f77b5e4db6
17 files changed
+5708 -9

No files matched your search

+174
View File
@@ -0,0 +1,174 @@
using System.Buffers.Binary;
using Febe.Core.Codecs.H264;
namespace Febe.Core.Codecs.H265;
/// <summary>A malformed or unsupported HEVC stream.</summary>
public sealed class H265Exception(string message) : Exception(message);
/// <summary>
/// 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 <see cref="NalUnits.Padding"/>), so reads never
/// need a bounds check; reading past the payload gives zeros and is detected through <see cref="BitsLeft"/>.
/// </summary>
internal sealed class BitReader
{
private readonly byte[] data;
private readonly int length;
private int position;
/// <param name="data">The payload, followed by at least sixteen bytes of zero padding.</param>
/// <param name="length">Bytes of payload.</param>
/// <param name="startByte">First byte to read (after the two-byte NAL unit header).</param>
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;
/// <summary>more_rbsp_data() (§7.2): true while bits remain before the rbsp_stop_one_bit.</summary>
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));
}
/// <summary>u(n), 0 to 32 bits.</summary>
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;
}
/// <summary>ue(v): Exp-Golomb code (§9.2).</summary>
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));
}
/// <summary>A ue(v) value that must not exceed <paramref name="max"/>.</summary>
internal int ReadUe(int max)
{
var value = ReadUe();
if (value > (uint)max)
{
throw new H265Exception("Valore fuori dall'intervallo ammesso.");
}
return (int)value;
}
/// <summary>se(v): signed Exp-Golomb code (§9.2.2).</summary>
internal int ReadSe()
{
var code = ReadUe();
var magnitude = (int)((code + 1) >> 1);
return (code & 1) != 0 ? magnitude : -magnitude;
}
/// <summary>A se(v) value inside [<paramref name="min"/>, <paramref name="max"/>].</summary>
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;
}
/// <summary>Moves to the next byte boundary (byte_alignment() and the alignment bits before PCM samples).</summary>
internal void AlignToByte() => position = (position + 7) & ~7;
}
/// <summary>One HEVC NAL unit, with its RBSP (the two-byte header included at its start).</summary>
internal readonly record struct H265NalUnit(int Type, int LayerId, int TemporalId, byte[] Rbsp, int Length)
{
/// <summary>A reader positioned after the two-byte NAL unit header (§7.3.1.2).</summary>
internal BitReader Reader() => new(Rbsp, Length, 2);
/// <summary>Removes the emulation prevention bytes of one NAL unit into <paramref name="buffer"/>, grown when needed.</summary>
internal static H265NalUnit Unescape(ReadOnlySpan<byte> 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);
}
}
+201
View File
@@ -0,0 +1,201 @@
using System.Buffers.Binary;
using System.Numerics;
using Lps = Febe.Core.Codecs.H264.CabacTables;
namespace Febe.Core.Codecs.H265;
/// <summary>
/// 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 &lt;&lt; 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.
/// </summary>
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;
/// <summary>Initialises every context variable for an initType and the slice QP (§9.3.2.2).</summary>
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);
}
}
/// <summary>
/// Initialises the arithmetic decoder (§9.3.2.5) at a bit position of <paramref name="source"/>; reading stops at
/// <paramref name="endByte"/> (the end of the slice segment data), past which the decoder sees zeros.
/// </summary>
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.");
}
}
/// <summary>The bit position right after the last bit the decoder has read (after a terminating bin equal to 1).</summary>
internal int BitPosition => (next * 8) - bits;
/// <summary>DecodeDecision (§9.3.4.3.2).</summary>
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;
/// <summary>DecodeBypass (§9.3.4.3.4).</summary>
internal int Bypass()
{
offset = (offset << 1) | Take(1);
if (offset >= range)
{
offset -= range;
return 1;
}
return 0;
}
/// <summary><paramref name="count"/> bypass bins (at most 16), the first one in the most significant bit.</summary>
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;
}
/// <summary>
/// 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 <see cref="BitPosition"/> is where the bitstream goes on.
/// </summary>
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;
}
}
}
+141
View File
@@ -0,0 +1,141 @@
namespace Febe.Core.Codecs.H265;
/// <summary>
/// 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 (<see cref="H264.CabacTables"/>).
/// </summary>
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;
/// <summary>Number of context variables kept by the decoder.</summary>
internal const int ContextCount = CuChromaQpOffsetIdx + 1;
/// <summary>
/// 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).
/// </summary>
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]),
];
/// <summary>initValue of every context by initType: InitValues[initType][ctx].</summary>
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<byte>(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;
}
}
@@ -0,0 +1,479 @@
namespace Febe.Core.Codecs.H265;
/// <summary>The in-loop filters (§8.7): deblocking (§8.7.2) then sample adaptive offset (§8.7.3), on the whole picture.</summary>
public sealed partial class H265Decoder
{
private ushort[] saoSource = [];
/// <summary>The left and top edges of a coding block, unless filterEdgeFlag of §8.7.2.3 is 0 for them.</summary>
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);
}
}
/// <summary>Whether deblocking may cross into the block at (xN, yN) from the current one: slice and tile boundaries.</summary>
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;
}
/// <summary>The edges between the prediction blocks of an inter coding unit (§8.7.2.3).</summary>
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;
}
}
}
/// <summary>bS of §8.7.2.4 between the 4×4 blocks <paramref name="p"/> and <paramref name="q"/> of the grid.</summary>
private int BoundaryStrength(int p, int q, int kind)
{
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;
}
/// <summary>Filters every vertical (or horizontal) edge of the picture: luma on the 8×8 grid, chroma on the 16×16 one.</summary>
private void Deblock(Picture picture, bool vertical)
{
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);
}
}
}
}
/// <summary>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.</summary>
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);
}
}
}
}
}
/// <summary>dSam of §8.7.2.5.6 for one line.</summary>
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);
}
/// <summary>Sample adaptive offset (§8.7.3) of every CTB, from a copy of the deblocked picture.</summary>
private void ApplySao(Picture picture)
{
var log2Ctb = sps.Log2CtbSize;
var heightInCtbs = sps.HeightInCtbs;
Span<bool> 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);
}
}
}
}
/// <summary>Whether the samples of the CTB at (nx, ny) can be used by the edge offset of the CTB <paramref name="rs"/>.</summary>
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<short> offsets, int bitDepth, int max, int shift)
{
Span<int> 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<short> offsets, int max, int shift, ReadOnlySpan<bool> 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<int> 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);
}
}
}
}
}
@@ -0,0 +1,269 @@
namespace Febe.Core.Codecs.H265;
/// <summary>Intra sample prediction (§8.4.4.2): reference samples, their substitution and filtering, planar, DC and angular.</summary>
public sealed partial class H265Decoder
{
/// <summary>
/// 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.
/// </summary>
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];
/// <summary>Predicts a block of component <paramref name="cIdx"/> at (<paramref name="x0"/>, <paramref name="y0"/>) in its own samples.</summary>
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<int> 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];
/// <summary>Whether a neighbouring sample can be used for intra prediction (§8.4.4.2.2), in luma locations.</summary>
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;
}
}
@@ -0,0 +1,449 @@
namespace Febe.Core.Codecs.H265;
/// <summary>residual_coding() (§7.3.8.11) and the scaling, transformation and reconstruction of §8.6.</summary>
public sealed partial class H265Decoder
{
/// <summary>ctxIdxMap of sig_coeff_flag in 4×4 blocks (9-55), by raster position.</summary>
private static readonly byte[] s_sigCtxMap4x4 = [0, 1, 4, 5, 2, 3, 4, 5, 6, 6, 8, 8, 7, 7, 8, 8];
/// <summary>TransCoeffLevel of the block being decoded, raster order (y &lt;&lt; log2) + x; zero outside it.</summary>
private readonly int[] coefficients = new int[32 * 32];
/// <summary>Raster positions of the nonzero entries of <see cref="coefficients"/>.</summary>
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];
/// <summary>Decodes the residual of one transform block and adds it to the prediction in the picture.</summary>
/// <param name="cIdx">Colour component.</param>
/// <param name="x0">Left of the block, in samples of the component.</param>
/// <param name="y0">Top of the block, in samples of the component.</param>
/// <param name="log2">Log2 of the block size.</param>
/// <param name="predModeIntra">The intra prediction mode of the block, −1 for inter.</param>
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);
}
}
}
/// <summary>The scaling process for transform coefficients (§8.6.3), on the nonzero coefficients.</summary>
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);
}
}
/// <summary>
/// residual_coding(): fills <see cref="coefficients"/> and <see cref="nonzero"/>; returns the number of nonzero
/// coefficients and the largest column and row that hold one.
/// </summary>
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<int> sigPositions = stackalloc int[16];
Span<int> 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);
}
}
File diff suppressed because it is too large. Load diff
+571
View File
@@ -0,0 +1,571 @@
using Febe.Core.Codecs.H264;
namespace Febe.Core.Codecs.H265;
/// <summary>
/// An HEVC (ITU-T H.265 | ISO/IEC 23008-2) decoder written from the Recommendation, for the Main, Main 10 and Main Still
/// Picture profiles: 4:2:0 at 8 to 10 bits (up to 12 accepted), tiles, wavefronts, dependent slice segments, PCM, transform
/// skip, sign data hiding, scaling lists, deblocking and SAO. Intra pictures only for now: inter prediction is the next step,
/// and a P or B slice raises an <see cref="H265Exception"/> (see <see cref="ParseInterSlices"/>). Not handled (an
/// <see cref="H265Exception"/>): the range extensions (4:0:0, 4:2:2, 4:4:4 and their coding tools), separate colour planes
/// and the layers above 0 of scalable and multiview streams, which are ignored.
/// </summary>
public sealed partial class H265Decoder
{
private readonly Sps?[] spss = new Sps?[16];
private readonly Pps?[] ppss = new Pps?[64];
private readonly List<Picture> dpb = [];
private readonly Stack<Picture> pool = new();
private byte[]? rbsp;
/// <summary>No picture decoded yet: the next IRAP picture is "picture 0" of C.5.2.2.</summary>
private bool firstPicture = true;
/// <summary>At the start of the bitstream or after an end of sequence: the next CRA picture has NoRaslOutputFlag 1.</summary>
private bool afterEndOfSequence = true;
private bool seenIrap;
/// <summary>NoRaslOutputFlag of the IRAP picture the current pictures are associated with.</summary>
private bool irapNoRaslOutput;
/// <summary>PicOrderCntVal of prevTid0Pic (§8.3.1).</summary>
private int prevTid0Poc;
private long codedPictures;
/// <summary>The slices of the current picture are skipped (a RASL picture that cannot be decoded, no IRAP yet).</summary>
private bool skipping;
/// <summary>The five lists of the reference picture set of the current picture (§8.3.2); null for "no reference picture".</summary>
private readonly List<Picture?> refStCurrBefore = [];
private readonly List<Picture?> refStCurrAfter = [];
private readonly List<Picture?> refLtCurr = [];
/// <summary>Raised for each frame in output order (the bumping process of C.5.2.4), cropped.</summary>
public event Action<H265Frame>? FrameOutput;
/// <summary>Raised for each picture once decoded and filtered, in decoding order (for the decoded picture hash).</summary>
internal event Action<Picture>? PictureDecoded;
/// <summary>
/// Decodes the syntax of P and B slices (with every prediction unit predicted as mid-grey) instead of refusing them:
/// only to check the parsing of the inter syntax before inter prediction exists. The pictures are not correct.
/// </summary>
internal bool ParseInterSlices { get; set; }
/// <summary>Coded pictures met so far, also those skipped.</summary>
public long PicturesDecoded => codedPictures;
/// <summary>Decodes a whole Annex B byte stream, then outputs every picture left.</summary>
public void DecodeAnnexB(ReadOnlySpan<byte> stream)
{
var position = 0;
while (NalUnits.NextAnnexB(stream, ref position, out var unit))
{
Decode(stream[unit]);
}
Flush();
}
/// <summary>
/// Reads the parameter sets of an <c>hvcC</c> box (HEVCDecoderConfigurationRecord, ISO/IEC 14496-15 §8.3.3); returns
/// the size of the NAL length fields of the samples.
/// </summary>
public int ConfigureHvcC(ReadOnlySpan<byte> 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;
}
/// <summary>Decodes one access unit stored with length prefixes (an MP4 or Matroska sample) and finishes its picture.</summary>
public void DecodeSample(ReadOnlySpan<byte> sample, int lengthSize)
{
var position = 0;
while (NalUnits.NextLengthPrefixed(sample, lengthSize, ref position, out var unit))
{
Decode(sample[unit]);
}
FinishPicture();
}
/// <summary>Finishes the picture being decoded and outputs every picture still waiting, in output order.</summary>
public void Flush()
{
FinishPicture();
while (Bump())
{
}
}
private void Decode(ReadOnlySpan<byte> 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);
}
/// <summary>The decoding process for the reference picture set (§8.3.2), and the marking of the DPB it implies.</summary>
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<bool> 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<bool> 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;
}
/// <summary>The conditions of C.5.2.2 and C.5.2.3 on the pictures waiting for output.</summary>
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);
}
}
}
/// <summary>The bumping process (C.5.2.4): outputs the waiting picture with the smallest POC; false when none waits.</summary>
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);
}
/// <summary>
/// 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 <see cref="H265Exception"/> and is dropped.
/// </summary>
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;
}
}
}
}
+175
View File
@@ -0,0 +1,175 @@
namespace Febe.Core.Codecs.H265;
/// <summary>
/// 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).
/// </summary>
internal static class H265Tables
{
/// <summary>intraPredAngle by intra prediction mode (table 8-4); modes 0 (planar) and 1 (DC) have none.</summary>
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,
];
/// <summary>invAngle of the modes 11 to 25 (table 8-5), indexed by mode − 11.</summary>
internal static readonly short[] InvAngle = [-4096, -1638, -910, -630, -482, -390, -315, -256, -315, -390, -482, -630, -910, -1638, -4096];
/// <summary>QpC as a function of qPi for ChromaArrayType 1 (table 8-10), for qPi from 30 to 43.</summary>
internal static readonly byte[] ChromaQp30To43 = [29, 30, 31, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37];
/// <summary>β′ for Q from 0 to 51 (table 8-12).</summary>
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,
];
/// <summary>tC′ for Q from 0 to 53 (table 8-12).</summary>
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,
];
/// <summary>levelScale[qP % 6] of the scaling process (§8.6.3).</summary>
internal static readonly int[] LevelScale = [40, 45, 51, 57, 64, 72];
/// <summary>Default values of ScalingList[1..3][0..2] (intra), in up-right diagonal order (table 7-6).</summary>
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,
];
/// <summary>Default values of ScalingList[1..3][3..5] (inter), in up-right diagonal order (table 7-6).</summary>
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,
];
/// <summary>
/// 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 &lt;&lt; 8).
/// </summary>
internal static readonly ushort[][][] ScanOrder = BuildScans();
/// <summary>For the 4×4 scans: position in scan order of each raster position (y * 4 + x), by scanIdx.</summary>
internal static readonly byte[][] ScanPosition4x4 = BuildInverse4x4();
/// <summary>
/// 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.
/// </summary>
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,
];
/// <summary>
/// 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.
/// </summary>
internal static readonly short[] DctMatrix = BuildDct();
/// <summary>The 4×4 DST matrix of §8.6.4.2 (trType 1), transMatrix[k][n] = DstMatrix[k * 4 + n].</summary>
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;
}
}
+972
View File
@@ -0,0 +1,972 @@
namespace Febe.Core.Codecs.H265;
/// <summary>A short-term reference picture set (§7.3.7, §7.4.8): the POC deltas of the negative and positive pictures.</summary>
internal sealed class ShortTermRps
{
/// <summary>At most sps_max_dec_pic_buffering_minus1 + 1 ≤ 16 pictures in each half.</summary>
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;
/// <summary>
/// st_ref_pic_set(stRpsIdx): <paramref name="index"/> is stRpsIdx, <paramref name="spsSets"/> the sets already read
/// from the SPS (all of them when the set is in a slice header, where <paramref name="index"/> equals their number).
/// </summary>
internal static ShortTermRps Parse(BitReader r, int index, int spsCount, IReadOnlyList<ShortTermRps> 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<bool> used = stackalloc bool[(MaxPictures * 2) + 1];
Span<bool> 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;
}
}
/// <summary>
/// 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).
/// </summary>
internal sealed class ScalingList
{
private ScalingList()
{
}
/// <summary>Factors[sizeId * 6 + matrixId].</summary>
internal byte[][] Factors { get; } = new byte[24][];
/// <summary>The lists when scaling_list_enabled_flag is 1 and no list is sent: table 7-5 and table 7-6.</summary>
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);
}
/// <summary>scaling_list_data().</summary>
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<int>)[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;
}
/// <summary>ScalingFactor from the lists (7-40 to 7-44): lists in diagonal order, upsampled beyond 8×8, with the DC.</summary>
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;
}
}
/// <summary>A sequence parameter set (§7.3.2.2), with what decoding needs.</summary>
internal sealed class Sps
{
/// <summary>MaxLumaPs of level 6.2 (table A.8): the largest picture of any level.</summary>
internal const int MaxLumaPs = 35_651_584;
/// <summary>Largest width or height of any level: Sqrt(MaxLumaPs × 8).</summary>
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<ShortTermRps> 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;
/// <summary>VUI colour description: matrix_coeffs (2 = unspecified) and video_full_range_flag.</summary>
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;
}
}
/// <summary>profile_tier_level() (§7.3.3): skipped, except general_profile_idc.</summary>
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<bool> profile = stackalloc bool[8];
Span<bool> 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;
}
}
/// <summary>vui_parameters() (Annex E): only the colour description is kept.</summary>
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();
}
}
}
/// <summary>hrd_parameters() (E.2.2), skipped.</summary>
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);
}
}
}
}
}
/// <summary>A picture parameter set (§7.3.2.3), with what decoding needs.</summary>
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;
/// <summary>The tile layout of the SPS the arrays below were computed for.</summary>
private Sps? layoutSps;
/// <summary>CtbAddrRsToTs, CtbAddrTsToRs and TileId (by raster address) of §6.5.1.</summary>
internal int[] CtbAddrRsToTs = [];
internal int[] CtbAddrTsToRs = [];
internal int[] TileIdRs = [];
/// <summary>colBd and rowBd: the first CTB column and row of each tile, with one more entry for the end.</summary>
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;
}
/// <summary>Computes the tile layout and the scan conversions of §6.5.1 for <paramref name="sps"/>, once.</summary>
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;
}
}
+159
View File
@@ -0,0 +1,159 @@
namespace Febe.Core.Codecs.H265;
/// <summary>
/// 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).
/// </summary>
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],
];
}
/// <summary>The SPS of the picture: a picture of the pool is reused for another SPS of the same size.</summary>
internal Sps Sps { get; set; }
internal int Width { get; }
internal int Height { get; }
internal int ChromaWidth { get; }
internal int ChromaHeight { get; }
/// <summary>Y, Cb and Cr; the chroma arrays are empty for 4:0:0.</summary>
internal ushort[][] Planes { get; }
internal int Poc;
internal bool ShortTerm;
internal bool LongTerm;
/// <summary>Marked "needed for output" (C.5.2).</summary>
internal bool NeededForOutput;
internal bool OutputFlag;
internal int LatencyCount;
/// <summary>Position of the coded picture in decoding order, counting the pictures that are skipped too.</summary>
internal long DecodeIndex;
/// <summary>A picture generated for a missing reference (§8.3.3): never output, its samples are not meaningful.</summary>
internal bool Generated;
/// <summary>Every slice of the picture is an I slice: it does not depend on other pictures.</summary>
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);
/// <summary>The picture cropped to the conformance window.</summary>
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;
}
}
/// <summary>A decoded HEVC frame, cropped to the conformance window, with one 16-bit value per sample.</summary>
/// <param name="Width">Luma width after cropping.</param>
/// <param name="Height">Luma height after cropping.</param>
/// <param name="ChromaFormat">ChromaArrayType: 0 (only luma), 1 (4:2:0), 2 (4:2:2), 3 (4:4:4).</param>
/// <param name="BitDepthLuma">Bits per luma sample.</param>
/// <param name="BitDepthChroma">Bits per chroma sample.</param>
/// <param name="Y">Luma, <paramref name="Width"/> × <paramref name="Height"/>.</param>
/// <param name="Cb">Blue-difference chroma (empty for 4:0:0).</param>
/// <param name="Cr">Red-difference chroma, same size as <paramref name="Cb"/>.</param>
/// <param name="Poc">Picture order count.</param>
/// <param name="DecodeIndex">Position of the coded picture in decoding order.</param>
/// <param name="MatrixCoefficients">matrix_coeffs of the VUI (1 = BT.709, 5 and 6 = BT.601, 2 = unspecified).</param>
/// <param name="FullRange">video_full_range_flag of the VUI.</param>
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)
{
/// <summary>
/// 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.
/// </summary>
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<ushort[]>)[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;
}
}
+480
View File
@@ -0,0 +1,480 @@
namespace Febe.Core.Codecs.H265;
/// <summary>slice_type (§7.4.7.1).</summary>
internal enum SliceType
{
B = 0,
P = 1,
I = 2,
}
/// <summary>
/// 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.
/// </summary>
internal sealed class SliceHeader
{
internal bool FirstSliceSegmentInPic;
internal bool NoOutputOfPriorPics;
internal int PpsId;
internal bool Dependent;
internal int SegmentAddress;
/// <summary>SliceAddrRs: the address of the first CTB of the slice (of its independent slice segment).</summary>
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;
/// <summary>LumaWeightLX and luma_offset_lX by [list][refIdx] (§7.4.7.3).</summary>
internal readonly int[][] LumaWeight = [new int[16], new int[16]];
internal readonly int[][] LumaOffset = [new int[16], new int[16]];
/// <summary>ChromaWeightLX and ChromaOffsetLX by [list][refIdx * 2 + (cIdx − 1)].</summary>
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 = [];
/// <summary>NumPicTotalCurr (7-55).</summary>
internal int NumPicTotalCurr;
/// <summary>The byte where slice_segment_data() starts in the RBSP.</summary>
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,
};
/// <summary>
/// Reads a slice segment header. <paramref name="previous"/> is the header of the last independent slice segment of
/// the current picture (for a dependent one); <paramref name="sps"/> and <paramref name="pps"/> are those it refers to.
/// </summary>
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();
}
}
/// <summary>pred_weight_table() (§7.3.6.3), as the weights and offsets of §7.4.7.3.</summary>
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<bool> lumaFlags = stackalloc bool[16];
Span<bool> 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;
}
}
}
}
}
}
+58
View File
@@ -0,0 +1,58 @@
namespace Febe.Core.Codecs.H265;
/// <summary>
/// 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.
/// </summary>
internal static class Transform
{
/// <param name="coefficients">Scaled coefficients d, raster (y &lt;&lt; log2) + x.</param>
/// <param name="output">Residual samples, raster.</param>
/// <param name="temp">Intermediate values, at least the block size.</param>
/// <param name="log2">Log2 of the block size.</param>
/// <param name="dst">trType 1: the 4×4 DST of intra luma blocks.</param>
/// <param name="maxX">Largest column with a nonzero coefficient.</param>
/// <param name="maxY">Largest row with a nonzero coefficient.</param>
/// <param name="bitDepth">Bit depth of the component.</param>
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<short> 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;
}
}
}
}