namespace Febe.Core.Codecs.H264;
/// What an access unit offers to start decoding from (see ).
public enum H264AccessPoint
{
/// A P or B picture, or no picture: decoding cannot start here.
None,
/// A picture of I slices that is not IDR: the pictures after it may still refer to earlier ones.
IntraPicture,
/// An IDR picture: nothing after it refers to anything before.
Idr,
}
///
/// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Extended, Main and the High
/// profiles — 4:2:0, 4:2:2, 4:4:4 (also with the colour planes coded separately) and monochrome, 8 to 14 bits per sample,
/// lossless macroblocks (qpprime_y_zero_transform_bypass_flag) — CAVLC and CABAC, I, P and B slices, 8×8 transform and
/// scaling matrices, spatial
/// and temporal direct prediction, list modification, memory management operations and long-term references,
/// deblocking — for progressive frames and for interlaced video: field pictures, frames and fields mixed picture by
/// picture (PAFF), frames of frame and field macroblock pairs (MBAFF). Frames come out whole: the two fields of a pair are
/// interleaved. The tools of Baseline and Extended: slice groups (FMO, map types 0–6), slices in any order (ASO), SP and
/// SI slices (switching pictures), slice data partitioning (NAL units 2–4); redundant coded pictures are skipped, the
/// primary one is decoded. Written from the standard but not yet checked against a conformance stream: explicit and
/// implicit weighted prediction, gaps in frame_num, I_PCM, SI macroblocks and sp_for_switch_flag, data partitioning
/// (checked only on conformance streams split into partitions), 4:4:4, separate colour planes, lossless coding and bit
/// depths above 10. Not handled (an ): CABAC in 4:4:4 with the colour planes coded together
/// (its contexts 460–1023 are not transcribed yet), SP and SI slices outside 4:2:0 at 8 bits.
/// Multiview streams (MVC, Annex H): every view, with inter-view prediction (see H264Decoder.Mvc.cs), each frame tagged
/// with its ; false gives the base view only. Scalable streams
/// (SVC, Annex G): the base layer always, and above it the quality refinements of the base resolution (MGS, CAVLC); the
/// other enhancement layers are left out and says why (see H264Decoder.Svc.cs).
///
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;
/// The frame store being decoded into (a frame, or one field of it).
private Picture? cur;
/// The structure of the picture being decoded: 0 frame, 1 top field, 2 bottom field.
private int curStructure;
/// The picture being decoded is the second field of .
private bool curSecondField;
/// A first field already decoded, waiting for the second field of its frame.
private Picture? openField;
private int openStructure;
private int openRefIdc;
private SliceHeader? picHeader;
private int picNalType;
private int picRefIdc;
private bool picMmco5;
private bool picSkipped;
private int sliceCounter;
/// The RBSP of the NAL unit being decoded: one buffer for the whole stream.
private byte[]? rbsp;
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. A picture that is not used for reference
/// and is not wanted is not reconstructed at all: only its header counts. In an MVC stream decoded with
/// the same filter applies to every view, each with its own decoding index
/// ( counts the view components of a view): when every access unit has all the
/// views, index n of each view is the n-th access unit.
///
public Func? Wanted
{
get => root is null ? wanted : root.Wanted;
set => wanted = value;
}
private Func? wanted;
/// 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)
{
DecodeUnitsAnnexB(stream);
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.Unescape(avcC.Slice(offset, size), ref rbsp));
offset += size;
}
}
return lengthSize;
}
///
/// Decodes one access unit stored with length prefixes (an MP4 or Matroska sample) and finishes its picture. A
/// sample holding only the first field of a frame leaves it waiting for the second one, in the next sample.
///
public void DecodeSample(ReadOnlySpan sample, int lengthSize)
{
var position = 0;
while (NalUnits.NextLengthPrefixed(sample, lengthSize, ref position, out var unit))
{
Decode(NalUnits.Unescape(sample[unit], ref rbsp));
}
FinishAccessUnit();
}
/// Decodes one access unit in Annex B form and finishes its picture (as ).
public void DecodeAccessUnitAnnexB(ReadOnlySpan accessUnit)
{
DecodeUnitsAnnexB(accessUnit);
FinishAccessUnit();
}
/// Finishes the picture of every view of the access unit.
private void FinishAccessUnit()
{
FinishPicture();
FinishViews();
}
///
/// Whether decoding can start at this access unit: exactly at an IDR picture; only approximately at a picture whose
/// first slice is an I slice, since the pictures after it may still refer to earlier ones.
/// is the size of the NAL length fields, 0 for Annex B.
///
public static H264AccessPoint AccessPoint(ReadOnlySpan accessUnit, int lengthSize)
{
var position = 0;
while (true)
{
Range unit;
var more = lengthSize == 0
? NalUnits.NextAnnexB(accessUnit, ref position, out unit)
: NalUnits.NextLengthPrefixed(accessUnit, lengthSize, ref position, out unit);
if (!more)
{
return H264AccessPoint.None;
}
var nal = accessUnit[unit];
switch (nal[0] & 0x1F)
{
case 5:
return H264AccessPoint.Idr;
case 1:
case 2: // partition A starts like a slice
try
{
// first_mb_in_slice and slice_type: a few bytes of the header are enough.
var reader = NalUnits.Parse(nal[..Math.Min(nal.Length, 16)]).Reader();
_ = reader.ReadUe();
return (SliceType)(reader.ReadUe(9) % 5) is SliceType.I or SliceType.SI ? H264AccessPoint.IntraPicture : H264AccessPoint.None;
}
catch (H264Exception)
{
return H264AccessPoint.None;
}
}
}
}
private void DecodeUnitsAnnexB(ReadOnlySpan stream)
{
var position = 0;
while (NalUnits.NextAnnexB(stream, ref position, out var unit))
{
Decode(NalUnits.Unescape(stream[unit], ref rbsp));
}
}
/// Finishes the picture being decoded, if any, and hands out a first field still waiting for its pair.
public void Flush()
{
FinishPicture();
if (openField is { } field)
{
openField = null;
HandOut(field, activeSps!);
}
FlushViews();
}
///
/// 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
{
if (partitionPending)
{
DecodePartitionedSlice();
}
CompletePicture();
}
catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException or NullReferenceException)
{
cur = null;
picHeader = null;
openField = null;
throw new H264Exception("Flusso H.264 troncato o danneggiato.");
}
}
/// Decodes one NAL unit (with its header, without start code) and leaves the picture open: for the tests.
internal void DecodeUnit(ReadOnlySpan nal) => Decode(NalUnits.Unescape(nal, ref rbsp));
private void Decode(NalUnit nal)
{
try
{
// The partitions B and C of a slice follow its partition A: anything else completes it.
if (partitionPending && nal.Type is not (3 or 4))
{
DecodePartitionedSlice();
}
switch (nal.Type)
{
case 1:
case 5:
if (viewDecoders.Count > 0)
{
// The base view opens a new access unit: the view components of the last one are complete.
FinishViews();
}
DecodeSlice(nal);
break;
case 14:
if (nal.HeaderLength == 4 && nal.IsSvc)
{
ReadSvcPrefix(nal);
}
else
{
ReadPrefix(nal);
}
break;
case 15:
{
var subset = Sps.ParseSubset(nal.Reader());
subsetSequences[subset.Id] = subset;
multiview |= subset.Mvc is not null;
scalable |= subset.Svc is not null;
break;
}
case 20:
if (nal.HeaderLength == 4 && nal.IsSvc)
{
DecodeSvcSlice(nal);
}
else
{
DecodeViewSlice(nal);
}
break;
case 2:
StorePartitionA(nal);
break;
case 3:
case 4:
StorePartition(nal);
break;
case 7:
{
var sps = Sps.Parse(nal.Reader());
sequences[sps.Id] = sps;
break;
}
case 8:
{
var pps = Pps.Parse(nal.Reader(), sequences, subsetSequences);
pictures[pps.Id] = pps;
break;
}
case 11: // end of stream
Flush();
break;
}
}
catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException or NullReferenceException)
{
throw new H264Exception("Flusso H.264 troncato o danneggiato.");
}
}
private void DecodeSlice(NalUnit nal)
{
var reader = nal.Reader();
var header = ParseSliceHeader(reader, nal, out var sps, out var pps);
// A redundant coded picture (§7.4.3) repeats the primary one, which is decoded: it is skipped.
if (header.RedundantPicCnt > 0)
{
return;
}
DecodeParsedSlice(nal, reader, header, sps, pps);
}
private SliceHeader ParseSliceHeader(RbspReader reader, NalUnit nal, out Sps sps, out Pps pps)
{
return SliceHeader.Parse(reader, nal, sequences, pictures, out sps, out pps);
}
/// A slice whose header is read: the picture it belongs to, then its macroblocks.
private void DecodeParsedSlice(NalUnit nal, RbspReader reader, SliceHeader header, Sps sps, Pps pps)
{
if (cur is null || picHeader is null || StartsNewPicture(header, nal) || FirstMacroblockDone(header, sps))
{
FinishPicture();
StartPicture(nal, header, sps);
}
if (picSkipped)
{
return;
}
if (separatePlanes)
{
SelectColourPlane(header.ColourPlaneId);
}
if (!header.IsIntra && !HasReference())
{
// A P or B slice without any picture to predict from: decoding started away from a random access point
// (a missing index, a damaged stream). Predicting from nothing would give a corrupt frame.
throw new H264Exception("Slice P o B senza immagini di riferimento.");
}
DecodeSliceData(reader, nal, header, sps, pps);
}
/// The first slice of a new primary picture (§7.4.1.2.4), compared with the first slice of the current one.
private bool StartsNewPicture(SliceHeader h, NalUnit nal)
{
var p = picHeader!;
if (h.FrameNum != p.FrameNum || h.PpsId != p.PpsId || h.FieldPic != p.FieldPic || h.BottomField != p.BottomField
|| (nal.RefIdc == 0) != (picRefIdc == 0) || (nal.Type == 5) != (picNalType == 5) || (nal.Type == 5 && h.IdrPicId != p.IdrPicId))
{
return true;
}
return activeSps!.PocType switch
{
0 => h.PocLsb != p.PocLsb || h.DeltaPocBottom != p.DeltaPocBottom,
1 => h.DeltaPoc0 != p.DeltaPoc0 || h.DeltaPoc1 != p.DeltaPoc1,
_ => false,
};
}
/// A slice starting on a macroblock already decoded: the previous picture lost its end, this is a new one.
private bool FirstMacroblockDone(SliceHeader h, Sps sps)
{
if (!ReferenceEquals(sps, activeSps) || mbSlice.Length != sps.WidthInMbs * sps.HeightInMbs)
{
return false;
}
// Colour planes coded separately: the macroblocks of the plane of the slice.
var slices = separatePlanes ? planeStates[h.ColourPlaneId].Slice : mbSlice;
var w = sps.WidthInMbs;
int index;
if (h.FieldPic)
{
index = (((2 * (h.FirstMb / w)) + (h.BottomField ? 1 : 0)) * w) + (h.FirstMb % w);
}
else if (sps.MbAdaptiveFrameField)
{
index = (2 * (h.FirstMb / w) * w) + (h.FirstMb % w);
}
else
{
index = h.FirstMb;
}
return (uint)index < (uint)slices.Length && slices[index] >= 0;
}
/// Whether a picture other than the one being decoded can be predicted from.
private bool HasReference()
{
if (root is not null && HasInterViewReference())
{
return true;
}
foreach (var p in dpb)
{
if (!ReferenceEquals(p, cur))
{
if (p.IsReference)
{
return true;
}
}
else if (curStructure != 0 && ((p.ShortMask | p.LongMask) & (3 - curStructure)) != 0)
{
return true; // the first field of the frame
}
}
return false;
}
private void StartPicture(NalUnit nal, SliceHeader header, Sps sps)
{
if (activeSps is null || !ReferenceEquals(activeSps, sps))
{
if (activeSps is null || !SameLayout(activeSps, sps))
{
if (openField is { } waiting && activeSps is not null)
{
openField = null;
HandOut(waiting, activeSps);
}
dpb.Clear();
pool.Clear();
AllocateMacroblockState(sps.WidthInMbs, sps.HeightInMbs, sps.SeparateColourPlane ? 3 : 1);
}
activeSps = sps;
ConfigureFormat(sps);
}
var idr = nal.Type == 5;
var structure = header.Structure;
// The second field of a frame (§3.30, §3.31): the field after a first field of the opposite parity, with the same
// frame_num, both reference fields or both not, and not an IDR picture (which would release the first one).
curSecondField = false;
if (openField is { } first)
{
openField = null;
if (structure != 0 && structure != openStructure && header.FrameNum == first.FrameNum && !idr
&& (nal.RefIdc != 0) == (openRefIdc != 0))
{
cur = first;
curSecondField = true;
}
else
{
HandOut(first, sps);
}
}
if (!curSecondField)
{
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;
cur.CodedAsFields = structure != 0;
cur.Decoded = 0;
cur.Skipped = false;
}
var picture = cur!;
NoteViewComponent(picture);
picDqId = 0;
picSvcStopped = false;
curStructure = structure;
picHeader = header;
picNalType = nal.Type;
picRefIdc = nal.RefIdc;
picMmco5 = header.Mmco.Exists(m => m.Op == 5);
ComputePoc(picture, header, nal, sps, idr, structure);
picture.Decoded |= structure == 0 ? 3 : structure;
sliceCounter = 0;
sliceFilters.Clear();
sliceSwitching.Clear();
anySwitching = false;
foreach (var state in planeStates)
{
Array.Fill(state.Slice, -1);
}
// A picture nobody refers to and nobody wants: its header has set the state above, its slices are not decoded.
picSkipped = nal.RefIdc == 0 && !NeededByOtherViews && Wanted is { } wanted && !wanted(picture.DecodeIndex);
if (picSkipped)
{
picture.Skipped = true;
}
}
private Picture NewPicture(Sps sps)
{
while (pool.Count > 0)
{
var p = pool.Pop();
if (p.Fits(sps.WidthInMbs, sps.HeightInMbs, sps.ChromaFormatIdc, BytesPerSample, PlaneCount(sps)) && !p.InDpb && !ReferenceEquals(p, openField))
{
p.ShortMask = p.LongMask = 0;
p.NonExisting = false;
p.ClearReferences();
return p;
}
}
return new Picture(sps.WidthInMbs, sps.HeightInMbs, sps.ChromaFormatIdc, BytesPerSample, PlaneCount(sps));
}
private int BytesPerSample => wide ? 2 : 1;
private static int PlaneCount(Sps sps) => sps.SeparateColourPlane ? 3 : 1;
/// Two sequences whose pictures and macroblock data have the same shape: size, chroma format, sample size.
private static bool SameLayout(Sps a, Sps b) =>
a.WidthInMbs == b.WidthInMbs && a.HeightInMbs == b.HeightInMbs && a.ChromaFormatIdc == b.ChromaFormatIdc
&& a.SeparateColourPlane == b.SeparateColourPlane && SampleBytes(a) == SampleBytes(b);
/// Bytes of each stored sample of a sequence: 2 when luma, or chroma if present, has more than 8 bits.
private static int SampleBytes(Sps s) =>
s.BitDepthLuma > 8 || (s.ChromaFormatIdc != 0 && !s.SeparateColourPlane && s.BitDepthChroma > 8) ? 2 : 1;
/// Picture order count (§8.2.1) of the picture starting now, into the fields of it codes.
private void ComputePoc(Picture p, SliceHeader h, NalUnit nal, Sps sps, bool idr, int structure)
{
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 = bottom = pocMsb + h.PocLsb;
if (structure == 0)
{
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;
}
if (structure == 0)
{
top = expected + h.DeltaPoc0;
bottom = top + sps.OffsetForTopToBottomField + h.DeltaPoc1;
}
else
{
top = expected + h.DeltaPoc0;
bottom = expected + sps.OffsetForTopToBottomField + h.DeltaPoc0;
}
break;
}
default:
{
UpdateFrameNumOffset(h, sps, idr);
top = bottom = idr ? 0 : nal.RefIdc == 0 ? (2 * (frameNumOffset + h.FrameNum)) - 1 : 2 * (frameNumOffset + h.FrameNum);
break;
}
}
if (structure != 2)
{
p.TopPoc = top;
}
if (structure != 1)
{
p.BottomPoc = 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, and their frame number offset
/// (§8.2.1), which carries the wraps of frame_num to the pictures after the gap. Of a gap longer than the buffer only
/// the last frames can stay references: the earlier ones are counted, never allocated.
///
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);
if (missing > keep)
{
foreach (var p in dpb)
{
p.ShortMask = 0;
}
}
var skipped = missing - keep;
var i = 0;
for (var n = (prevRefFrameNum + 1) % max; n != frameNum; n = (n + 1) % max, i++)
{
if (sps.PocType != 0)
{
// UpdateFrameNumOffset for the inferred frame n (never an IDR picture).
frameNumOffset = prevFrameNum > n ? prevFrameNumOffset + max : prevFrameNumOffset;
prevFrameNumOffset = frameNumOffset;
}
prevRefFrameNum = n;
prevFrameNum = n;
if (i < skipped)
{
continue;
}
var gap = NewPicture(sps);
gap.FrameNum = n;
gap.NonExisting = true;
gap.Period = period;
gap.TopPoc = gap.BottomPoc = 0;
gap.Decoded = 3;
gap.CodedAsFields = false;
gap.MarkAsGap();
SlidingWindow(sps, n, null);
gap.ShortMask = 3;
AddToDpb(gap);
}
PruneDpb();
}
private void CompletePicture()
{
if (cur is null || picHeader is null || activeSps is null)
{
return;
}
var sps = activeSps;
var picture = cur;
var structure = curStructure;
var skipped = picSkipped;
picSkipped = false;
if (!skipped)
{
Deblock(picture);
}
if (picRefIdc != 0)
{
MarkReferences(picture, sps);
}
// State for the next picture.
if (picMmco5)
{
// After a memory_management_control_operation 5 the picture counts as frame_num 0 with its order count
// brought to 0 (tempPicOrderCnt of §8.2.1).
var temp = structure == 1 ? picture.TopPoc : structure == 2 ? picture.BottomPoc : Math.Min(picture.TopPoc, picture.BottomPoc);
if (structure != 2)
{
picture.TopPoc -= temp;
}
if (structure != 1)
{
picture.BottomPoc -= temp;
}
prevPocMsb = 0;
prevPocLsb = structure == 2 ? 0 : picture.TopPoc;
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;
}
cur = null;
picHeader = null;
if (structure != 0 && !curSecondField)
{
// A first field: the frame comes out with its second field.
openField = picture;
openStructure = structure;
openRefIdc = picRefIdc;
}
else
{
HandOut(picture, sps);
}
curSecondField = false;
PruneDpb();
}
/// Hands out a finished frame (or a field left without its pair) and counts it.
private void HandOut(Picture picture, Sps sps)
{
if (!picture.Skipped && (Wanted?.Invoke(picture.DecodeIndex) ?? true))
{
FrameDecoded?.Invoke(Crop(picture, sps, viewId));
}
decodeCounter++;
if (!picture.IsReference && !picture.InDpb)
{
pool.Push(picture);
}
}
///
/// The frame of a picture, cropped (§7.4.2.1.1, CropUnitX and CropUnitY). A monochrome frame gets chroma planes of
/// 4:2:0 size at the middle value, the rows of a field without its pair the middle value too, as the reference
/// decoder writes them; colour planes coded separately come out as 4:4:4 with the luma bit depth.
///
private static H264Frame Crop(Picture p, Sps sps, int viewId)
{
var bps = p.BytesPerSample;
var format = sps.ChromaFormatIdc;
var bitDepthY = sps.BitDepthLuma;
var bitDepthC = format == 0 || sps.SeparateColourPlane ? bitDepthY : sps.BitDepthChroma;
int unitX = sps.CropUnitX, unitY = sps.CropUnitY;
var left = sps.CropLeft * unitX;
var top = sps.CropTop * unitY;
var width = Math.Max(2, p.Width - left - (sps.CropRight * unitX));
var height = Math.Max(2, p.Height - top - (sps.CropBottom * unitY));
var y = CopyRect(p.Y, p.Width, left, top, width, height, bps);
byte[] cb, cr;
int ch, chromaTop;
if (format == 0)
{
int cw = (width + 1) / 2;
ch = (height + 1) / 2;
chromaTop = 0;
cb = new byte[cw * ch * bps];
FillMiddle(cb, bps, bitDepthC);
cr = (byte[])cb.Clone();
}
else
{
int subW = sps.SubWidthC, subH = sps.SubHeightC;
var cw = (width + subW - 1) / subW;
ch = (height + subH - 1) / subH;
chromaTop = top / subH;
cb = CopyRect(p.Cb, p.ChromaWidth, left / subW, chromaTop, cw, ch, bps);
cr = CopyRect(p.Cr, p.ChromaWidth, left / subW, chromaTop, cw, ch, bps);
}
if (p.Decoded != 3)
{
// A field without its pair: the rows of the missing field are grey (the middle value), since the stream has none
// for them and the decoder does not invent any; H.264 leaves the output of an unpaired field open.
var missing = p.Decoded == 1 ? 1 : 0;
var rowY = width * bps;
for (var r = 0; r < height; r++)
{
if (((top + r) & 1) == missing)
{
FillMiddle(y.AsSpan(r * rowY, rowY), bps, bitDepthY);
}
}
if (format != 0)
{
var rowC = cb.Length / ch;
for (var r = 0; r < ch; r++)
{
if (((chromaTop + r) & 1) == missing)
{
FillMiddle(cb.AsSpan(r * rowC, rowC), bps, bitDepthC);
FillMiddle(cr.AsSpan(r * rowC, rowC), bps, bitDepthC);
}
}
}
}
return new H264Frame(width, height, y, cb, cr, p.Poc, p.Period, p.DecodeIndex, sps.MatrixCoefficients, sps.FullRange, format, bitDepthY, bitDepthC, viewId);
}
/// A × rectangle of a plane samples wide.
private static byte[] CopyRect(byte[] plane, int stride, int left, int top, int width, int height, int bps)
{
var result = new byte[width * height * bps];
for (var r = 0; r < height; r++)
{
Array.Copy(plane, (((top + r) * stride) + left) * bps, result, r * width * bps, width * bps);
}
return result;
}
/// Samples at the middle value 2^(bitDepth − 1).
private static void FillMiddle(Span samples, int bps, int bitDepth)
{
if (bps == 1)
{
samples.Fill((byte)(1 << (bitDepth - 1)));
}
else
{
System.Runtime.InteropServices.MemoryMarshal.Cast(samples).Fill((ushort)(1 << (bitDepth - 1)));
}
}
private void AddToDpb(Picture p)
{
if (!p.InDpb)
{
p.InDpb = true;
dpb.Add(p);
}
}
/// The bit of a field in the masks of : 1 top, 2 bottom, 3 the frame.
private static int FieldBit(int structure) => structure == 0 ? 3 : structure;
/// Decoded reference picture marking (§8.2.5) of the picture (frame or field) just decoded.
private void MarkReferences(Picture picture, Sps sps)
{
var h = picHeader!;
var bit = FieldBit(curStructure);
if (picNalType == 5)
{
foreach (var p in dpb)
{
if (!ReferenceEquals(p, picture))
{
p.ShortMask = p.LongMask = 0;
}
}
if (h.LongTermReference)
{
picture.LongMask |= bit;
picture.LongTermFrameIdx = 0;
maxLongTermFrameIdx = 0;
}
else
{
picture.ShortMask |= bit;
maxLongTermFrameIdx = -1;
}
AddToDpb(picture);
return;
}
var becameLongTerm = false;
if (h.AdaptiveMarking)
{
becameLongTerm = ApplyMmco(picture, h, sps, bit);
if (picMmco5)
{
period++;
picture.Period = period;
}
}
else if (!(curSecondField && (picture.ShortMask & (3 - bit)) != 0))
{
// The second field of a pair whose first field is a short-term reference joins it without the sliding window.
SlidingWindow(sps, picture.FrameNum, picture);
}
if (!becameLongTerm)
{
picture.ShortMask |= bit;
}
AddToDpb(picture);
LimitReferences(picture, sps);
}
/// The memory management control operations of the picture (§8.2.5.4); true when it became long-term.
private bool ApplyMmco(Picture picture, SliceHeader h, Sps sps, int bit)
{
var field = curStructure != 0;
var parity = curStructure == 2 ? 1 : 0;
var currPicNum = field ? (2 * h.FrameNum) + 1 : h.FrameNum;
var becameLongTerm = false;
UpdateFrameNumWrap(h.FrameNum, sps);
foreach (var (op, a, b) in h.Mmco)
{
switch (op)
{
case 1:
{
var picNumX = currPicNum - (a + 1);
if (FindShortTerm(picNumX, field, parity, out var p, out var q))
{
p.ShortMask &= ~q;
}
break;
}
case 2:
if (FindLongTerm(a, field, parity, out var lp, out var lq))
{
lp.LongMask &= ~lq;
}
break;
case 3:
{
var picNumX = currPicNum - (a + 1);
if (!FindShortTerm(picNumX, field, parity, out var p, out var q))
{
break;
}
// LongTermFrameIdx b goes to this picture: any other frame or field holding it is released, unless
// it is the other field of the same frame.
foreach (var other in dpb)
{
if (other.LongMask != 0 && other.LongTermFrameIdx == b && !ReferenceEquals(other, p))
{
other.LongMask = 0;
}
}
if (p.LongMask != 0 && p.LongTermFrameIdx != b)
{
p.LongMask = 0;
}
p.ShortMask &= ~q;
p.LongMask |= q;
p.LongTermFrameIdx = b;
break;
}
case 4:
maxLongTermFrameIdx = a - 1;
foreach (var p in dpb)
{
if (p.LongMask != 0 && p.LongTermFrameIdx > maxLongTermFrameIdx)
{
p.LongMask = 0;
}
}
break;
case 5:
foreach (var p in dpb)
{
if (!ReferenceEquals(p, picture))
{
p.ShortMask = p.LongMask = 0;
}
}
// The first field of the frame, too: after this operation nothing before the picture is a reference.
picture.ShortMask = picture.LongMask = 0;
maxLongTermFrameIdx = -1;
break;
case 6:
foreach (var p in dpb)
{
if (p.LongMask != 0 && p.LongTermFrameIdx == b && !ReferenceEquals(p, picture))
{
p.LongMask = 0;
}
}
if (picture.LongMask != 0 && picture.LongTermFrameIdx != b)
{
picture.LongMask = 0;
}
picture.LongMask |= bit;
picture.LongTermFrameIdx = b;
becameLongTerm = true;
break;
}
}
return becameLongTerm;
}
/// The short-term frame (or field) whose PicNum is (§8.2.4.1); q is its mask bit.
private bool FindShortTerm(int picNum, bool field, int parity, out Picture p, out int q)
{
foreach (var candidate in dpb)
{
if (!field)
{
if (candidate.ShortMask == 3 && candidate.FrameNumWrap == picNum)
{
(p, q) = (candidate, 3);
return true;
}
continue;
}
for (var f = 0; f < 2; f++)
{
if ((candidate.ShortMask & (1 << f)) != 0 && (2 * candidate.FrameNumWrap) + (f == parity ? 1 : 0) == picNum)
{
(p, q) = (candidate, 1 << f);
return true;
}
}
}
(p, q) = (null!, 0);
return false;
}
/// The long-term frame (or field) whose LongTermPicNum is .
private bool FindLongTerm(int longTermPicNum, bool field, int parity, out Picture p, out int q)
{
foreach (var candidate in dpb)
{
if (!field)
{
if (candidate.LongMask == 3 && candidate.LongTermFrameIdx == longTermPicNum)
{
(p, q) = (candidate, 3);
return true;
}
continue;
}
for (var f = 0; f < 2; f++)
{
if ((candidate.LongMask & (1 << f)) != 0 && (2 * candidate.LongTermFrameIdx) + (f == parity ? 1 : 0) == longTermPicNum)
{
(p, q) = (candidate, 1 << f);
return true;
}
}
}
(p, q) = (null!, 0);
return false;
}
///
/// 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.ShortMask != 0 && (oldestShort is null || p.FrameNumWrap < oldestShort.FrameNumWrap))
{
oldestShort = p;
}
else if (p.ShortMask == 0 && (oldestLong is null || p.LongTermFrameIdx < oldestLong.LongTermFrameIdx))
{
oldestLong = p;
}
}
if (count <= limit || (oldestShort ?? oldestLong) is not { } victim)
{
return;
}
victim.ShortMask = victim.LongMask = 0;
}
}
///
/// Sliding window marking (§8.2.5.3) before a new short-term picture is added: frames, field pairs and single fields
/// count as one each; the frame store of the current picture () is not removed.
///
private void SlidingWindow(Sps sps, int frameNum, Picture? current)
{
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.ShortMask != 0)
{
shortCount++;
if (!ReferenceEquals(p, current) && (oldest is null || p.FrameNumWrap < oldest.FrameNumWrap))
{
oldest = p;
}
}
else if (p.LongMask != 0)
{
longCount++;
}
}
if (shortCount + longCount < limit || oldest is null)
{
return;
}
oldest.ShortMask = 0;
}
}
private void UpdateFrameNumWrap(int frameNum, Sps sps)
{
foreach (var p in dpb)
{
if (p.ShortMask != 0)
{
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) && !ReferenceEquals(p, openField))
{
dpb.RemoveAt(i);
p.InDpb = false;
pool.Push(p);
}
}
}
/// Reference picture lists of the slice (§8.2.4): initialisation, then modification.
private void BuildReferenceLists(SliceHeader h, Sps sps)
{
UpdateFrameNumWrap(h.FrameNum, sps);
if (curStructure == 0)
{
BuildFrameLists(h, sps);
}
else
{
BuildFieldLists(h, sps);
}
}
private void BuildFrameLists(SliceHeader h, Sps sps)
{
var picture = cur!;
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.IsP)
{
shortTerm.Sort((a, b) => b.PicNum.CompareTo(a.PicNum));
foreach (var p in shortTerm)
{
init0.Add(new RefEntry(p, -1));
}
foreach (var p in longTerm)
{
init0.Add(new RefEntry(p, -1));
}
}
else
{
var poc = picture.Poc;
var before = shortTerm.FindAll(p => p.Poc < poc);
var after = shortTerm.FindAll(p => p.Poc > poc);
before.Sort((a, b) => b.Poc.CompareTo(a.Poc));
after.Sort((a, b) => a.Poc.CompareTo(b.Poc));
foreach (var p in (List)[.. before, .. after, .. longTerm])
{
init0.Add(new RefEntry(p, -1));
}
foreach (var p in (List)[.. after, .. before, .. longTerm])
{
init1.Add(new RefEntry(p, -1));
}
SwapIfSame(init0, init1);
}
AppendInterView(init0, 0);
refList[0] = Modify(init0, 0, h.NumRefIdxActiveL0, h.Modifications[0], h, sps);
if (h.IsB)
{
AppendInterView(init1, 1);
}
refList[1] = h.IsB ? Modify(init1, 1, h.NumRefIdxActiveL1, h.Modifications[1], h, sps) : [];
}
/// Lists of a field picture (§8.2.4.2.2, §8.2.4.2.4 and §8.2.4.2.5): frames ordered, then their fields alternated.
private void BuildFieldLists(SliceHeader h, Sps sps)
{
var parity = curStructure == 2 ? 1 : 0;
var picture = cur!;
var shortTerm = new List();
var longTerm = new List();
foreach (var p in dpb)
{
if (p.ShortMask != 0)
{
shortTerm.Add(p);
}
else if (p.LongMask != 0)
{
longTerm.Add(p);
}
}
longTerm.Sort((a, b) => a.LongTermFrameIdx.CompareTo(b.LongTermFrameIdx));
List init0 = [], init1 = [];
if (h.IsP)
{
shortTerm.Sort((a, b) => b.FrameNumWrap.CompareTo(a.FrameNumWrap));
Alternate(shortTerm, parity, longTerm: false, init0);
Alternate(longTerm, parity, longTerm: true, init0);
}
else
{
var poc = picture.PocOf(parity);
var before = shortTerm.FindAll(p => ShortTermPoc(p) <= poc);
var after = shortTerm.FindAll(p => ShortTermPoc(p) > poc);
before.Sort((a, b) => ShortTermPoc(b).CompareTo(ShortTermPoc(a)));
after.Sort((a, b) => ShortTermPoc(a).CompareTo(ShortTermPoc(b)));
Alternate([.. before, .. after], parity, longTerm: false, init0);
Alternate(longTerm, parity, longTerm: true, init0);
Alternate([.. after, .. before], parity, longTerm: false, init1);
Alternate(longTerm, parity, longTerm: true, init1);
SwapIfSame(init0, init1);
}
AppendInterView(init0, 0);
refList[0] = Modify(init0, 0, h.NumRefIdxActiveL0, h.Modifications[0], h, sps);
if (h.IsB)
{
AppendInterView(init1, 1);
}
refList[1] = h.IsB ? Modify(init1, 1, h.NumRefIdxActiveL1, h.Modifications[1], h, sps) : [];
}
/// PicOrderCnt of a frame entry for the field lists: the smaller of its fields marked short-term.
private static int ShortTermPoc(Picture p) => p.ShortMask switch
{
1 => p.TopPoc,
2 => p.BottomPoc,
_ => Math.Min(p.TopPoc, p.BottomPoc),
};
///
/// §8.2.4.2.5: fields taken from the ordered frames alternately, starting with the parity of the current field; the
/// fields not marked (short-term or long-term, as the list) are skipped, and when one parity runs out the rest of
/// the other follows in order.
///
private static void Alternate(List frames, int parity, bool longTerm, List output)
{
int same = 0, opposite = 0, n = frames.Count;
int sameBit = 1 << parity, oppositeBit = 1 << (1 - parity);
while (same < n || opposite < n)
{
while (same < n && ((longTerm ? frames[same].LongMask : frames[same].ShortMask) & sameBit) == 0)
{
same++;
}
while (opposite < n && ((longTerm ? frames[opposite].LongMask : frames[opposite].ShortMask) & oppositeBit) == 0)
{
opposite++;
}
if (same < n)
{
output.Add(new RefEntry(frames[same++], parity));
}
if (opposite < n)
{
output.Add(new RefEntry(frames[opposite++], 1 - parity));
}
}
}
/// When list 1 has more than one entry and equals list 0, its first two entries are switched (§8.2.4.2.3).
private static void SwapIfSame(List init0, List init1)
{
if (init1.Count > 1 && init0.Count == init1.Count)
{
for (var i = 0; i < init0.Count; i++)
{
if (!ReferenceEquals(init0[i].Pic, init1[i].Pic) || init0[i].Parity != init1[i].Parity)
{
return;
}
}
(init1[0], init1[1]) = (init1[1], init1[0]);
}
}
///
/// The modification of list (§8.2.4.3), for frames or fields; in a non-base view also
/// with the inter-view references (§H.8.2.2.3).
///
private RefEntry[] Modify(List initial, int listIndex, int count, List<(int Idc, int Value)> modifications, SliceHeader h, Sps sps)
{
var list = new RefEntry[count + 1];
for (var i = 0; i < count && i < initial.Count; i++)
{
list[i] = initial[i];
}
var field = curStructure != 0;
var parity = curStructure == 2 ? 1 : 0;
var maxPicNum = field ? 2 * sps.MaxFrameNum : sps.MaxFrameNum;
var currPicNum = field ? (2 * h.FrameNum) + 1 : h.FrameNum;
var pred = currPicNum;
var viewPred = -1;
var refIdx = 0;
foreach (var (idc, value) in modifications)
{
if (refIdx >= count)
{
break;
}
RefEntry found = default;
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;
if (FindShortTerm(picNum, field, parity, out var p, out var q) && !(ReferenceEquals(p, cur) && q == FieldBit(curStructure)))
{
found = new RefEntry(p, field ? q - 1 : -1);
}
}
else if (idc is 4 or 5)
{
found = ModifiedInterView(listIndex, idc, value, ref viewPred);
}
else if (FindLongTerm(value, field, parity, out var p, out var q) && !(ReferenceEquals(p, cur) && q == FieldBit(curStructure)))
{
found = new RefEntry(p, field ? q - 1 : -1);
}
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 (found.Pic is null || !ReferenceEquals(list[c].Pic, found.Pic) || list[c].Parity != found.Parity)
{
list[n++] = list[c];
}
}
}
Array.Resize(ref list, count);
return list;
}
}