namespace Febe.Core.Codecs.H264;
///
/// 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 ): interlaced
/// pictures (fields and MBAFF), slice groups, SP/SI slices, data partitioning, 4:2:2/4:4:4 and depths above 8 bits.
///
public sealed partial class H264Decoder
{
private readonly Dictionary sequences = [];
private readonly Dictionary pictures = [];
private readonly List dpb = [];
private readonly Stack 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;
/// Which frames to hand out, by decoding index; null hands out all of them.
public Func? Wanted { get; set; }
/// Raised for each decoded frame that accepts, in decoding order.
public event Action? FrameDecoded;
/// Frames decoded so far (including those not handed out).
public long FramesDecoded => decodeCounter;
/// Decodes a whole Annex B byte stream (start codes), then flushes the last picture.
public void DecodeAnnexB(ReadOnlySpan stream)
{
foreach (var nal in NalUnits.SplitAnnexB(stream))
{
Decode(nal);
}
Flush();
}
///
/// Reads the SPS and PPS of an avcC box (AVCDecoderConfigurationRecord); returns the size of the NAL length
/// fields of the samples.
///
public int ConfigureAvcC(ReadOnlySpan 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;
}
/// Decodes one access unit stored with length prefixes (an MP4 or Matroska sample) and finishes its picture.
public void DecodeSample(ReadOnlySpan sample, int lengthSize)
{
foreach (var nal in NalUnits.SplitLengthPrefixed(sample, lengthSize))
{
Decode(nal);
}
FinishPicture();
}
/// Decodes one access unit in Annex B form and finishes its picture.
public void DecodeAccessUnitAnnexB(ReadOnlySpan accessUnit)
{
foreach (var nal in NalUnits.SplitAnnexB(accessUnit))
{
Decode(nal);
}
FinishPicture();
}
/// Finishes the picture being decoded, if any.
public void Flush() => FinishPicture();
///
/// Finishes the picture being decoded; a damaged picture whose deblocking or cropping fails raises an
/// like the rest of the stream, and is dropped.
///
private void FinishPicture()
{
try
{
CompletePicture();
}
catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException)
{
cur = null;
picHeader = null;
throw new H264Exception("Flusso H.264 troncato o danneggiato.");
}
}
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 (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException)
{
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);
}
/// Picture order count (§8.2.1) of the picture starting now.
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;
}
}
/// Frames inferred for a gap in frame_num (§8.2.5.2): only their marking matters.
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 CompletePicture()
{
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);
}
/// Decoded reference picture marking (§8.2.5) of the picture just decoded.
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);
LimitReferences(picture, sps);
}
///
/// A stream may never keep more than Max(max_num_ref_frames, 1) reference frames (§8.2.5.4 and §7.4.2.1.1); a damaged
/// one whose marking operations never release any would make the buffer grow with every picture. Here the oldest
/// references beyond the limit are released, as the sliding window would.
///
private void LimitReferences(Picture current, Sps sps)
{
var limit = Math.Max(1, sps.MaxNumRefFrames);
while (true)
{
var count = 0;
Picture? oldestShort = null, oldestLong = null;
foreach (var p in dpb)
{
if (!p.IsReference)
{
continue;
}
count++;
if (ReferenceEquals(p, current))
{
continue;
}
if (p.ShortTerm && (oldestShort is null || p.FrameNumWrap < oldestShort.FrameNumWrap))
{
oldestShort = p;
}
else if (p.LongTerm && (oldestLong is null || p.LongTermFrameIdx < oldestLong.LongTermFrameIdx))
{
oldestLong = p;
}
}
if (count <= limit || (oldestShort ?? oldestLong) is not { } victim)
{
return;
}
victim.ShortTerm = victim.LongTerm = false;
}
}
/// Sliding window marking (§8.2.5.3) before a new short-term frame is added.
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;
}
}
}
/// Drops the pictures no longer used for reference from the buffer (they are already handed out).
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);
}
}
}
/// Reference picture lists of the slice (§8.2.4): initialisation, then modification.
private void BuildReferenceLists(SliceHeader h, Sps sps)
{
var picture = cur!;
UpdateFrameNumWrap(h.FrameNum, sps);
var shortTerm = new List();
var longTerm = new List();
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 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 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;
}
}