Decodificatore H.264 scritto in casa, provato sui flussi di conformità (#58)
Decodifica Baseline, Main e High a fotogrammi progressivi 4:2:0 a 8 bit (CAVLC e CABAC, slice I/P/B, trasformata 8x8 e matrici di quantizzazione, predizione pesata, diretta spaziale e temporale, gestione dei riferimenti, filtro di deblocco), scritta dallo standard ITU-T H.264 senza codice di terzi. I dodici flussi della suite ITU-T H.264.1 in tests/Febe.Tests/Media/H264/Conformita danno, fotogramma per fotogramma, gli MD5 della ricostruzione ufficiale. Le tabelle di inizializzazione CABAC sono trascritte dal testo della Raccomandazione (03/2005): quelle a memoria per cabac_init_idc 1 e 2 erano sbagliate e le prove le hanno scoperte. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9958745e53
commit
697de97ec3
55 files changed
+7072
No files matched your search
@@ -0,0 +1,113 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>
|
||||
/// The arithmetic decoding engine of CABAC (§9.3.1.2 and §9.3.3.2), reading the slice data bit by bit, with the
|
||||
/// context variables of the slice.
|
||||
/// </summary>
|
||||
internal sealed class CabacEngine
|
||||
{
|
||||
private readonly byte[] state = new byte[CabacTables.ContextCount];
|
||||
private readonly byte[] mps = new byte[CabacTables.ContextCount];
|
||||
private RbspReader reader = null!;
|
||||
private int range;
|
||||
private int offset;
|
||||
|
||||
/// <summary>Initialises the context variables (§9.3.1.1).</summary>
|
||||
internal void InitContexts(SliceHeader header, int sliceQp)
|
||||
{
|
||||
var table = header.IsIntra ? CabacTables.InitI : CabacTables.InitPB[header.CabacInitIdc];
|
||||
var qp = Math.Clamp(sliceQp, 0, 51);
|
||||
for (var i = 0; i < CabacTables.ContextCount; i++)
|
||||
{
|
||||
int m = table[i * 2], n = table[(i * 2) + 1];
|
||||
var pre = Math.Clamp(((m * qp) >> 4) + n, 1, 126);
|
||||
if (pre <= 63)
|
||||
{
|
||||
state[i] = (byte)(63 - pre);
|
||||
mps[i] = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
state[i] = (byte)(pre - 64);
|
||||
mps[i] = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Initialises the decoding engine at the current, byte-aligned position (§9.3.1.2).</summary>
|
||||
internal void Start(RbspReader source)
|
||||
{
|
||||
reader = source;
|
||||
range = 510;
|
||||
offset = (int)source.Read(9);
|
||||
if (offset >= range)
|
||||
{
|
||||
throw new H264Exception("Dati CABAC non validi.");
|
||||
}
|
||||
}
|
||||
|
||||
internal int Decision(int ctx)
|
||||
{
|
||||
var s = state[ctx];
|
||||
var lps = CabacTables.RangeLps[(s << 2) + ((range >> 6) & 3)];
|
||||
range -= lps;
|
||||
int bin;
|
||||
if (offset >= range)
|
||||
{
|
||||
bin = mps[ctx] ^ 1;
|
||||
offset -= range;
|
||||
range = lps;
|
||||
if (s == 0)
|
||||
{
|
||||
mps[ctx] ^= 1;
|
||||
}
|
||||
|
||||
state[ctx] = CabacTables.NextStateLps[s];
|
||||
}
|
||||
else
|
||||
{
|
||||
bin = mps[ctx];
|
||||
if (s < 62)
|
||||
{
|
||||
state[ctx] = (byte)(s + 1);
|
||||
}
|
||||
}
|
||||
|
||||
while (range < 256)
|
||||
{
|
||||
range <<= 1;
|
||||
offset = (offset << 1) | reader.ReadBit();
|
||||
}
|
||||
|
||||
return bin;
|
||||
}
|
||||
|
||||
internal int Bypass()
|
||||
{
|
||||
offset = (offset << 1) | reader.ReadBit();
|
||||
if (offset >= range)
|
||||
{
|
||||
offset -= range;
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal int Terminate()
|
||||
{
|
||||
range -= 2;
|
||||
if (offset >= range)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
while (range < 256)
|
||||
{
|
||||
range <<= 1;
|
||||
offset = (offset << 1) | reader.ReadBit();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>
|
||||
/// Tables of the CABAC engine (ITU-T H.264 §9.3): rangeTabLPS, the state transitions and the (m, n) pairs that
|
||||
/// initialise the context variables (tables 9-12 to 9-24, transcribed from the text of ITU-T H.264 03/2005). The
|
||||
/// contexts of field coding are included for completeness, though Febe decodes progressive frames only.
|
||||
/// </summary>
|
||||
internal static class CabacTables
|
||||
{
|
||||
/// <summary>Number of context variables kept by the decoder.</summary>
|
||||
internal const int ContextCount = 460;
|
||||
|
||||
/// <summary>rangeTabLPS[pStateIdx * 4 + qCodIRangeIdx] (table 9-44).</summary>
|
||||
internal static readonly byte[] RangeLps =
|
||||
[
|
||||
128, 176, 208, 240, 128, 167, 197, 227, 128, 158, 187, 216, 123, 150, 178, 205, 116, 142, 169, 195,
|
||||
111, 135, 160, 185, 105, 128, 152, 175, 100, 122, 144, 166, 95, 116, 137, 158, 90, 110, 130, 150,
|
||||
85, 104, 123, 142, 81, 99, 117, 135, 77, 94, 111, 128, 73, 89, 105, 122, 69, 85, 100, 116,
|
||||
66, 80, 95, 110, 62, 76, 90, 104, 59, 72, 86, 99, 56, 69, 81, 94, 53, 65, 77, 89,
|
||||
51, 62, 73, 85, 48, 59, 69, 80, 46, 56, 66, 76, 43, 53, 63, 72, 41, 50, 59, 69,
|
||||
39, 48, 56, 65, 37, 45, 54, 62, 35, 43, 51, 59, 33, 41, 48, 56, 32, 39, 46, 53,
|
||||
30, 37, 43, 50, 29, 35, 41, 48, 27, 33, 39, 45, 26, 31, 37, 43, 24, 30, 35, 41,
|
||||
23, 28, 33, 39, 22, 27, 32, 37, 21, 26, 30, 35, 20, 24, 29, 33, 19, 23, 27, 31,
|
||||
18, 22, 26, 30, 17, 21, 25, 28, 16, 20, 23, 27, 15, 19, 22, 25, 14, 18, 21, 24,
|
||||
14, 17, 20, 23, 13, 16, 19, 22, 12, 15, 18, 21, 12, 14, 17, 20, 11, 14, 16, 19,
|
||||
11, 13, 15, 18, 10, 12, 15, 17, 10, 12, 14, 16, 9, 11, 13, 15, 9, 11, 12, 14,
|
||||
8, 10, 12, 14, 8, 9, 11, 13, 7, 9, 11, 12, 7, 9, 10, 12, 7, 8, 10, 11,
|
||||
6, 8, 9, 11, 6, 7, 9, 10, 6, 7, 8, 9, 2, 2, 2, 2,
|
||||
];
|
||||
|
||||
/// <summary>transIdxLPS (table 9-45).</summary>
|
||||
internal static readonly byte[] NextStateLps =
|
||||
[
|
||||
0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12, 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24,
|
||||
24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33, 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38,
|
||||
38, 63,
|
||||
];
|
||||
|
||||
|
||||
|
||||
// Tables 9-12 to 9-24 of ITU-T H.264 (03/2005), every ctxIdx from 0 to 459 in order, each as m, n. Context 276
|
||||
// (end_of_slice_flag) has no initialisation; contexts 11-59 do not occur in I slices.
|
||||
private static readonly sbyte[] I =
|
||||
[
|
||||
20, -15, 2, 54, 3, 74, 20, -15, 2, 54, 3, 74, -28, 127, -23, 104, -6, 53, -1, 54,
|
||||
7, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 41, 0, 63, 0, 63, 0, 63, -9, 83, 4, 86, 0, 97, -7, 72, 13, 41, 3, 62,
|
||||
0, 11, 1, 55, 0, 69, -17, 127, -13, 102, 0, 82, -7, 74, -21, 107, -27, 127, -31, 127,
|
||||
-24, 127, -18, 95, -27, 127, -21, 114, -30, 127, -17, 123, -12, 115, -16, 122, -11, 115, -12, 63,
|
||||
-2, 68, -15, 84, -13, 104, -3, 70, -8, 93, -10, 90, -30, 127, -1, 74, -6, 97, -7, 91,
|
||||
-20, 127, -4, 56, -5, 82, -7, 76, -22, 125, -7, 93, -11, 87, -3, 77, -5, 71, -4, 63,
|
||||
-4, 68, -12, 84, -7, 62, -7, 65, 8, 61, 5, 56, -2, 66, 1, 64, 0, 61, -2, 78,
|
||||
1, 50, 7, 52, 10, 35, 0, 44, 11, 38, 1, 45, 0, 46, 5, 44, 31, 17, 1, 51,
|
||||
7, 50, 28, 19, 16, 33, 14, 62, -13, 108, -15, 100, -13, 101, -13, 91, -12, 94, -10, 88,
|
||||
-16, 84, -10, 86, -7, 83, -13, 87, -19, 94, 1, 70, 0, 72, -5, 74, 18, 59, -8, 102,
|
||||
-15, 100, 0, 95, -4, 75, 2, 72, -11, 75, -3, 71, 15, 46, -13, 69, 0, 62, 0, 65,
|
||||
21, 37, -15, 72, 9, 57, 16, 54, 0, 62, 12, 72, 24, 0, 15, 9, 8, 25, 13, 18,
|
||||
15, 9, 13, 19, 10, 37, 12, 18, 6, 29, 20, 33, 15, 30, 4, 45, 1, 58, 0, 62,
|
||||
7, 61, 12, 38, 11, 45, 15, 39, 11, 42, 13, 44, 16, 45, 12, 41, 10, 49, 30, 34,
|
||||
18, 42, 10, 55, 17, 51, 17, 46, 0, 89, 26, -19, 22, -17, 26, -17, 30, -25, 28, -20,
|
||||
33, -23, 37, -27, 33, -23, 40, -28, 38, -17, 33, -11, 40, -15, 41, -6, 38, 1, 41, 17,
|
||||
30, -6, 27, 3, 26, 22, 37, -16, 35, -4, 38, -8, 38, -3, 37, 3, 38, 5, 42, 0,
|
||||
35, 16, 39, 22, 14, 48, 27, 37, 21, 60, 12, 68, 2, 97, -3, 71, -6, 42, -5, 50,
|
||||
-3, 54, -2, 62, 0, 58, 1, 63, -2, 72, -1, 74, -9, 91, -5, 67, -5, 27, -3, 39,
|
||||
-2, 44, 0, 46, -16, 64, -8, 68, -10, 78, -6, 77, -10, 86, -12, 92, -15, 55, -10, 60,
|
||||
-6, 62, -4, 65, -12, 73, -8, 76, -7, 80, -9, 88, -17, 110, -11, 97, -20, 84, -11, 79,
|
||||
-6, 73, -4, 74, -13, 86, -13, 96, -11, 97, -19, 117, -8, 78, -5, 33, -4, 48, -2, 53,
|
||||
-3, 62, -13, 71, -10, 79, -12, 86, -13, 90, -14, 97, 0, 0, -6, 93, -6, 84, -8, 79,
|
||||
0, 66, -1, 71, 0, 62, -2, 60, -2, 59, -5, 75, -3, 62, -4, 58, -9, 66, -1, 79,
|
||||
0, 71, 3, 68, 10, 44, -7, 62, 15, 36, 14, 40, 16, 27, 12, 29, 1, 44, 20, 36,
|
||||
18, 32, 5, 42, 1, 48, 10, 62, 17, 46, 9, 64, -12, 104, -11, 97, -16, 96, -7, 88,
|
||||
-8, 85, -7, 85, -9, 85, -13, 88, 4, 66, -3, 77, -3, 76, -6, 76, 10, 58, -1, 76,
|
||||
-1, 83, -7, 99, -14, 95, 2, 95, 0, 76, -5, 74, 0, 70, -11, 75, 1, 68, 0, 65,
|
||||
-14, 73, 3, 62, 4, 62, -1, 68, -13, 75, 11, 55, 5, 64, 12, 70, 15, 6, 6, 19,
|
||||
7, 16, 12, 14, 18, 13, 13, 11, 13, 15, 15, 16, 12, 23, 13, 23, 15, 20, 14, 26,
|
||||
14, 44, 17, 40, 17, 47, 24, 17, 21, 21, 25, 22, 31, 27, 22, 29, 19, 35, 14, 50,
|
||||
10, 57, 7, 63, -2, 77, -4, 82, -3, 94, 9, 69, -12, 109, 36, -35, 36, -34, 32, -26,
|
||||
37, -30, 44, -32, 34, -18, 34, -15, 40, -15, 33, -7, 35, -5, 33, 0, 38, 2, 33, 13,
|
||||
23, 35, 13, 58, 29, -3, 26, 0, 22, 30, 31, -7, 35, -15, 34, -3, 34, 3, 36, -1,
|
||||
34, 5, 32, 11, 35, 5, 34, 12, 39, 11, 30, 29, 34, 26, 29, 39, 19, 66, 31, 21,
|
||||
31, 31, 25, 50, -17, 120, -20, 112, -18, 114, -11, 85, -15, 92, -14, 89, -26, 71, -15, 81,
|
||||
-14, 80, 0, 68, -14, 70, -24, 56, -23, 68, -24, 50, -11, 74, 23, -13, 26, -13, 40, -15,
|
||||
49, -14, 44, 3, 45, 6, 44, 34, 33, 54, 19, 82, -3, 75, -1, 23, 1, 34, 1, 43,
|
||||
0, 54, -2, 55, 0, 61, 1, 64, 0, 68, -9, 92, -14, 106, -13, 97, -15, 90, -12, 90,
|
||||
-18, 88, -10, 73, -9, 79, -14, 86, -10, 73, -10, 70, -10, 69, -5, 66, -9, 64, -5, 58,
|
||||
2, 59, 21, -10, 24, -11, 28, -8, 28, -1, 29, 3, 29, 9, 35, 20, 29, 36, 14, 67,
|
||||
];
|
||||
|
||||
private static readonly sbyte[] P0 =
|
||||
[
|
||||
20, -15, 2, 54, 3, 74, 20, -15, 2, 54, 3, 74, -28, 127, -23, 104, -6, 53, -1, 54,
|
||||
7, 51, 23, 33, 23, 2, 21, 0, 1, 9, 0, 49, -37, 118, 5, 57, -13, 78, -11, 65,
|
||||
1, 62, 12, 49, -4, 73, 17, 50, 18, 64, 9, 43, 29, 0, 26, 67, 16, 90, 9, 104,
|
||||
-46, 127, -20, 104, 1, 67, -13, 78, -11, 65, 1, 62, -6, 86, -17, 95, -6, 61, 9, 45,
|
||||
-3, 69, -6, 81, -11, 96, 6, 55, 7, 67, -5, 86, 2, 88, 0, 58, -3, 76, -10, 94,
|
||||
5, 54, 4, 69, -3, 81, 0, 88, -7, 67, -5, 74, -4, 74, -5, 80, -7, 72, 1, 58,
|
||||
0, 41, 0, 63, 0, 63, 0, 63, -9, 83, 4, 86, 0, 97, -7, 72, 13, 41, 3, 62,
|
||||
0, 45, -4, 78, -3, 96, -27, 126, -28, 98, -25, 101, -23, 67, -28, 82, -20, 94, -16, 83,
|
||||
-22, 110, -21, 91, -18, 102, -13, 93, -29, 127, -7, 92, -5, 89, -7, 96, -13, 108, -3, 46,
|
||||
-1, 65, -1, 57, -9, 93, -3, 74, -9, 92, -8, 87, -23, 126, 5, 54, 6, 60, 6, 59,
|
||||
6, 69, -1, 48, 0, 68, -4, 69, -8, 88, -2, 85, -6, 78, -1, 75, -7, 77, 2, 54,
|
||||
5, 50, -3, 68, 1, 50, 6, 42, -4, 81, 1, 63, -4, 70, 0, 67, 2, 57, -2, 76,
|
||||
11, 35, 4, 64, 1, 61, 11, 35, 18, 25, 12, 24, 13, 29, 13, 36, -10, 93, -7, 73,
|
||||
-2, 73, 13, 46, 9, 49, -7, 100, 9, 53, 2, 53, 5, 53, -2, 61, 0, 56, 0, 56,
|
||||
-13, 63, -5, 60, -1, 62, 4, 57, -6, 69, 4, 57, 14, 39, 4, 51, 13, 68, 3, 64,
|
||||
1, 61, 9, 63, 7, 50, 16, 39, 5, 44, 4, 52, 11, 48, -5, 60, -1, 59, 0, 59,
|
||||
22, 33, 5, 44, 14, 43, -1, 78, 0, 60, 9, 69, 11, 28, 2, 40, 3, 44, 0, 49,
|
||||
0, 46, 2, 44, 2, 51, 0, 47, 4, 39, 2, 62, 6, 46, 0, 54, 3, 54, 2, 58,
|
||||
4, 63, 6, 51, 6, 57, 7, 53, 6, 52, 6, 55, 11, 45, 14, 36, 8, 53, -1, 82,
|
||||
7, 55, -3, 78, 15, 46, 22, 31, -1, 84, 25, 7, 30, -7, 28, 3, 28, 4, 32, 0,
|
||||
34, -1, 30, 6, 30, 6, 32, 9, 31, 19, 26, 27, 26, 30, 37, 20, 28, 34, 17, 70,
|
||||
1, 67, 5, 59, 9, 67, 16, 30, 18, 32, 18, 35, 22, 29, 24, 31, 23, 38, 18, 43,
|
||||
20, 41, 11, 63, 9, 59, 9, 64, -1, 94, -2, 89, -9, 108, -6, 76, -2, 44, 0, 45,
|
||||
0, 52, -3, 64, -2, 59, -4, 70, -4, 75, -8, 82, -17, 102, -9, 77, 3, 24, 0, 42,
|
||||
0, 48, 0, 55, -6, 59, -7, 71, -12, 83, -11, 87, -30, 119, 1, 58, -3, 29, -1, 36,
|
||||
1, 38, 2, 43, -6, 55, 0, 58, 0, 64, -3, 74, -10, 90, 0, 70, -4, 29, 5, 31,
|
||||
7, 42, 1, 59, -2, 58, -3, 72, -3, 81, -11, 97, 0, 58, 8, 5, 10, 14, 14, 18,
|
||||
13, 27, 2, 40, 0, 58, -3, 70, -6, 79, -8, 85, 0, 0, -13, 106, -16, 106, -10, 87,
|
||||
-21, 114, -18, 110, -14, 98, -22, 110, -21, 106, -18, 103, -21, 107, -23, 108, -26, 112, -10, 96,
|
||||
-12, 95, -5, 91, -9, 93, -22, 94, -5, 86, 9, 67, -4, 80, -10, 85, -1, 70, 7, 60,
|
||||
9, 58, 5, 61, 12, 50, 15, 50, 18, 49, 17, 54, 10, 41, 7, 46, -1, 51, 7, 49,
|
||||
8, 52, 9, 41, 6, 47, 2, 55, 13, 41, 10, 44, 6, 50, 5, 53, 13, 49, 4, 63,
|
||||
6, 64, -2, 69, -2, 59, 6, 70, 10, 44, 9, 31, 12, 43, 3, 53, 14, 34, 10, 38,
|
||||
-3, 52, 13, 40, 17, 32, 7, 44, 7, 38, 13, 50, 10, 57, 26, 43, 14, 11, 11, 14,
|
||||
9, 11, 18, 11, 21, 9, 23, -2, 32, -15, 32, -15, 34, -21, 39, -23, 42, -33, 41, -31,
|
||||
46, -28, 38, -12, 21, 29, 45, -24, 53, -45, 48, -26, 65, -43, 43, -19, 39, -10, 30, 9,
|
||||
18, 26, 20, 27, 0, 57, -14, 82, -5, 75, -19, 97, -35, 125, 27, 0, 28, 0, 31, -4,
|
||||
27, 6, 34, 8, 30, 10, 24, 22, 33, 19, 22, 32, 26, 31, 21, 41, 26, 44, 23, 47,
|
||||
16, 65, 14, 71, 8, 60, 6, 63, 17, 65, 21, 24, 23, 20, 26, 23, 27, 32, 28, 23,
|
||||
28, 24, 23, 40, 24, 32, 28, 29, 23, 42, 19, 57, 22, 53, 22, 61, 11, 86, 12, 40,
|
||||
11, 51, 14, 59, -4, 79, -7, 71, -5, 69, -9, 70, -8, 66, -10, 68, -19, 73, -12, 69,
|
||||
-16, 70, -15, 67, -20, 62, -19, 70, -16, 66, -22, 65, -20, 63, 9, -2, 26, -9, 33, -9,
|
||||
39, -7, 41, -2, 45, 3, 49, 9, 45, 27, 36, 59, -6, 66, -7, 35, -7, 42, -8, 45,
|
||||
-5, 48, -12, 56, -6, 60, -5, 62, -8, 66, -8, 76, -5, 85, -6, 81, -10, 77, -7, 81,
|
||||
-17, 80, -18, 73, -4, 74, -10, 83, -9, 71, -9, 67, -1, 61, -8, 66, -14, 66, 0, 59,
|
||||
2, 59, 21, -13, 33, -14, 39, -7, 46, -2, 51, 2, 60, 6, 61, 17, 55, 34, 42, 62,
|
||||
];
|
||||
|
||||
private static readonly sbyte[] P1 =
|
||||
[
|
||||
20, -15, 2, 54, 3, 74, 20, -15, 2, 54, 3, 74, -28, 127, -23, 104, -6, 53, -1, 54,
|
||||
7, 51, 22, 25, 34, 0, 16, 0, -2, 9, 4, 41, -29, 118, 2, 65, -6, 71, -13, 79,
|
||||
5, 52, 9, 50, -3, 70, 10, 54, 26, 34, 19, 22, 40, 0, 57, 2, 41, 36, 26, 69,
|
||||
-45, 127, -15, 101, -4, 76, -6, 71, -13, 79, 5, 52, 6, 69, -13, 90, 0, 52, 8, 43,
|
||||
-2, 69, -5, 82, -10, 96, 2, 59, 2, 75, -3, 87, -3, 100, 1, 56, -3, 74, -6, 85,
|
||||
0, 59, -3, 81, -7, 86, -5, 95, -1, 66, -1, 77, 1, 70, -2, 86, -5, 72, 0, 61,
|
||||
0, 41, 0, 63, 0, 63, 0, 63, -9, 83, 4, 86, 0, 97, -7, 72, 13, 41, 3, 62,
|
||||
13, 15, 7, 51, 2, 80, -39, 127, -18, 91, -17, 96, -26, 81, -35, 98, -24, 102, -23, 97,
|
||||
-27, 119, -24, 99, -21, 110, -18, 102, -36, 127, 0, 80, -5, 89, -7, 94, -4, 92, 0, 39,
|
||||
0, 65, -15, 84, -35, 127, -2, 73, -12, 104, -9, 91, -31, 127, 3, 55, 7, 56, 7, 55,
|
||||
8, 61, -3, 53, 0, 68, -7, 74, -9, 88, -13, 103, -13, 91, -9, 89, -14, 92, -8, 76,
|
||||
-12, 87, -23, 110, -24, 105, -10, 78, -20, 112, -17, 99, -78, 127, -70, 127, -50, 127, -46, 127,
|
||||
-4, 66, -5, 78, -4, 71, -8, 72, 2, 59, -1, 55, -7, 70, -6, 75, -8, 89, -34, 119,
|
||||
-3, 75, 32, 20, 30, 22, -44, 127, 0, 54, -5, 61, 0, 58, -1, 60, -3, 61, -8, 67,
|
||||
-25, 84, -14, 74, -5, 65, 5, 52, 2, 57, 0, 61, -9, 69, -11, 70, 18, 55, -4, 71,
|
||||
0, 58, 7, 61, 9, 41, 18, 25, 9, 32, 5, 43, 9, 47, 0, 44, 0, 51, 2, 46,
|
||||
19, 38, -4, 66, 15, 38, 12, 42, 9, 34, 0, 89, 4, 45, 10, 28, 10, 31, 33, -11,
|
||||
52, -43, 18, 15, 28, 0, 35, -22, 38, -25, 34, 0, 39, -18, 32, -12, 102, -94, 0, 0,
|
||||
56, -15, 33, -4, 29, 10, 37, -5, 51, -29, 39, -9, 52, -34, 69, -58, 67, -63, 44, -5,
|
||||
32, 7, 55, -29, 32, 1, 0, 0, 27, 36, 33, -25, 34, -30, 36, -28, 38, -28, 38, -27,
|
||||
34, -18, 35, -16, 34, -14, 32, -8, 37, -6, 35, 0, 30, 10, 28, 18, 26, 25, 29, 41,
|
||||
0, 75, 2, 72, 8, 77, 14, 35, 18, 31, 17, 35, 21, 30, 17, 45, 20, 42, 18, 45,
|
||||
27, 26, 16, 54, 7, 66, 16, 56, 11, 73, 10, 67, -10, 116, -23, 112, -15, 71, -7, 61,
|
||||
0, 53, -5, 66, -11, 77, -9, 80, -9, 84, -10, 87, -34, 127, -21, 101, -3, 39, -5, 53,
|
||||
-7, 61, -11, 75, -15, 77, -17, 91, -25, 107, -25, 111, -28, 122, -11, 76, -10, 44, -10, 52,
|
||||
-10, 57, -9, 58, -16, 72, -7, 69, -4, 69, -5, 74, -9, 86, 2, 66, -9, 34, 1, 32,
|
||||
11, 31, 5, 52, -2, 55, -2, 67, 0, 73, -8, 89, 3, 52, 7, 4, 10, 8, 17, 8,
|
||||
16, 19, 3, 37, -1, 61, -5, 73, -1, 70, -4, 78, 0, 0, -21, 126, -23, 124, -20, 110,
|
||||
-26, 126, -25, 124, -17, 105, -27, 121, -27, 117, -17, 102, -26, 117, -27, 116, -33, 122, -10, 95,
|
||||
-14, 100, -8, 95, -17, 111, -28, 114, -6, 89, -2, 80, -4, 82, -9, 85, -8, 81, -1, 72,
|
||||
5, 64, 1, 67, 9, 56, 0, 69, 1, 69, 7, 69, -7, 69, -6, 67, -16, 77, -2, 64,
|
||||
2, 61, -6, 67, -3, 64, 2, 57, -3, 65, -3, 66, 0, 62, 9, 51, -1, 66, -2, 71,
|
||||
-2, 75, -1, 70, -9, 72, 14, 60, 16, 37, 0, 47, 18, 35, 11, 37, 12, 41, 10, 41,
|
||||
2, 48, 12, 41, 13, 41, 0, 59, 3, 50, 19, 40, 3, 66, 18, 50, 19, -6, 18, -6,
|
||||
14, 0, 26, -12, 31, -16, 33, -25, 33, -22, 37, -28, 39, -30, 42, -30, 47, -42, 45, -36,
|
||||
49, -34, 41, -17, 32, 9, 69, -71, 63, -63, 66, -64, 77, -74, 54, -39, 52, -35, 41, -10,
|
||||
36, 0, 40, -1, 30, 14, 28, 26, 23, 37, 12, 55, 11, 65, 37, -33, 39, -36, 40, -37,
|
||||
38, -30, 46, -33, 42, -30, 40, -24, 49, -29, 38, -12, 40, -10, 38, -3, 46, -5, 31, 20,
|
||||
29, 30, 25, 44, 12, 48, 11, 49, 26, 45, 22, 22, 23, 22, 27, 21, 33, 20, 26, 28,
|
||||
30, 24, 27, 34, 18, 42, 25, 39, 18, 50, 12, 70, 21, 54, 14, 71, 11, 83, 25, 32,
|
||||
21, 49, 21, 54, -5, 85, -6, 81, -10, 77, -7, 81, -17, 80, -18, 73, -4, 74, -10, 83,
|
||||
-9, 71, -9, 67, -1, 61, -8, 66, -14, 66, 0, 59, 2, 59, 17, -10, 32, -13, 42, -9,
|
||||
49, -5, 53, 0, 64, 3, 68, 10, 66, 27, 47, 57, -5, 71, 0, 24, -1, 36, -2, 42,
|
||||
-2, 52, -9, 57, -6, 63, -4, 65, -4, 67, -7, 82, -3, 81, -3, 76, -7, 72, -6, 78,
|
||||
-12, 72, -14, 68, -3, 70, -6, 76, -5, 66, -5, 62, 0, 57, -4, 61, -9, 60, 1, 54,
|
||||
2, 58, 17, -10, 32, -13, 42, -9, 49, -5, 53, 0, 64, 3, 68, 10, 66, 27, 47, 57,
|
||||
];
|
||||
|
||||
private static readonly sbyte[] P2 =
|
||||
[
|
||||
20, -15, 2, 54, 3, 74, 20, -15, 2, 54, 3, 74, -28, 127, -23, 104, -6, 53, -1, 54,
|
||||
7, 51, 29, 16, 25, 0, 14, 0, -10, 51, -3, 62, -27, 99, 26, 16, -4, 85, -24, 102,
|
||||
5, 57, 6, 57, -17, 73, 14, 57, 20, 40, 20, 10, 29, 0, 54, 0, 37, 42, 12, 97,
|
||||
-32, 127, -22, 117, -2, 74, -4, 85, -24, 102, 5, 57, -6, 93, -14, 88, -6, 44, 4, 55,
|
||||
-11, 89, -15, 103, -21, 116, 19, 57, 20, 58, 4, 84, 6, 96, 1, 63, -5, 85, -13, 106,
|
||||
5, 63, 6, 75, -3, 90, -1, 101, 3, 55, -4, 79, -2, 75, -12, 97, -7, 50, 1, 60,
|
||||
0, 41, 0, 63, 0, 63, 0, 63, -9, 83, 4, 86, 0, 97, -7, 72, 13, 41, 3, 62,
|
||||
7, 34, -9, 88, -20, 127, -36, 127, -17, 91, -14, 95, -25, 84, -25, 86, -12, 89, -17, 91,
|
||||
-31, 127, -14, 76, -18, 103, -13, 90, -37, 127, 11, 80, 5, 76, 2, 84, 5, 78, -6, 55,
|
||||
4, 61, -14, 83, -37, 127, -5, 79, -11, 104, -11, 91, -30, 127, 0, 65, -2, 79, 0, 72,
|
||||
-4, 92, -6, 56, 3, 68, -8, 71, -13, 98, -4, 86, -12, 88, -5, 82, -3, 72, -4, 67,
|
||||
-8, 72, -16, 89, -9, 69, -1, 59, 5, 66, 4, 57, -4, 71, -2, 71, 2, 58, -1, 74,
|
||||
-4, 44, -1, 69, 0, 62, -7, 51, -4, 47, -6, 42, -3, 41, -6, 53, 8, 76, -9, 78,
|
||||
-11, 83, 9, 52, 0, 67, -5, 90, 1, 67, -15, 72, -5, 75, -8, 80, -21, 83, -21, 64,
|
||||
-13, 31, -25, 64, -29, 94, 9, 75, 17, 63, -8, 74, -5, 35, -2, 27, 13, 91, 3, 65,
|
||||
-7, 69, 8, 77, -10, 66, 3, 62, -3, 68, -20, 81, 0, 30, 1, 7, -3, 23, -21, 74,
|
||||
16, 66, -23, 124, 17, 37, 44, -18, 50, -34, -22, 127, 4, 39, 0, 42, 7, 34, 11, 29,
|
||||
8, 31, 6, 37, 7, 42, 3, 40, 8, 33, 13, 43, 13, 36, 4, 47, 3, 55, 2, 58,
|
||||
6, 60, 8, 44, 11, 44, 14, 42, 7, 48, 4, 56, 4, 52, 13, 37, 9, 49, 19, 58,
|
||||
10, 48, 12, 45, 0, 69, 20, 33, 8, 63, 35, -18, 33, -25, 28, -3, 24, 10, 27, 0,
|
||||
34, -14, 52, -44, 39, -24, 19, 17, 31, 25, 36, 29, 24, 33, 34, 15, 30, 20, 22, 73,
|
||||
20, 34, 19, 31, 27, 44, 19, 16, 15, 36, 15, 36, 21, 28, 25, 21, 30, 20, 31, 12,
|
||||
27, 16, 24, 42, 0, 93, 14, 56, 15, 57, 26, 38, -24, 127, -24, 115, -22, 82, -9, 62,
|
||||
0, 53, 0, 59, -14, 85, -13, 89, -13, 94, -11, 92, -29, 127, -21, 100, -14, 57, -12, 67,
|
||||
-11, 71, -10, 77, -21, 85, -16, 88, -23, 104, -15, 98, -37, 127, -10, 82, -8, 48, -8, 61,
|
||||
-8, 66, -7, 70, -14, 75, -10, 79, -9, 83, -12, 92, -18, 108, -4, 79, -22, 69, -16, 75,
|
||||
-2, 58, 1, 58, -13, 78, -9, 83, -4, 81, -13, 99, -13, 81, -6, 38, -13, 62, -6, 58,
|
||||
-2, 59, -16, 73, -10, 76, -13, 86, -9, 83, -10, 87, 0, 0, -22, 127, -25, 127, -25, 120,
|
||||
-27, 127, -19, 114, -23, 117, -25, 118, -26, 117, -24, 113, -28, 118, -31, 120, -37, 124, -10, 94,
|
||||
-15, 102, -10, 99, -13, 106, -50, 127, -5, 92, 17, 57, -5, 86, -13, 94, -12, 91, -2, 77,
|
||||
0, 71, -1, 73, 4, 64, -7, 81, 5, 64, 15, 57, 1, 67, 0, 68, -10, 67, 1, 68,
|
||||
0, 77, 2, 64, 0, 68, -5, 78, 7, 55, 5, 59, 2, 65, 14, 54, 15, 44, 5, 60,
|
||||
2, 70, -2, 76, -18, 86, 12, 70, 5, 64, -12, 70, 11, 55, 5, 56, 0, 69, 2, 65,
|
||||
-6, 74, 5, 54, 7, 54, -6, 76, -11, 82, -2, 77, -2, 77, 25, 42, 17, -13, 16, -9,
|
||||
17, -12, 27, -21, 37, -30, 41, -40, 42, -41, 48, -47, 39, -32, 46, -40, 52, -51, 46, -41,
|
||||
52, -39, 43, -19, 32, 11, 61, -55, 56, -46, 62, -50, 81, -67, 45, -20, 35, -2, 28, 15,
|
||||
34, 1, 39, 1, 30, 17, 20, 38, 18, 45, 15, 54, 0, 79, 36, -16, 37, -14, 37, -17,
|
||||
32, 1, 34, 15, 29, 15, 24, 25, 34, 22, 31, 16, 35, 18, 31, 28, 33, 41, 36, 28,
|
||||
27, 47, 21, 62, 18, 31, 19, 26, 36, 24, 24, 23, 27, 16, 24, 30, 31, 29, 22, 41,
|
||||
22, 42, 16, 60, 15, 52, 14, 60, 3, 78, -16, 123, 21, 53, 22, 56, 25, 61, 21, 33,
|
||||
19, 50, 17, 61, -3, 78, -8, 74, -9, 72, -10, 72, -18, 75, -12, 71, -11, 63, -5, 70,
|
||||
-17, 75, -14, 72, -16, 67, -8, 53, -14, 59, -9, 52, -11, 68, 9, -2, 30, -10, 31, -4,
|
||||
33, -1, 33, 7, 31, 12, 37, 23, 31, 38, 20, 64, -9, 71, -7, 37, -8, 44, -11, 49,
|
||||
-10, 56, -12, 59, -8, 63, -9, 67, -6, 68, -10, 79, -3, 78, -8, 74, -9, 72, -10, 72,
|
||||
-18, 75, -12, 71, -11, 63, -5, 70, -17, 75, -14, 72, -16, 67, -8, 53, -14, 59, -9, 52,
|
||||
-11, 68, 9, -2, 30, -10, 31, -4, 33, -1, 33, 7, 31, 12, 37, 23, 31, 38, 20, 64,
|
||||
];
|
||||
|
||||
/// <summary>(m, n) pairs for I slices, [ctxIdx * 2].</summary>
|
||||
internal static readonly sbyte[] InitI = I;
|
||||
|
||||
/// <summary>(m, n) pairs for P and B slices by cabac_init_idc, [idc][ctxIdx * 2].</summary>
|
||||
internal static readonly sbyte[][] InitPB = [P0, P1, P2];
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>
|
||||
/// The variable-length codes of CAVLC (ITU-T H.264, tables 9-5, 9-7, 9-8, 9-9 and 9-10), written as bit strings and
|
||||
/// turned once into lookup tables indexed by the next 16 bits of the stream.
|
||||
/// </summary>
|
||||
internal static class CavlcTables
|
||||
{
|
||||
/// <summary>coeff_token for 0 ≤ nC < 2, indexed [TotalCoeff * 4 + TrailingOnes].</summary>
|
||||
private static readonly string?[] CoeffToken0 =
|
||||
[
|
||||
"1", null, null, null,
|
||||
"000101", "01", null, null,
|
||||
"00000111", "000100", "001", null,
|
||||
"000000111", "00000110", "0000101", "00011",
|
||||
"0000000111", "000000110", "00000101", "000011",
|
||||
"00000000111", "0000000110", "000000101", "0000100",
|
||||
"0000000001111", "00000000110", "0000000101", "00000100",
|
||||
"0000000001011", "0000000001110", "00000000101", "000000100",
|
||||
"0000000001000", "0000000001010", "0000000001101", "0000000100",
|
||||
"00000000001111", "00000000001110", "0000000001001", "00000000100",
|
||||
"00000000001011", "00000000001010", "00000000001101", "0000000001100",
|
||||
"000000000001111", "000000000001110", "00000000001001", "00000000001100",
|
||||
"000000000001011", "000000000001010", "000000000001101", "00000000001000",
|
||||
"0000000000001111", "000000000000001", "000000000001001", "000000000001100",
|
||||
"0000000000001011", "0000000000001110", "0000000000001101", "000000000001000",
|
||||
"0000000000000111", "0000000000001010", "0000000000001001", "0000000000001100",
|
||||
"0000000000000100", "0000000000000110", "0000000000000101", "0000000000001000",
|
||||
];
|
||||
|
||||
/// <summary>coeff_token for 2 ≤ nC < 4.</summary>
|
||||
private static readonly string?[] CoeffToken1 =
|
||||
[
|
||||
"11", null, null, null,
|
||||
"001011", "10", null, null,
|
||||
"000111", "00111", "011", null,
|
||||
"0000111", "001010", "001001", "0101",
|
||||
"00000111", "000110", "000101", "0100",
|
||||
"00000100", "0000110", "0000101", "00110",
|
||||
"000000111", "00000110", "00000101", "001000",
|
||||
"00000001111", "000000110", "000000101", "000100",
|
||||
"00000001011", "00000001110", "00000001101", "0000100",
|
||||
"000000001111", "00000001010", "00000001001", "000000100",
|
||||
"000000001011", "000000001110", "000000001101", "00000001100",
|
||||
"000000001000", "000000001010", "000000001001", "00000001000",
|
||||
"0000000001111", "0000000001110", "0000000001101", "000000001100",
|
||||
"0000000001011", "0000000001010", "0000000001001", "0000000001100",
|
||||
"0000000000111", "00000000001011", "0000000000110", "0000000001000",
|
||||
"00000000001001", "00000000001000", "00000000001010", "0000000000001",
|
||||
"00000000000111", "00000000000110", "00000000000101", "00000000000100",
|
||||
];
|
||||
|
||||
/// <summary>coeff_token for 4 ≤ nC < 8.</summary>
|
||||
private static readonly string?[] CoeffToken2 =
|
||||
[
|
||||
"1111", null, null, null,
|
||||
"001111", "1110", null, null,
|
||||
"001011", "01111", "1101", null,
|
||||
"001000", "01100", "01110", "1100",
|
||||
"0001111", "01010", "01011", "1011",
|
||||
"0001011", "01000", "01001", "1010",
|
||||
"0001001", "001110", "001101", "1001",
|
||||
"0001000", "001010", "001001", "1000",
|
||||
"00001111", "0001110", "0001101", "01101",
|
||||
"00001011", "00001110", "0001010", "001100",
|
||||
"000001111", "00001010", "00001101", "0001100",
|
||||
"000001011", "000001110", "00001001", "00001100",
|
||||
"000001000", "000001010", "000001101", "00001000",
|
||||
"0000001101", "000000111", "000001001", "000001100",
|
||||
"0000001001", "0000001100", "0000001011", "0000001010",
|
||||
"0000000101", "0000001000", "0000000111", "0000000110",
|
||||
"0000000001", "0000000100", "0000000011", "0000000010",
|
||||
];
|
||||
|
||||
/// <summary>coeff_token for the chroma DC of 4:2:0 (nC = −1).</summary>
|
||||
private static readonly string?[] CoeffTokenChromaDc =
|
||||
[
|
||||
"01", null, null, null,
|
||||
"000111", "1", null, null,
|
||||
"000100", "000110", "001", null,
|
||||
"000011", "0000011", "0000010", "000101",
|
||||
"000010", "00000011", "00000010", "0000000",
|
||||
];
|
||||
|
||||
/// <summary>total_zeros of 4×4 blocks, indexed [TotalCoeff − 1][total_zeros].</summary>
|
||||
private static readonly string[][] TotalZeros4x4 =
|
||||
[
|
||||
["1", "011", "010", "0011", "0010", "00011", "00010", "000011", "000010", "0000011", "0000010", "00000011", "00000010", "000000011", "000000010", "000000001"],
|
||||
["111", "110", "101", "100", "011", "0101", "0100", "0011", "0010", "00011", "00010", "000011", "000010", "000001", "000000"],
|
||||
["0101", "111", "110", "101", "0100", "0011", "100", "011", "0010", "00011", "00010", "000001", "00001", "000000"],
|
||||
["00011", "111", "0101", "0100", "110", "101", "100", "0011", "011", "0010", "00010", "00001", "00000"],
|
||||
["0101", "0100", "0011", "111", "110", "101", "100", "011", "0010", "00001", "0001", "00000"],
|
||||
["000001", "00001", "111", "110", "101", "100", "011", "010", "0001", "001", "000000"],
|
||||
["000001", "00001", "101", "100", "011", "11", "010", "0001", "001", "000000"],
|
||||
["000001", "0001", "00001", "011", "11", "10", "010", "001", "000000"],
|
||||
["000001", "000000", "0001", "11", "10", "001", "01", "00001"],
|
||||
["00001", "00000", "001", "11", "10", "01", "0001"],
|
||||
["0000", "0001", "001", "010", "1", "011"],
|
||||
["0000", "0001", "01", "1", "001"],
|
||||
["000", "001", "1", "01"],
|
||||
["00", "01", "1"],
|
||||
["0", "1"],
|
||||
];
|
||||
|
||||
/// <summary>total_zeros of the 4:2:0 chroma DC, indexed [TotalCoeff − 1][total_zeros].</summary>
|
||||
private static readonly string[][] TotalZerosChromaDc =
|
||||
[
|
||||
["1", "01", "001", "000"],
|
||||
["1", "01", "00"],
|
||||
["1", "0"],
|
||||
];
|
||||
|
||||
/// <summary>run_before, indexed [Min(zerosLeft, 7) − 1][run_before].</summary>
|
||||
private static readonly string[][] RunBefore =
|
||||
[
|
||||
["1", "0"],
|
||||
["1", "01", "00"],
|
||||
["11", "10", "01", "00"],
|
||||
["11", "10", "01", "001", "000"],
|
||||
["11", "10", "011", "010", "001", "000"],
|
||||
["11", "000", "001", "011", "010", "101", "100"],
|
||||
["111", "110", "101", "100", "011", "010", "001", "0001", "00001", "000001", "0000001", "00000001", "000000001", "0000000001", "00000000001"],
|
||||
];
|
||||
|
||||
/// <summary>Lookup tables of coeff_token: [0..2] by nC class, [3] for nC ≥ 8 (fixed 6 bits), [4] for the chroma DC.</summary>
|
||||
internal static readonly ushort[][] CoeffTokenLookup = BuildCoeffTokenLookups();
|
||||
|
||||
internal static readonly ushort[][] TotalZerosLookup = BuildLookups(TotalZeros4x4);
|
||||
|
||||
internal static readonly ushort[][] TotalZerosChromaDcLookup = BuildLookups(TotalZerosChromaDc);
|
||||
|
||||
internal static readonly ushort[][] RunBeforeLookup = BuildLookups(RunBefore);
|
||||
|
||||
/// <summary>All the code tables, for the self-checks of the tests (prefix-free, complete where the standard is).</summary>
|
||||
internal static IEnumerable<(string Name, string?[] Codes)> AllCodeTables()
|
||||
{
|
||||
yield return ("coeff_token 0", CoeffToken0);
|
||||
yield return ("coeff_token 1", CoeffToken1);
|
||||
yield return ("coeff_token 2", CoeffToken2);
|
||||
yield return ("coeff_token -1", CoeffTokenChromaDc);
|
||||
for (var i = 0; i < TotalZeros4x4.Length; i++)
|
||||
{
|
||||
yield return ($"total_zeros {i + 1}", TotalZeros4x4[i]);
|
||||
}
|
||||
|
||||
for (var i = 0; i < TotalZerosChromaDc.Length; i++)
|
||||
{
|
||||
yield return ($"total_zeros DC {i + 1}", TotalZerosChromaDc[i]);
|
||||
}
|
||||
|
||||
for (var i = 0; i < RunBefore.Length; i++)
|
||||
{
|
||||
yield return ($"run_before {i + 1}", RunBefore[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A 65536-entry table: for the next 16 bits of the stream, (code length << 8) | value; zero when no code
|
||||
/// matches.
|
||||
/// </summary>
|
||||
private static ushort[] Build(string?[] codes)
|
||||
{
|
||||
var table = new ushort[1 << 16];
|
||||
for (var value = 0; value < codes.Length; value++)
|
||||
{
|
||||
var code = codes[value];
|
||||
if (code is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var bits = 0;
|
||||
foreach (var c in code)
|
||||
{
|
||||
bits = (bits << 1) | (c == '1' ? 1 : 0);
|
||||
}
|
||||
|
||||
var shift = 16 - code.Length;
|
||||
var first = bits << shift;
|
||||
var count = 1 << shift;
|
||||
var entry = (ushort)((code.Length << 8) | value);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
table[first + i] = entry;
|
||||
}
|
||||
}
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
private static ushort[][] BuildLookups(string[][] tables)
|
||||
{
|
||||
var result = new ushort[tables.Length][];
|
||||
for (var i = 0; i < tables.Length; i++)
|
||||
{
|
||||
result[i] = Build(tables[i]);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static ushort[][] BuildCoeffTokenLookups()
|
||||
{
|
||||
var fixedLength = new string?[17 * 4];
|
||||
fixedLength[0] = "000011";
|
||||
for (var total = 1; total <= 16; total++)
|
||||
{
|
||||
for (var ones = 0; ones <= Math.Min(3, total); ones++)
|
||||
{
|
||||
var code = ((total - 1) << 2) | ones;
|
||||
fixedLength[(total * 4) + ones] = Convert.ToString(code, 2).PadLeft(6, '0');
|
||||
}
|
||||
}
|
||||
|
||||
return [Build(CoeffToken0), Build(CoeffToken1), Build(CoeffToken2), Build(fixedLength), Build(CoeffTokenChromaDc)];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
public sealed partial class H264Decoder
|
||||
{
|
||||
/// <summary>Deblocking filter (§8.7) over the whole decoded picture, macroblock by macroblock in raster order.</summary>
|
||||
private void Deblock(Picture picture)
|
||||
{
|
||||
var any = false;
|
||||
foreach (var filter in sliceFilters)
|
||||
{
|
||||
any |= filter.Disable != 1;
|
||||
}
|
||||
|
||||
if (!any)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var stride = picture.Width;
|
||||
var cstride = stride / 2;
|
||||
Span<byte> bs = stackalloc byte[16];
|
||||
for (var m = 0; m < mbCount; m++)
|
||||
{
|
||||
var s = mbSlice[m];
|
||||
if (s < 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var (disable, alphaOffset, betaOffset) = sliceFilters[s];
|
||||
if (disable == 1)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int mx = m % widthInMbs, my = m / widthInMbs;
|
||||
var leftOk = mx > 0 && mbSlice[m - 1] >= 0 && (disable != 2 || mbSlice[m - 1] == s);
|
||||
var topOk = my > 0 && mbSlice[m - widthInMbs] >= 0 && (disable != 2 || mbSlice[m - widthInMbs] == s);
|
||||
var t8 = mbT8[m];
|
||||
for (var dir = 0; dir < 2; dir++)
|
||||
{
|
||||
var edgeOk = dir == 0 ? leftOk : topOk;
|
||||
var neighbour = dir == 0 ? m - 1 : m - widthInMbs;
|
||||
for (var edge = 0; edge < 4; edge++)
|
||||
{
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
var value = 0;
|
||||
if ((edge != 0 || edgeOk) && !(t8 && (edge & 1) != 0))
|
||||
{
|
||||
var qb = dir == 0 ? (i * 4) + edge : (edge * 4) + i;
|
||||
int pm, pb;
|
||||
if (edge == 0)
|
||||
{
|
||||
pm = neighbour;
|
||||
pb = dir == 0 ? (i * 4) + 3 : 12 + i;
|
||||
}
|
||||
else
|
||||
{
|
||||
pm = m;
|
||||
pb = qb - (dir == 0 ? 1 : 4);
|
||||
}
|
||||
|
||||
value = BoundaryStrength(picture, pm, pb, m, qb, edge == 0);
|
||||
}
|
||||
|
||||
bs[(edge * 4) + i] = (byte)value;
|
||||
}
|
||||
}
|
||||
|
||||
// Luma.
|
||||
for (var edge = 0; edge < 4; edge++)
|
||||
{
|
||||
if ((bs[edge * 4] | bs[(edge * 4) + 1] | bs[(edge * 4) + 2] | bs[(edge * 4) + 3]) == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var pm = edge == 0 ? neighbour : m;
|
||||
var qpav = (mbQp[pm] + mbQp[m] + 1) >> 1;
|
||||
var indexA = Math.Clamp(qpav + alphaOffset, 0, 51);
|
||||
var indexB = Math.Clamp(qpav + betaOffset, 0, 51);
|
||||
int alpha = H264Tables.Alpha[indexA], beta = H264Tables.Beta[indexB];
|
||||
if (alpha == 0 || beta == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (var k = 0; k < 16; k++)
|
||||
{
|
||||
var strength = bs[(edge * 4) + (k >> 2)];
|
||||
if (strength == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int o, step;
|
||||
if (dir == 0)
|
||||
{
|
||||
o = (((my * 16) + k) * stride) + (mx * 16) + (edge * 4);
|
||||
step = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
o = (((my * 16) + (edge * 4)) * stride) + (mx * 16) + k;
|
||||
step = stride;
|
||||
}
|
||||
|
||||
FilterLuma(picture.Y, o, step, strength, alpha, beta, indexA);
|
||||
}
|
||||
}
|
||||
|
||||
// Chroma (4:2:0): the edges at 0 and 4 chroma samples, with the strength of luma edges 0 and 2.
|
||||
for (var ce = 0; ce < 2; ce++)
|
||||
{
|
||||
var edge = ce * 2;
|
||||
if ((bs[edge * 4] | bs[(edge * 4) + 1] | bs[(edge * 4) + 2] | bs[(edge * 4) + 3]) == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var pm = edge == 0 ? neighbour : m;
|
||||
for (var c = 0; c < 2; c++)
|
||||
{
|
||||
var plane = c == 0 ? picture.Cb : picture.Cr;
|
||||
var qpav = (mbQpC[(pm * 2) + c] + mbQpC[(m * 2) + c] + 1) >> 1;
|
||||
var indexA = Math.Clamp(qpav + alphaOffset, 0, 51);
|
||||
var indexB = Math.Clamp(qpav + betaOffset, 0, 51);
|
||||
int alpha = H264Tables.Alpha[indexA], beta = H264Tables.Beta[indexB];
|
||||
if (alpha == 0 || beta == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (var k = 0; k < 8; k++)
|
||||
{
|
||||
var strength = bs[(edge * 4) + (k >> 1)];
|
||||
if (strength == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int o, step;
|
||||
if (dir == 0)
|
||||
{
|
||||
o = (((my * 8) + k) * cstride) + (mx * 8) + (ce * 4);
|
||||
step = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
o = (((my * 8) + (ce * 4)) * cstride) + (mx * 8) + k;
|
||||
step = cstride;
|
||||
}
|
||||
|
||||
FilterChroma(plane, o, step, strength, alpha, beta, indexA);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>bS of the edge between 4×4 luma blocks <paramref name="pb"/> of <paramref name="pm"/> and <paramref name="qb"/> of <paramref name="qm"/> (§8.7.2.1).</summary>
|
||||
private int BoundaryStrength(Picture picture, int pm, int pb, int qm, int qb, bool mbEdge)
|
||||
{
|
||||
if (picture.MbIntra[pm] || picture.MbIntra[qm])
|
||||
{
|
||||
return mbEdge ? 4 : 3;
|
||||
}
|
||||
|
||||
if (HasCoefficients(pm, pb) || HasCoefficients(qm, qb))
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
int pi = (pm * 4) + B8OfRaster(pb), qi = (qm * 4) + B8OfRaster(qb);
|
||||
var l1 = mbCount * 4;
|
||||
var p0 = picture.RefIdx[pi] >= 0 ? picture.RefPic[pi] ?? picture : null;
|
||||
var p1 = picture.RefIdx[l1 + pi] >= 0 ? picture.RefPic[l1 + pi] ?? picture : null;
|
||||
var q0 = picture.RefIdx[qi] >= 0 ? picture.RefPic[qi] ?? picture : null;
|
||||
var q1 = picture.RefIdx[l1 + qi] >= 0 ? picture.RefPic[l1 + qi] ?? picture : null;
|
||||
var countP = (p0 is null ? 0 : 1) + (p1 is null ? 0 : 1);
|
||||
var countQ = (q0 is null ? 0 : 1) + (q1 is null ? 0 : 1);
|
||||
if (countP != countQ)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
var mv = picture.Mv;
|
||||
var l1Mv = mbCount * 32;
|
||||
int pv0 = ((pm * 16) + pb) * 2, qv0 = ((qm * 16) + qb) * 2;
|
||||
int pv1 = l1Mv + pv0, qv1 = l1Mv + qv0;
|
||||
if (countP == 1)
|
||||
{
|
||||
var refP = p0 ?? p1;
|
||||
var refQ = q0 ?? q1;
|
||||
if (!ReferenceEquals(refP, refQ))
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
return MvFar(mv, p0 is not null ? pv0 : pv1, q0 is not null ? qv0 : qv1) ? 1 : 0;
|
||||
}
|
||||
|
||||
if (countP == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var sameSet = (ReferenceEquals(p0, q0) && ReferenceEquals(p1, q1)) || (ReferenceEquals(p0, q1) && ReferenceEquals(p1, q0));
|
||||
if (!sameSet)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!ReferenceEquals(p0, p1))
|
||||
{
|
||||
return ReferenceEquals(p0, q0)
|
||||
? (MvFar(mv, pv0, qv0) || MvFar(mv, pv1, qv1) ? 1 : 0)
|
||||
: (MvFar(mv, pv0, qv1) || MvFar(mv, pv1, qv0) ? 1 : 0);
|
||||
}
|
||||
|
||||
// Both motion vectors of both blocks refer to the same picture.
|
||||
var straight = MvFar(mv, pv0, qv0) || MvFar(mv, pv1, qv1);
|
||||
var crossed = MvFar(mv, pv0, qv1) || MvFar(mv, pv1, qv0);
|
||||
return straight && crossed ? 1 : 0;
|
||||
}
|
||||
|
||||
private static bool MvFar(short[] mv, int a, int b) => Math.Abs(mv[a] - mv[b]) >= 4 || Math.Abs(mv[a + 1] - mv[b + 1]) >= 4;
|
||||
|
||||
private bool HasCoefficients(int m, int blk)
|
||||
{
|
||||
var baseIndex = m * 24;
|
||||
if (!mbT8[m])
|
||||
{
|
||||
return nz[baseIndex + blk] != 0;
|
||||
}
|
||||
|
||||
// The 8×8 transform block containing the 4×4 block.
|
||||
var r0 = ((blk >> 3) * 8) + (((blk & 3) >> 1) * 2);
|
||||
return (nz[baseIndex + r0] | nz[baseIndex + r0 + 1] | nz[baseIndex + r0 + 4] | nz[baseIndex + r0 + 5]) != 0;
|
||||
}
|
||||
|
||||
private static void FilterLuma(byte[] s, int o, int step, int bS, int alpha, int beta, int indexA)
|
||||
{
|
||||
int p0 = s[o - step], q0 = s[o];
|
||||
if (Math.Abs(p0 - q0) >= alpha)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int p1 = s[o - (2 * step)], q1 = s[o + step];
|
||||
if (Math.Abs(p1 - p0) >= beta || Math.Abs(q1 - q0) >= beta)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int p2 = s[o - (3 * step)], q2 = s[o + (2 * step)];
|
||||
var ap = Math.Abs(p2 - p0) < beta;
|
||||
var aq = Math.Abs(q2 - q0) < beta;
|
||||
if (bS < 4)
|
||||
{
|
||||
int tc0 = H264Tables.Tc0[(indexA * 3) + bS - 1];
|
||||
var tc = tc0 + (ap ? 1 : 0) + (aq ? 1 : 0);
|
||||
var delta = Math.Clamp((((q0 - p0) << 2) + (p1 - q1) + 4) >> 3, -tc, tc);
|
||||
s[o - step] = Clip(p0 + delta);
|
||||
s[o] = Clip(q0 - delta);
|
||||
if (ap)
|
||||
{
|
||||
s[o - (2 * step)] = (byte)(p1 + Math.Clamp((p2 + ((p0 + q0 + 1) >> 1) - (p1 << 1)) >> 1, -tc0, tc0));
|
||||
}
|
||||
|
||||
if (aq)
|
||||
{
|
||||
s[o + step] = (byte)(q1 + Math.Clamp((q2 + ((p0 + q0 + 1) >> 1) - (q1 << 1)) >> 1, -tc0, tc0));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var strong = Math.Abs(p0 - q0) < ((alpha >> 2) + 2);
|
||||
if (ap && strong)
|
||||
{
|
||||
int p3 = s[o - (4 * step)];
|
||||
s[o - step] = (byte)((p2 + (2 * p1) + (2 * p0) + (2 * q0) + q1 + 4) >> 3);
|
||||
s[o - (2 * step)] = (byte)((p2 + p1 + p0 + q0 + 2) >> 2);
|
||||
s[o - (3 * step)] = (byte)(((2 * p3) + (3 * p2) + p1 + p0 + q0 + 4) >> 3);
|
||||
}
|
||||
else
|
||||
{
|
||||
s[o - step] = (byte)(((2 * p1) + p0 + q1 + 2) >> 2);
|
||||
}
|
||||
|
||||
if (aq && strong)
|
||||
{
|
||||
int q3 = s[o + (3 * step)];
|
||||
s[o] = (byte)((p1 + (2 * p0) + (2 * q0) + (2 * q1) + q2 + 4) >> 3);
|
||||
s[o + step] = (byte)((p0 + q0 + q1 + q2 + 2) >> 2);
|
||||
s[o + (2 * step)] = (byte)(((2 * q3) + (3 * q2) + q1 + q0 + p0 + 4) >> 3);
|
||||
}
|
||||
else
|
||||
{
|
||||
s[o] = (byte)(((2 * q1) + q0 + p1 + 2) >> 2);
|
||||
}
|
||||
}
|
||||
|
||||
private static void FilterChroma(byte[] s, int o, int step, int bS, int alpha, int beta, int indexA)
|
||||
{
|
||||
int p0 = s[o - step], q0 = s[o];
|
||||
if (Math.Abs(p0 - q0) >= alpha)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int p1 = s[o - (2 * step)], q1 = s[o + step];
|
||||
if (Math.Abs(p1 - p0) >= beta || Math.Abs(q1 - q0) >= beta)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (bS < 4)
|
||||
{
|
||||
var tc = H264Tables.Tc0[(indexA * 3) + bS - 1] + 1;
|
||||
var delta = Math.Clamp((((q0 - p0) << 2) + (p1 - q1) + 4) >> 3, -tc, tc);
|
||||
s[o - step] = Clip(p0 + delta);
|
||||
s[o] = Clip(q0 - delta);
|
||||
return;
|
||||
}
|
||||
|
||||
s[o - step] = (byte)(((2 * p1) + p0 + q1 + 2) >> 2);
|
||||
s[o] = (byte)(((2 * q1) + q0 + p1 + 2) >> 2);
|
||||
}
|
||||
|
||||
private static byte Clip(int v) => (byte)(v < 0 ? 0 : v > 255 ? 255 : v);
|
||||
}
|
||||
@@ -0,0 +1,826 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
public sealed partial class H264Decoder
|
||||
{
|
||||
private static readonly byte[] CbfCatOffset = [0, 4, 8, 12, 16];
|
||||
private static readonly byte[] SigCatOffset = [0, 15, 29, 44, 47];
|
||||
private static readonly byte[] AbsCatOffset = [0, 10, 20, 30, 39];
|
||||
|
||||
private static int B8OfRaster(int blk) => ((blk >> 3) << 1) | ((blk >> 1) & 1);
|
||||
|
||||
private int ReadMbSkip()
|
||||
{
|
||||
var inc = (availA && !IsSkip(mb - 1) ? 1 : 0) + (availB && !IsSkip(mb - widthInMbs) ? 1 : 0);
|
||||
return cabac.Decision((sh.IsB ? 24 : 11) + inc);
|
||||
}
|
||||
|
||||
private int ReadMbType()
|
||||
{
|
||||
if (!cabacMode)
|
||||
{
|
||||
return rd.ReadUe(48);
|
||||
}
|
||||
|
||||
switch (sh.Type)
|
||||
{
|
||||
case SliceType.I:
|
||||
{
|
||||
var inc = (availA && mbKind[mb - 1] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0)
|
||||
+ (availB && mbKind[mb - widthInMbs] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0);
|
||||
if (cabac.Decision(3 + inc) == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return IntraMbTypeSuffix(3, intraSlice: true);
|
||||
}
|
||||
|
||||
case SliceType.P:
|
||||
if (cabac.Decision(14) == 0)
|
||||
{
|
||||
if (cabac.Decision(15) == 0)
|
||||
{
|
||||
return 3 * cabac.Decision(16);
|
||||
}
|
||||
|
||||
return 2 - cabac.Decision(17);
|
||||
}
|
||||
|
||||
return 5 + (cabac.Decision(17) == 0 ? 0 : IntraMbTypeSuffix(17, intraSlice: false));
|
||||
default:
|
||||
{
|
||||
var inc = (availA && mbKind[mb - 1] is not (MbKind.BSkip or MbKind.BDirect) ? 1 : 0)
|
||||
+ (availB && mbKind[mb - widthInMbs] is not (MbKind.BSkip or MbKind.BDirect) ? 1 : 0);
|
||||
if (cabac.Decision(27 + inc) == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (cabac.Decision(27 + 3) == 0)
|
||||
{
|
||||
return 1 + cabac.Decision(27 + 5);
|
||||
}
|
||||
|
||||
var bits = cabac.Decision(27 + 4) << 3;
|
||||
bits |= cabac.Decision(27 + 5) << 2;
|
||||
bits |= cabac.Decision(27 + 5) << 1;
|
||||
bits |= cabac.Decision(27 + 5);
|
||||
if (bits < 8)
|
||||
{
|
||||
return bits + 3;
|
||||
}
|
||||
|
||||
if (bits == 13)
|
||||
{
|
||||
return 23 + (cabac.Decision(32) == 0 ? 0 : IntraMbTypeSuffix(32, intraSlice: false));
|
||||
}
|
||||
|
||||
if (bits == 14)
|
||||
{
|
||||
return 11;
|
||||
}
|
||||
|
||||
if (bits == 15)
|
||||
{
|
||||
return 22;
|
||||
}
|
||||
|
||||
bits = (bits << 1) | cabac.Decision(27 + 5);
|
||||
return bits - 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The part of an intra mb_type after its first bin (which said «not I_NxN»): I_PCM or one of the I_16x16 types.
|
||||
/// </summary>
|
||||
private int IntraMbTypeSuffix(int offset, bool intraSlice)
|
||||
{
|
||||
if (cabac.Terminate() != 0)
|
||||
{
|
||||
return 25;
|
||||
}
|
||||
|
||||
var state = intraSlice ? offset + 2 : offset;
|
||||
var type = 1 + (12 * cabac.Decision(state + 1));
|
||||
if (cabac.Decision(state + 2) != 0)
|
||||
{
|
||||
type += 4 + (4 * cabac.Decision(state + 2 + (intraSlice ? 1 : 0)));
|
||||
}
|
||||
|
||||
type += 2 * cabac.Decision(state + 3 + (intraSlice ? 1 : 0));
|
||||
type += cabac.Decision(state + 3 + (intraSlice ? 2 : 0));
|
||||
return type;
|
||||
}
|
||||
|
||||
private int ReadSubMbType()
|
||||
{
|
||||
if (!cabacMode)
|
||||
{
|
||||
return rd.ReadUe(12);
|
||||
}
|
||||
|
||||
if (!sh.IsB)
|
||||
{
|
||||
if (cabac.Decision(21) != 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (cabac.Decision(22) == 0)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
return cabac.Decision(23) != 0 ? 2 : 3;
|
||||
}
|
||||
|
||||
if (cabac.Decision(36) == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (cabac.Decision(37) == 0)
|
||||
{
|
||||
return 1 + cabac.Decision(39);
|
||||
}
|
||||
|
||||
var type = 3;
|
||||
if (cabac.Decision(38) != 0)
|
||||
{
|
||||
if (cabac.Decision(39) != 0)
|
||||
{
|
||||
return 11 + cabac.Decision(39);
|
||||
}
|
||||
|
||||
type += 4;
|
||||
}
|
||||
|
||||
type += 2 * cabac.Decision(39);
|
||||
type += cabac.Decision(39);
|
||||
return type;
|
||||
}
|
||||
|
||||
private int ReadRefIdx(int list, int px, int py, int active)
|
||||
{
|
||||
if (!cabacMode)
|
||||
{
|
||||
return active == 2 ? 1 - rd.ReadBit() : rd.ReadUe(31);
|
||||
}
|
||||
|
||||
var inc = RefIdxCond(list, px - 1, py) + (2 * RefIdxCond(list, px, py - 1));
|
||||
var value = 0;
|
||||
var ctx = 54 + inc;
|
||||
while (cabac.Decision(ctx) != 0)
|
||||
{
|
||||
value++;
|
||||
ctx = value == 1 ? 58 : 59;
|
||||
if (value > 31)
|
||||
{
|
||||
throw new H264Exception("ref_idx non valido.");
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
private int RefIdxCond(int list, int xN, int yN)
|
||||
{
|
||||
if (Neighbor(xN, yN, out var n, out var blk) == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (IsSkip(n) || IsIntra(n) || mbKind[n] == MbKind.BDirect)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var b8 = B8OfRaster(blk);
|
||||
if (subDirect[(n * 4) + b8])
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return cur!.RefIdx[(((list * mbCount) + n) * 4) + b8] > 0 ? 1 : 0;
|
||||
}
|
||||
|
||||
private int ReadMvd(int list, int comp, int px, int py)
|
||||
{
|
||||
if (!cabacMode)
|
||||
{
|
||||
return rd.ReadSe();
|
||||
}
|
||||
|
||||
var sum = MvdAbs(list, comp, px - 1, py) + MvdAbs(list, comp, px, py - 1);
|
||||
var baseCtx = comp == 0 ? 40 : 47;
|
||||
var inc = sum < 3 ? 0 : sum <= 32 ? 1 : 2;
|
||||
if (cabac.Decision(baseCtx + inc) == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var value = 1;
|
||||
var k = 1;
|
||||
while (value < 9 && cabac.Decision(baseCtx + (k < 4 ? k + 2 : 6)) != 0)
|
||||
{
|
||||
value++;
|
||||
k++;
|
||||
}
|
||||
|
||||
if (value >= 9)
|
||||
{
|
||||
var bits = 3;
|
||||
while (cabac.Bypass() != 0)
|
||||
{
|
||||
value += 1 << bits;
|
||||
if (++bits > 24)
|
||||
{
|
||||
throw new H264Exception("mvd non valido.");
|
||||
}
|
||||
}
|
||||
|
||||
while (bits-- > 0)
|
||||
{
|
||||
value += cabac.Bypass() << bits;
|
||||
}
|
||||
}
|
||||
|
||||
return cabac.Bypass() != 0 ? -value : value;
|
||||
}
|
||||
|
||||
private int MvdAbs(int list, int comp, int xN, int yN)
|
||||
{
|
||||
if (Neighbor(xN, yN, out var n, out var blk) == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return mvdAbs[(((((list * mbCount) + n) * 16) + blk) * 2) + comp];
|
||||
}
|
||||
|
||||
private bool ReadTransform8x8()
|
||||
{
|
||||
if (!cabacMode)
|
||||
{
|
||||
return rd.ReadFlag();
|
||||
}
|
||||
|
||||
var inc = (availA && mbT8[mb - 1] ? 1 : 0) + (availB && mbT8[mb - widthInMbs] ? 1 : 0);
|
||||
return cabac.Decision(399 + inc) != 0;
|
||||
}
|
||||
|
||||
private (bool Prev, int Rem) ReadIntraPredMode()
|
||||
{
|
||||
if (!cabacMode)
|
||||
{
|
||||
return rd.ReadFlag() ? (true, 0) : (false, (int)rd.Read(3));
|
||||
}
|
||||
|
||||
if (cabac.Decision(68) != 0)
|
||||
{
|
||||
return (true, 0);
|
||||
}
|
||||
|
||||
var rem = cabac.Decision(69);
|
||||
rem |= cabac.Decision(69) << 1;
|
||||
rem |= cabac.Decision(69) << 2;
|
||||
return (false, rem);
|
||||
}
|
||||
|
||||
private int ReadChromaPredMode()
|
||||
{
|
||||
if (!cabacMode)
|
||||
{
|
||||
return rd.ReadUe(3);
|
||||
}
|
||||
|
||||
var inc = ChromaModeCond(availA, mb - 1) + ChromaModeCond(availB, mb - widthInMbs);
|
||||
if (cabac.Decision(64 + inc) == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (cabac.Decision(67) == 0)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
return cabac.Decision(67) == 0 ? 2 : 3;
|
||||
}
|
||||
|
||||
private int ChromaModeCond(bool available, int n) =>
|
||||
available && IsIntra(n) && mbKind[n] != MbKind.IPcm && chromaModes[n] != 0 ? 1 : 0;
|
||||
|
||||
private int ReadCbp(bool intra)
|
||||
{
|
||||
if (!cabacMode)
|
||||
{
|
||||
var code = rd.ReadUe(47);
|
||||
return intra ? H264Tables.CbpIntra[code] : H264Tables.CbpInter[code];
|
||||
}
|
||||
|
||||
var cbp = 0;
|
||||
for (var b8 = 0; b8 < 4; b8++)
|
||||
{
|
||||
int bx = b8 & 1, by = b8 >> 1;
|
||||
int condA, condB;
|
||||
if (bx == 1)
|
||||
{
|
||||
condA = ((cbp >> (b8 - 1)) & 1) == 0 ? 1 : 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
condA = availA && ((mbCbp[mb - 1] >> (b8 + 1)) & 1) == 0 ? 1 : 0;
|
||||
}
|
||||
|
||||
if (by == 1)
|
||||
{
|
||||
condB = ((cbp >> (b8 - 2)) & 1) == 0 ? 1 : 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
condB = availB && ((mbCbp[mb - widthInMbs] >> (b8 + 2)) & 1) == 0 ? 1 : 0;
|
||||
}
|
||||
|
||||
cbp |= cabac.Decision(73 + condA + (2 * condB)) << b8;
|
||||
}
|
||||
|
||||
var a = availA ? mbCbp[mb - 1] >> 4 : 0;
|
||||
var b = availB ? mbCbp[mb - widthInMbs] >> 4 : 0;
|
||||
var inc = (a != 0 ? 1 : 0) + (b != 0 ? 2 : 0);
|
||||
if (cabac.Decision(77 + inc) != 0)
|
||||
{
|
||||
inc = (a == 2 ? 1 : 0) + (b == 2 ? 2 : 0);
|
||||
cbp |= (1 + cabac.Decision(77 + 4 + inc)) << 4;
|
||||
}
|
||||
|
||||
return cbp;
|
||||
}
|
||||
|
||||
private int ReadQpDelta()
|
||||
{
|
||||
if (!cabacMode)
|
||||
{
|
||||
return rd.ReadSe();
|
||||
}
|
||||
|
||||
var ctx = 60 + (lastQpDelta != 0 ? 1 : 0);
|
||||
var k = 0;
|
||||
while (cabac.Decision(ctx) != 0)
|
||||
{
|
||||
k++;
|
||||
ctx = k == 1 ? 62 : 63;
|
||||
if (k > 104)
|
||||
{
|
||||
throw new H264Exception("mb_qp_delta non valido.");
|
||||
}
|
||||
}
|
||||
|
||||
return (k & 1) != 0 ? (k + 1) / 2 : -(k / 2);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// residual_block() of category <paramref name="cat"/> (0 luma DC, 1 luma AC, 2 luma 4×4, 3 chroma DC, 4 chroma AC,
|
||||
/// 5 luma 8×8): the levels by coefficient index into <paramref name="output"/>; returns the number of non-zero ones.
|
||||
/// </summary>
|
||||
private int ReadBlock(int cat, int blk, int comp, int[] output, int maxNum)
|
||||
{
|
||||
Array.Clear(output, 0, maxNum);
|
||||
return cabacMode ? ReadCabacBlock(cat, blk, comp, output, maxNum) : ReadCavlcBlock(cat, blk, comp, output, maxNum);
|
||||
}
|
||||
|
||||
private int ReadCavlcBlock(int cat, int blk, int comp, int[] output, int maxNum)
|
||||
{
|
||||
int nC;
|
||||
if (cat == 3)
|
||||
{
|
||||
nC = -1;
|
||||
}
|
||||
else if (cat == 4)
|
||||
{
|
||||
nC = ChromaNc(blk, comp);
|
||||
}
|
||||
else
|
||||
{
|
||||
nC = LumaNc(blk);
|
||||
}
|
||||
|
||||
var table = nC switch
|
||||
{
|
||||
-1 => CavlcTables.CoeffTokenLookup[4],
|
||||
< 2 => CavlcTables.CoeffTokenLookup[0],
|
||||
< 4 => CavlcTables.CoeffTokenLookup[1],
|
||||
< 8 => CavlcTables.CoeffTokenLookup[2],
|
||||
_ => CavlcTables.CoeffTokenLookup[3],
|
||||
};
|
||||
var entry = table[rd.Peek(16)];
|
||||
if (entry == 0)
|
||||
{
|
||||
throw new H264Exception("coeff_token non valido.");
|
||||
}
|
||||
|
||||
rd.Skip(entry >> 8);
|
||||
var token = entry & 0xFF;
|
||||
var total = token >> 2;
|
||||
var ones = token & 3;
|
||||
if (total == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (total > maxNum)
|
||||
{
|
||||
throw new H264Exception("Troppi coefficienti.");
|
||||
}
|
||||
|
||||
Span<int> levelVal = stackalloc int[16];
|
||||
var suffixLength = total > 10 && ones < 3 ? 1 : 0;
|
||||
for (var i = 0; i < total; i++)
|
||||
{
|
||||
if (i < ones)
|
||||
{
|
||||
levelVal[i] = rd.ReadBit() != 0 ? -1 : 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
var prefix = 0;
|
||||
while (rd.ReadBit() == 0)
|
||||
{
|
||||
if (++prefix > 32)
|
||||
{
|
||||
throw new H264Exception("level_prefix non valido.");
|
||||
}
|
||||
}
|
||||
|
||||
var levelCode = Math.Min(15, prefix) << suffixLength;
|
||||
if (suffixLength > 0 || prefix >= 14)
|
||||
{
|
||||
var size = prefix == 14 && suffixLength == 0 ? 4 : prefix >= 15 ? prefix - 3 : suffixLength;
|
||||
if (size > 0)
|
||||
{
|
||||
levelCode += (int)rd.Read(size);
|
||||
}
|
||||
}
|
||||
|
||||
if (prefix >= 15 && suffixLength == 0)
|
||||
{
|
||||
levelCode += 15;
|
||||
}
|
||||
|
||||
if (prefix >= 16)
|
||||
{
|
||||
levelCode += (1 << (prefix - 3)) - 4096;
|
||||
}
|
||||
|
||||
if (i == ones && ones < 3)
|
||||
{
|
||||
levelCode += 2;
|
||||
}
|
||||
|
||||
levelVal[i] = (levelCode & 1) == 0 ? (levelCode + 2) >> 1 : (-levelCode - 1) >> 1;
|
||||
if (suffixLength == 0)
|
||||
{
|
||||
suffixLength = 1;
|
||||
}
|
||||
|
||||
if (Math.Abs(levelVal[i]) > (3 << (suffixLength - 1)) && suffixLength < 6)
|
||||
{
|
||||
suffixLength++;
|
||||
}
|
||||
}
|
||||
|
||||
var zerosLeft = 0;
|
||||
if (total < maxNum)
|
||||
{
|
||||
var tz = cat == 3 ? CavlcTables.TotalZerosChromaDcLookup[total - 1] : CavlcTables.TotalZerosLookup[total - 1];
|
||||
var e = tz[rd.Peek(16)];
|
||||
if (e == 0)
|
||||
{
|
||||
throw new H264Exception("total_zeros non valido.");
|
||||
}
|
||||
|
||||
rd.Skip(e >> 8);
|
||||
zerosLeft = e & 0xFF;
|
||||
}
|
||||
|
||||
if (total + zerosLeft > maxNum)
|
||||
{
|
||||
throw new H264Exception("total_zeros fuori dal blocco.");
|
||||
}
|
||||
|
||||
Span<int> run = stackalloc int[16];
|
||||
for (var i = 0; i < total - 1; i++)
|
||||
{
|
||||
if (zerosLeft > 0)
|
||||
{
|
||||
var rb = CavlcTables.RunBeforeLookup[Math.Min(zerosLeft, 7) - 1][rd.Peek(16)];
|
||||
if (rb == 0)
|
||||
{
|
||||
throw new H264Exception("run_before non valido.");
|
||||
}
|
||||
|
||||
rd.Skip(rb >> 8);
|
||||
run[i] = rb & 0xFF;
|
||||
if (run[i] > zerosLeft)
|
||||
{
|
||||
throw new H264Exception("run_before fuori dal blocco.");
|
||||
}
|
||||
|
||||
zerosLeft -= run[i];
|
||||
}
|
||||
else
|
||||
{
|
||||
run[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
run[total - 1] = zerosLeft;
|
||||
var coeffNum = -1;
|
||||
for (var i = total - 1; i >= 0; i--)
|
||||
{
|
||||
coeffNum += run[i] + 1;
|
||||
output[coeffNum] = levelVal[i];
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
/// <summary>nC of a luma 4×4 block (raster index) from the blocks to its left and above (§9.2.1).</summary>
|
||||
private int LumaNc(int raster)
|
||||
{
|
||||
int bx = raster & 3, by = raster >> 2;
|
||||
bool hasA = true, hasB = true;
|
||||
int nA = 0, nB = 0;
|
||||
if (bx > 0)
|
||||
{
|
||||
nA = nz[(mb * 24) + raster - 1];
|
||||
}
|
||||
else if (availA)
|
||||
{
|
||||
nA = nz[((mb - 1) * 24) + raster + 3];
|
||||
}
|
||||
else
|
||||
{
|
||||
hasA = false;
|
||||
}
|
||||
|
||||
if (by > 0)
|
||||
{
|
||||
nB = nz[(mb * 24) + raster - 4];
|
||||
}
|
||||
else if (availB)
|
||||
{
|
||||
nB = nz[((mb - widthInMbs) * 24) + raster + 12];
|
||||
}
|
||||
else
|
||||
{
|
||||
hasB = false;
|
||||
}
|
||||
|
||||
return hasA && hasB ? (nA + nB + 1) >> 1 : hasA ? nA : hasB ? nB : 0;
|
||||
}
|
||||
|
||||
private int ChromaNc(int b, int comp)
|
||||
{
|
||||
int bx = b & 1, by = b >> 1;
|
||||
var baseIndex = 16 + (comp * 4);
|
||||
bool hasA = true, hasB = true;
|
||||
int nA = 0, nB = 0;
|
||||
if (bx > 0)
|
||||
{
|
||||
nA = nz[(mb * 24) + baseIndex + b - 1];
|
||||
}
|
||||
else if (availA)
|
||||
{
|
||||
nA = nz[((mb - 1) * 24) + baseIndex + b + 1];
|
||||
}
|
||||
else
|
||||
{
|
||||
hasA = false;
|
||||
}
|
||||
|
||||
if (by > 0)
|
||||
{
|
||||
nB = nz[(mb * 24) + baseIndex + b - 2];
|
||||
}
|
||||
else if (availB)
|
||||
{
|
||||
nB = nz[((mb - widthInMbs) * 24) + baseIndex + b + 2];
|
||||
}
|
||||
else
|
||||
{
|
||||
hasB = false;
|
||||
}
|
||||
|
||||
return hasA && hasB ? (nA + nB + 1) >> 1 : hasA ? nA : hasB ? nB : 0;
|
||||
}
|
||||
|
||||
private int ReadCabacBlock(int cat, int blk, int comp, int[] output, int maxNum)
|
||||
{
|
||||
if (cat != 5)
|
||||
{
|
||||
var inc = CbfCond(cat, blk, comp, left: true) + (2 * CbfCond(cat, blk, comp, left: false)) + CbfCatOffset[cat];
|
||||
if (cabac.Decision(85 + inc) == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (cat == 0)
|
||||
{
|
||||
cbfDc[mb] |= 1;
|
||||
}
|
||||
else if (cat == 3)
|
||||
{
|
||||
cbfDc[mb] |= (byte)(2 << comp);
|
||||
}
|
||||
}
|
||||
|
||||
int sigBase, lastBase, absBase;
|
||||
if (cat == 5)
|
||||
{
|
||||
(sigBase, lastBase, absBase) = (402, 417, 426);
|
||||
}
|
||||
else
|
||||
{
|
||||
sigBase = 105 + SigCatOffset[cat];
|
||||
lastBase = 166 + SigCatOffset[cat];
|
||||
absBase = 227 + AbsCatOffset[cat];
|
||||
}
|
||||
|
||||
Span<bool> significant = stackalloc bool[64];
|
||||
significant.Clear();
|
||||
var last = -1;
|
||||
for (var i = 0; i < maxNum - 1; i++)
|
||||
{
|
||||
var ctx = cat == 5 ? H264Tables.SignificantContext8x8[i] : cat == 3 ? Math.Min(i, 2) : i;
|
||||
if (cabac.Decision(sigBase + ctx) == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
significant[i] = true;
|
||||
var lastCtx = cat == 5 ? H264Tables.LastContext8x8[i] : cat == 3 ? Math.Min(i, 2) : i;
|
||||
if (cabac.Decision(lastBase + lastCtx) != 0)
|
||||
{
|
||||
last = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (last < 0)
|
||||
{
|
||||
last = maxNum - 1;
|
||||
significant[last] = true;
|
||||
}
|
||||
|
||||
int gt1 = 0, eq1 = 0, count = 0;
|
||||
var maxGt1 = cat == 3 ? 3 : 4;
|
||||
for (var i = last; i >= 0; i--)
|
||||
{
|
||||
if (!significant[i])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int abs;
|
||||
if (cabac.Decision(absBase + (gt1 != 0 ? 0 : Math.Min(4, 1 + eq1))) == 0)
|
||||
{
|
||||
abs = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
var ctx = absBase + 5 + Math.Min(maxGt1, gt1);
|
||||
var v = 1;
|
||||
while (v < 14 && cabac.Decision(ctx) != 0)
|
||||
{
|
||||
v++;
|
||||
}
|
||||
|
||||
if (v == 14)
|
||||
{
|
||||
var k = 0;
|
||||
while (cabac.Bypass() != 0)
|
||||
{
|
||||
v += 1 << k;
|
||||
if (++k > 24)
|
||||
{
|
||||
throw new H264Exception("coeff_abs_level_minus1 non valido.");
|
||||
}
|
||||
}
|
||||
|
||||
while (k-- > 0)
|
||||
{
|
||||
v += cabac.Bypass() << k;
|
||||
}
|
||||
}
|
||||
|
||||
abs = v + 1;
|
||||
}
|
||||
|
||||
if (abs == 1)
|
||||
{
|
||||
eq1++;
|
||||
}
|
||||
else
|
||||
{
|
||||
gt1++;
|
||||
}
|
||||
|
||||
output[i] = cabac.Bypass() != 0 ? -abs : abs;
|
||||
count++;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
/// <summary>condTermFlagN of coded_block_flag (§9.3.3.1.1.9) for the block to the left or above.</summary>
|
||||
private int CbfCond(int cat, int blk, int comp, bool left)
|
||||
{
|
||||
var currentIntra = IsIntra(mb);
|
||||
int n;
|
||||
int index;
|
||||
switch (cat)
|
||||
{
|
||||
case 0:
|
||||
if (!(left ? availA : availB))
|
||||
{
|
||||
return currentIntra ? 1 : 0;
|
||||
}
|
||||
|
||||
n = left ? mb - 1 : mb - widthInMbs;
|
||||
if (mbKind[n] == MbKind.IPcm)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
return mbKind[n] == MbKind.I16x16 ? cbfDc[n] & 1 : 0;
|
||||
case 3:
|
||||
if (!(left ? availA : availB))
|
||||
{
|
||||
return currentIntra ? 1 : 0;
|
||||
}
|
||||
|
||||
n = left ? mb - 1 : mb - widthInMbs;
|
||||
if (mbKind[n] == MbKind.IPcm)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
return (cbfDc[n] >> (1 + comp)) & 1;
|
||||
case 4:
|
||||
{
|
||||
int bx = blk & 1, by = blk >> 1;
|
||||
if (left ? bx > 0 : by > 0)
|
||||
{
|
||||
n = mb;
|
||||
index = left ? blk - 1 : blk - 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!(left ? availA : availB))
|
||||
{
|
||||
return currentIntra ? 1 : 0;
|
||||
}
|
||||
|
||||
n = left ? mb - 1 : mb - widthInMbs;
|
||||
index = left ? blk + 1 : blk + 2;
|
||||
}
|
||||
|
||||
if (mbKind[n] == MbKind.IPcm)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
return nz[(n * 24) + 16 + (comp * 4) + index] != 0 ? 1 : 0;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
int bx = blk & 3, by = blk >> 2;
|
||||
if (left ? bx > 0 : by > 0)
|
||||
{
|
||||
n = mb;
|
||||
index = left ? blk - 1 : blk - 4;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!(left ? availA : availB))
|
||||
{
|
||||
return currentIntra ? 1 : 0;
|
||||
}
|
||||
|
||||
n = left ? mb - 1 : mb - widthInMbs;
|
||||
index = left ? blk + 3 : blk + 12;
|
||||
}
|
||||
|
||||
if (mbKind[n] == MbKind.IPcm)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
return nz[(n * 24) + index] != 0 ? 1 : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,537 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
public sealed partial class H264Decoder
|
||||
{
|
||||
private int weightMode;
|
||||
private int[] implicitW0 = [];
|
||||
|
||||
/// <summary>
|
||||
/// The neighbouring 4×4 luma block covering (<paramref name="xN"/>, <paramref name="yN"/>) relative to the current
|
||||
/// macroblock (§6.4.12): 0 not available, 1 in another macroblock, 2 in the current one (its availability then
|
||||
/// depends on the decoding order, <see cref="blkDone"/>).
|
||||
/// </summary>
|
||||
private int Neighbor(int xN, int yN, out int n, out int blk)
|
||||
{
|
||||
blk = (((yN & 15) >> 2) * 4) + ((xN & 15) >> 2);
|
||||
n = -1;
|
||||
if (yN < 0)
|
||||
{
|
||||
if (xN < 0)
|
||||
{
|
||||
if (!availD)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
n = mb - widthInMbs - 1;
|
||||
}
|
||||
else if (xN < 16)
|
||||
{
|
||||
if (!availB)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
n = mb - widthInMbs;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!availC)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
n = mb - widthInMbs + 1;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (yN >= 16)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (xN < 0)
|
||||
{
|
||||
if (!availA)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
n = mb - 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (xN >= 16)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
n = mb;
|
||||
return 2;
|
||||
}
|
||||
|
||||
private (bool Available, int RefIdx, int X, int Y) MotionNeighbor(int list, int xN, int yN)
|
||||
{
|
||||
var where = Neighbor(xN, yN, out var n, out var blk);
|
||||
if (where == 0 || (where == 2 && !blkDone[blk]))
|
||||
{
|
||||
return (false, -1, 0, 0);
|
||||
}
|
||||
|
||||
var picture = cur!;
|
||||
var refIdx = picture.RefIdx[(((list * mbCount) + n) * 4) + B8OfRaster(blk)];
|
||||
if (refIdx < 0 || picture.MbIntra[n])
|
||||
{
|
||||
return (true, -1, 0, 0);
|
||||
}
|
||||
|
||||
var i = ((((list * mbCount) + n) * 16) + blk) * 2;
|
||||
return (true, refIdx, picture.Mv[i], picture.Mv[i + 1]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Luma motion vector prediction (§8.4.1.3). <paramref name="directional"/>: 0 none, 1/2 the upper/lower 16×8
|
||||
/// partition, 3/4 the left/right 8×16 partition.
|
||||
/// </summary>
|
||||
private (int X, int Y) Mvp(int list, int refIdx, int px, int py, int w, int directional)
|
||||
{
|
||||
var a = MotionNeighbor(list, px - 1, py);
|
||||
var b = MotionNeighbor(list, px, py - 1);
|
||||
var c = MotionNeighbor(list, px + w, py - 1);
|
||||
if (!c.Available)
|
||||
{
|
||||
c = MotionNeighbor(list, px - 1, py - 1);
|
||||
}
|
||||
|
||||
switch (directional)
|
||||
{
|
||||
case 1 when b.RefIdx == refIdx:
|
||||
return (b.X, b.Y);
|
||||
case 2 when a.RefIdx == refIdx:
|
||||
return (a.X, a.Y);
|
||||
case 3 when a.RefIdx == refIdx:
|
||||
return (a.X, a.Y);
|
||||
case 4 when c.RefIdx == refIdx:
|
||||
return (c.X, c.Y);
|
||||
}
|
||||
|
||||
if (!b.Available && !c.Available && a.Available)
|
||||
{
|
||||
b = a;
|
||||
c = a;
|
||||
}
|
||||
|
||||
var matches = (a.RefIdx == refIdx ? 1 : 0) + (b.RefIdx == refIdx ? 1 : 0) + (c.RefIdx == refIdx ? 1 : 0);
|
||||
if (matches == 1)
|
||||
{
|
||||
return a.RefIdx == refIdx ? (a.X, a.Y) : b.RefIdx == refIdx ? (b.X, b.Y) : (c.X, c.Y);
|
||||
}
|
||||
|
||||
return (Median(a.X, b.X, c.X), Median(a.Y, b.Y, c.Y));
|
||||
}
|
||||
|
||||
private static int Median(int a, int b, int c) => Math.Max(Math.Min(a, b), Math.Min(Math.Max(a, b), c));
|
||||
|
||||
private void DeriveMv(int list, int px, int py, int w, int h, int directional)
|
||||
{
|
||||
var picture = cur!;
|
||||
var b8 = ((py >> 3) * 2) + (px >> 3);
|
||||
var refIdx = picture.RefIdx[(((list * mbCount) + mb) * 4) + b8];
|
||||
var (x, y) = Mvp(list, refIdx, px, py, w, directional);
|
||||
var blk = ((py >> 2) * 4) + (px >> 2);
|
||||
x += mvdValue[((list * 16) + blk) * 2];
|
||||
y += mvdValue[(((list * 16) + blk) * 2) + 1];
|
||||
FillMv(list, px, py, w, h, x, y);
|
||||
}
|
||||
|
||||
private void FillMv(int list, int px, int py, int w, int h, int x, int y)
|
||||
{
|
||||
var mv = cur!.Mv;
|
||||
for (var by = py; by < py + h; by += 4)
|
||||
{
|
||||
for (var bx = px; bx < px + w; bx += 4)
|
||||
{
|
||||
var i = ((((list * mbCount) + mb) * 16) + ((by >> 2) * 4) + (bx >> 2)) * 2;
|
||||
mv[i] = (short)x;
|
||||
mv[i + 1] = (short)y;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void PredictPSkip()
|
||||
{
|
||||
for (var b8 = 0; b8 < 4; b8++)
|
||||
{
|
||||
SetRefIdx(0, b8, 0);
|
||||
}
|
||||
|
||||
var a = MotionNeighbor(0, -1, 0);
|
||||
var b = MotionNeighbor(0, 0, -1);
|
||||
int x = 0, y = 0;
|
||||
if (a.Available && b.Available && !(a.RefIdx == 0 && a.X == 0 && a.Y == 0) && !(b.RefIdx == 0 && b.X == 0 && b.Y == 0))
|
||||
{
|
||||
(x, y) = Mvp(0, 0, 0, 0, 16, 0);
|
||||
}
|
||||
|
||||
FillMv(0, 0, 0, 16, 16, x, y);
|
||||
MarkDone(0, 0, 16, 16);
|
||||
}
|
||||
|
||||
private static int MinPositive(int a, int b) => a >= 0 && b >= 0 ? Math.Min(a, b) : Math.Max(a, b);
|
||||
|
||||
/// <summary>Direct prediction (§8.4.1.2) of the sub-macroblocks <paramref name="first"/> to <paramref name="end"/> − 1.</summary>
|
||||
private void PredictDirect(int first, int end)
|
||||
{
|
||||
var picture = cur!;
|
||||
var col = Reference(1, 0);
|
||||
var inference = sps.Direct8x8Inference;
|
||||
|
||||
int ref0 = -1, ref1 = -1;
|
||||
int mvp0x = 0, mvp0y = 0, mvp1x = 0, mvp1y = 0;
|
||||
var directZero = false;
|
||||
if (sh.DirectSpatialMvPred)
|
||||
{
|
||||
for (var list = 0; list < 2; list++)
|
||||
{
|
||||
var a = MotionNeighbor(list, -1, 0);
|
||||
var b = MotionNeighbor(list, 0, -1);
|
||||
var c = MotionNeighbor(list, 16, -1);
|
||||
if (!c.Available)
|
||||
{
|
||||
c = MotionNeighbor(list, -1, -1);
|
||||
}
|
||||
|
||||
var r = MinPositive(a.RefIdx, MinPositive(b.RefIdx, c.RefIdx));
|
||||
if (list == 0)
|
||||
{
|
||||
ref0 = r;
|
||||
}
|
||||
else
|
||||
{
|
||||
ref1 = r;
|
||||
}
|
||||
}
|
||||
|
||||
if (ref0 < 0 && ref1 < 0)
|
||||
{
|
||||
ref0 = ref1 = 0;
|
||||
directZero = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (ref0 >= 0)
|
||||
{
|
||||
(mvp0x, mvp0y) = Mvp(0, ref0, 0, 0, 16, 0);
|
||||
}
|
||||
|
||||
if (ref1 >= 0)
|
||||
{
|
||||
(mvp1x, mvp1y) = Mvp(1, ref1, 0, 0, 16, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var sub = first; sub < end; sub++)
|
||||
{
|
||||
for (var k = 0; k < 4; k++)
|
||||
{
|
||||
var blk = ((((sub >> 1) * 2) + (k >> 1)) * 4) + ((sub & 1) * 2) + (k & 1);
|
||||
var colBlk = inference ? sub switch { 0 => 0, 1 => 3, 2 => 12, _ => 15 } : blk;
|
||||
int colX = 0, colY = 0, colRef = -1;
|
||||
Picture? colRefPic = null;
|
||||
if (!col.MbIntra[mb])
|
||||
{
|
||||
var colB8 = B8OfRaster(colBlk);
|
||||
var list = col.RefIdx[(mb * 4) + colB8] >= 0 ? 0 : 1;
|
||||
colRef = col.RefIdx[(((list * mbCount) + mb) * 4) + colB8];
|
||||
colRefPic = col.RefPic[(((list * mbCount) + mb) * 4) + colB8];
|
||||
var i = ((((list * mbCount) + mb) * 16) + colBlk) * 2;
|
||||
colX = col.Mv[i];
|
||||
colY = col.Mv[i + 1];
|
||||
}
|
||||
|
||||
int r0, r1, m0x, m0y, m1x, m1y;
|
||||
if (sh.DirectSpatialMvPred)
|
||||
{
|
||||
var colZero = !col.LongTerm && colRef == 0 && colX is >= -1 and <= 1 && colY is >= -1 and <= 1;
|
||||
r0 = ref0;
|
||||
r1 = ref1;
|
||||
if (directZero || (r0 == 0 && colZero))
|
||||
{
|
||||
(m0x, m0y) = (0, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
(m0x, m0y) = (mvp0x, mvp0y);
|
||||
}
|
||||
|
||||
if (directZero || (r1 == 0 && colZero))
|
||||
{
|
||||
(m1x, m1y) = (0, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
(m1x, m1y) = (mvp1x, mvp1y);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
r0 = colRef < 0 ? 0 : MapColToList0(colRefPic);
|
||||
r1 = 0;
|
||||
var pic0 = Reference(0, r0);
|
||||
var td = Math.Clamp(col.Poc - pic0.Poc, -128, 127);
|
||||
if (pic0.LongTerm || td == 0)
|
||||
{
|
||||
(m0x, m0y) = (colX, colY);
|
||||
(m1x, m1y) = (0, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
var tb = Math.Clamp(picture.Poc - pic0.Poc, -128, 127);
|
||||
var tx = (16384 + Math.Abs(td / 2)) / td;
|
||||
var scale = Math.Clamp(((tb * tx) + 32) >> 6, -1024, 1023);
|
||||
m0x = ((scale * colX) + 128) >> 8;
|
||||
m0y = ((scale * colY) + 128) >> 8;
|
||||
m1x = m0x - colX;
|
||||
m1y = m0y - colY;
|
||||
}
|
||||
}
|
||||
|
||||
if (k == 0)
|
||||
{
|
||||
SetDirectRef(0, sub, r0);
|
||||
SetDirectRef(1, sub, r1);
|
||||
}
|
||||
|
||||
var mv = picture.Mv;
|
||||
var i0 = (((0 * mbCount) + mb) * 16) + blk;
|
||||
var i1 = (((1 * mbCount) + mb) * 16) + blk;
|
||||
mv[i0 * 2] = (short)(r0 >= 0 ? m0x : 0);
|
||||
mv[(i0 * 2) + 1] = (short)(r0 >= 0 ? m0y : 0);
|
||||
mv[i1 * 2] = (short)(r1 >= 0 ? m1x : 0);
|
||||
mv[(i1 * 2) + 1] = (short)(r1 >= 0 ? m1y : 0);
|
||||
blkDone[blk] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void SetDirectRef(int list, int b8, int refIdx)
|
||||
{
|
||||
var index = (((list * mbCount) + mb) * 4) + b8;
|
||||
var active = list == 0 ? sh.NumRefIdxActiveL0 : sh.NumRefIdxActiveL1;
|
||||
if (refIdx < 0 || refIdx >= active)
|
||||
{
|
||||
cur!.RefIdx[index] = -1;
|
||||
cur.RefPic[index] = null;
|
||||
return;
|
||||
}
|
||||
|
||||
cur!.RefIdx[index] = (sbyte)refIdx;
|
||||
cur.RefPic[index] = Reference(list, refIdx);
|
||||
}
|
||||
|
||||
private int MapColToList0(Picture? picture)
|
||||
{
|
||||
var list = refList[0];
|
||||
for (var i = 0; i < list.Length; i++)
|
||||
{
|
||||
if (ReferenceEquals(list[i], picture))
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>A reference picture of the slice; a substitute when the stream refers to a missing one.</summary>
|
||||
private Picture Reference(int list, int refIdx)
|
||||
{
|
||||
var l = refList[list];
|
||||
if ((uint)refIdx < (uint)l.Length && l[refIdx] is { } p)
|
||||
{
|
||||
return p;
|
||||
}
|
||||
|
||||
foreach (var q in l)
|
||||
{
|
||||
if (q is not null)
|
||||
{
|
||||
return q;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var q in dpb)
|
||||
{
|
||||
if (q.IsReference && !ReferenceEquals(q, cur))
|
||||
{
|
||||
return q;
|
||||
}
|
||||
}
|
||||
|
||||
return cur!;
|
||||
}
|
||||
|
||||
private void PrepareWeights()
|
||||
{
|
||||
weightMode = sh.Type == SliceType.P ? (pps.WeightedPred ? 1 : 0) : sh.IsB ? pps.WeightedBipredIdc : 0;
|
||||
if (weightMode != 2)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int n0 = sh.NumRefIdxActiveL0, n1 = sh.NumRefIdxActiveL1;
|
||||
if (implicitW0.Length < n0 * n1)
|
||||
{
|
||||
implicitW0 = new int[Math.Max(n0 * n1, 1)];
|
||||
}
|
||||
|
||||
var poc = cur!.Poc;
|
||||
for (var i = 0; i < n0; i++)
|
||||
{
|
||||
for (var j = 0; j < n1; j++)
|
||||
{
|
||||
var p0 = Reference(0, i);
|
||||
var p1 = Reference(1, j);
|
||||
var w0 = 32;
|
||||
var td = Math.Clamp(p1.Poc - p0.Poc, -128, 127);
|
||||
if (td != 0 && !p0.LongTerm && !p1.LongTerm)
|
||||
{
|
||||
var tb = Math.Clamp(poc - p0.Poc, -128, 127);
|
||||
var tx = (16384 + Math.Abs(td / 2)) / td;
|
||||
var scale = Math.Clamp(((tb * tx) + 32) >> 6, -1024, 1023);
|
||||
if ((scale >> 2) is >= -64 and <= 128)
|
||||
{
|
||||
w0 = 64 - (scale >> 2);
|
||||
}
|
||||
}
|
||||
|
||||
implicitW0[(i * n1) + j] = w0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void MotionCompensateDirect(int first, int end)
|
||||
{
|
||||
for (var sub = first; sub < end; sub++)
|
||||
{
|
||||
int ox = (sub & 1) * 8, oy = (sub >> 1) * 8;
|
||||
if (sps.Direct8x8Inference)
|
||||
{
|
||||
MotionCompensate(ox, oy, 8, 8);
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var k = 0; k < 4; k++)
|
||||
{
|
||||
MotionCompensate(ox + ((k & 1) * 4), oy + ((k >> 1) * 4), 4, 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Inter prediction of one partition with its motion (§8.4.2), written into the current picture.</summary>
|
||||
private void MotionCompensate(int px, int py, int w, int h)
|
||||
{
|
||||
var picture = cur!;
|
||||
var b8 = ((py >> 3) * 2) + (px >> 3);
|
||||
var blk = ((py >> 2) * 4) + (px >> 2);
|
||||
int r0 = picture.RefIdx[(mb * 4) + b8];
|
||||
int r1 = picture.RefIdx[((mbCount + mb) * 4) + b8];
|
||||
var i0 = ((mb * 16) + blk) * 2;
|
||||
var i1 = (((mbCount + mb) * 16) + blk) * 2;
|
||||
var x = (mbX * 16) + px;
|
||||
var y = (mbY * 16) + py;
|
||||
|
||||
Span<byte> a = stackalloc byte[256];
|
||||
Span<byte> b = stackalloc byte[256];
|
||||
var size = w * h;
|
||||
var pa = a[..size];
|
||||
var pb = b[..size];
|
||||
Picture? p0 = r0 >= 0 ? Reference(0, r0) : null;
|
||||
Picture? p1 = r1 >= 0 ? Reference(1, r1) : null;
|
||||
if (p0 is null && p1 is null)
|
||||
{
|
||||
p0 = Reference(0, 0);
|
||||
r0 = 0;
|
||||
}
|
||||
|
||||
int mv0x = picture.Mv[i0], mv0y = picture.Mv[i0 + 1], mv1x = picture.Mv[i1], mv1y = picture.Mv[i1 + 1];
|
||||
|
||||
// Luma.
|
||||
if (p0 is not null)
|
||||
{
|
||||
InterPrediction.Luma(p0, (x * 4) + mv0x, (y * 4) + mv0y, w, h, pa);
|
||||
}
|
||||
|
||||
if (p1 is not null)
|
||||
{
|
||||
InterPrediction.Luma(p1, (x * 4) + mv1x, (y * 4) + mv1y, w, h, p0 is null ? pa : pb);
|
||||
}
|
||||
|
||||
Combine(pa, pb, p0 is not null, p1 is not null, r0, r1, 0);
|
||||
var stride = picture.Width;
|
||||
for (var row = 0; row < h; row++)
|
||||
{
|
||||
pa.Slice(row * w, w).CopyTo(picture.Y.AsSpan(((y + row) * stride) + x, w));
|
||||
}
|
||||
|
||||
// Chroma.
|
||||
int cw = w / 2, ch = h / 2, cstride = stride / 2, cheight = picture.Height / 2;
|
||||
var csize = cw * ch;
|
||||
var ca = a[..csize];
|
||||
var cb = b[..csize];
|
||||
for (var comp = 1; comp <= 2; comp++)
|
||||
{
|
||||
if (p0 is not null)
|
||||
{
|
||||
InterPrediction.Chroma(comp == 1 ? p0.Cb : p0.Cr, cstride, cheight, (x * 4) + mv0x, (y * 4) + mv0y, cw, ch, ca);
|
||||
}
|
||||
|
||||
if (p1 is not null)
|
||||
{
|
||||
InterPrediction.Chroma(comp == 1 ? p1.Cb : p1.Cr, cstride, cheight, (x * 4) + mv1x, (y * 4) + mv1y, cw, ch, p0 is null ? ca : cb);
|
||||
}
|
||||
|
||||
Combine(ca, cb, p0 is not null, p1 is not null, r0, r1, comp);
|
||||
var plane = comp == 1 ? picture.Cb : picture.Cr;
|
||||
for (var row = 0; row < ch; row++)
|
||||
{
|
||||
ca.Slice(row * cw, cw).CopyTo(plane.AsSpan((((y / 2) + row) * cstride) + (x / 2), cw));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Combine(Span<byte> a, ReadOnlySpan<byte> b, bool use0, bool use1, int r0, int r1, int comp)
|
||||
{
|
||||
if (use0 && use1)
|
||||
{
|
||||
if (weightMode == 1 && sh.Weights is { } weights && sh.Offsets is { } offsets)
|
||||
{
|
||||
var logWd = comp == 0 ? sh.LumaLog2WeightDenom : sh.ChromaLog2WeightDenom;
|
||||
InterPrediction.WeightTwo(a, b, logWd, weights[0][(r0 * 3) + comp], weights[1][(r1 * 3) + comp], offsets[0][(r0 * 3) + comp], offsets[1][(r1 * 3) + comp]);
|
||||
}
|
||||
else if (weightMode == 2)
|
||||
{
|
||||
var w0 = implicitW0[(r0 * sh.NumRefIdxActiveL1) + r1];
|
||||
InterPrediction.WeightTwo(a, b, 5, w0, 64 - w0, 0, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
InterPrediction.Average(a, b);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (weightMode == 1 && sh.Weights is { } w && sh.Offsets is { } o)
|
||||
{
|
||||
var list = use0 ? 0 : 1;
|
||||
var r = use0 ? r0 : r1;
|
||||
var logWd = comp == 0 ? sh.LumaLog2WeightDenom : sh.ChromaLog2WeightDenom;
|
||||
InterPrediction.WeightOne(a, logWd, w[list][(r * 3) + comp], o[list][(r * 3) + comp]);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,782 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>
|
||||
/// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Main and High profiles for
|
||||
/// progressive frames in 4:2:0 with 8-bit samples — CAVLC and CABAC, I, P and B slices, 8×8 transform and scaling
|
||||
/// matrices, explicit and implicit weighted prediction, spatial and temporal direct prediction, multiple reference frames
|
||||
/// with list modification and memory management, deblocking. Not handled (an <see cref="H264Exception"/>): interlaced
|
||||
/// pictures (fields and MBAFF), slice groups, SP/SI slices, data partitioning, 4:2:2/4:4:4 and depths above 8 bits.
|
||||
/// </summary>
|
||||
public sealed partial class H264Decoder
|
||||
{
|
||||
private readonly Dictionary<int, Sps> sequences = [];
|
||||
private readonly Dictionary<int, Pps> pictures = [];
|
||||
private readonly List<Picture> dpb = [];
|
||||
private readonly Stack<Picture> pool = new();
|
||||
|
||||
private Sps? activeSps;
|
||||
private Picture? cur;
|
||||
private SliceHeader? picHeader;
|
||||
private int picNalType;
|
||||
private int picRefIdc;
|
||||
private bool picMmco5;
|
||||
private int sliceCounter;
|
||||
|
||||
private int prevPocMsb;
|
||||
private int prevPocLsb;
|
||||
private int prevFrameNumOffset;
|
||||
private int prevFrameNum;
|
||||
private int prevRefFrameNum;
|
||||
private bool haveReference;
|
||||
private int frameNumOffset;
|
||||
private int pocMsb;
|
||||
private int maxLongTermFrameIdx = -1;
|
||||
private int period;
|
||||
private long decodeCounter;
|
||||
|
||||
/// <summary>Which frames to hand out, by decoding index; null hands out all of them.</summary>
|
||||
public Func<long, bool>? Wanted { get; set; }
|
||||
|
||||
/// <summary>Raised for each decoded frame that <see cref="Wanted"/> accepts, in decoding order.</summary>
|
||||
public event Action<H264Frame>? FrameDecoded;
|
||||
|
||||
/// <summary>Frames decoded so far (including those not handed out).</summary>
|
||||
public long FramesDecoded => decodeCounter;
|
||||
|
||||
/// <summary>Decodes a whole Annex B byte stream (start codes), then flushes the last picture.</summary>
|
||||
public void DecodeAnnexB(ReadOnlySpan<byte> stream)
|
||||
{
|
||||
foreach (var nal in NalUnits.SplitAnnexB(stream))
|
||||
{
|
||||
Decode(nal);
|
||||
}
|
||||
|
||||
Flush();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the SPS and PPS of an <c>avcC</c> box (AVCDecoderConfigurationRecord); returns the size of the NAL length
|
||||
/// fields of the samples.
|
||||
/// </summary>
|
||||
public int ConfigureAvcC(ReadOnlySpan<byte> avcC)
|
||||
{
|
||||
if (avcC.Length < 7 || avcC[0] != 1)
|
||||
{
|
||||
throw new H264Exception("Configurazione avcC non valida.");
|
||||
}
|
||||
|
||||
var lengthSize = (avcC[4] & 3) + 1;
|
||||
var offset = 5;
|
||||
for (var pass = 0; pass < 2; pass++)
|
||||
{
|
||||
if (offset >= avcC.Length)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var count = pass == 0 ? avcC[offset] & 0x1F : avcC[offset];
|
||||
offset++;
|
||||
for (var i = 0; i < count && offset + 2 <= avcC.Length; i++)
|
||||
{
|
||||
var size = (avcC[offset] << 8) | avcC[offset + 1];
|
||||
offset += 2;
|
||||
if (size == 0 || offset + size > avcC.Length)
|
||||
{
|
||||
throw new H264Exception("Configurazione avcC troncata.");
|
||||
}
|
||||
|
||||
Decode(NalUnits.Parse(avcC.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)
|
||||
{
|
||||
foreach (var nal in NalUnits.SplitLengthPrefixed(sample, lengthSize))
|
||||
{
|
||||
Decode(nal);
|
||||
}
|
||||
|
||||
FinishPicture();
|
||||
}
|
||||
|
||||
/// <summary>Decodes one access unit in Annex B form and finishes its picture.</summary>
|
||||
public void DecodeAccessUnitAnnexB(ReadOnlySpan<byte> accessUnit)
|
||||
{
|
||||
foreach (var nal in NalUnits.SplitAnnexB(accessUnit))
|
||||
{
|
||||
Decode(nal);
|
||||
}
|
||||
|
||||
FinishPicture();
|
||||
}
|
||||
|
||||
/// <summary>Finishes the picture being decoded, if any.</summary>
|
||||
public void Flush() => FinishPicture();
|
||||
|
||||
private void Decode(NalUnit nal)
|
||||
{
|
||||
try
|
||||
{
|
||||
switch (nal.Type)
|
||||
{
|
||||
case 1:
|
||||
case 5:
|
||||
DecodeSlice(nal);
|
||||
break;
|
||||
case 2:
|
||||
case 3:
|
||||
case 4:
|
||||
throw new H264Exception("Il partizionamento dei dati non è gestito.");
|
||||
case 7:
|
||||
{
|
||||
var sps = Sps.Parse(nal.Reader());
|
||||
sequences[sps.Id] = sps;
|
||||
break;
|
||||
}
|
||||
|
||||
case 8:
|
||||
{
|
||||
var pps = Pps.Parse(nal.Reader(), sequences);
|
||||
pictures[pps.Id] = pps;
|
||||
break;
|
||||
}
|
||||
|
||||
case 11: // end of stream
|
||||
FinishPicture();
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (IndexOutOfRangeException)
|
||||
{
|
||||
throw new H264Exception("Flusso H.264 troncato o danneggiato.");
|
||||
}
|
||||
catch (ArgumentOutOfRangeException)
|
||||
{
|
||||
throw new H264Exception("Flusso H.264 troncato o danneggiato.");
|
||||
}
|
||||
}
|
||||
|
||||
private void DecodeSlice(NalUnit nal)
|
||||
{
|
||||
var reader = nal.Reader();
|
||||
var header = SliceHeader.Parse(reader, nal, sequences, pictures, out var sps, out var pps);
|
||||
if (sps.ChromaFormatIdc != 1 || sps.BitDepthLuma != 8 || sps.BitDepthChroma != 8)
|
||||
{
|
||||
throw new H264Exception("Solo video 4:2:0 a 8 bit.");
|
||||
}
|
||||
|
||||
if (!sps.FrameMbsOnly)
|
||||
{
|
||||
throw new H264Exception("I video interlacciati non sono gestiti.");
|
||||
}
|
||||
|
||||
if (sps.TransformBypass)
|
||||
{
|
||||
throw new H264Exception("La codifica senza perdita non è gestita.");
|
||||
}
|
||||
|
||||
if (header.FirstMb == 0 || cur is null)
|
||||
{
|
||||
FinishPicture();
|
||||
StartPicture(nal, header, sps);
|
||||
}
|
||||
|
||||
DecodeSliceData(reader, nal, header, sps, pps);
|
||||
}
|
||||
|
||||
private void StartPicture(NalUnit nal, SliceHeader header, Sps sps)
|
||||
{
|
||||
if (activeSps is null || !ReferenceEquals(activeSps, sps))
|
||||
{
|
||||
if (activeSps is null || activeSps.WidthInMbs != sps.WidthInMbs || activeSps.HeightInMbs != sps.HeightInMbs)
|
||||
{
|
||||
dpb.Clear();
|
||||
pool.Clear();
|
||||
AllocateMacroblockState(sps.WidthInMbs, sps.HeightInMbs);
|
||||
}
|
||||
|
||||
activeSps = sps;
|
||||
}
|
||||
|
||||
var idr = nal.Type == 5;
|
||||
if (idr)
|
||||
{
|
||||
period++;
|
||||
}
|
||||
else if (haveReference && header.FrameNum != prevRefFrameNum && header.FrameNum != (prevRefFrameNum + 1) % sps.MaxFrameNum)
|
||||
{
|
||||
FillFrameNumGap(header.FrameNum, sps);
|
||||
}
|
||||
|
||||
cur = NewPicture(sps);
|
||||
cur.FrameNum = header.FrameNum;
|
||||
cur.Period = period;
|
||||
cur.DecodeIndex = decodeCounter;
|
||||
picHeader = header;
|
||||
picNalType = nal.Type;
|
||||
picRefIdc = nal.RefIdc;
|
||||
picMmco5 = header.Mmco.Exists(m => m.Op == 5);
|
||||
cur.Poc = ComputePoc(header, nal, sps, idr);
|
||||
sliceCounter = 0;
|
||||
sliceFilters.Clear();
|
||||
Array.Fill(mbSlice, -1);
|
||||
}
|
||||
|
||||
private Picture NewPicture(Sps sps)
|
||||
{
|
||||
while (pool.Count > 0)
|
||||
{
|
||||
var p = pool.Pop();
|
||||
if (p.Fits(sps.WidthInMbs, sps.HeightInMbs))
|
||||
{
|
||||
p.ShortTerm = p.LongTerm = p.NonExisting = false;
|
||||
Array.Clear(p.RefPic);
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
return new Picture(sps.WidthInMbs, sps.HeightInMbs);
|
||||
}
|
||||
|
||||
/// <summary>Picture order count (§8.2.1) of the picture starting now.</summary>
|
||||
private int ComputePoc(SliceHeader h, NalUnit nal, Sps sps, bool idr)
|
||||
{
|
||||
int top, bottom;
|
||||
switch (sps.PocType)
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
if (idr)
|
||||
{
|
||||
prevPocMsb = 0;
|
||||
prevPocLsb = 0;
|
||||
}
|
||||
|
||||
var max = 1 << sps.Log2MaxPocLsb;
|
||||
if (h.PocLsb < prevPocLsb && prevPocLsb - h.PocLsb >= max / 2)
|
||||
{
|
||||
pocMsb = prevPocMsb + max;
|
||||
}
|
||||
else if (h.PocLsb > prevPocLsb && h.PocLsb - prevPocLsb > max / 2)
|
||||
{
|
||||
pocMsb = prevPocMsb - max;
|
||||
}
|
||||
else
|
||||
{
|
||||
pocMsb = prevPocMsb;
|
||||
}
|
||||
|
||||
top = pocMsb + h.PocLsb;
|
||||
bottom = top + h.DeltaPocBottom;
|
||||
break;
|
||||
}
|
||||
|
||||
case 1:
|
||||
{
|
||||
UpdateFrameNumOffset(h, sps, idr);
|
||||
var cycle = sps.OffsetForRefFrame.Length;
|
||||
var absFrameNum = cycle != 0 ? frameNumOffset + h.FrameNum : 0;
|
||||
if (nal.RefIdc == 0 && absFrameNum > 0)
|
||||
{
|
||||
absFrameNum--;
|
||||
}
|
||||
|
||||
var expected = 0;
|
||||
if (absFrameNum > 0)
|
||||
{
|
||||
var delta = 0;
|
||||
foreach (var o in sps.OffsetForRefFrame)
|
||||
{
|
||||
delta += o;
|
||||
}
|
||||
|
||||
var cycleCount = (absFrameNum - 1) / cycle;
|
||||
var inCycle = (absFrameNum - 1) % cycle;
|
||||
expected = cycleCount * delta;
|
||||
for (var i = 0; i <= inCycle; i++)
|
||||
{
|
||||
expected += sps.OffsetForRefFrame[i];
|
||||
}
|
||||
}
|
||||
|
||||
if (nal.RefIdc == 0)
|
||||
{
|
||||
expected += sps.OffsetForNonRefPic;
|
||||
}
|
||||
|
||||
top = expected + h.DeltaPoc0;
|
||||
bottom = top + sps.OffsetForTopToBottomField + h.DeltaPoc1;
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
UpdateFrameNumOffset(h, sps, idr);
|
||||
top = bottom = idr ? 0 : nal.RefIdc == 0 ? (2 * (frameNumOffset + h.FrameNum)) - 1 : 2 * (frameNumOffset + h.FrameNum);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return Math.Min(top, bottom);
|
||||
}
|
||||
|
||||
private void UpdateFrameNumOffset(SliceHeader h, Sps sps, bool idr)
|
||||
{
|
||||
if (idr)
|
||||
{
|
||||
frameNumOffset = 0;
|
||||
}
|
||||
else if (prevFrameNum > h.FrameNum)
|
||||
{
|
||||
frameNumOffset = prevFrameNumOffset + sps.MaxFrameNum;
|
||||
}
|
||||
else
|
||||
{
|
||||
frameNumOffset = prevFrameNumOffset;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Frames inferred for a gap in frame_num (§8.2.5.2): only their marking matters.</summary>
|
||||
private void FillFrameNumGap(int frameNum, Sps sps)
|
||||
{
|
||||
var max = sps.MaxFrameNum;
|
||||
var missing = ((frameNum - prevRefFrameNum - 1) % max + max) % max;
|
||||
var keep = Math.Max(1, sps.MaxNumRefFrames);
|
||||
var first = missing > keep ? (frameNum - keep + max) % max : (prevRefFrameNum + 1) % max;
|
||||
if (missing > keep)
|
||||
{
|
||||
foreach (var p in dpb)
|
||||
{
|
||||
p.ShortTerm = false;
|
||||
}
|
||||
}
|
||||
|
||||
for (var n = first; n != frameNum; n = (n + 1) % max)
|
||||
{
|
||||
var gap = NewPicture(sps);
|
||||
gap.FrameNum = n;
|
||||
gap.NonExisting = true;
|
||||
gap.Period = period;
|
||||
gap.Poc = 0;
|
||||
Array.Fill(gap.MbIntra, true);
|
||||
SlidingWindow(sps, n);
|
||||
gap.ShortTerm = true;
|
||||
dpb.Add(gap);
|
||||
prevRefFrameNum = n;
|
||||
prevFrameNum = n;
|
||||
if (sps.PocType != 0)
|
||||
{
|
||||
prevFrameNumOffset = frameNumOffset;
|
||||
}
|
||||
}
|
||||
|
||||
PruneDpb();
|
||||
}
|
||||
|
||||
private void FinishPicture()
|
||||
{
|
||||
if (cur is null || picHeader is null || activeSps is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var sps = activeSps;
|
||||
var picture = cur;
|
||||
Deblock(picture);
|
||||
|
||||
if (picRefIdc != 0)
|
||||
{
|
||||
MarkReferences(picture, sps);
|
||||
}
|
||||
|
||||
// State for the next picture.
|
||||
if (picMmco5)
|
||||
{
|
||||
var temp = picture.Poc;
|
||||
prevPocMsb = 0;
|
||||
prevPocLsb = 0;
|
||||
picture.Poc -= temp;
|
||||
prevFrameNum = 0;
|
||||
prevFrameNumOffset = 0;
|
||||
picture.FrameNum = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (picRefIdc != 0)
|
||||
{
|
||||
prevPocMsb = pocMsb;
|
||||
prevPocLsb = picHeader.PocLsb;
|
||||
}
|
||||
|
||||
prevFrameNum = picture.FrameNum;
|
||||
prevFrameNumOffset = frameNumOffset;
|
||||
}
|
||||
|
||||
if (picRefIdc != 0)
|
||||
{
|
||||
prevRefFrameNum = picture.FrameNum;
|
||||
haveReference = true;
|
||||
}
|
||||
|
||||
if (Wanted?.Invoke(picture.DecodeIndex) ?? true)
|
||||
{
|
||||
FrameDecoded?.Invoke(Crop(picture, sps));
|
||||
}
|
||||
|
||||
decodeCounter++;
|
||||
if (!picture.IsReference)
|
||||
{
|
||||
pool.Push(picture);
|
||||
}
|
||||
|
||||
cur = null;
|
||||
picHeader = null;
|
||||
PruneDpb();
|
||||
}
|
||||
|
||||
private static H264Frame Crop(Picture p, Sps sps)
|
||||
{
|
||||
var left = sps.CropLeft * 2;
|
||||
var top = sps.CropTop * 2;
|
||||
var width = Math.Max(2, p.Width - left - (sps.CropRight * 2));
|
||||
var height = Math.Max(2, p.Height - top - (sps.CropBottom * 2));
|
||||
var y = new byte[width * height];
|
||||
for (var r = 0; r < height; r++)
|
||||
{
|
||||
Array.Copy(p.Y, ((top + r) * p.Width) + left, y, r * width, width);
|
||||
}
|
||||
|
||||
int cw = (width + 1) / 2, ch = (height + 1) / 2, pcw = p.Width / 2;
|
||||
var cb = new byte[cw * ch];
|
||||
var cr = new byte[cw * ch];
|
||||
for (var r = 0; r < ch; r++)
|
||||
{
|
||||
Array.Copy(p.Cb, (((top / 2) + r) * pcw) + (left / 2), cb, r * cw, cw);
|
||||
Array.Copy(p.Cr, (((top / 2) + r) * pcw) + (left / 2), cr, r * cw, cw);
|
||||
}
|
||||
|
||||
return new H264Frame(width, height, y, cb, cr, p.Poc, p.Period, p.DecodeIndex, sps.MatrixCoefficients, sps.FullRange);
|
||||
}
|
||||
|
||||
/// <summary>Decoded reference picture marking (§8.2.5) of the picture just decoded.</summary>
|
||||
private void MarkReferences(Picture picture, Sps sps)
|
||||
{
|
||||
var h = picHeader!;
|
||||
if (picNalType == 5)
|
||||
{
|
||||
foreach (var p in dpb)
|
||||
{
|
||||
p.ShortTerm = p.LongTerm = false;
|
||||
}
|
||||
|
||||
if (h.LongTermReference)
|
||||
{
|
||||
picture.LongTerm = true;
|
||||
picture.LongTermFrameIdx = 0;
|
||||
maxLongTermFrameIdx = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
picture.ShortTerm = true;
|
||||
maxLongTermFrameIdx = -1;
|
||||
}
|
||||
|
||||
dpb.Add(picture);
|
||||
return;
|
||||
}
|
||||
|
||||
var becameLongTerm = false;
|
||||
if (h.AdaptiveMarking)
|
||||
{
|
||||
var currPicNum = picture.FrameNum;
|
||||
UpdateFrameNumWrap(picture.FrameNum, sps);
|
||||
foreach (var (op, a, b) in h.Mmco)
|
||||
{
|
||||
switch (op)
|
||||
{
|
||||
case 1:
|
||||
{
|
||||
var picNumX = currPicNum - (a + 1);
|
||||
foreach (var p in dpb)
|
||||
{
|
||||
if (p.ShortTerm && p.PicNum == picNumX)
|
||||
{
|
||||
p.ShortTerm = false;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case 2:
|
||||
foreach (var p in dpb)
|
||||
{
|
||||
if (p.LongTerm && p.LongTermPicNum == a)
|
||||
{
|
||||
p.LongTerm = false;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case 3:
|
||||
{
|
||||
var picNumX = currPicNum - (a + 1);
|
||||
foreach (var p in dpb)
|
||||
{
|
||||
if (p.LongTerm && p.LongTermFrameIdx == b)
|
||||
{
|
||||
p.LongTerm = false;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var p in dpb)
|
||||
{
|
||||
if (p.ShortTerm && p.PicNum == picNumX)
|
||||
{
|
||||
p.ShortTerm = false;
|
||||
p.LongTerm = true;
|
||||
p.LongTermFrameIdx = b;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case 4:
|
||||
maxLongTermFrameIdx = a - 1;
|
||||
foreach (var p in dpb)
|
||||
{
|
||||
if (p.LongTerm && p.LongTermFrameIdx > maxLongTermFrameIdx)
|
||||
{
|
||||
p.LongTerm = false;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case 5:
|
||||
foreach (var p in dpb)
|
||||
{
|
||||
p.ShortTerm = p.LongTerm = false;
|
||||
}
|
||||
|
||||
maxLongTermFrameIdx = -1;
|
||||
break;
|
||||
case 6:
|
||||
foreach (var p in dpb)
|
||||
{
|
||||
if (p.LongTerm && p.LongTermFrameIdx == b)
|
||||
{
|
||||
p.LongTerm = false;
|
||||
}
|
||||
}
|
||||
|
||||
picture.LongTerm = true;
|
||||
picture.LongTermFrameIdx = b;
|
||||
becameLongTerm = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (picMmco5)
|
||||
{
|
||||
period++;
|
||||
picture.Period = period;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
SlidingWindow(sps, picture.FrameNum);
|
||||
}
|
||||
|
||||
if (!becameLongTerm)
|
||||
{
|
||||
picture.ShortTerm = true;
|
||||
}
|
||||
|
||||
dpb.Add(picture);
|
||||
}
|
||||
|
||||
/// <summary>Sliding window marking (§8.2.5.3) before a new short-term frame is added.</summary>
|
||||
private void SlidingWindow(Sps sps, int frameNum)
|
||||
{
|
||||
UpdateFrameNumWrap(frameNum, sps);
|
||||
var limit = Math.Max(1, sps.MaxNumRefFrames);
|
||||
while (true)
|
||||
{
|
||||
int shortCount = 0, longCount = 0;
|
||||
Picture? oldest = null;
|
||||
foreach (var p in dpb)
|
||||
{
|
||||
if (p.ShortTerm)
|
||||
{
|
||||
shortCount++;
|
||||
if (oldest is null || p.FrameNumWrap < oldest.FrameNumWrap)
|
||||
{
|
||||
oldest = p;
|
||||
}
|
||||
}
|
||||
else if (p.LongTerm)
|
||||
{
|
||||
longCount++;
|
||||
}
|
||||
}
|
||||
|
||||
if (shortCount + longCount < limit || oldest is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
oldest.ShortTerm = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateFrameNumWrap(int frameNum, Sps sps)
|
||||
{
|
||||
foreach (var p in dpb)
|
||||
{
|
||||
if (p.ShortTerm)
|
||||
{
|
||||
p.FrameNumWrap = p.FrameNum > frameNum ? p.FrameNum - sps.MaxFrameNum : p.FrameNum;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Drops the pictures no longer used for reference from the buffer (they are already handed out).</summary>
|
||||
private void PruneDpb()
|
||||
{
|
||||
for (var i = dpb.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var p = dpb[i];
|
||||
if (!p.IsReference && !ReferenceEquals(p, cur))
|
||||
{
|
||||
dpb.RemoveAt(i);
|
||||
pool.Push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reference picture lists of the slice (§8.2.4): initialisation, then modification.</summary>
|
||||
private void BuildReferenceLists(SliceHeader h, Sps sps)
|
||||
{
|
||||
var picture = cur!;
|
||||
UpdateFrameNumWrap(h.FrameNum, sps);
|
||||
var shortTerm = new List<Picture>();
|
||||
var longTerm = new List<Picture>();
|
||||
foreach (var p in dpb)
|
||||
{
|
||||
if (ReferenceEquals(p, picture))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (p.ShortTerm)
|
||||
{
|
||||
shortTerm.Add(p);
|
||||
}
|
||||
else if (p.LongTerm)
|
||||
{
|
||||
longTerm.Add(p);
|
||||
}
|
||||
}
|
||||
|
||||
longTerm.Sort((a, b) => a.LongTermPicNum.CompareTo(b.LongTermPicNum));
|
||||
List<Picture> init0, init1 = [];
|
||||
if (h.Type == SliceType.P)
|
||||
{
|
||||
shortTerm.Sort((a, b) => b.PicNum.CompareTo(a.PicNum));
|
||||
init0 = [.. shortTerm, .. longTerm];
|
||||
}
|
||||
else
|
||||
{
|
||||
var before = shortTerm.FindAll(p => p.Poc < picture.Poc);
|
||||
var after = shortTerm.FindAll(p => p.Poc > picture.Poc);
|
||||
before.Sort((a, b) => b.Poc.CompareTo(a.Poc));
|
||||
after.Sort((a, b) => a.Poc.CompareTo(b.Poc));
|
||||
init0 = [.. before, .. after, .. longTerm];
|
||||
init1 = [.. after, .. before, .. longTerm];
|
||||
if (init1.Count > 1 && init0.Count == init1.Count)
|
||||
{
|
||||
var same = true;
|
||||
for (var i = 0; i < init0.Count && same; i++)
|
||||
{
|
||||
same = ReferenceEquals(init0[i], init1[i]);
|
||||
}
|
||||
|
||||
if (same)
|
||||
{
|
||||
(init1[0], init1[1]) = (init1[1], init1[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
refList[0] = Modify(init0, h.NumRefIdxActiveL0, h.Modifications[0], h, sps);
|
||||
refList[1] = h.IsB ? Modify(init1, h.NumRefIdxActiveL1, h.Modifications[1], h, sps) : [];
|
||||
}
|
||||
|
||||
private Picture?[] Modify(List<Picture> initial, int count, List<(int Idc, int Value)> modifications, SliceHeader h, Sps sps)
|
||||
{
|
||||
var list = new Picture?[count + 1];
|
||||
for (var i = 0; i < count && i < initial.Count; i++)
|
||||
{
|
||||
list[i] = initial[i];
|
||||
}
|
||||
|
||||
var maxPicNum = sps.MaxFrameNum;
|
||||
var currPicNum = h.FrameNum;
|
||||
var pred = currPicNum;
|
||||
var refIdx = 0;
|
||||
foreach (var (idc, value) in modifications)
|
||||
{
|
||||
if (refIdx >= count)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
Picture? found = null;
|
||||
if (idc is 0 or 1)
|
||||
{
|
||||
var abs = value + 1;
|
||||
int noWrap;
|
||||
if (idc == 0)
|
||||
{
|
||||
noWrap = pred - abs < 0 ? pred - abs + maxPicNum : pred - abs;
|
||||
}
|
||||
else
|
||||
{
|
||||
noWrap = pred + abs >= maxPicNum ? pred + abs - maxPicNum : pred + abs;
|
||||
}
|
||||
|
||||
pred = noWrap;
|
||||
var picNum = noWrap > currPicNum ? noWrap - maxPicNum : noWrap;
|
||||
found = dpb.Find(p => p.ShortTerm && p.PicNum == picNum && !ReferenceEquals(p, cur));
|
||||
}
|
||||
else
|
||||
{
|
||||
found = dpb.Find(p => p.LongTerm && p.LongTermPicNum == value && !ReferenceEquals(p, cur));
|
||||
}
|
||||
|
||||
for (var c = count; c > refIdx; c--)
|
||||
{
|
||||
list[c] = list[c - 1];
|
||||
}
|
||||
|
||||
list[refIdx++] = found;
|
||||
var n = refIdx;
|
||||
for (var c = refIdx; c <= count; c++)
|
||||
{
|
||||
if (!ReferenceEquals(list[c], found) || found is null)
|
||||
{
|
||||
list[n++] = list[c];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Array.Resize(ref list, count);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>Fixed tables of ITU-T H.264 other than the variable-length codes and the CABAC contexts.</summary>
|
||||
internal static class H264Tables
|
||||
{
|
||||
/// <summary>Zig-zag scan of 4×4 frame blocks: scan index → raster position (row * 4 + column).</summary>
|
||||
internal static readonly byte[] ZigZag4x4 = BuildZigZag(4);
|
||||
|
||||
/// <summary>Zig-zag scan of 8×8 frame blocks: scan index → raster position (row * 8 + column).</summary>
|
||||
internal static readonly byte[] ZigZag8x8 = BuildZigZag(8);
|
||||
|
||||
/// <summary>luma4x4BlkIdx → raster index of the 4×4 block in the macroblock ((y / 4) * 4 + x / 4).</summary>
|
||||
internal static readonly byte[] BlockToRaster = [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15];
|
||||
|
||||
/// <summary>Raster index of a 4×4 block → luma4x4BlkIdx.</summary>
|
||||
internal static readonly byte[] RasterToBlock = [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15];
|
||||
|
||||
/// <summary>coded_block_pattern of Intra_4x4 and Intra_8x8 macroblocks from codeNum (table 9-4, 4:2:0 and 4:2:2).</summary>
|
||||
internal static readonly byte[] CbpIntra =
|
||||
[
|
||||
47, 31, 15, 0, 23, 27, 29, 30, 7, 11, 13, 14, 39, 43, 45, 46, 16, 3, 5, 10, 12, 19, 21, 26, 28, 35, 37, 42, 44, 1, 2, 4,
|
||||
8, 17, 18, 20, 24, 6, 9, 22, 25, 32, 33, 34, 36, 40, 38, 41,
|
||||
];
|
||||
|
||||
/// <summary>coded_block_pattern of inter macroblocks from codeNum (table 9-4).</summary>
|
||||
internal static readonly byte[] CbpInter =
|
||||
[
|
||||
0, 16, 1, 2, 4, 8, 32, 3, 5, 10, 12, 15, 47, 7, 11, 13, 14, 6, 9, 31, 35, 37, 42, 44, 33, 34, 36, 40, 39, 43, 45, 46,
|
||||
17, 18, 20, 24, 19, 21, 26, 28, 23, 27, 29, 30, 22, 25, 38, 41,
|
||||
];
|
||||
|
||||
/// <summary>normAdjust4x4 values v[m][0..2] (equation 8-315).</summary>
|
||||
internal static readonly byte[,] NormAdjust4x4 =
|
||||
{
|
||||
{ 10, 16, 13 }, { 11, 18, 14 }, { 13, 20, 16 }, { 14, 23, 18 }, { 16, 25, 20 }, { 18, 29, 23 },
|
||||
};
|
||||
|
||||
/// <summary>normAdjust8x8 values v[m][0..5] (equation 8-318).</summary>
|
||||
internal static readonly byte[,] NormAdjust8x8 =
|
||||
{
|
||||
{ 20, 18, 32, 19, 25, 24 }, { 22, 19, 35, 21, 28, 26 }, { 26, 23, 42, 24, 33, 31 },
|
||||
{ 28, 25, 45, 26, 35, 33 }, { 32, 28, 51, 30, 40, 38 }, { 36, 32, 58, 34, 46, 43 },
|
||||
};
|
||||
|
||||
/// <summary>Default_4x4_Intra in zig-zag order (table 7-3).</summary>
|
||||
internal static readonly byte[] Default4x4Intra = [6, 13, 13, 20, 20, 20, 28, 28, 28, 28, 32, 32, 32, 37, 37, 42];
|
||||
|
||||
/// <summary>Default_4x4_Inter in zig-zag order (table 7-3).</summary>
|
||||
internal static readonly byte[] Default4x4Inter = [10, 14, 14, 20, 20, 20, 24, 24, 24, 24, 27, 27, 27, 30, 30, 34];
|
||||
|
||||
/// <summary>Default_8x8_Intra in zig-zag order (table 7-4).</summary>
|
||||
internal static readonly byte[] Default8x8Intra =
|
||||
[
|
||||
6, 10, 10, 13, 11, 13, 16, 16, 16, 16, 18, 18, 18, 18, 18, 23, 23, 23, 23, 23, 23, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27, 27,
|
||||
27, 27, 27, 27, 29, 29, 29, 29, 29, 29, 29, 31, 31, 31, 31, 31, 31, 33, 33, 33, 33, 33, 36, 36, 36, 36, 38, 38, 38, 40, 40, 42,
|
||||
];
|
||||
|
||||
/// <summary>Default_8x8_Inter in zig-zag order (table 7-4).</summary>
|
||||
internal static readonly byte[] Default8x8Inter =
|
||||
[
|
||||
9, 13, 13, 15, 13, 15, 17, 17, 17, 17, 19, 19, 19, 19, 19, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 24, 24, 24, 24,
|
||||
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 30, 30, 30, 30, 32, 32, 32, 33, 33, 35,
|
||||
];
|
||||
|
||||
/// <summary>QPc from qPI (table 8-15), for qPI 0..51.</summary>
|
||||
internal static readonly byte[] ChromaQp =
|
||||
[
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
|
||||
29, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 39,
|
||||
];
|
||||
|
||||
/// <summary>α′ of the deblocking filter (table 8-16), by indexA.</summary>
|
||||
internal static readonly byte[] Alpha =
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 17, 20, 22, 25, 28,
|
||||
32, 36, 40, 45, 50, 56, 63, 71, 80, 90, 101, 113, 127, 144, 162, 182, 203, 226, 255, 255,
|
||||
];
|
||||
|
||||
/// <summary>β′ of the deblocking filter (table 8-16), by indexB.</summary>
|
||||
internal static readonly byte[] Beta =
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 6, 6, 7, 7, 8, 8,
|
||||
9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
|
||||
];
|
||||
|
||||
/// <summary>tC0′ of the deblocking filter (table 8-17), [indexA * 3 + bS − 1].</summary>
|
||||
internal static readonly byte[] Tc0 =
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 2,
|
||||
1, 1, 2, 1, 2, 3, 1, 2, 3, 2, 2, 3, 2, 2, 4, 2, 3, 4, 2, 3, 4, 3, 3, 5, 3, 4, 6, 3, 4, 6, 4, 5, 7, 4, 5, 8, 4, 6, 9,
|
||||
5, 7, 10, 6, 8, 11, 6, 8, 13, 7, 10, 14, 8, 11, 16, 9, 12, 18, 10, 13, 20, 11, 15, 23, 13, 17, 25,
|
||||
];
|
||||
|
||||
/// <summary>ctxIdxInc of significant_coeff_flag for 8×8 frame blocks (table 9-43), by levelListIdx.</summary>
|
||||
internal static readonly byte[] SignificantContext8x8 =
|
||||
[
|
||||
0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5, 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9, 10, 9, 8, 7,
|
||||
7, 6, 11, 12, 13, 11, 6, 7, 8, 9, 14, 10, 9, 8, 6, 11, 12, 13, 11, 6, 9, 14, 10, 9, 11, 12, 13, 11, 14, 10, 12,
|
||||
];
|
||||
|
||||
/// <summary>ctxIdxInc of last_significant_coeff_flag for 8×8 blocks (table 9-43), by levelListIdx.</summary>
|
||||
internal static readonly byte[] LastContext8x8 =
|
||||
[
|
||||
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
|
||||
3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8,
|
||||
];
|
||||
|
||||
private static byte[] BuildZigZag(int size)
|
||||
{
|
||||
var scan = new byte[size * size];
|
||||
int x = 0, y = 0;
|
||||
for (var i = 0; i < scan.Length; i++)
|
||||
{
|
||||
scan[i] = (byte)((y * size) + x);
|
||||
if (((x + y) & 1) == 0)
|
||||
{
|
||||
// Moving up and to the right.
|
||||
if (x == size - 1)
|
||||
{
|
||||
y++;
|
||||
}
|
||||
else if (y == 0)
|
||||
{
|
||||
x++;
|
||||
}
|
||||
else
|
||||
{
|
||||
x++;
|
||||
y--;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Moving down and to the left.
|
||||
if (y == size - 1)
|
||||
{
|
||||
x++;
|
||||
}
|
||||
else if (x == 0)
|
||||
{
|
||||
y++;
|
||||
}
|
||||
else
|
||||
{
|
||||
x--;
|
||||
y++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return scan;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>Fractional sample interpolation (§8.4.2.2) and weighted sample prediction (§8.4.2.3).</summary>
|
||||
internal static class InterPrediction
|
||||
{
|
||||
/// <summary>
|
||||
/// Luma prediction of a <paramref name="w"/> × <paramref name="h"/> block whose top-left corner, in quarter
|
||||
/// samples, is (<paramref name="qx"/>, <paramref name="qy"/>). Samples outside the picture repeat the edge.
|
||||
/// </summary>
|
||||
internal static void Luma(Picture reference, int qx, int qy, int w, int h, Span<byte> dst)
|
||||
{
|
||||
var plane = reference.Y;
|
||||
int pw = reference.Width, ph = reference.Height;
|
||||
int xInt = qx >> 2, yInt = qy >> 2, xFrac = qx & 3, yFrac = qy & 3;
|
||||
|
||||
// Window with two samples before and three after in each direction.
|
||||
var ww = w + 5;
|
||||
var wh = h + 5;
|
||||
Span<int> win = stackalloc int[21 * 21];
|
||||
var inside = xInt - 2 >= 0 && yInt - 2 >= 0 && xInt + w + 3 <= pw && yInt + h + 3 <= ph;
|
||||
for (var r = 0; r < wh; r++)
|
||||
{
|
||||
var sy = yInt - 2 + r;
|
||||
if (!inside)
|
||||
{
|
||||
sy = sy < 0 ? 0 : sy >= ph ? ph - 1 : sy;
|
||||
}
|
||||
|
||||
var rowBase = sy * pw;
|
||||
for (var c = 0; c < ww; c++)
|
||||
{
|
||||
var sx = xInt - 2 + c;
|
||||
if (!inside)
|
||||
{
|
||||
sx = sx < 0 ? 0 : sx >= pw ? pw - 1 : sx;
|
||||
}
|
||||
|
||||
win[(r * ww) + c] = plane[rowBase + sx];
|
||||
}
|
||||
}
|
||||
|
||||
if (xFrac == 0 && yFrac == 0)
|
||||
{
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
dst[(y * w) + x] = (byte)win[((y + 2) * ww) + x + 2];
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Horizontal half samples b (rows 0..h, the extra row is s), vertical half samples h (columns 0..w, the extra
|
||||
// column is m), centre half samples j.
|
||||
Span<int> bh = stackalloc int[17 * 16];
|
||||
Span<int> vh = stackalloc int[16 * 17];
|
||||
Span<int> jc = stackalloc int[16 * 16];
|
||||
if (xFrac != 0)
|
||||
{
|
||||
for (var y = 0; y <= h && y + 2 < wh; y++)
|
||||
{
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
var b = ((y + 2) * ww) + x;
|
||||
var v = win[b] - (5 * win[b + 1]) + (20 * win[b + 2]) + (20 * win[b + 3]) - (5 * win[b + 4]) + win[b + 5];
|
||||
bh[(y * w) + x] = Clip((v + 16) >> 5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (yFrac != 0)
|
||||
{
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
for (var x = 0; x <= w && x + 2 < ww; x++)
|
||||
{
|
||||
var b = (y * ww) + x + 2;
|
||||
var v = win[b] - (5 * win[b + ww]) + (20 * win[b + (2 * ww)]) + (20 * win[b + (3 * ww)]) - (5 * win[b + (4 * ww)]) + win[b + (5 * ww)];
|
||||
vh[(y * (w + 1)) + x] = Clip((v + 16) >> 5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var needJ = (xFrac == 2 && yFrac != 0) || (yFrac == 2 && xFrac != 0);
|
||||
if (needJ)
|
||||
{
|
||||
// Unrounded horizontal half samples of every window row, then the vertical filter over them.
|
||||
Span<int> b1 = stackalloc int[21 * 16];
|
||||
for (var r = 0; r < wh; r++)
|
||||
{
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
var b = (r * ww) + x;
|
||||
b1[(r * w) + x] = win[b] - (5 * win[b + 1]) + (20 * win[b + 2]) + (20 * win[b + 3]) - (5 * win[b + 4]) + win[b + 5];
|
||||
}
|
||||
}
|
||||
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
var b = (y * w) + x;
|
||||
var v = b1[b] - (5 * b1[b + w]) + (20 * b1[b + (2 * w)]) + (20 * b1[b + (3 * w)]) - (5 * b1[b + (4 * w)]) + b1[b + (5 * w)];
|
||||
jc[b] = Clip((v + 512) >> 10);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
var g = win[((y + 2) * ww) + x + 2];
|
||||
int value;
|
||||
switch ((xFrac << 2) | yFrac)
|
||||
{
|
||||
case 0x1: // d
|
||||
value = (g + vh[(y * (w + 1)) + x] + 1) >> 1;
|
||||
break;
|
||||
case 0x2: // h
|
||||
value = vh[(y * (w + 1)) + x];
|
||||
break;
|
||||
case 0x3: // n
|
||||
value = (win[((y + 3) * ww) + x + 2] + vh[(y * (w + 1)) + x] + 1) >> 1;
|
||||
break;
|
||||
case 0x4: // a
|
||||
value = (g + bh[(y * w) + x] + 1) >> 1;
|
||||
break;
|
||||
case 0x5: // e
|
||||
value = (bh[(y * w) + x] + vh[(y * (w + 1)) + x] + 1) >> 1;
|
||||
break;
|
||||
case 0x6: // i
|
||||
value = (vh[(y * (w + 1)) + x] + jc[(y * w) + x] + 1) >> 1;
|
||||
break;
|
||||
case 0x7: // p
|
||||
value = (vh[(y * (w + 1)) + x] + bh[((y + 1) * w) + x] + 1) >> 1;
|
||||
break;
|
||||
case 0x8: // b
|
||||
value = bh[(y * w) + x];
|
||||
break;
|
||||
case 0x9: // f
|
||||
value = (bh[(y * w) + x] + jc[(y * w) + x] + 1) >> 1;
|
||||
break;
|
||||
case 0xA: // j
|
||||
value = jc[(y * w) + x];
|
||||
break;
|
||||
case 0xB: // q
|
||||
value = (jc[(y * w) + x] + bh[((y + 1) * w) + x] + 1) >> 1;
|
||||
break;
|
||||
case 0xC: // c
|
||||
value = (win[((y + 2) * ww) + x + 3] + bh[(y * w) + x] + 1) >> 1;
|
||||
break;
|
||||
case 0xD: // g
|
||||
value = (bh[(y * w) + x] + vh[(y * (w + 1)) + x + 1] + 1) >> 1;
|
||||
break;
|
||||
case 0xE: // k
|
||||
value = (jc[(y * w) + x] + vh[(y * (w + 1)) + x + 1] + 1) >> 1;
|
||||
break;
|
||||
default: // 0xF, r
|
||||
value = (vh[(y * (w + 1)) + x + 1] + bh[((y + 1) * w) + x] + 1) >> 1;
|
||||
break;
|
||||
}
|
||||
|
||||
dst[(y * w) + x] = (byte)value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Chroma prediction (4:2:0) of a <paramref name="w"/> × <paramref name="h"/> block whose corner, in eighths of a
|
||||
/// chroma sample, is (<paramref name="ex"/>, <paramref name="ey"/>).
|
||||
/// </summary>
|
||||
internal static void Chroma(byte[] plane, int pw, int ph, int ex, int ey, int w, int h, Span<byte> dst)
|
||||
{
|
||||
int xInt = ex >> 3, yInt = ey >> 3, xFrac = ex & 7, yFrac = ey & 7;
|
||||
int wA = (8 - xFrac) * (8 - yFrac), wB = xFrac * (8 - yFrac), wC = (8 - xFrac) * yFrac, wD = xFrac * yFrac;
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
var y0 = Math.Clamp(yInt + y, 0, ph - 1) * pw;
|
||||
var y1 = Math.Clamp(yInt + y + 1, 0, ph - 1) * pw;
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
var x0 = Math.Clamp(xInt + x, 0, pw - 1);
|
||||
var x1 = Math.Clamp(xInt + x + 1, 0, pw - 1);
|
||||
dst[(y * w) + x] = (byte)(((wA * plane[y0 + x0]) + (wB * plane[y0 + x1]) + (wC * plane[y1 + x0]) + (wD * plane[y1 + x1]) + 32) >> 6);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Default bi-prediction average (equation 8-273), into <paramref name="a"/>.</summary>
|
||||
internal static void Average(Span<byte> a, ReadOnlySpan<byte> b)
|
||||
{
|
||||
for (var i = 0; i < a.Length; i++)
|
||||
{
|
||||
a[i] = (byte)((a[i] + b[i] + 1) >> 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Weighted prediction from one list (equation 8-270).</summary>
|
||||
internal static void WeightOne(Span<byte> a, int logWd, int weight, int offset)
|
||||
{
|
||||
for (var i = 0; i < a.Length; i++)
|
||||
{
|
||||
var v = logWd >= 1 ? ((a[i] * weight) + (1 << (logWd - 1))) >> logWd : a[i] * weight;
|
||||
a[i] = (byte)Clip(v + offset);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Weighted bi-prediction (equation 8-272), into <paramref name="a"/>.</summary>
|
||||
internal static void WeightTwo(Span<byte> a, ReadOnlySpan<byte> b, int logWd, int w0, int w1, int o0, int o1)
|
||||
{
|
||||
var offset = (o0 + o1 + 1) >> 1;
|
||||
for (var i = 0; i < a.Length; i++)
|
||||
{
|
||||
var v = (((a[i] * w0) + (b[i] * w1) + (1 << logWd)) >> (logWd + 1)) + offset;
|
||||
a[i] = (byte)Clip(v);
|
||||
}
|
||||
}
|
||||
|
||||
private static int Clip(int v) => v < 0 ? 0 : v > 255 ? 255 : v;
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>Intra prediction of luma 4×4, 8×8 and 16×16 blocks and of 4:2:0 chroma (§8.3), written into the plane.</summary>
|
||||
internal static class IntraPrediction
|
||||
{
|
||||
/// <summary>Intra_4x4 (§8.3.1.2) of the block at <paramref name="o"/>.</summary>
|
||||
internal static void Predict4x4(byte[] p, int o, int stride, int mode, bool left, bool top, bool topRight, bool topLeft)
|
||||
{
|
||||
Span<int> t = stackalloc int[8];
|
||||
Span<int> l = stackalloc int[4];
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
t[i] = top ? p[o - stride + i] : 128;
|
||||
l[i] = left ? p[o + (i * stride) - 1] : 128;
|
||||
}
|
||||
|
||||
for (var i = 4; i < 8; i++)
|
||||
{
|
||||
t[i] = topRight ? p[o - stride + i] : t[3];
|
||||
}
|
||||
|
||||
var tl = topLeft ? p[o - stride - 1] : 128;
|
||||
switch (mode)
|
||||
{
|
||||
case 0: // Vertical
|
||||
for (var y = 0; y < 4; y++)
|
||||
{
|
||||
for (var x = 0; x < 4; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)t[x];
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case 1: // Horizontal
|
||||
for (var y = 0; y < 4; y++)
|
||||
{
|
||||
for (var x = 0; x < 4; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)l[y];
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case 2: // DC
|
||||
{
|
||||
int dc;
|
||||
if (top && left)
|
||||
{
|
||||
dc = (t[0] + t[1] + t[2] + t[3] + l[0] + l[1] + l[2] + l[3] + 4) >> 3;
|
||||
}
|
||||
else if (left)
|
||||
{
|
||||
dc = (l[0] + l[1] + l[2] + l[3] + 2) >> 2;
|
||||
}
|
||||
else if (top)
|
||||
{
|
||||
dc = (t[0] + t[1] + t[2] + t[3] + 2) >> 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
dc = 128;
|
||||
}
|
||||
|
||||
Fill(p, o, stride, 4, 4, dc);
|
||||
break;
|
||||
}
|
||||
|
||||
case 3: // Diagonal_Down_Left
|
||||
for (var y = 0; y < 4; y++)
|
||||
{
|
||||
for (var x = 0; x < 4; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)(x == 3 && y == 3
|
||||
? (t[6] + (3 * t[7]) + 2) >> 2
|
||||
: (t[x + y] + (2 * t[x + y + 1]) + t[x + y + 2] + 2) >> 2);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
{
|
||||
// Modes 4–8 use the edge as one array: e[0..3] = left from bottom to top, e[4] = top-left,
|
||||
// e[5..12] = top. Index of p[-1, y] is 3 − y, of p[x, −1] is 5 + x.
|
||||
Span<int> e = stackalloc int[13];
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
e[3 - i] = l[i];
|
||||
}
|
||||
|
||||
e[4] = tl;
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
e[5 + i] = t[i];
|
||||
}
|
||||
|
||||
for (var y = 0; y < 4; y++)
|
||||
{
|
||||
for (var x = 0; x < 4; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)Directional(e, 4, mode, x, y, 4);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Modes 4–8 of Intra_4x4 and Intra_8x8 on an edge array where p[−1, y] is at <c>c − 1 − y</c>, p[−1, −1] at
|
||||
/// <c>c</c> and p[x, −1] at <c>c + 1 + x</c> (<paramref name="c"/> = block size).
|
||||
/// </summary>
|
||||
private static int Directional(ReadOnlySpan<int> e, int c, int mode, int x, int y, int n)
|
||||
{
|
||||
switch (mode)
|
||||
{
|
||||
case 4: // Diagonal_Down_Right
|
||||
if (x > y)
|
||||
{
|
||||
return (T(e, c, x - y - 2) + (2 * T(e, c, x - y - 1)) + T(e, c, x - y) + 2) >> 2;
|
||||
}
|
||||
|
||||
if (x < y)
|
||||
{
|
||||
return (L(e, c, y - x - 2) + (2 * L(e, c, y - x - 1)) + L(e, c, y - x) + 2) >> 2;
|
||||
}
|
||||
|
||||
return (T(e, c, 0) + (2 * T(e, c, -1)) + L(e, c, 0) + 2) >> 2;
|
||||
case 5: // Vertical_Right
|
||||
{
|
||||
var z = (2 * x) - y;
|
||||
if (z >= 0 && (z & 1) == 0)
|
||||
{
|
||||
return (T(e, c, x - (y >> 1) - 1) + T(e, c, x - (y >> 1)) + 1) >> 1;
|
||||
}
|
||||
|
||||
if (z >= 0)
|
||||
{
|
||||
return (T(e, c, x - (y >> 1) - 2) + (2 * T(e, c, x - (y >> 1) - 1)) + T(e, c, x - (y >> 1)) + 2) >> 2;
|
||||
}
|
||||
|
||||
if (z == -1)
|
||||
{
|
||||
return (L(e, c, 0) + (2 * L(e, c, -1)) + T(e, c, 0) + 2) >> 2;
|
||||
}
|
||||
|
||||
return (L(e, c, y - (2 * x) - 1) + (2 * L(e, c, y - (2 * x) - 2)) + L(e, c, y - (2 * x) - 3) + 2) >> 2;
|
||||
}
|
||||
|
||||
case 6: // Horizontal_Down
|
||||
{
|
||||
var z = (2 * y) - x;
|
||||
if (z >= 0 && (z & 1) == 0)
|
||||
{
|
||||
return (L(e, c, y - (x >> 1) - 1) + L(e, c, y - (x >> 1)) + 1) >> 1;
|
||||
}
|
||||
|
||||
if (z >= 0)
|
||||
{
|
||||
return (L(e, c, y - (x >> 1) - 2) + (2 * L(e, c, y - (x >> 1) - 1)) + L(e, c, y - (x >> 1)) + 2) >> 2;
|
||||
}
|
||||
|
||||
if (z == -1)
|
||||
{
|
||||
return (L(e, c, 0) + (2 * L(e, c, -1)) + T(e, c, 0) + 2) >> 2;
|
||||
}
|
||||
|
||||
return (T(e, c, x - (2 * y) - 1) + (2 * T(e, c, x - (2 * y) - 2)) + T(e, c, x - (2 * y) - 3) + 2) >> 2;
|
||||
}
|
||||
|
||||
case 7: // Vertical_Left
|
||||
if ((y & 1) == 0)
|
||||
{
|
||||
return (T(e, c, x + (y >> 1)) + T(e, c, x + (y >> 1) + 1) + 1) >> 1;
|
||||
}
|
||||
|
||||
return (T(e, c, x + (y >> 1)) + (2 * T(e, c, x + (y >> 1) + 1)) + T(e, c, x + (y >> 1) + 2) + 2) >> 2;
|
||||
default: // 8, Horizontal_Up
|
||||
{
|
||||
var z = x + (2 * y);
|
||||
var last = (2 * n) - 3;
|
||||
if (z < last && (z & 1) == 0)
|
||||
{
|
||||
return (L(e, c, y + (x >> 1)) + L(e, c, y + (x >> 1) + 1) + 1) >> 1;
|
||||
}
|
||||
|
||||
if (z < last)
|
||||
{
|
||||
return (L(e, c, y + (x >> 1)) + (2 * L(e, c, y + (x >> 1) + 1)) + L(e, c, y + (x >> 1) + 2) + 2) >> 2;
|
||||
}
|
||||
|
||||
if (z == last)
|
||||
{
|
||||
return (L(e, c, n - 2) + (3 * L(e, c, n - 1)) + 2) >> 2;
|
||||
}
|
||||
|
||||
return L(e, c, n - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>p[i, −1] of the edge array, i ≥ −1.</summary>
|
||||
private static int T(ReadOnlySpan<int> e, int c, int i) => e[c + 1 + i];
|
||||
|
||||
/// <summary>p[−1, i] of the edge array, i ≥ −1.</summary>
|
||||
private static int L(ReadOnlySpan<int> e, int c, int i) => e[c - 1 - i];
|
||||
|
||||
/// <summary>Intra_8x8 with the reference sample filtering of §8.3.2.2.1.</summary>
|
||||
internal static void Predict8x8(byte[] p, int o, int stride, int mode, bool left, bool top, bool topRight, bool topLeft)
|
||||
{
|
||||
Span<int> t = stackalloc int[16];
|
||||
Span<int> l = stackalloc int[8];
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
t[i] = top ? p[o - stride + i] : 128;
|
||||
l[i] = left ? p[o + (i * stride) - 1] : 128;
|
||||
}
|
||||
|
||||
for (var i = 8; i < 16; i++)
|
||||
{
|
||||
t[i] = topRight ? p[o - stride + i] : t[7];
|
||||
}
|
||||
|
||||
var tl = topLeft ? p[o - stride - 1] : 128;
|
||||
|
||||
// Filtered references p′.
|
||||
Span<int> ft = stackalloc int[16];
|
||||
Span<int> fl = stackalloc int[8];
|
||||
var ftl = tl;
|
||||
if (top)
|
||||
{
|
||||
ft[0] = topLeft ? (tl + (2 * t[0]) + t[1] + 2) >> 2 : ((3 * t[0]) + t[1] + 2) >> 2;
|
||||
for (var x = 1; x < 15; x++)
|
||||
{
|
||||
ft[x] = (t[x - 1] + (2 * t[x]) + t[x + 1] + 2) >> 2;
|
||||
}
|
||||
|
||||
ft[15] = (t[14] + (3 * t[15]) + 2) >> 2;
|
||||
}
|
||||
|
||||
if (topLeft)
|
||||
{
|
||||
if (top && left)
|
||||
{
|
||||
ftl = (t[0] + (2 * tl) + l[0] + 2) >> 2;
|
||||
}
|
||||
else if (top)
|
||||
{
|
||||
ftl = ((3 * tl) + t[0] + 2) >> 2;
|
||||
}
|
||||
else if (left)
|
||||
{
|
||||
ftl = ((3 * tl) + l[0] + 2) >> 2;
|
||||
}
|
||||
}
|
||||
|
||||
if (left)
|
||||
{
|
||||
fl[0] = topLeft ? (tl + (2 * l[0]) + l[1] + 2) >> 2 : ((3 * l[0]) + l[1] + 2) >> 2;
|
||||
for (var y = 1; y < 7; y++)
|
||||
{
|
||||
fl[y] = (l[y - 1] + (2 * l[y]) + l[y + 1] + 2) >> 2;
|
||||
}
|
||||
|
||||
fl[7] = (l[6] + (3 * l[7]) + 2) >> 2;
|
||||
}
|
||||
|
||||
switch (mode)
|
||||
{
|
||||
case 0:
|
||||
for (var y = 0; y < 8; y++)
|
||||
{
|
||||
for (var x = 0; x < 8; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)ft[x];
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case 1:
|
||||
for (var y = 0; y < 8; y++)
|
||||
{
|
||||
for (var x = 0; x < 8; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)fl[y];
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case 2:
|
||||
{
|
||||
int sumT = 0, sumL = 0;
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
sumT += ft[i];
|
||||
sumL += fl[i];
|
||||
}
|
||||
|
||||
var dc = top && left ? (sumT + sumL + 8) >> 4 : left ? (sumL + 4) >> 3 : top ? (sumT + 4) >> 3 : 128;
|
||||
Fill(p, o, stride, 8, 8, dc);
|
||||
break;
|
||||
}
|
||||
|
||||
case 3:
|
||||
for (var y = 0; y < 8; y++)
|
||||
{
|
||||
for (var x = 0; x < 8; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)(x == 7 && y == 7
|
||||
? (ft[14] + (3 * ft[15]) + 2) >> 2
|
||||
: (ft[x + y] + (2 * ft[x + y + 1]) + ft[x + y + 2] + 2) >> 2);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
{
|
||||
Span<int> e = stackalloc int[25];
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
e[7 - i] = fl[i];
|
||||
}
|
||||
|
||||
e[8] = ftl;
|
||||
for (var i = 0; i < 16; i++)
|
||||
{
|
||||
e[9 + i] = ft[i];
|
||||
}
|
||||
|
||||
for (var y = 0; y < 8; y++)
|
||||
{
|
||||
for (var x = 0; x < 8; x++)
|
||||
{
|
||||
p[o + (y * stride) + x] = (byte)Directional(e, 8, mode, x, y, 8);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Intra_16x16 (§8.3.3).</summary>
|
||||
internal static void Predict16x16(byte[] p, int o, int stride, int mode, bool left, bool top, bool topLeft)
|
||||
{
|
||||
switch (mode)
|
||||
{
|
||||
case 0:
|
||||
for (var y = 0; y < 16; y++)
|
||||
{
|
||||
Array.Copy(p, o - stride, p, o + (y * stride), 16);
|
||||
}
|
||||
|
||||
break;
|
||||
case 1:
|
||||
for (var y = 0; y < 16; y++)
|
||||
{
|
||||
var v = p[o + (y * stride) - 1];
|
||||
p.AsSpan(o + (y * stride), 16).Fill(v);
|
||||
}
|
||||
|
||||
break;
|
||||
case 2:
|
||||
{
|
||||
int sumT = 0, sumL = 0;
|
||||
for (var i = 0; i < 16; i++)
|
||||
{
|
||||
if (top)
|
||||
{
|
||||
sumT += p[o - stride + i];
|
||||
}
|
||||
|
||||
if (left)
|
||||
{
|
||||
sumL += p[o + (i * stride) - 1];
|
||||
}
|
||||
}
|
||||
|
||||
var dc = top && left ? (sumT + sumL + 16) >> 5 : left ? (sumL + 8) >> 4 : top ? (sumT + 8) >> 4 : 128;
|
||||
Fill(p, o, stride, 16, 16, dc);
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
Plane(p, o, stride, 16, 16, topLeft);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Chroma prediction of one 8×8 4:2:0 component (§8.3.4): 0 DC, 1 horizontal, 2 vertical, 3 plane.</summary>
|
||||
internal static void PredictChroma(byte[] p, int o, int stride, int mode, bool left, bool top, bool topLeft)
|
||||
{
|
||||
switch (mode)
|
||||
{
|
||||
case 0:
|
||||
for (var by = 0; by < 2; by++)
|
||||
{
|
||||
for (var bx = 0; bx < 2; bx++)
|
||||
{
|
||||
var b = o + (by * 4 * stride) + (bx * 4);
|
||||
int sumT = 0, sumL = 0;
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
if (top)
|
||||
{
|
||||
sumT += p[o - stride + (bx * 4) + i];
|
||||
}
|
||||
|
||||
if (left)
|
||||
{
|
||||
sumL += p[o + (((by * 4) + i) * stride) - 1];
|
||||
}
|
||||
}
|
||||
|
||||
int dc;
|
||||
if ((bx == 0 && by == 0) || (bx == 1 && by == 1))
|
||||
{
|
||||
dc = top && left ? (sumT + sumL + 4) >> 3 : left ? (sumL + 2) >> 2 : top ? (sumT + 2) >> 2 : 128;
|
||||
}
|
||||
else if (bx == 1)
|
||||
{
|
||||
dc = top ? (sumT + 2) >> 2 : left ? (sumL + 2) >> 2 : 128;
|
||||
}
|
||||
else
|
||||
{
|
||||
dc = left ? (sumL + 2) >> 2 : top ? (sumT + 2) >> 2 : 128;
|
||||
}
|
||||
|
||||
Fill(p, b, stride, 4, 4, dc);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case 1:
|
||||
for (var y = 0; y < 8; y++)
|
||||
{
|
||||
var v = p[o + (y * stride) - 1];
|
||||
p.AsSpan(o + (y * stride), 8).Fill(v);
|
||||
}
|
||||
|
||||
break;
|
||||
case 2:
|
||||
for (var y = 0; y < 8; y++)
|
||||
{
|
||||
Array.Copy(p, o - stride, p, o + (y * stride), 8);
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
Plane(p, o, stride, 8, 8, topLeft);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Plane prediction of a 16×16 luma or 8×8 chroma block.</summary>
|
||||
private static void Plane(byte[] p, int o, int stride, int w, int h, bool topLeft)
|
||||
{
|
||||
_ = topLeft; // the plane mode is only used when all three neighbours are available
|
||||
var hw = w / 2;
|
||||
var hh = h / 2;
|
||||
int sumH = 0, sumV = 0;
|
||||
for (var i = 0; i < hw; i++)
|
||||
{
|
||||
var right = p[o - stride + hw + i];
|
||||
var leftIndex = hw - 2 - i;
|
||||
var leftSample = leftIndex >= 0 ? p[o - stride + leftIndex] : p[o - stride - 1];
|
||||
sumH += (i + 1) * (right - leftSample);
|
||||
}
|
||||
|
||||
for (var i = 0; i < hh; i++)
|
||||
{
|
||||
var below = p[o + ((hh + i) * stride) - 1];
|
||||
var aboveIndex = hh - 2 - i;
|
||||
var aboveSample = aboveIndex >= 0 ? p[o + (aboveIndex * stride) - 1] : p[o - stride - 1];
|
||||
sumV += (i + 1) * (below - aboveSample);
|
||||
}
|
||||
|
||||
var a = 16 * (p[o + ((h - 1) * stride) - 1] + p[o - stride + w - 1]);
|
||||
int b, c;
|
||||
if (w == 16)
|
||||
{
|
||||
b = ((5 * sumH) + 32) >> 6;
|
||||
c = ((5 * sumV) + 32) >> 6;
|
||||
}
|
||||
else
|
||||
{
|
||||
b = ((34 * sumH) + 32) >> 6;
|
||||
c = ((34 * sumV) + 32) >> 6;
|
||||
}
|
||||
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
var v = (a + (b * (x - (hw - 1))) + (c * (y - (hh - 1))) + 16) >> 5;
|
||||
p[o + (y * stride) + x] = (byte)Math.Clamp(v, 0, 255);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void Fill(byte[] p, int o, int stride, int w, int h, int value)
|
||||
{
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
p.AsSpan(o + (y * stride), w).Fill((byte)value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>A sequence parameter set (§7.3.2.1.1), with the fields Febe uses.</summary>
|
||||
internal sealed class Sps
|
||||
{
|
||||
internal int ProfileIdc;
|
||||
internal int LevelIdc;
|
||||
internal int Id;
|
||||
internal int ChromaFormatIdc = 1;
|
||||
internal int BitDepthLuma = 8;
|
||||
internal int BitDepthChroma = 8;
|
||||
internal bool TransformBypass;
|
||||
|
||||
/// <summary>Scaling lists 0–5 (4×4) and 6–11 (8×8) in zig-zag order, after the fall-back rule A.</summary>
|
||||
internal byte[][] ScalingLists = ScalingMatrix.Flat();
|
||||
|
||||
/// <summary>seq_scaling_matrix_present_flag: chooses fall-back rule B (instead of A) for the PPS lists.</summary>
|
||||
internal bool ScalingMatrixPresent;
|
||||
|
||||
internal int Log2MaxFrameNum;
|
||||
internal int PocType;
|
||||
internal int Log2MaxPocLsb;
|
||||
internal bool DeltaPicOrderAlwaysZero;
|
||||
internal int OffsetForNonRefPic;
|
||||
internal int OffsetForTopToBottomField;
|
||||
internal int[] OffsetForRefFrame = [];
|
||||
internal int MaxNumRefFrames;
|
||||
internal bool GapsInFrameNumAllowed;
|
||||
internal int WidthInMbs;
|
||||
internal int HeightInMapUnits;
|
||||
internal bool FrameMbsOnly;
|
||||
internal bool MbAdaptiveFrameField;
|
||||
internal bool Direct8x8Inference;
|
||||
internal int CropLeft, CropRight, CropTop, CropBottom;
|
||||
|
||||
/// <summary>VUI colour description: matrix_coefficients (2 = unspecified) and video_full_range_flag.</summary>
|
||||
internal int MatrixCoefficients = 2;
|
||||
|
||||
internal bool FullRange;
|
||||
|
||||
internal int MaxFrameNum => 1 << Log2MaxFrameNum;
|
||||
|
||||
internal int HeightInMbs => (2 - (FrameMbsOnly ? 1 : 0)) * HeightInMapUnits;
|
||||
|
||||
internal static Sps Parse(RbspReader r)
|
||||
{
|
||||
var s = new Sps { ProfileIdc = (int)r.Read(8) };
|
||||
r.Skip(8); // constraint flags and reserved bits
|
||||
s.LevelIdc = (int)r.Read(8);
|
||||
s.Id = r.ReadUe(31);
|
||||
if (s.ProfileIdc is 100 or 110 or 122 or 244 or 44 or 83 or 86 or 118 or 128 or 138 or 139 or 134 or 135)
|
||||
{
|
||||
s.ChromaFormatIdc = r.ReadUe(3);
|
||||
if (s.ChromaFormatIdc == 3)
|
||||
{
|
||||
r.Skip(1); // separate_colour_plane_flag
|
||||
}
|
||||
|
||||
s.BitDepthLuma = r.ReadUe(6) + 8;
|
||||
s.BitDepthChroma = r.ReadUe(6) + 8;
|
||||
s.TransformBypass = r.ReadFlag();
|
||||
if (r.ReadFlag())
|
||||
{
|
||||
s.ScalingMatrixPresent = true;
|
||||
s.ScalingLists = ScalingMatrix.ParseLists(r, s.ChromaFormatIdc == 3 ? 12 : 8, null);
|
||||
}
|
||||
}
|
||||
|
||||
s.Log2MaxFrameNum = r.ReadUe(12) + 4;
|
||||
s.PocType = r.ReadUe(2);
|
||||
if (s.PocType == 0)
|
||||
{
|
||||
s.Log2MaxPocLsb = r.ReadUe(12) + 4;
|
||||
}
|
||||
else if (s.PocType == 1)
|
||||
{
|
||||
s.DeltaPicOrderAlwaysZero = r.ReadFlag();
|
||||
s.OffsetForNonRefPic = r.ReadSe();
|
||||
s.OffsetForTopToBottomField = r.ReadSe();
|
||||
var cycle = r.ReadUe(255);
|
||||
s.OffsetForRefFrame = new int[cycle];
|
||||
for (var i = 0; i < cycle; i++)
|
||||
{
|
||||
s.OffsetForRefFrame[i] = r.ReadSe();
|
||||
}
|
||||
}
|
||||
|
||||
s.MaxNumRefFrames = r.ReadUe(16);
|
||||
s.GapsInFrameNumAllowed = r.ReadFlag();
|
||||
s.WidthInMbs = r.ReadUe(1023) + 1;
|
||||
s.HeightInMapUnits = r.ReadUe(1023) + 1;
|
||||
s.FrameMbsOnly = r.ReadFlag();
|
||||
if (!s.FrameMbsOnly)
|
||||
{
|
||||
s.MbAdaptiveFrameField = r.ReadFlag();
|
||||
}
|
||||
|
||||
s.Direct8x8Inference = r.ReadFlag();
|
||||
if (r.ReadFlag())
|
||||
{
|
||||
s.CropLeft = r.ReadUe(8192);
|
||||
s.CropRight = r.ReadUe(8192);
|
||||
s.CropTop = r.ReadUe(8192);
|
||||
s.CropBottom = r.ReadUe(8192);
|
||||
}
|
||||
|
||||
if (r.ReadFlag())
|
||||
{
|
||||
ParseVuiColour(r, s);
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>The start of the VUI (§E.1.1), up to the colour description; the rest is not needed.</summary>
|
||||
private static void ParseVuiColour(RbspReader r, Sps s)
|
||||
{
|
||||
if (r.ReadFlag())
|
||||
{
|
||||
var aspect = r.Read(8);
|
||||
if (aspect == 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 = (int)r.Read(8);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A picture parameter set (§7.3.2.2).</summary>
|
||||
internal sealed class Pps
|
||||
{
|
||||
internal int Id;
|
||||
internal int SpsId;
|
||||
internal bool Cabac;
|
||||
internal bool BottomFieldPicOrderInFramePresent;
|
||||
internal int NumRefIdxL0DefaultActive;
|
||||
internal int NumRefIdxL1DefaultActive;
|
||||
internal bool WeightedPred;
|
||||
internal int WeightedBipredIdc;
|
||||
internal int PicInitQp;
|
||||
internal int ChromaQpIndexOffset;
|
||||
internal int SecondChromaQpIndexOffset;
|
||||
internal bool DeblockingFilterControlPresent;
|
||||
internal bool ConstrainedIntraPred;
|
||||
internal bool RedundantPicCntPresent;
|
||||
internal bool Transform8x8Mode;
|
||||
|
||||
/// <summary>The scaling lists of the picture, null when the PPS has none (those of the SPS apply).</summary>
|
||||
internal byte[][]? ScalingLists;
|
||||
|
||||
internal static Pps Parse(RbspReader r, IReadOnlyDictionary<int, Sps> sequences)
|
||||
{
|
||||
var p = new Pps { Id = r.ReadUe(255), SpsId = r.ReadUe(31) };
|
||||
p.Cabac = r.ReadFlag();
|
||||
p.BottomFieldPicOrderInFramePresent = r.ReadFlag();
|
||||
if (r.ReadUe(7) > 0)
|
||||
{
|
||||
throw new H264Exception("I gruppi di slice (FMO) non sono gestiti.");
|
||||
}
|
||||
|
||||
p.NumRefIdxL0DefaultActive = r.ReadUe(31) + 1;
|
||||
p.NumRefIdxL1DefaultActive = r.ReadUe(31) + 1;
|
||||
p.WeightedPred = r.ReadFlag();
|
||||
p.WeightedBipredIdc = (int)r.Read(2);
|
||||
p.PicInitQp = 26 + r.ReadSe();
|
||||
r.ReadSe(); // pic_init_qs_minus26
|
||||
p.ChromaQpIndexOffset = r.ReadSe();
|
||||
p.DeblockingFilterControlPresent = r.ReadFlag();
|
||||
p.ConstrainedIntraPred = r.ReadFlag();
|
||||
p.RedundantPicCntPresent = r.ReadFlag();
|
||||
p.SecondChromaQpIndexOffset = p.ChromaQpIndexOffset;
|
||||
if (r.MoreRbspData)
|
||||
{
|
||||
p.Transform8x8Mode = r.ReadFlag();
|
||||
if (r.ReadFlag())
|
||||
{
|
||||
var chroma444 = sequences.TryGetValue(p.SpsId, out var sps) && sps.ChromaFormatIdc == 3;
|
||||
var count = 6 + ((chroma444 ? 6 : 2) * (p.Transform8x8Mode ? 1 : 0));
|
||||
p.ScalingLists = ScalingMatrix.ParseLists(r, count, sps is { ScalingMatrixPresent: true } ? sps.ScalingLists : null);
|
||||
}
|
||||
|
||||
p.SecondChromaQpIndexOffset = r.ReadSe();
|
||||
}
|
||||
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Scaling lists (§7.3.2.1.1.1, tables 7-2 to 7-4) and the scale factors derived from them (§8.5.9).</summary>
|
||||
internal static class ScalingMatrix
|
||||
{
|
||||
/// <summary>Twelve flat lists (Flat_4x4_16 and Flat_8x8_16).</summary>
|
||||
internal static byte[][] Flat()
|
||||
{
|
||||
var lists = new byte[12][];
|
||||
for (var i = 0; i < 12; i++)
|
||||
{
|
||||
lists[i] = new byte[i < 6 ? 16 : 64];
|
||||
Array.Fill(lists[i], (byte)16);
|
||||
}
|
||||
|
||||
return lists;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses <paramref name="count"/> lists and applies the fall-back rules: rule A (from the defaults) for the SPS,
|
||||
/// rule B (from the lists of the SPS, <paramref name="sequenceLists"/>) for the PPS. Lists that are not
|
||||
/// transmitted at all (8×8 without transform_8x8_mode) keep the SPS ones, or flat.
|
||||
/// </summary>
|
||||
internal static byte[][] ParseLists(RbspReader r, int count, byte[][]? sequenceLists)
|
||||
{
|
||||
var lists = new byte[12][];
|
||||
for (var i = 0; i < 12; i++)
|
||||
{
|
||||
var size = i < 6 ? 16 : 64;
|
||||
var present = i < count && r.ReadFlag();
|
||||
if (present)
|
||||
{
|
||||
var list = new byte[size];
|
||||
if (ParseList(r, list))
|
||||
{
|
||||
lists[i] = Default(i);
|
||||
}
|
||||
else
|
||||
{
|
||||
lists[i] = list;
|
||||
}
|
||||
}
|
||||
else if (i < count)
|
||||
{
|
||||
lists[i] = FallBack(i, lists, sequenceLists);
|
||||
}
|
||||
else
|
||||
{
|
||||
lists[i] = sequenceLists?[i] ?? FallBack(i, lists, null);
|
||||
}
|
||||
}
|
||||
|
||||
return lists;
|
||||
}
|
||||
|
||||
/// <summary>Reads one list; true when it says «use the default matrix».</summary>
|
||||
private static bool ParseList(RbspReader r, byte[] list)
|
||||
{
|
||||
var last = 8;
|
||||
var next = 8;
|
||||
for (var j = 0; j < list.Length; j++)
|
||||
{
|
||||
if (next != 0)
|
||||
{
|
||||
var delta = r.ReadSe();
|
||||
if (delta is < -128 or > 127)
|
||||
{
|
||||
throw new H264Exception("Matrice di quantizzazione non valida.");
|
||||
}
|
||||
|
||||
next = (last + delta + 256) % 256;
|
||||
if (j == 0 && next == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
list[j] = (byte)(next == 0 ? last : next);
|
||||
last = list[j];
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static byte[] Default(int i) => i switch
|
||||
{
|
||||
< 3 => H264Tables.Default4x4Intra,
|
||||
< 6 => H264Tables.Default4x4Inter,
|
||||
_ => (i & 1) == 0 ? H264Tables.Default8x8Intra : H264Tables.Default8x8Inter,
|
||||
};
|
||||
|
||||
/// <summary>Fall-back rule A (<paramref name="sequenceLists"/> null) or B.</summary>
|
||||
private static byte[] FallBack(int i, byte[][] lists, byte[][]? sequenceLists) => i switch
|
||||
{
|
||||
0 or 3 => sequenceLists?[i] ?? Default(i),
|
||||
1 or 2 or 4 or 5 => lists[i - 1],
|
||||
6 or 7 => sequenceLists?[i] ?? Default(i),
|
||||
_ => lists[i - 2],
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// LevelScale4x4[m][i] for the six 4×4 lists (raster positions): <c>result[list][m * 16 + pos]</c>.
|
||||
/// </summary>
|
||||
internal static int[][] LevelScale4x4(byte[][] lists)
|
||||
{
|
||||
var result = new int[6][];
|
||||
for (var l = 0; l < 6; l++)
|
||||
{
|
||||
var scale = new int[6 * 16];
|
||||
for (var k = 0; k < 16; k++)
|
||||
{
|
||||
var pos = H264Tables.ZigZag4x4[k];
|
||||
int row = pos >> 2, col = pos & 3;
|
||||
var cls = (row & 1) == 0 && (col & 1) == 0 ? 0 : (row & 1) == 1 && (col & 1) == 1 ? 1 : 2;
|
||||
for (var m = 0; m < 6; m++)
|
||||
{
|
||||
scale[(m * 16) + pos] = lists[l][k] * H264Tables.NormAdjust4x4[m, cls];
|
||||
}
|
||||
}
|
||||
|
||||
result[l] = scale;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>LevelScale8x8 for the 8×8 lists 6–11 (raster positions): <c>result[list − 6][m * 64 + pos]</c>.</summary>
|
||||
internal static int[][] LevelScale8x8(byte[][] lists)
|
||||
{
|
||||
var result = new int[6][];
|
||||
for (var l = 0; l < 6; l++)
|
||||
{
|
||||
var scale = new int[6 * 64];
|
||||
for (var k = 0; k < 64; k++)
|
||||
{
|
||||
var pos = H264Tables.ZigZag8x8[k];
|
||||
int i = pos >> 3, j = pos & 7;
|
||||
int cls;
|
||||
if ((i & 3) == 0 && (j & 3) == 0)
|
||||
{
|
||||
cls = 0;
|
||||
}
|
||||
else if ((i & 1) == 1 && (j & 1) == 1)
|
||||
{
|
||||
cls = 1;
|
||||
}
|
||||
else if ((i & 3) == 2 && (j & 3) == 2)
|
||||
{
|
||||
cls = 2;
|
||||
}
|
||||
else if (((i & 3) == 0 && (j & 1) == 1) || ((i & 1) == 1 && (j & 3) == 0))
|
||||
{
|
||||
cls = 3;
|
||||
}
|
||||
else if (((i & 3) == 0 && (j & 3) == 2) || ((i & 3) == 2 && (j & 3) == 0))
|
||||
{
|
||||
cls = 4;
|
||||
}
|
||||
else
|
||||
{
|
||||
cls = 5;
|
||||
}
|
||||
|
||||
for (var m = 0; m < 6; m++)
|
||||
{
|
||||
scale[(m * 64) + pos] = lists[6 + l][k] * H264Tables.NormAdjust8x8[m, cls];
|
||||
}
|
||||
}
|
||||
|
||||
result[l] = scale;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>
|
||||
/// A decoded frame with what later pictures need from it: samples (4:2:0, 8 bits, the full macroblock area), motion
|
||||
/// vectors and references of every block (for direct prediction and the deblocking of the pictures that follow), and
|
||||
/// its state in the decoded picture buffer.
|
||||
/// </summary>
|
||||
internal sealed class Picture
|
||||
{
|
||||
internal Picture(int widthInMbs, int heightInMbs)
|
||||
{
|
||||
WidthInMbs = widthInMbs;
|
||||
HeightInMbs = heightInMbs;
|
||||
Width = widthInMbs * 16;
|
||||
Height = heightInMbs * 16;
|
||||
var mbs = widthInMbs * heightInMbs;
|
||||
Y = new byte[Width * Height];
|
||||
Cb = new byte[Width * Height / 4];
|
||||
Cr = new byte[Width * Height / 4];
|
||||
Mv = new short[2 * mbs * 16 * 2];
|
||||
RefIdx = new sbyte[2 * mbs * 4];
|
||||
RefPic = new Picture?[2 * mbs * 4];
|
||||
MbIntra = new bool[mbs];
|
||||
}
|
||||
|
||||
internal int WidthInMbs { get; }
|
||||
|
||||
internal int HeightInMbs { get; }
|
||||
|
||||
internal int Width { get; }
|
||||
|
||||
internal int Height { get; }
|
||||
|
||||
internal byte[] Y { get; }
|
||||
|
||||
internal byte[] Cb { get; }
|
||||
|
||||
internal byte[] Cr { get; }
|
||||
|
||||
/// <summary>Motion vectors: [((list * mbs + mb) * 16 + raster 4×4 block) * 2 + component], quarter samples.</summary>
|
||||
internal short[] Mv { get; }
|
||||
|
||||
/// <summary>Reference indices: [(list * mbs + mb) * 4 + 8×8 block]; −1 when the list is not used.</summary>
|
||||
internal sbyte[] RefIdx { get; }
|
||||
|
||||
/// <summary>The picture each 8×8 block refers to, by list (same index as <see cref="RefIdx"/>).</summary>
|
||||
internal Picture?[] RefPic { get; }
|
||||
|
||||
internal bool[] MbIntra { get; }
|
||||
|
||||
internal int MbCount => WidthInMbs * HeightInMbs;
|
||||
|
||||
internal int Poc;
|
||||
internal int FrameNum;
|
||||
internal int FrameNumWrap;
|
||||
internal int LongTermFrameIdx;
|
||||
internal bool ShortTerm;
|
||||
internal bool LongTerm;
|
||||
|
||||
/// <summary>A frame inferred for a gap in frame_num (§8.2.5.2): never output, its samples are not meaningful.</summary>
|
||||
internal bool NonExisting;
|
||||
|
||||
/// <summary>Decoding order of the picture in the stream.</summary>
|
||||
internal long DecodeIndex;
|
||||
|
||||
/// <summary>Counts IDR pictures (and memory_management_control_operation 5): output order restarts with each.</summary>
|
||||
internal int Period;
|
||||
|
||||
internal bool IsReference => ShortTerm || LongTerm;
|
||||
|
||||
internal int PicNum => FrameNumWrap;
|
||||
|
||||
internal int LongTermPicNum => LongTermFrameIdx;
|
||||
|
||||
internal bool Fits(int widthInMbs, int heightInMbs) => WidthInMbs == widthInMbs && HeightInMbs == heightInMbs;
|
||||
}
|
||||
|
||||
/// <summary>A decoded frame, cropped, in planar YUV 4:2:0.</summary>
|
||||
/// <param name="Width">Luma width after cropping.</param>
|
||||
/// <param name="Height">Luma height after cropping.</param>
|
||||
/// <param name="Y">Luma, <paramref name="Width"/> × <paramref name="Height"/>.</param>
|
||||
/// <param name="Cb">Blue-difference chroma, (Width + 1) / 2 × (Height + 1) / 2.</param>
|
||||
/// <param name="Cr">Red-difference chroma, same size as <paramref name="Cb"/>.</param>
|
||||
/// <param name="Poc">Picture order count: frames are shown by increasing value within a <paramref name="Period"/>.</param>
|
||||
/// <param name="Period">Increases at each IDR picture.</param>
|
||||
/// <param name="DecodeIndex">Position of the frame in decoding order (0 for the first).</param>
|
||||
/// <param name="MatrixCoefficients">matrix_coefficients 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 H264Frame(
|
||||
int Width, int Height, byte[] Y, byte[] Cb, byte[] Cr, int Poc, int Period, long DecodeIndex, int MatrixCoefficients, bool FullRange)
|
||||
{
|
||||
/// <summary>The frame as one I420 buffer (Y, then Cb, then Cr), as reference decoders write it.</summary>
|
||||
public byte[] ToI420()
|
||||
{
|
||||
var buffer = new byte[Y.Length + Cb.Length + Cr.Length];
|
||||
Y.CopyTo(buffer, 0);
|
||||
Cb.CopyTo(buffer, Y.Length);
|
||||
Cr.CopyTo(buffer, Y.Length + Cb.Length);
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
using System.Buffers.Binary;
|
||||
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>A malformed or unsupported H.264 stream.</summary>
|
||||
public sealed class H264Exception(string message) : Exception(message);
|
||||
|
||||
/// <summary>
|
||||
/// Reads the bits of a raw byte sequence payload (RBSP): a NAL unit with its emulation prevention bytes removed
|
||||
/// (ITU-T H.264 §7.4.1). The buffer carries sixteen zero bytes past the end, so reads never need a bounds check; reading
|
||||
/// past the payload gives zeros and is detected by the callers through <see cref="BitsLeft"/>.
|
||||
/// </summary>
|
||||
internal sealed class RbspReader
|
||||
{
|
||||
private readonly byte[] data;
|
||||
private readonly int length;
|
||||
private readonly int stopBit;
|
||||
private int position;
|
||||
|
||||
/// <param name="data">The payload, followed by at least sixteen bytes of padding.</param>
|
||||
/// <param name="length">Bytes of payload.</param>
|
||||
/// <param name="startByte">First byte to read (after the NAL unit header).</param>
|
||||
internal RbspReader(byte[] data, int length, int startByte)
|
||||
{
|
||||
this.data = data;
|
||||
this.length = length;
|
||||
position = startByte * 8;
|
||||
|
||||
// The rbsp_stop_one_bit is the last bit set in the payload (trailing cabac_zero_words are all zero).
|
||||
var last = length - 1;
|
||||
while (last >= startByte && data[last] == 0)
|
||||
{
|
||||
last--;
|
||||
}
|
||||
|
||||
stopBit = last < startByte ? startByte * 8 : (last * 8) + 7 - System.Numerics.BitOperations.TrailingZeroCount(data[last]);
|
||||
}
|
||||
|
||||
internal byte[] Data => data;
|
||||
|
||||
internal int Position
|
||||
{
|
||||
get => position;
|
||||
set => position = value;
|
||||
}
|
||||
|
||||
internal int BitsLeft => (length * 8) - position;
|
||||
|
||||
internal bool ByteAligned => (position & 7) == 0;
|
||||
|
||||
/// <summary>more_rbsp_data(): true while bits remain before the stop bit.</summary>
|
||||
internal bool MoreRbspData => position < stopBit;
|
||||
|
||||
internal uint Peek(int count)
|
||||
{
|
||||
var index = position >> 3;
|
||||
var word = BinaryPrimitives.ReadUInt64BigEndian(data.AsSpan(index, 8));
|
||||
return (uint)((word << (position & 7)) >> (64 - count));
|
||||
}
|
||||
|
||||
internal uint Read(int count)
|
||||
{
|
||||
if (count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var value = Peek(count);
|
||||
position += count;
|
||||
return value;
|
||||
}
|
||||
|
||||
internal void Skip(int count) => position += count;
|
||||
|
||||
internal int ReadBit()
|
||||
{
|
||||
var bit = (data[position >> 3] >> (7 - (position & 7))) & 1;
|
||||
position++;
|
||||
return bit;
|
||||
}
|
||||
|
||||
internal bool ReadFlag() => ReadBit() != 0;
|
||||
|
||||
/// <summary>ue(v): Exp-Golomb code (§9.1).</summary>
|
||||
internal uint ReadUe()
|
||||
{
|
||||
var zeros = 0;
|
||||
while (ReadBit() == 0)
|
||||
{
|
||||
if (++zeros > 31 || position > (length * 8) + 32)
|
||||
{
|
||||
throw new H264Exception("Codice Exp-Golomb non valido.");
|
||||
}
|
||||
}
|
||||
|
||||
if (zeros == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (uint)(((1UL << zeros) - 1) + Read(zeros));
|
||||
}
|
||||
|
||||
/// <summary>se(v): signed Exp-Golomb code (§9.1.1).</summary>
|
||||
internal int ReadSe()
|
||||
{
|
||||
var code = ReadUe();
|
||||
var magnitude = (int)((code + 1) >> 1);
|
||||
return (code & 1) != 0 ? magnitude : -magnitude;
|
||||
}
|
||||
|
||||
/// <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 H264Exception("Valore fuori dall'intervallo ammesso.");
|
||||
}
|
||||
|
||||
return (int)value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One NAL unit, with its RBSP.</summary>
|
||||
internal readonly record struct NalUnit(int Type, int RefIdc, byte[] Rbsp, int Length)
|
||||
{
|
||||
/// <summary>A reader positioned after the one-byte header.</summary>
|
||||
internal RbspReader Reader() => new(Rbsp, Length, 1);
|
||||
}
|
||||
|
||||
/// <summary>Splitting of byte streams (Annex B) and length-prefixed samples (ISO/IEC 14496-15) into NAL units.</summary>
|
||||
internal static class NalUnits
|
||||
{
|
||||
/// <summary>Removes the emulation prevention bytes (0x000003 → 0x0000) of one NAL unit (§7.4.1).</summary>
|
||||
internal static NalUnit Parse(ReadOnlySpan<byte> nal)
|
||||
{
|
||||
if (nal.Length < 1)
|
||||
{
|
||||
throw new H264Exception("Unità NAL vuota.");
|
||||
}
|
||||
|
||||
var buffer = new byte[nal.Length + 16];
|
||||
var count = 0;
|
||||
var zeros = 0;
|
||||
for (var i = 0; i < nal.Length; i++)
|
||||
{
|
||||
var b = nal[i];
|
||||
if (zeros >= 2 && b == 3)
|
||||
{
|
||||
zeros = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
buffer[count++] = b;
|
||||
zeros = b == 0 ? zeros + 1 : 0;
|
||||
}
|
||||
|
||||
return new NalUnit(nal[0] & 0x1F, (nal[0] >> 5) & 3, buffer, count);
|
||||
}
|
||||
|
||||
/// <summary>The NAL units of an Annex B byte stream (start codes 0x000001 or 0x00000001).</summary>
|
||||
internal static List<NalUnit> SplitAnnexB(ReadOnlySpan<byte> stream)
|
||||
{
|
||||
var units = new List<NalUnit>();
|
||||
var start = -1;
|
||||
var i = 0;
|
||||
while (i + 2 < stream.Length)
|
||||
{
|
||||
if (stream[i] == 0 && stream[i + 1] == 0 && stream[i + 2] == 1)
|
||||
{
|
||||
if (start >= 0)
|
||||
{
|
||||
AddTrimmed(units, stream[start..i]);
|
||||
}
|
||||
|
||||
i += 3;
|
||||
start = i;
|
||||
continue;
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
if (start >= 0 && start < stream.Length)
|
||||
{
|
||||
AddTrimmed(units, stream[start..]);
|
||||
}
|
||||
|
||||
return units;
|
||||
}
|
||||
|
||||
/// <summary>The NAL units of a sample whose units are each prefixed by a big-endian length.</summary>
|
||||
internal static List<NalUnit> SplitLengthPrefixed(ReadOnlySpan<byte> sample, int lengthSize)
|
||||
{
|
||||
var units = new List<NalUnit>();
|
||||
var offset = 0;
|
||||
while (offset + lengthSize <= sample.Length)
|
||||
{
|
||||
var size = 0;
|
||||
for (var k = 0; k < lengthSize; k++)
|
||||
{
|
||||
size = (size << 8) | sample[offset + k];
|
||||
}
|
||||
|
||||
offset += lengthSize;
|
||||
if (size <= 0 || size > sample.Length - offset)
|
||||
{
|
||||
break; // damaged: keep what was read
|
||||
}
|
||||
|
||||
units.Add(Parse(sample.Slice(offset, size)));
|
||||
offset += size;
|
||||
}
|
||||
|
||||
return units;
|
||||
}
|
||||
|
||||
private static void AddTrimmed(List<NalUnit> units, ReadOnlySpan<byte> nal)
|
||||
{
|
||||
// Zero bytes before the next start code belong to it (four-byte start codes, trailing_zero_8bits).
|
||||
var end = nal.Length;
|
||||
while (end > 0 && nal[end - 1] == 0)
|
||||
{
|
||||
end--;
|
||||
}
|
||||
|
||||
if (end > 0)
|
||||
{
|
||||
units.Add(Parse(nal[..end]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>Slice types (slice_type modulo 5).</summary>
|
||||
internal enum SliceType
|
||||
{
|
||||
P = 0,
|
||||
B = 1,
|
||||
I = 2,
|
||||
SP = 3,
|
||||
SI = 4,
|
||||
}
|
||||
|
||||
/// <summary>A slice header (§7.3.3), with the reference list modifications, weights and marking it carries.</summary>
|
||||
internal sealed class SliceHeader
|
||||
{
|
||||
internal int FirstMb;
|
||||
internal SliceType Type;
|
||||
internal int PpsId;
|
||||
internal int FrameNum;
|
||||
internal bool FieldPic;
|
||||
internal int IdrPicId;
|
||||
internal int PocLsb;
|
||||
internal int DeltaPocBottom;
|
||||
internal int DeltaPoc0;
|
||||
internal int DeltaPoc1;
|
||||
internal bool DirectSpatialMvPred;
|
||||
internal int NumRefIdxActiveL0;
|
||||
internal int NumRefIdxActiveL1;
|
||||
|
||||
/// <summary>ref_pic_list_modification: (modification_of_pic_nums_idc, value) per list.</summary>
|
||||
internal List<(int Idc, int Value)>[] Modifications = [[], []];
|
||||
|
||||
internal int LumaLog2WeightDenom;
|
||||
internal int ChromaLog2WeightDenom;
|
||||
|
||||
/// <summary>Explicit weights [list][refIdx * 3 + component] and offsets; null when there is no pred_weight_table.</summary>
|
||||
internal int[][]? Weights;
|
||||
|
||||
internal int[][]? Offsets;
|
||||
|
||||
internal bool NoOutputOfPriorPics;
|
||||
internal bool LongTermReference;
|
||||
internal bool AdaptiveMarking;
|
||||
|
||||
/// <summary>memory_management_control_operation entries: (operation, value 1, value 2).</summary>
|
||||
internal List<(int Op, int A, int B)> Mmco = [];
|
||||
|
||||
internal int CabacInitIdc;
|
||||
internal int QpDelta;
|
||||
internal int DisableDeblocking;
|
||||
internal int AlphaOffset;
|
||||
internal int BetaOffset;
|
||||
|
||||
internal bool IsIntra => Type is SliceType.I or SliceType.SI;
|
||||
|
||||
internal bool IsB => Type == SliceType.B;
|
||||
|
||||
internal static SliceHeader Parse(RbspReader r, NalUnit nal, IReadOnlyDictionary<int, Sps> sequences, IReadOnlyDictionary<int, Pps> pictures, out Sps sps, out Pps pps)
|
||||
{
|
||||
var h = new SliceHeader { FirstMb = (int)r.ReadUe() };
|
||||
var type = r.ReadUe(9);
|
||||
h.Type = (SliceType)(type % 5);
|
||||
h.PpsId = r.ReadUe(255);
|
||||
if (!pictures.TryGetValue(h.PpsId, out pps!) || !sequences.TryGetValue(pps.SpsId, out sps!))
|
||||
{
|
||||
throw new H264Exception("Slice senza i suoi insiemi di parametri.");
|
||||
}
|
||||
|
||||
if (h.Type is SliceType.SP or SliceType.SI)
|
||||
{
|
||||
throw new H264Exception("Le slice SP e SI non sono gestite.");
|
||||
}
|
||||
|
||||
h.FrameNum = (int)r.Read(sps.Log2MaxFrameNum);
|
||||
if (!sps.FrameMbsOnly)
|
||||
{
|
||||
h.FieldPic = r.ReadFlag();
|
||||
if (h.FieldPic)
|
||||
{
|
||||
throw new H264Exception("I video interlacciati non sono gestiti.");
|
||||
}
|
||||
}
|
||||
|
||||
if (nal.Type == 5)
|
||||
{
|
||||
h.IdrPicId = (int)r.ReadUe();
|
||||
}
|
||||
|
||||
if (sps.PocType == 0)
|
||||
{
|
||||
h.PocLsb = (int)r.Read(sps.Log2MaxPocLsb);
|
||||
if (pps.BottomFieldPicOrderInFramePresent && !h.FieldPic)
|
||||
{
|
||||
h.DeltaPocBottom = r.ReadSe();
|
||||
}
|
||||
}
|
||||
else if (sps.PocType == 1 && !sps.DeltaPicOrderAlwaysZero)
|
||||
{
|
||||
h.DeltaPoc0 = r.ReadSe();
|
||||
if (pps.BottomFieldPicOrderInFramePresent && !h.FieldPic)
|
||||
{
|
||||
h.DeltaPoc1 = r.ReadSe();
|
||||
}
|
||||
}
|
||||
|
||||
if (pps.RedundantPicCntPresent)
|
||||
{
|
||||
r.ReadUe(); // redundant_pic_cnt
|
||||
}
|
||||
|
||||
if (h.IsB)
|
||||
{
|
||||
h.DirectSpatialMvPred = r.ReadFlag();
|
||||
}
|
||||
|
||||
h.NumRefIdxActiveL0 = pps.NumRefIdxL0DefaultActive;
|
||||
h.NumRefIdxActiveL1 = pps.NumRefIdxL1DefaultActive;
|
||||
if (!h.IsIntra)
|
||||
{
|
||||
if (r.ReadFlag())
|
||||
{
|
||||
h.NumRefIdxActiveL0 = r.ReadUe(31) + 1;
|
||||
if (h.IsB)
|
||||
{
|
||||
h.NumRefIdxActiveL1 = r.ReadUe(31) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
ParseModifications(r, h.Modifications[0]);
|
||||
if (h.IsB)
|
||||
{
|
||||
ParseModifications(r, h.Modifications[1]);
|
||||
}
|
||||
}
|
||||
|
||||
if (!h.IsB)
|
||||
{
|
||||
h.NumRefIdxActiveL1 = 0;
|
||||
}
|
||||
|
||||
if (h.IsIntra)
|
||||
{
|
||||
h.NumRefIdxActiveL0 = 0;
|
||||
}
|
||||
|
||||
if ((pps.WeightedPred && h.Type == SliceType.P) || (pps.WeightedBipredIdc == 1 && h.IsB))
|
||||
{
|
||||
ParseWeights(r, h, sps);
|
||||
}
|
||||
|
||||
if (nal.RefIdc != 0)
|
||||
{
|
||||
if (nal.Type == 5)
|
||||
{
|
||||
h.NoOutputOfPriorPics = r.ReadFlag();
|
||||
h.LongTermReference = r.ReadFlag();
|
||||
}
|
||||
else if ((h.AdaptiveMarking = r.ReadFlag()))
|
||||
{
|
||||
for (var guard = 0; guard < 100; guard++)
|
||||
{
|
||||
var op = r.ReadUe(6);
|
||||
if (op == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
int a = 0, b = 0;
|
||||
if (op is 1 or 3)
|
||||
{
|
||||
a = (int)r.ReadUe(); // difference_of_pic_nums_minus1
|
||||
}
|
||||
|
||||
if (op == 2)
|
||||
{
|
||||
a = (int)r.ReadUe(); // long_term_pic_num
|
||||
}
|
||||
|
||||
if (op is 3 or 6)
|
||||
{
|
||||
b = (int)r.ReadUe(); // long_term_frame_idx
|
||||
}
|
||||
|
||||
if (op == 4)
|
||||
{
|
||||
a = (int)r.ReadUe(); // max_long_term_frame_idx_plus1
|
||||
}
|
||||
|
||||
h.Mmco.Add((op, a, b));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (pps.Cabac && !h.IsIntra)
|
||||
{
|
||||
h.CabacInitIdc = r.ReadUe(2);
|
||||
}
|
||||
|
||||
h.QpDelta = r.ReadSe();
|
||||
if (pps.DeblockingFilterControlPresent)
|
||||
{
|
||||
h.DisableDeblocking = r.ReadUe(2);
|
||||
if (h.DisableDeblocking != 1)
|
||||
{
|
||||
h.AlphaOffset = r.ReadSe() * 2;
|
||||
h.BetaOffset = r.ReadSe() * 2;
|
||||
}
|
||||
}
|
||||
|
||||
return h;
|
||||
}
|
||||
|
||||
private static void ParseModifications(RbspReader r, List<(int, int)> list)
|
||||
{
|
||||
if (!r.ReadFlag())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
for (var guard = 0; guard < 100; guard++)
|
||||
{
|
||||
var idc = r.ReadUe(5);
|
||||
if (idc == 3)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (idc > 2)
|
||||
{
|
||||
throw new H264Exception("Modifica della lista di riferimento non gestita.");
|
||||
}
|
||||
|
||||
list.Add((idc, (int)r.ReadUe()));
|
||||
}
|
||||
|
||||
throw new H264Exception("Modifiche della lista di riferimento senza fine.");
|
||||
}
|
||||
|
||||
private static void ParseWeights(RbspReader r, SliceHeader h, Sps sps)
|
||||
{
|
||||
h.LumaLog2WeightDenom = r.ReadUe(7);
|
||||
var chroma = sps.ChromaFormatIdc != 0;
|
||||
if (chroma)
|
||||
{
|
||||
h.ChromaLog2WeightDenom = r.ReadUe(7);
|
||||
}
|
||||
|
||||
h.Weights = new int[2][];
|
||||
h.Offsets = new int[2][];
|
||||
for (var list = 0; list < (h.IsB ? 2 : 1); list++)
|
||||
{
|
||||
var count = list == 0 ? h.NumRefIdxActiveL0 : h.NumRefIdxActiveL1;
|
||||
var weights = new int[count * 3];
|
||||
var offsets = new int[count * 3];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
weights[i * 3] = 1 << h.LumaLog2WeightDenom;
|
||||
weights[(i * 3) + 1] = weights[(i * 3) + 2] = 1 << h.ChromaLog2WeightDenom;
|
||||
if (r.ReadFlag())
|
||||
{
|
||||
weights[i * 3] = r.ReadSe();
|
||||
offsets[i * 3] = r.ReadSe();
|
||||
}
|
||||
|
||||
if (chroma && r.ReadFlag())
|
||||
{
|
||||
for (var c = 1; c <= 2; c++)
|
||||
{
|
||||
weights[(i * 3) + c] = r.ReadSe();
|
||||
offsets[(i * 3) + c] = r.ReadSe();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
h.Weights[list] = weights;
|
||||
h.Offsets[list] = offsets;
|
||||
}
|
||||
|
||||
h.Weights[1] ??= [];
|
||||
h.Offsets[1] ??= [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>Inverse transforms of §8.5.12 and §8.5.13, adding the residual to the prediction already in the plane.</summary>
|
||||
internal static class Transform
|
||||
{
|
||||
/// <summary>Inverse 4×4 transform of scaled coefficients (raster order), added to the 4×4 block at <paramref name="o"/>.</summary>
|
||||
internal static void Add4x4(Span<int> d, byte[] plane, int o, int stride)
|
||||
{
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
var r = d.Slice(i * 4, 4);
|
||||
int e0 = r[0] + r[2], e1 = r[0] - r[2], e2 = (r[1] >> 1) - r[3], e3 = r[1] + (r[3] >> 1);
|
||||
r[0] = e0 + e3;
|
||||
r[1] = e1 + e2;
|
||||
r[2] = e1 - e2;
|
||||
r[3] = e0 - e3;
|
||||
}
|
||||
|
||||
for (var j = 0; j < 4; j++)
|
||||
{
|
||||
int f0 = d[j], f1 = d[4 + j], f2 = d[8 + j], f3 = d[12 + j];
|
||||
int g0 = f0 + f2, g1 = f0 - f2, g2 = (f1 >> 1) - f3, g3 = f1 + (f3 >> 1);
|
||||
AddSample(plane, o + j, g0 + g3);
|
||||
AddSample(plane, o + stride + j, g1 + g2);
|
||||
AddSample(plane, o + (2 * stride) + j, g1 - g2);
|
||||
AddSample(plane, o + (3 * stride) + j, g0 - g3);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Inverse 8×8 transform (§8.5.13), added to the 8×8 block at <paramref name="o"/>.</summary>
|
||||
internal static void Add8x8(Span<int> d, byte[] plane, int o, int stride)
|
||||
{
|
||||
Span<int> tmp = stackalloc int[8];
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
var row = d.Slice(i * 8, 8);
|
||||
Butterfly8(row, row);
|
||||
}
|
||||
|
||||
Span<int> column = stackalloc int[8];
|
||||
for (var j = 0; j < 8; j++)
|
||||
{
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
column[i] = d[(i * 8) + j];
|
||||
}
|
||||
|
||||
Butterfly8(column, tmp);
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
AddSample(plane, o + (i * stride) + j, tmp[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void Butterfly8(ReadOnlySpan<int> d, Span<int> output)
|
||||
{
|
||||
int a0 = d[0] + d[4], a4 = d[0] - d[4], a2 = (d[2] >> 1) - d[6], a6 = d[2] + (d[6] >> 1);
|
||||
int b0 = a0 + a6, b2 = a4 + a2, b4 = a4 - a2, b6 = a0 - a6;
|
||||
var a1 = -d[3] + d[5] - d[7] - (d[7] >> 1);
|
||||
var a3 = d[1] + d[7] - d[3] - (d[3] >> 1);
|
||||
var a5 = -d[1] + d[7] + d[5] + (d[5] >> 1);
|
||||
var a7 = d[3] + d[5] + d[1] + (d[1] >> 1);
|
||||
int b1 = a1 + (a7 >> 2), b7 = a7 - (a1 >> 2), b3 = a3 + (a5 >> 2), b5 = (a3 >> 2) - a5;
|
||||
output[0] = b0 + b7;
|
||||
output[1] = b2 + b5;
|
||||
output[2] = b4 + b3;
|
||||
output[3] = b6 + b1;
|
||||
output[4] = b6 - b1;
|
||||
output[5] = b4 - b3;
|
||||
output[6] = b2 - b5;
|
||||
output[7] = b0 - b7;
|
||||
}
|
||||
|
||||
/// <summary>Inverse 4×4 Hadamard transform of the Intra_16x16 DC coefficients (§8.5.10), in place, raster order.</summary>
|
||||
internal static void Hadamard4x4(Span<int> c)
|
||||
{
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
var r = c.Slice(i * 4, 4);
|
||||
int e0 = r[0] + r[1], e1 = r[0] - r[1], e2 = r[2] + r[3], e3 = r[2] - r[3];
|
||||
r[0] = e0 + e2;
|
||||
r[1] = e0 - e2;
|
||||
r[2] = e1 - e3;
|
||||
r[3] = e1 + e3;
|
||||
}
|
||||
|
||||
// The matrix is [1 1 1 1; 1 1 -1 -1; 1 -1 -1 1; 1 -1 1 -1]: rows above, then columns.
|
||||
for (var j = 0; j < 4; j++)
|
||||
{
|
||||
int f0 = c[j], f1 = c[4 + j], f2 = c[8 + j], f3 = c[12 + j];
|
||||
int e0 = f0 + f1, e1 = f0 - f1, e2 = f2 + f3, e3 = f2 - f3;
|
||||
c[j] = e0 + e2;
|
||||
c[4 + j] = e0 - e2;
|
||||
c[8 + j] = e1 - e3;
|
||||
c[12 + j] = e1 + e3;
|
||||
}
|
||||
}
|
||||
|
||||
private static void AddSample(byte[] plane, int index, int residual)
|
||||
{
|
||||
var v = plane[index] + ((residual + 32) >> 6);
|
||||
plane[index] = (byte)(v < 0 ? 0 : v > 255 ? 255 : v);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user