Decodificatore H.264 per MVC e per le qualità MGS di SVC (#58)

MVC (Annex H): SPS di sottoinsieme, prefissi NAL 14 e slice NAL 20, un
decodificatore per vista con il suo stato, predizione fra viste (riferimenti
della stessa unità di accesso in coda alle liste, modifiche 4 e 5). Escono
tutte le viste, ciascuna con il suo ViewId; VideoFrameDecoder chiede solo la
vista base, che è il video 2D, per le miniature. I flussi MVC della serie non
hanno ricostruzione ufficiale: le prove controllano che ogni vista si
decodifichi pulita e che la vista base resti identica a quella di H.264 puro.

SVC (Annex G): lo strato base sempre; sopra, gli strati di qualità della
stessa risoluzione in CAVLC, decodificati uno sull'altro. Un macroblocco
intra con base_mode_flag somma il residuo accumulato alla ricostruzione dello
strato in cui era intra e per i vicini conta come I_BL. SVCBMT-13 coincide
ora con lo strato L2 ufficiale in tutti i 20 fotogrammi. Scalabilità
spaziale, CGS e CABAC negli strati di miglioramento non sono ancora scritti:
il decodificatore dà lo strato base esatto e dice perché, e SVCBST-19 e
SVCBCT-1 restano inconclusivi con l'elenco di ciò che manca.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 18:15:19 +01:00
1 parent da84c79f7e
commit 898e9d60e7
13 files changed
+1754 -59

No files matched your search

@@ -122,8 +122,10 @@ public sealed partial class H264Decoder
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);
// SVC motion_prediction_flag: the motion vector of the layer below is the predictor (§G.8.4.1).
var (x, y) = MotionFromBase(list, b8) ? BaseMv(list, blk) : Mvp(list, refIdx, px, py, w, directional);
x += mvdValue[((list * 16) + blk) * 2];
y += mvdValue[(((list * 16) + blk) * 2) + 1];
FillMv(list, px, py, w, h, x, y);
@@ -236,7 +238,8 @@ public sealed partial class H264Decoder
}
}
var colShort = !colEntry.IsLongTerm;
// An inter-view reference (MVC) is neither short-term nor long-term: no colZeroFlag.
var colShort = !colEntry.IsLongTerm && !colEntry.InterView;
for (var sub = first; sub < end; sub++)
{
for (var k = 0; k < 4; k++)
@@ -0,0 +1,284 @@
namespace Febe.Core.Codecs.H264;
/// <summary>
/// Multiview video coding (MVC, Annex H): the base view is decoded by this decoder as plain H.264 (its prefix NAL units
/// 14 only say which view it is and whether the other views refer to it); each other view by a decoder of its own,
/// created on its first view component (NAL unit 20 with svc_extension_flag 0), with its own picture order, frame_num,
/// marking and reference frames, as §H.8 wants them per view. A view component may also predict from the view
/// components of the same access unit that come before it in view order (inter-view prediction): they are appended to
/// its reference lists (§H.8.2.1) and can be moved by the list modifications 4 and 5 (§H.8.2.2.3).
/// </summary>
public sealed partial class H264Decoder
{
/// <summary>Subset sequence parameter sets (NAL unit 15) of the root decoder; the view decoders use them as their SPSs.</summary>
private readonly Dictionary<int, Sps> subsetSequences = [];
/// <summary>The decoder of the base view, for the decoder of another view; null for the root decoder itself.</summary>
private readonly H264Decoder? root;
/// <summary>The decoders of the non-base views (root decoder only), in the order they appeared.</summary>
private readonly List<H264Decoder> viewDecoders = [];
/// <summary>view_id of the view this decoder decodes.</summary>
private int viewId;
/// <summary>Root decoder: access units started so far (one per picture of the base view).</summary>
private long accessUnit;
/// <summary>The frame store of the view component of the latest access unit, its access unit and its inter_view_flag.</summary>
private Picture? auPicture;
private long auPictureUnit = -1;
private bool auPictureInterView;
/// <summary>The view component being decoded is an anchor picture (anchor_pic_flag): it uses the anchor references.</summary>
private bool anchorPicture;
/// <summary>inter_view_flag of the view component whose slices come next (from its prefix or extension header).</summary>
private bool pendingInterView = true;
/// <summary>A subset SPS with the multiview extension was read: the stream is MVC.</summary>
private bool multiview;
public H264Decoder()
{
}
/// <summary>The decoder of a non-base view: it shares the parameter sets of the root decoder.</summary>
private H264Decoder(H264Decoder root, int viewId)
{
this.root = root;
this.viewId = viewId;
sequences = root.subsetSequences;
pictures = root.pictures;
FrameDecoded += frame => root.FrameDecoded?.Invoke(frame);
}
/// <summary>
/// Whether the non-base views of an MVC stream are decoded too (the default), each frame carrying its
/// <see cref="H264Frame.ViewId"/>; false keeps only the base view, which is plain H.264, and skips the rest.
/// </summary>
public bool DecodeAllViews { get; set; } = true;
/// <summary>A prefix NAL unit (14, §7.3.2.12): with the MVC header it says the view and inter_view_flag of the base view.</summary>
private void ReadPrefix(NalUnit nal)
{
if (nal.HeaderLength != 4 || nal.IsSvc)
{
return;
}
viewId = (nal.Rbsp[2] << 2) | (nal.Rbsp[3] >> 6);
pendingInterView = (nal.Rbsp[3] & 2) != 0;
}
/// <summary>A slice of a non-base view (NAL unit 20 with the MVC header, §H.7.3.1.1), given to the decoder of its view.</summary>
private void DecodeViewSlice(NalUnit nal)
{
if (!DecodeAllViews || nal.HeaderLength != 4)
{
return;
}
var nonIdr = (nal.Rbsp[1] & 0x40) != 0;
var id = (nal.Rbsp[2] << 2) | (nal.Rbsp[3] >> 6);
if (id == viewId && auPicture is not null)
{
throw new H264Exception("Vista non base con lo stesso view_id della vista base.");
}
// The view components before this one in the access unit are finished: deblocked, they can be referred to.
FinishPicture();
H264Decoder? decoder = null;
foreach (var other in viewDecoders)
{
if (other.viewId == id)
{
decoder = other;
}
else
{
other.FinishPicture();
}
}
if (decoder is null)
{
if (viewDecoders.Count >= 1023)
{
throw new H264Exception("Troppe viste.");
}
decoder = new H264Decoder(this, id);
viewDecoders.Add(decoder);
}
decoder.anchorPicture = (nal.Rbsp[3] & 4) != 0;
decoder.pendingInterView = (nal.Rbsp[3] & 2) != 0;
decoder.DecodeViewComponentSlice(nal, idr: !nonIdr);
}
/// <summary>One slice of the view of this decoder: parsed with the subset SPS, decoded like a slice of the base view.</summary>
private void DecodeViewComponentSlice(NalUnit nal, bool idr)
{
var reader = nal.Reader();
// The rest of the decoder tells IDR pictures by NAL unit type: the view component stands as a unit 5 or 1.
var unit = nal with { Type = idr ? 5 : 1 };
var header = SliceHeader.Parse(reader, unit, sequences, pictures, out var sps, out var pps, multiview: true);
if (sps.Mvc is null || sps.Mvc.OrderOf(viewId) <= 0)
{
throw new H264Exception("Vista assente dall'SPS di sottoinsieme.");
}
if (header.RedundantPicCnt > 0)
{
return;
}
DecodeParsedSlice(unit, reader, header, sps, pps);
}
/// <summary>Finishes the pictures of the other views (at the end of an access unit, or before the next base view one).</summary>
private void FinishViews()
{
foreach (var decoder in viewDecoders)
{
decoder.FinishPicture();
}
}
/// <summary>Flushes the decoders of the other views.</summary>
private void FlushViews()
{
foreach (var decoder in viewDecoders)
{
decoder.Flush();
}
}
/// <summary>Records the frame store of the view component starting now, for the views that refer to it.</summary>
private void NoteViewComponent(Picture picture)
{
if (root is null)
{
accessUnit++;
}
auPicture = picture;
auPictureUnit = (root ?? this).accessUnit;
auPictureInterView = pendingInterView;
}
/// <summary>
/// A picture of the base view that nobody refers to in time may still be needed by the other views of its access
/// unit (inter_view_flag): it is then always reconstructed.
/// </summary>
private bool NeededByOtherViews => root is null && multiview && DecodeAllViews && pendingInterView;
/// <summary>The view_ids of the inter-view references of list <paramref name="list"/> of the current view component.</summary>
private int[] InterViewRefs(int list)
{
if (root is null || activeSps?.Mvc is not { } mvc)
{
return [];
}
var order = mvc.OrderOf(viewId);
if (order <= 0)
{
return [];
}
return (anchorPicture ? mvc.AnchorRefs : mvc.NonAnchorRefs)[list][order];
}
/// <summary>
/// The view component of view <paramref name="id"/> in the current access unit, as an inter-view reference of the
/// current picture (the field of the same parity for a field); empty when it is missing or not for inter-view use.
/// </summary>
private RefEntry InterViewPicture(int id)
{
var top = root!;
H264Decoder? decoder = top.viewId == id ? top : null;
if (decoder is null)
{
foreach (var other in top.viewDecoders)
{
if (other.viewId == id)
{
decoder = other;
break;
}
}
}
if (decoder is null || decoder == this || decoder.auPicture is not { } picture || decoder.auPictureUnit != top.accessUnit
|| !decoder.auPictureInterView || picture.Skipped)
{
return default;
}
var parity = curStructure == 0 ? -1 : curStructure - 1;
var bit = parity < 0 ? 3 : 1 << parity;
if ((picture.Decoded & bit) != bit || !picture.Fits(widthInMbs, heightInMbs, activeSps!.ChromaFormatIdc, BytesPerSample, PlaneCount(activeSps)))
{
return default;
}
return new RefEntry(picture, parity, InterView: true);
}
/// <summary>Whether some inter-view reference of the current view component is there.</summary>
private bool HasInterViewReference()
{
for (var list = 0; list < 2; list++)
{
foreach (var id in InterViewRefs(list))
{
if (InterViewPicture(id).Pic is not null)
{
return true;
}
}
}
return false;
}
/// <summary>§H.8.2.1: the inter-view references of the list, in the order of the SPS, after the temporal ones.</summary>
private void AppendInterView(List<RefEntry> list, int index)
{
foreach (var id in InterViewRefs(index))
{
var entry = InterViewPicture(id);
if (entry.Pic is not null)
{
list.Add(entry);
}
}
}
/// <summary>
/// The inter-view reference picked by modification_of_pic_nums_idc 4 (subtract) or 5 (add) with
/// abs_diff_view_idx_minus1 <paramref name="value"/> (§H.8.2.2.3); <paramref name="pred"/> is picViewIdxPred.
/// </summary>
private RefEntry ModifiedInterView(int list, int idc, int value, ref int pred)
{
var refs = InterViewRefs(list);
var max = refs.Length;
if (max == 0)
{
return default;
}
if ((uint)value >= (uint)max)
{
return default;
}
var abs = value + 1;
pred = idc == 4 ? (pred - abs < 0 ? pred - abs + max : pred - abs) : (pred + abs >= max ? pred + abs - max : pred + abs);
return (uint)pred < (uint)max ? InterViewPicture(refs[pred]) : default;
}
}
+66 -5
View File
@@ -333,7 +333,16 @@ public sealed partial class H264Decoder
scalePps = p;
}
if (!header.IsIntra)
if (svcSlice is not null)
{
// A quality refinement predicts from the lists of the layer below, built for the same picture.
if (header.IsIntra)
{
refList[0] = [];
refList[1] = [];
}
}
else if (!header.IsIntra)
{
BuildReferenceLists(header, s);
PrepareWeights();
@@ -366,7 +375,15 @@ public sealed partial class H264Decoder
PrepareSliceGroups(header, s, p);
if (!mbaff)
if (svcSlice is { SliceSkip: true })
{
DecodeSkippedSlice(addr, total);
}
else if (RecordLayers && mbaff)
{
throw new H264Exception("SVC con MBAFF non gestito.");
}
else if (!mbaff)
{
DecodeMacroblocks(addr, total);
}
@@ -383,6 +400,8 @@ public sealed partial class H264Decoder
private void DecodeMacroblocks(int addr, int total)
{
var isIntraSlice = sh.IsIntra;
var record = RecordLayers;
var scalableSlice = svcSlice is not null;
while (addr < total)
{
if (!isIntraSlice && !cabacMode)
@@ -402,7 +421,19 @@ public sealed partial class H264Decoder
BeginMacroblock(addr);
addr = NextAddress(addr);
DecodeSkip();
if (scalableSlice)
{
DecodeScalableSkip();
}
else
{
DecodeSkip();
}
if (record)
{
RecordLayer();
}
}
if ((run > 0 && !rd.MoreRbspData) || addr >= total)
@@ -417,11 +448,20 @@ public sealed partial class H264Decoder
{
DecodeSkip();
}
else if (scalableSlice)
{
DecodeScalableMacroblock();
}
else
{
DecodeMacroblock();
}
if (record)
{
RecordLayer();
}
var more = cabacMode ? cabac.Terminate() == 0 : rd.MoreRbspData;
if (!more)
{
@@ -769,6 +809,8 @@ public sealed partial class H264Decoder
private void BeginMacroblock(int addr)
{
PlaceMacroblock(addr);
mbResidualSet = false;
mbRefinedIntra = false;
Array.Clear(blkDone);
Array.Clear(nz, mb * NzPerMb, NzPerMb);
cbfDc[mb] = 0;
@@ -892,6 +934,7 @@ public sealed partial class H264Decoder
{
mbKind[mb] = MbKind.I16x16;
predMode16 = (type - 1) % 4;
lastPred16 = predMode16;
cbp = ((((type - 1) / 4) % 3) << 4) | (type >= 13 ? 15 : 0);
}
@@ -1180,6 +1223,11 @@ public sealed partial class H264Decoder
partPred[i] = isB ? BSubPred[subType[i]] : 1;
}
if (svcOwnMb)
{
ReadMotionPredictionFlags(4, subPartitions: true);
}
var ref0 = !isB && type == 4;
for (var list = 0; list < 2; list++)
{
@@ -1191,7 +1239,8 @@ public sealed partial class H264Decoder
continue;
}
var refIdx = active > 1 && !ref0 ? ReadRefIdx(list, (i & 1) * 8, (i >> 1) * 8, active) : 0;
var refIdx = MotionFromBase(list, i) ? BaseRefIdx(list, i)
: active > 1 && !ref0 ? ReadRefIdx(list, (i & 1) * 8, (i >> 1) * 8, active) : 0;
SetRefIdx(list, i, refIdx);
}
}
@@ -1238,6 +1287,11 @@ public sealed partial class H264Decoder
}
count = shape == Shape16x16 ? 1 : 2;
if (svcOwnMb)
{
ReadMotionPredictionFlags(count, subPartitions: false);
}
for (var list = 0; list < 2; list++)
{
var active = RefIdxRange(list);
@@ -1249,7 +1303,8 @@ public sealed partial class H264Decoder
}
Partition(part, out var px, out var py, out _, out _);
var refIdx = active > 1 ? ReadRefIdx(list, px, py, active) : 0;
var b8 = ((py >> 3) * 2) + (px >> 3);
var refIdx = MotionFromBase(list, b8) ? BaseRefIdx(list, b8) : active > 1 ? ReadRefIdx(list, px, py, active) : 0;
SetPartitionRefIdx(list, part, refIdx);
}
}
@@ -1271,6 +1326,7 @@ public sealed partial class H264Decoder
}
}
var residualPrediction = svcOwnMb && ReadResidualPredictionFlag();
var cbp = ReadCbp(intra: false);
mbCbp[mb] = (byte)cbp;
if ((cbp & 15) != 0 && pps.Transform8x8Mode && noSubLessThan8x8 && (!direct16 || sps.Direct8x8Inference))
@@ -1293,6 +1349,10 @@ public sealed partial class H264Decoder
}
StoreQp();
if (residualPrediction)
{
AddBaseCoefficients();
}
// Motion vectors, partition by partition in decoding order, then the prediction.
if (direct16)
@@ -1496,6 +1556,7 @@ public sealed partial class H264Decoder
private void ClearResidual()
{
mbResidualSet = true;
Array.Clear(lumaCoef, 0, 256 * LumaLikePlanes);
Array.Clear(lumaHas);
if (numC8x8 != 0)
@@ -0,0 +1,569 @@
namespace Febe.Core.Codecs.H264;
/// <summary>
/// Scalable video coding (SVC, Annex G), the part written so far: quality refinement within the base dependency
/// representation (dependency_id 0, quality_id above 0: MGS) with CAVLC. The layers of a picture are decoded one over the
/// other into the same frame store: the base layer (AVC, NAL units 1 and 5) as usual, then each refinement slice (NAL
/// unit 20) macroblock by macroblock, so the frame left by the highest layer is the target layer representation, and the
/// decoded picture buffer holds it, as the motion compensation of the target dependency wants it without key pictures.
/// A macroblock with base_mode_flag inherits type, intra modes and motion of the layer below. An inter one adds its
/// scaled transform coefficients to those of the layer below when residual_prediction_flag says so (§G.8.5) and is
/// predicted again with the inherited motion. An intra one is never predicted again: its residual, accumulated in the
/// coefficient domain over the refinements, is added to the samples of the layer where the macroblock was last coded as
/// intra; for the intra mode prediction of its neighbours it counts as I_BL (DC). A macroblock with base_mode_flag 0 is an
/// ordinary one of the current layer, which may take the motion of the layer below as predictor (motion_prediction_flag).
/// This reproduces the official reconstruction of SVCBMT-13 (three MGS levels) bit for bit.
/// Not written yet, and left to the base layer (the enhancement NAL units are then skipped for the rest of the stream,
/// <see cref="EnhancementLayersSkipped"/> says why): dependency_id above 0 (spatial scalability and CGS, with the
/// inter-layer prediction and upsampling of §G.8.6), enhancement slices with CABAC (the contexts of base_mode_flag,
/// motion_prediction_flag and residual_prediction_flag), key pictures (store_ref_base_pic_flag, use_ref_base_pic_flag),
/// coefficient subsets (scan_idx_start, scan_idx_end), tcoeff_level_prediction_flag, the 8×8 transform, interlace and
/// formats other than 4:2:0 at 8 bits in the refinements.
/// </summary>
public sealed partial class H264Decoder
{
private const int CoefPerMb = 512;
/// <summary>A subset SPS with the scalable extension was read: the stream is SVC.</summary>
private bool scalable;
/// <summary>The enhancement layers of the stream use something not written yet: from then on only the base layer.</summary>
private string? svcUnsupported;
/// <summary>DQId of the highest layer decoded into the current picture (0 the base layer).</summary>
private int picDqId;
/// <summary>A layer of the current picture could not be decoded: the layers above it are skipped.</summary>
private bool picSvcStopped;
/// <summary>The refinement slice being decoded, null for an AVC slice.</summary>
private SvcSliceFields? svcSlice;
/// <summary>The macroblock being decoded is an ordinary one of a refinement slice (base_mode_flag 0).</summary>
private bool svcOwnMb;
/// <summary>motion_prediction_flag_lX of the macroblock, by list and 8×8 block.</summary>
private readonly bool[] svcMotionPred = new bool[8];
/// <summary>The residual of the macroblock was cleared and read (else it is that of a skipped macroblock: none).</summary>
private bool mbResidualSet;
/// <summary>Intra_16x16 prediction mode of the macroblock being decoded.</summary>
private int lastPred16;
// The layer just decoded, macroblock by macroblock: scaled coefficients (luma 256, chroma 2 × 128) and the
// Intra_16x16 mode; and the same, with type, modes and motion, of the layer below the one being decoded.
private int[] layerCoef = [];
private byte[] layerPred16 = [];
private int[] baseCoef = [];
private byte[] basePred16 = [];
private MbKind[] baseKind = [];
private sbyte[] baseIntraModes = [];
private byte[] baseChromaModes = [];
private bool[] baseT8 = [];
private short[] baseMv = [];
private sbyte[] baseRefIdx = [];
private Picture?[] baseRefPic = [];
private sbyte[] baseRefPar = [];
// The intra origin (see CopyIntraOrigin) and, per macroblock, whether it is a base_mode intra refinement in the layer
// just decoded and in the layer below.
private byte[] originY = [], originCb = [], originCr = [];
private bool[] mbIntraRefined = [];
/// <summary>The macroblock being decoded is a base_mode intra refinement.</summary>
private bool mbRefinedIntra;
private bool[] baseIntraRefined = [];
/// <summary>
/// Whether the enhancement layers of an SVC stream are decoded (the default): the frames are then those of the highest
/// layer the decoder handles; false gives the base layer, plain H.264, and skips the NAL units 14 and 20.
/// </summary>
public bool DecodeEnhancementLayers { get; set; } = true;
/// <summary>Why the enhancement layers of the stream are not decoded (null when they are, or the stream has none).</summary>
public string? EnhancementLayersSkipped => svcUnsupported;
/// <summary>The per-macroblock data of the layers is kept while the base layer is decoded.</summary>
private bool RecordLayers => scalable && DecodeEnhancementLayers && svcUnsupported is null && root is null;
/// <summary>The SVC prefix NAL unit (§G.7.3.2.12.1) before a base layer slice: key pictures are not handled.</summary>
private void ReadSvcPrefix(NalUnit nal)
{
var ext = SvcNalHeader.Of(nal);
if (ext.UseRefBasePic)
{
SvcUnsupported("immagini chiave (use_ref_base_pic_flag)");
}
if (nal.RefIdc != 0 && nal.Length > 4 && nal.Reader().ReadFlag())
{
SvcUnsupported("immagini chiave (store_ref_base_pic_flag)");
}
}
private void SvcUnsupported(string reason)
{
if (DecodeEnhancementLayers && svcUnsupported is null)
{
svcUnsupported = reason;
}
picSvcStopped = true;
}
/// <summary>A slice of an enhancement layer (NAL unit 20 with the SVC header): decoded over the current picture.</summary>
private void DecodeSvcSlice(NalUnit nal)
{
if (!DecodeEnhancementLayers || svcUnsupported is not null || nal.HeaderLength != 4 || root is not null)
{
return;
}
var ext = SvcNalHeader.Of(nal);
if (ext.DependencyId != 0)
{
SvcUnsupported("scalabilità spaziale o CGS (dependency_id maggiore di 0)");
return;
}
if (cur is null || picHeader is null || picSkipped || picSvcStopped || ext.DqId < picDqId)
{
return;
}
if (ext.DqId > picDqId + 1)
{
// A layer is missing: the ones above it cannot be decoded.
picSvcStopped = true;
return;
}
if (ext.UseRefBasePic)
{
SvcUnsupported("immagini chiave (use_ref_base_pic_flag)");
return;
}
var reader = nal.Reader();
var header = SliceHeader.ParseScalable(reader, nal, ext, subsetSequences, pictures, picHeader, out var s, out var p);
var svc = header.Svc!;
string? missing = null;
if (p.Cabac)
{
missing = "strati di miglioramento in CABAC";
}
else if (svc.ScanIdxStart != 0 || svc.ScanIdxEnd != 15)
{
missing = "sottoinsiemi di coefficienti (scan_idx_start, scan_idx_end)";
}
else if (svc.TcoeffLevelPrediction)
{
missing = "tcoeff_level_prediction_flag";
}
else if (svc.StoreRefBasePic)
{
missing = "immagini chiave (store_ref_base_pic_flag)";
}
else if (!s.FrameMbsOnly || s.WidthInMbs != activeSps!.WidthInMbs || s.HeightInMbs != activeSps.HeightInMbs || s.ChromaFormatIdc != 1
|| s.BitDepthLuma != 8 || s.BitDepthChroma != 8 || p.Transform8x8Mode)
{
missing = "strati di qualità interlacciati, con trasformata 8×8 o fuori dal 4:2:0 a 8 bit";
}
if (missing is not null)
{
SvcUnsupported(missing);
return;
}
if (header.RedundantPicCnt > 0)
{
return;
}
if (ext.DqId > picDqId)
{
SnapshotLayer();
picDqId = ext.DqId;
}
svcSlice = svc;
try
{
DecodeSliceData(reader, nal, header, s, p);
}
finally
{
svcSlice = null;
svcOwnMb = false;
}
}
/// <summary>Makes room for the per-macroblock data of the layers.</summary>
private void EnsureLayerArrays()
{
if (layerCoef.Length == mbCount * CoefPerMb)
{
return;
}
layerCoef = new int[mbCount * CoefPerMb];
layerPred16 = new byte[mbCount];
baseCoef = new int[mbCount * CoefPerMb];
basePred16 = new byte[mbCount];
baseKind = new MbKind[mbCount];
baseIntraModes = new sbyte[mbCount * 16];
baseChromaModes = new byte[mbCount];
baseT8 = new bool[mbCount];
mbIntraRefined = new bool[mbCount];
baseIntraRefined = new bool[mbCount];
baseMv = new short[2 * mbCount * 32];
baseRefIdx = new sbyte[2 * mbCount * 4];
baseRefPic = new Picture?[2 * mbCount * 4];
baseRefPar = new sbyte[2 * mbCount * 4];
}
/// <summary>The coefficients and Intra_16x16 mode of the macroblock just decoded, for the layer above it.</summary>
private void RecordLayer()
{
EnsureLayerArrays();
mbIntraRefined[mb] = mbRefinedIntra;
if (svcSlice is not null && !mbRefinedIntra && IsIntraKind(mbKind[mb]))
{
// An own intra macroblock of a refinement: the samples the layers above it refine.
CopyIntraOrigin(fromOrigin: false);
}
var target = layerCoef.AsSpan(mb * CoefPerMb, CoefPerMb);
if (!mbResidualSet || mbKind[mb] == MbKind.IPcm)
{
target.Clear();
}
else
{
lumaCoef.AsSpan(0, 256).CopyTo(target);
chromaCoef.AsSpan(0, 256).CopyTo(target[256..]);
}
layerPred16[mb] = (byte)(mbKind[mb] == MbKind.I16x16 ? lastPred16 : 0);
}
/// <summary>
/// Copies the samples of the current macroblock from the intra origin (the reconstruction an intra macroblock of a
/// refinement is built on) into the picture, or the other way round.
/// </summary>
private void CopyIntraOrigin(bool fromOrigin)
{
var picture = cur!;
CopyBlock(fromOrigin ? originY : picture.Y, fromOrigin ? picture.Y : originY, picture.Width, mbX * 16, mbY * 16, 16);
var cw = picture.ChromaWidth;
CopyBlock(fromOrigin ? originCb : picture.Cb, fromOrigin ? picture.Cb : originCb, cw, mbX * 8, mbY * 8, 8);
CopyBlock(fromOrigin ? originCr : picture.Cr, fromOrigin ? picture.Cr : originCr, cw, mbX * 8, mbY * 8, 8);
}
private static void CopyBlock(byte[] source, byte[] target, int stride, int x, int y, int size)
{
for (var r = 0; r < size; r++)
{
var offset = ((y + r) * stride) + x;
source.AsSpan(offset, size).CopyTo(target.AsSpan(offset, size));
}
}
private static void CopyPlane(byte[] source, ref byte[] target)
{
if (target.Length != source.Length)
{
target = new byte[source.Length];
}
source.AsSpan().CopyTo(target);
}
/// <summary>The layer decoded so far becomes the reference layer of the one starting (§G.8.1.5).</summary>
private void SnapshotLayer()
{
EnsureLayerArrays();
var picture = cur!;
if (picDqId == 0)
{
// Quality 0 is the intra origin of all its intra macroblocks.
CopyPlane(picture.Y, ref originY);
CopyPlane(picture.Cb, ref originCb);
CopyPlane(picture.Cr, ref originCr);
}
Array.Copy(layerCoef, baseCoef, layerCoef.Length);
Array.Copy(layerPred16, basePred16, mbCount);
Array.Copy(mbKind, baseKind, mbCount);
Array.Copy(intraModes, baseIntraModes, mbCount * 16);
Array.Copy(chromaModes, baseChromaModes, mbCount);
Array.Copy(mbT8, baseT8, mbCount);
Array.Copy(mbIntraRefined, baseIntraRefined, mbCount);
Array.Copy(picture.Mv, baseMv, baseMv.Length);
Array.Copy(picture.RefIdx, baseRefIdx, baseRefIdx.Length);
Array.Copy(picture.RefPic, baseRefPic, baseRefPic.Length);
Array.Copy(picture.RefPar, baseRefPar, baseRefPar.Length);
}
private static bool IsIntraKind(MbKind kind) => kind is MbKind.I4x4 or MbKind.I8x8 or MbKind.I16x16 or MbKind.IPcm or MbKind.SI;
/// <summary>A macroblock of a refinement slice (macroblock_layer_in_scalable_extension(), §G.7.3.6).</summary>
private void DecodeScalableMacroblock()
{
var s = svcSlice!;
var baseMode = s.AdaptiveBaseMode ? rd.ReadFlag() : s.DefaultBaseMode;
if (baseMode)
{
DecodeBaseModeMacroblock(readSyntax: true);
return;
}
svcOwnMb = true;
try
{
DecodeMacroblock();
}
finally
{
svcOwnMb = false;
}
}
/// <summary>A skipped macroblock of a refinement slice: P_Skip or B_Skip of the current layer, with the residual of the layer below when residual_prediction_flag is inferred to 1.</summary>
private void DecodeScalableSkip()
{
DecodeSkip();
var s = svcSlice!;
var residualPrediction = !s.AdaptiveResidualPrediction && s.DefaultResidualPrediction;
ClearResidual();
if (residualPrediction)
{
AddBaseCoefficients();
if (wide)
{
AddInterResidual<ushort>();
}
else
{
AddInterResidual<byte>();
}
}
}
/// <summary>
/// A macroblock with base_mode_flag 1 (or of a slice with slice_skip_flag): type, intra prediction modes and motion of
/// the layer below (§G.8.1.5.1, same resolution), its own residual added to that of the layer below in the scaled
/// coefficient domain.
/// </summary>
private void DecodeBaseModeMacroblock(bool readSyntax)
{
var s = svcSlice!;
var kind = baseKind[mb];
if (kind is MbKind.IPcm or MbKind.SI)
{
throw new H264Exception("Strato di qualità sopra un macroblocco I_PCM: non gestito.");
}
var intra = IsIntraKind(kind);
var residualPrediction = sh.Type != SliceType.I && (s.AdaptiveResidualPrediction ? readSyntax && rd.ReadFlag() : s.DefaultResidualPrediction || !readSyntax);
ClearResidual();
mbT8[mb] = false;
if (readSyntax)
{
var cbp = ReadCbp(intra: false);
mbCbp[mb] = (byte)cbp;
if (cbp != 0)
{
ApplyQpDelta(ReadQpDelta());
ReadResidual(false, cbp, intra);
}
else
{
lastQpDelta = 0;
}
}
else
{
lastQpDelta = 0;
}
StoreQp();
var picture = cur!;
if (intra)
{
// An intra macroblock is refined over the reconstruction of the layer where it was last coded as intra
// (quality 0, or an own intra macroblock of a refinement): the residual of each refinement since then is
// accumulated in the scaled coefficient domain and added to those samples, never predicted again.
if (baseIntraRefined[mb])
{
AddBaseCoefficients();
}
mbKind[mb] = kind;
picture.MbIntra[mb] = true;
mbRefinedIntra = true;
// For the prediction of the intra modes of the neighbours this is not an Intra_4x4 macroblock (I_BL): DC.
intraModes.AsSpan(mb * 16, 16).Fill(2);
chromaModes[mb] = baseChromaModes[mb];
lastPred16 = basePred16[mb];
CopyIntraOrigin(fromOrigin: true);
AddInterResidual<byte>();
return;
}
if (residualPrediction)
{
AddBaseCoefficients();
}
mbKind[mb] = sh.IsB ? MbKind.BInter : MbKind.PInter;
for (var list = 0; list < 2; list++)
{
baseMv.AsSpan(((list * mbCount) + mb) * 32, 32).CopyTo(picture.Mv.AsSpan(((list * mbCount) + mb) * 32, 32));
var r = ((list * mbCount) + mb) * 4;
baseRefIdx.AsSpan(r, 4).CopyTo(picture.RefIdx.AsSpan(r, 4));
baseRefPic.AsSpan(r, 4).CopyTo(picture.RefPic.AsSpan(r, 4));
baseRefPar.AsSpan(r, 4).CopyTo(picture.RefPar.AsSpan(r, 4));
}
MarkDone(0, 0, 16, 16);
for (var blk = 0; blk < 16; blk++)
{
MotionCompensate((blk & 3) * 4, (blk >> 2) * 4, 4, 4);
}
if (wide)
{
AddInterResidual<ushort>();
}
else
{
AddInterResidual<byte>();
}
}
/// <summary>Refinement (§G.8.5): the scaled coefficients of the layer below are added to those of this one.</summary>
private void AddBaseCoefficients()
{
var source = baseCoef.AsSpan(mb * CoefPerMb, CoefPerMb);
for (var raster = 0; raster < 16; raster++)
{
var any = false;
for (var k = 0; k < 16; k++)
{
var v = source[(raster * 16) + k];
if (v != 0)
{
lumaCoef[(raster * 16) + k] += v;
any = true;
}
}
if (any)
{
lumaHas[raster] = true;
}
}
for (var block = 0; block < 16; block++)
{
var any = false;
for (var k = 0; k < 16; k++)
{
var v = source[256 + (block * 16) + k];
if (v != 0)
{
chromaCoef[(block * 16) + k] += v;
any = true;
}
}
if (any)
{
chromaHas[block] = true;
}
}
}
/// <summary>
/// motion_prediction_flag_l0 and _l1 of an ordinary inter macroblock of a refinement slice (§G.7.3.6.1), for the
/// partitions <paramref name="parts"/> (8×8 blocks of each), read or inferred.
/// </summary>
private void ReadMotionPredictionFlags(int count, bool subPartitions)
{
Array.Clear(svcMotionPred);
var s = svcSlice!;
for (var list = 0; list < 2; list++)
{
for (var part = 0; part < count; part++)
{
if ((partPred[part] & (1 << list)) == 0 || (subPartitions && subDirect[(mb * 4) + part]))
{
continue;
}
var flag = s.AdaptiveMotionPrediction ? rd.ReadFlag() : s.DefaultMotionPrediction;
if (!flag)
{
continue;
}
if (subPartitions)
{
svcMotionPred[(list * 4) + part] = true;
}
else
{
for (var b8 = 0; b8 < 4; b8++)
{
if (shape == Shape16x16 || (shape == Shape16x8 && (b8 >> 1) == part) || (shape == Shape8x16 && (b8 & 1) == part))
{
svcMotionPred[(list * 4) + b8] = true;
}
}
}
}
}
}
/// <summary>Whether the motion of the 8×8 block <paramref name="b8"/> is predicted from the layer below.</summary>
private bool MotionFromBase(int list, int b8) => svcOwnMb && svcMotionPred[(list * 4) + b8];
/// <summary>The reference index of the layer below for an 8×8 block (0 where it has none).</summary>
private int BaseRefIdx(int list, int b8) => Math.Max(0, (int)baseRefIdx[(((list * mbCount) + mb) * 4) + b8]);
/// <summary>The motion vector of the layer below for a 4×4 block (raster index).</summary>
private (int X, int Y) BaseMv(int list, int blk)
{
if (baseRefIdx[(((list * mbCount) + mb) * 4) + (((blk >> 3) * 2) + ((blk & 3) >> 1))] < 0)
{
return (0, 0);
}
var i = ((((list * mbCount) + mb) * 16) + blk) * 2;
return (baseMv[i], baseMv[i + 1]);
}
/// <summary>residual_prediction_flag of an ordinary inter macroblock of a refinement slice, read or inferred.</summary>
private bool ReadResidualPredictionFlag()
{
var s = svcSlice!;
return s.AdaptiveResidualPrediction ? rd.ReadFlag() : s.DefaultResidualPrediction;
}
/// <summary>A slice with slice_skip_flag: every macroblock as base_mode_flag 1 with the residual of the layer below.</summary>
private void DecodeSkippedSlice(int addr, int total)
{
var count = svcSlice!.NumMbsInSlice;
for (var i = 0; i < count && addr < total; i++)
{
BeginMacroblock(addr);
addr = NextAddress(addr);
DecodeBaseModeMacroblock(readSyntax: false);
RecordLayer();
}
}
}
+91 -12
View File
@@ -28,6 +28,10 @@ public enum H264AccessPoint
/// (checked only on conformance streams split into partitions), 4:4:4, separate colour planes, lossless coding and bit
/// depths above 10. Not handled (an <see cref="H264Exception"/>): 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 <see cref="H264Frame.ViewId"/>; <see cref="DecodeAllViews"/> 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 <see cref="EnhancementLayersSkipped"/> says why (see H264Decoder.Svc.cs).
/// </summary>
public sealed partial class H264Decoder
{
@@ -145,14 +149,21 @@ public sealed partial class H264Decoder
Decode(NalUnits.Unescape(sample[unit], ref rbsp));
}
FinishPicture();
FinishAccessUnit();
}
/// <summary>Decodes one access unit in Annex B form and finishes its picture (as <see cref="DecodeSample"/>).</summary>
public void DecodeAccessUnitAnnexB(ReadOnlySpan<byte> accessUnit)
{
DecodeUnitsAnnexB(accessUnit);
FinishAccessUnit();
}
/// <summary>Finishes the picture of every view of the access unit.</summary>
private void FinishAccessUnit()
{
FinishPicture();
FinishViews();
}
/// <summary>
@@ -214,6 +225,8 @@ public sealed partial class H264Decoder
openField = null;
HandOut(field, activeSps!);
}
FlushViews();
}
/// <summary>
@@ -257,7 +270,44 @@ public sealed partial class H264Decoder
{
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);
@@ -275,7 +325,7 @@ public sealed partial class H264Decoder
case 8:
{
var pps = Pps.Parse(nal.Reader(), sequences);
var pps = Pps.Parse(nal.Reader(), sequences, subsetSequences);
pictures[pps.Id] = pps;
break;
}
@@ -389,6 +439,11 @@ public sealed partial class H264Decoder
/// <summary>Whether a picture other than the one being decoded can be predicted from.</summary>
private bool HasReference()
{
if (root is not null && HasInterViewReference())
{
return true;
}
foreach (var p in dpb)
{
if (!ReferenceEquals(p, cur))
@@ -470,6 +525,10 @@ public sealed partial class H264Decoder
}
var picture = cur!;
NoteViewComponent(picture);
picDqId = 0;
picSvcStopped = false;
curStructure = structure;
picHeader = header;
picNalType = nal.Type;
@@ -487,7 +546,7 @@ public sealed partial class H264Decoder
}
// A picture nobody refers to and nobody wants: its header has set the state above, its slices are not decoded.
picSkipped = nal.RefIdc == 0 && Wanted is { } wanted && !wanted(picture.DecodeIndex);
picSkipped = nal.RefIdc == 0 && !NeededByOtherViews && Wanted is { } wanted && !wanted(picture.DecodeIndex);
if (picSkipped)
{
picture.Skipped = true;
@@ -780,7 +839,7 @@ public sealed partial class H264Decoder
{
if (!picture.Skipped && (Wanted?.Invoke(picture.DecodeIndex) ?? true))
{
FrameDecoded?.Invoke(Crop(picture, sps));
FrameDecoded?.Invoke(Crop(picture, sps, viewId));
}
decodeCounter++;
@@ -795,7 +854,7 @@ public sealed partial class H264Decoder
/// 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.
/// </summary>
private static H264Frame Crop(Picture p, Sps sps)
private static H264Frame Crop(Picture p, Sps sps, int viewId)
{
var bps = p.BytesPerSample;
var format = sps.ChromaFormatIdc;
@@ -856,7 +915,7 @@ public sealed partial class H264Decoder
}
}
return new H264Frame(width, height, y, cb, cr, p.Poc, p.Period, p.DecodeIndex, sps.MatrixCoefficients, sps.FullRange, format, bitDepthY, bitDepthC);
return new H264Frame(width, height, y, cb, cr, p.Poc, p.Period, p.DecodeIndex, sps.MatrixCoefficients, sps.FullRange, format, bitDepthY, bitDepthC, viewId);
}
/// <summary>A <paramref name="width"/> × <paramref name="height"/> rectangle of a plane <paramref name="stride"/> samples wide.</summary>
@@ -1297,8 +1356,14 @@ public sealed partial class H264Decoder
SwapIfSame(init0, init1);
}
refList[0] = Modify(init0, h.NumRefIdxActiveL0, h.Modifications[0], h, sps);
refList[1] = h.IsB ? Modify(init1, h.NumRefIdxActiveL1, h.Modifications[1], h, sps) : [];
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) : [];
}
/// <summary>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.</summary>
@@ -1342,8 +1407,14 @@ public sealed partial class H264Decoder
SwapIfSame(init0, init1);
}
refList[0] = Modify(init0, h.NumRefIdxActiveL0, h.Modifications[0], h, sps);
refList[1] = h.IsB ? Modify(init1, h.NumRefIdxActiveL1, h.Modifications[1], h, sps) : [];
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) : [];
}
/// <summary>PicOrderCnt of a frame entry for the field lists: the smaller of its fields marked short-term.</summary>
@@ -1404,8 +1475,11 @@ public sealed partial class H264Decoder
}
}
/// <summary>The modification of a list (§8.2.4.3), for frames or fields.</summary>
private RefEntry[] Modify(List<RefEntry> initial, int count, List<(int Idc, int Value)> modifications, SliceHeader h, Sps sps)
/// <summary>
/// The modification of list <paramref name="listIndex"/> (§8.2.4.3), for frames or fields; in a non-base view also
/// with the inter-view references (§H.8.2.2.3).
/// </summary>
private RefEntry[] Modify(List<RefEntry> 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++)
@@ -1418,6 +1492,7 @@ public sealed partial class H264Decoder
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)
{
@@ -1447,6 +1522,10 @@ public sealed partial class H264Decoder
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);
+218 -3
View File
@@ -75,7 +75,36 @@ internal sealed class Sps
internal int HeightInMbs => (2 - (FrameMbsOnly ? 1 : 0)) * HeightInMapUnits;
internal static Sps Parse(RbspReader r)
/// <summary>The multiview extension of a subset SPS (profiles 118, 128 and 134), null otherwise.</summary>
internal MvcExtension? Mvc;
/// <summary>The scalable extension of a subset SPS (profiles 83 and 86), null otherwise.</summary>
internal SvcExtension? Svc;
/// <summary>
/// A subset sequence parameter set (NAL unit 15, §7.3.2.1.3): seq_parameter_set_data() with its whole VUI, then the
/// extension of its profile — scalable (§G.7.3.2.1.4) or multiview (§H.7.3.2.1.4); what follows the parts the decoder
/// uses is not read.
/// </summary>
internal static Sps ParseSubset(RbspReader r)
{
var s = Parse(r, wholeVui: true);
if (s.ProfileIdc is 83 or 86)
{
s.Svc = SvcExtension.Parse(r, s.ChromaArrayType);
}
else if (s.ProfileIdc is 118 or 128 or 134)
{
r.Skip(1); // bit_equal_to_one
s.Mvc = MvcExtension.Parse(r);
}
return s;
}
internal static Sps Parse(RbspReader r) => Parse(r, wholeVui: false);
private static Sps Parse(RbspReader r, bool wholeVui)
{
var s = new Sps { ProfileIdc = (int)r.Read(8) };
r.Skip(8); // constraint flags and reserved bits
@@ -160,11 +189,72 @@ internal sealed class Sps
if (r.ReadFlag())
{
ParseVuiColour(r, s);
if (wholeVui)
{
SkipVuiRest(r);
}
}
return s;
}
/// <summary>The VUI after the colour description (§E.1.1), read only to reach what follows it in a subset SPS.</summary>
private static void SkipVuiRest(RbspReader r)
{
if (r.ReadFlag())
{
_ = r.ReadUe(); // chroma_sample_loc_type_top_field
_ = r.ReadUe(); // chroma_sample_loc_type_bottom_field
}
if (r.ReadFlag())
{
r.Skip(65); // num_units_in_tick, time_scale, fixed_frame_rate_flag
}
var nalHrd = r.ReadFlag();
if (nalHrd)
{
SkipHrd(r);
}
var vclHrd = r.ReadFlag();
if (vclHrd)
{
SkipHrd(r);
}
if (nalHrd || vclHrd)
{
r.Skip(1); // low_delay_hrd_flag
}
r.Skip(1); // pic_struct_present_flag
if (r.ReadFlag())
{
r.Skip(1); // motion_vectors_over_pic_boundaries_flag
for (var i = 0; i < 6; i++)
{
_ = r.ReadUe();
}
}
}
/// <summary>hrd_parameters() (§E.1.2), skipped.</summary>
private static void SkipHrd(RbspReader r)
{
var count = r.ReadUe(31) + 1;
r.Skip(8); // bit_rate_scale, cpb_size_scale
for (var i = 0; i < count; i++)
{
_ = r.ReadUe();
_ = r.ReadUe();
r.Skip(1);
}
r.Skip(20);
}
/// <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)
{
@@ -195,6 +285,123 @@ internal sealed class Sps
}
}
/// <summary>
/// seq_parameter_set_mvc_extension() (§H.7.3.2.1.4) up to the dependencies between views: the views in view order, and
/// for each the views its anchor and non-anchor view components may refer to, per list.
/// </summary>
internal sealed class MvcExtension
{
/// <summary>view_id of each view, by view order index (VOIdx).</summary>
internal int[] ViewIds = [];
/// <summary>anchor_ref_lX[VOIdx][j] by list X: the view_id of each inter-view reference of an anchor view component.</summary>
internal int[][][] AnchorRefs = [[], []];
/// <summary>non_anchor_ref_lX[VOIdx][j] by list X.</summary>
internal int[][][] NonAnchorRefs = [[], []];
/// <summary>The view order index of a view, −1 when the sequence does not have it.</summary>
internal int OrderOf(int viewId) => Array.IndexOf(ViewIds, viewId);
internal static MvcExtension Parse(RbspReader r)
{
var views = r.ReadUe(1023) + 1;
var m = new MvcExtension { ViewIds = new int[views] };
for (var i = 0; i < views; i++)
{
m.ViewIds[i] = r.ReadUe(1023);
}
for (var list = 0; list < 2; list++)
{
m.AnchorRefs[list] = new int[views][];
m.NonAnchorRefs[list] = new int[views][];
m.AnchorRefs[list][0] = [];
m.NonAnchorRefs[list][0] = [];
}
for (var pass = 0; pass < 2; pass++)
{
var refs = pass == 0 ? m.AnchorRefs : m.NonAnchorRefs;
for (var i = 1; i < views; i++)
{
for (var list = 0; list < 2; list++)
{
var count = r.ReadUe(15);
var ids = new int[count];
for (var j = 0; j < count; j++)
{
ids[j] = r.ReadUe(1023);
}
refs[list][i] = ids;
}
}
}
return m;
}
}
/// <summary>seq_parameter_set_svc_extension() (§G.7.3.2.1.4).</summary>
internal sealed class SvcExtension
{
internal bool InterLayerDeblockingFilterControlPresent;
internal int ExtendedSpatialScalabilityIdc;
internal bool ChromaPhaseXPlus1;
internal int ChromaPhaseYPlus1 = 1;
internal bool SeqRefLayerChromaPhaseXPlus1;
internal int SeqRefLayerChromaPhaseYPlus1 = 1;
internal int SeqScaledRefLayerLeft;
internal int SeqScaledRefLayerTop;
internal int SeqScaledRefLayerRight;
internal int SeqScaledRefLayerBottom;
internal bool SeqTcoeffLevelPrediction;
internal bool AdaptiveTcoeffLevelPrediction;
internal bool SliceHeaderRestriction;
internal static SvcExtension Parse(RbspReader r, int chromaArrayType)
{
var e = new SvcExtension
{
InterLayerDeblockingFilterControlPresent = r.ReadFlag(),
ExtendedSpatialScalabilityIdc = (int)r.Read(2),
};
if (chromaArrayType is 1 or 2)
{
e.ChromaPhaseXPlus1 = r.ReadFlag();
}
if (chromaArrayType == 1)
{
e.ChromaPhaseYPlus1 = (int)r.Read(2);
}
if (e.ExtendedSpatialScalabilityIdc == 1)
{
if (chromaArrayType > 0)
{
e.SeqRefLayerChromaPhaseXPlus1 = r.ReadFlag();
e.SeqRefLayerChromaPhaseYPlus1 = (int)r.Read(2);
}
e.SeqScaledRefLayerLeft = r.ReadSe();
e.SeqScaledRefLayerTop = r.ReadSe();
e.SeqScaledRefLayerRight = r.ReadSe();
e.SeqScaledRefLayerBottom = r.ReadSe();
}
e.SeqTcoeffLevelPrediction = r.ReadFlag();
if (e.SeqTcoeffLevelPrediction)
{
e.AdaptiveTcoeffLevelPrediction = r.ReadFlag();
}
e.SliceHeaderRestriction = r.ReadFlag();
return e;
}
}
/// <summary>A picture parameter set (§7.3.2.2).</summary>
internal sealed class Pps
{
@@ -242,7 +449,10 @@ internal sealed class Pps
/// <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)
/// <param name="r">The RBSP after the NAL unit header.</param>
/// <param name="sequences">The SPSs read so far.</param>
/// <param name="subsetSequences">The subset SPSs read so far: a PPS of the enhancement layers or views may refer to one.</param>
internal static Pps Parse(RbspReader r, IReadOnlyDictionary<int, Sps> sequences, IReadOnlyDictionary<int, Sps>? subsetSequences = null)
{
var p = new Pps { Id = r.ReadUe(255), SpsId = r.ReadUe(31) };
p.Cabac = r.ReadFlag();
@@ -274,7 +484,12 @@ internal sealed class Pps
p.Transform8x8Mode = r.ReadFlag();
if (r.ReadFlag())
{
var chroma444 = sequences.TryGetValue(p.SpsId, out var sps) && sps.ChromaFormatIdc == 3;
if (!sequences.TryGetValue(p.SpsId, out var sps))
{
subsetSequences?.TryGetValue(p.SpsId, out sps);
}
var chroma444 = sps is { 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);
}
+9 -4
View File
@@ -194,12 +194,16 @@ internal sealed class Picture
}
}
/// <summary>A reference picture of a list: a frame (<see cref="Parity"/> −1) or one field of a frame store.</summary>
internal readonly record struct RefEntry(Picture? Pic, int Parity)
/// <summary>
/// A reference picture of a list: a frame (<see cref="Parity"/> −1) or one field of a frame store; for a non-base view of
/// MVC also the view component of another view in the same access unit (<see cref="InterView"/>), which is marked
/// "used for inter-view reference" only: neither a short-term nor a long-term reference of the current view.
/// </summary>
internal readonly record struct RefEntry(Picture? Pic, int Parity, bool InterView = false)
{
internal int Poc => Pic!.PocOf(Parity);
internal bool IsLongTerm => Pic!.IsLongTerm(Parity);
internal bool IsLongTerm => !InterView && Pic!.IsLongTerm(Parity);
}
/// <summary>
@@ -220,9 +224,10 @@ internal readonly record struct RefEntry(Picture? Pic, int Parity)
/// <param name="ChromaFormat">chroma_format_idc: 0 monochrome, 1 4:2:0, 2 4:2:2, 3 4:4:4.</param>
/// <param name="BitDepthLuma">Bits of each luma sample, 8 to 14.</param>
/// <param name="BitDepthChroma">Bits of each chroma sample, 8 to 14.</param>
/// <param name="ViewId">view_id of the view of an MVC stream the frame belongs to (that of the base view, usually 0, otherwise).</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,
int ChromaFormat = 1, int BitDepthLuma = 8, int BitDepthChroma = 8)
int ChromaFormat = 1, int BitDepthLuma = 8, int BitDepthChroma = 8, int ViewId = 0)
{
/// <summary>Width of <see cref="Cb"/> and <see cref="Cr"/> in samples.</summary>
public int ChromaWidth => ChromaFormat == 3 ? Width : (Width + 1) / 2;
+22 -6
View File
@@ -122,11 +122,24 @@ internal sealed class RbspReader
}
}
/// <summary>One NAL unit, with its RBSP.</summary>
/// <summary>
/// One NAL unit, with its RBSP. The units of the scalable and multiview extensions (prefix 14, slice extension 20 and
/// 21) carry three more header bytes (nal_unit_header_svc_extension or nal_unit_header_mvc_extension, §7.3.1), kept as
/// they are in <see cref="Rbsp"/>[1..3]: the emulation prevention bytes are removed only after them.
/// </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>Bytes of the NAL unit header: 4 for the extension units, else 1.</summary>
internal int HeaderLength => HasExtensionHeader(Type) && Length >= 4 ? 4 : 1;
/// <summary>svc_extension_flag of an extension unit: 1 for SVC (Annex G), 0 for MVC (Annex H).</summary>
internal bool IsSvc => (Rbsp[1] & 0x80) != 0;
/// <summary>A reader positioned after the header.</summary>
internal RbspReader Reader() => new(Rbsp, Length, HeaderLength);
/// <summary>NAL unit types whose header has the three extension bytes.</summary>
internal static bool HasExtensionHeader(int type) => type is 14 or 20 or 21;
}
/// <summary>
@@ -161,11 +174,14 @@ internal static class NalUnits
buffer = new byte[Math.Max(nal.Length + Padding, (buffer?.Length ?? 0) * 2)];
}
// Copied run by run between the 0x000003 patterns (a vectorised search), as the byte-by-byte rule of §7.4.1.
// Copied run by run between the 0x000003 patterns (a vectorised search), as the byte-by-byte rule of §7.4.1,
// after the header: the three extension bytes of the units 14, 20 and 21 are not part of the RBSP.
ReadOnlySpan<byte> pattern = [0, 0, 3];
var target = buffer.AsSpan();
var count = 0;
var rest = nal;
var head = NalUnit.HasExtensionHeader(nal[0] & 0x1F) ? Math.Min(4, nal.Length) : 0;
nal[..head].CopyTo(target);
var count = head;
var rest = nal[head..];
while (true)
{
var i = rest.IndexOf(pattern);
+355 -5
View File
@@ -10,6 +10,49 @@ internal enum SliceType
SI = 4,
}
/// <summary>nal_unit_header_svc_extension() (§G.7.3.1.1): where the NAL unit sits among the layers of an SVC stream.</summary>
internal readonly record struct SvcNalHeader(
bool Idr, int PriorityId, bool NoInterLayerPred, int DependencyId, int QualityId, int TemporalId, bool UseRefBasePic,
bool Discardable, bool Output)
{
/// <summary>DQId = (dependency_id &lt;&lt; 4) + quality_id.</summary>
internal int DqId => (DependencyId << 4) + QualityId;
/// <summary>The extension header of a NAL unit 14 or 20 with svc_extension_flag 1.</summary>
internal static SvcNalHeader Of(NalUnit nal)
{
int b1 = nal.Rbsp[1], b2 = nal.Rbsp[2], b3 = nal.Rbsp[3];
return new SvcNalHeader(
(b1 & 0x40) != 0, b1 & 0x3F, (b2 & 0x80) != 0, (b2 >> 4) & 7, b2 & 15, b3 >> 5, (b3 & 0x10) != 0, (b3 & 8) != 0, (b3 & 4) != 0);
}
}
/// <summary>The fields of slice_header_in_scalable_extension() that a slice of AVC does not have.</summary>
internal sealed class SvcSliceFields
{
internal SvcNalHeader Header;
internal bool BasePredWeightTable;
internal bool StoreRefBasePic;
internal bool BaseMarking;
internal int RefLayerDqId;
internal int DisableInterLayerDeblocking;
internal int InterLayerAlphaOffset;
internal int InterLayerBetaOffset;
internal bool ConstrainedIntraResampling;
internal bool ScaledRefLayerOffsets;
internal bool SliceSkip;
internal int NumMbsInSlice;
internal bool AdaptiveBaseMode;
internal bool DefaultBaseMode;
internal bool AdaptiveMotionPrediction;
internal bool DefaultMotionPrediction;
internal bool AdaptiveResidualPrediction;
internal bool DefaultResidualPrediction;
internal bool TcoeffLevelPrediction;
internal int ScanIdxStart;
internal int ScanIdxEnd = 15;
}
/// <summary>A slice header (§7.3.3), with the reference list modifications, weights and marking it carries.</summary>
internal sealed class SliceHeader
{
@@ -69,6 +112,9 @@ internal sealed class SliceHeader
/// <summary>slice_group_change_cycle (map types 3–5 of FMO).</summary>
internal int SliceGroupChangeCycle;
/// <summary>The scalable part of slice_header_in_scalable_extension() (§G.7.3.3.4), for a slice of NAL unit 20 of SVC.</summary>
internal SvcSliceFields? Svc;
internal bool IsIntra => Type is SliceType.I or SliceType.SI;
/// <summary>A P or SP slice: both are parsed and predicted alike (an SP slice differs in the reconstruction).</summary>
@@ -82,7 +128,12 @@ internal sealed class SliceHeader
/// <summary>0 frame, 1 top field, 2 bottom field.</summary>
internal int Structure => !FieldPic ? 0 : BottomField ? 2 : 1;
internal static SliceHeader Parse(RbspReader r, NalUnit nal, IReadOnlyDictionary<int, Sps> sequences, IReadOnlyDictionary<int, Pps> pictures, out Sps sps, out Pps pps)
/// <summary>
/// slice_header() of a NAL unit 1, 5 or (<paramref name="multiview"/>) of a non-base view: there the list
/// modifications may also insert inter-view references (modification_of_pic_nums_idc 4 and 5, §H.7.3.3.1.1), and
/// <paramref name="nal"/> stands for the view component, with type 5 when it is IDR.
/// </summary>
internal static SliceHeader Parse(RbspReader r, NalUnit nal, IReadOnlyDictionary<int, Sps> sequences, IReadOnlyDictionary<int, Pps> pictures, out Sps sps, out Pps pps, bool multiview = false)
{
var h = new SliceHeader { FirstMb = (int)r.ReadUe() };
var type = r.ReadUe(9);
@@ -157,10 +208,10 @@ internal sealed class SliceHeader
}
}
ParseModifications(r, h.Modifications[0]);
ParseModifications(r, h.Modifications[0], multiview);
if (h.IsB)
{
ParseModifications(r, h.Modifications[1]);
ParseModifications(r, h.Modifications[1], multiview);
}
}
@@ -264,7 +315,8 @@ internal sealed class SliceHeader
return h;
}
private static void ParseModifications(RbspReader r, List<(int, int)> list)
/// <summary>ref_pic_list_modification() (§7.3.3.1), or ref_pic_list_mvc_modification() (§H.7.3.3.1.1).</summary>
internal static void ParseModifications(RbspReader r, List<(int, int)> list, bool multiview = false)
{
if (!r.ReadFlag())
{
@@ -279,7 +331,7 @@ internal sealed class SliceHeader
return;
}
if (idc > 2)
if (idc > 2 && !(multiview && idc is 4 or 5))
{
throw new H264Exception("Modifica della lista di riferimento non gestita.");
}
@@ -290,6 +342,304 @@ internal sealed class SliceHeader
throw new H264Exception("Modifiche della lista di riferimento senza fine.");
}
/// <summary>
/// slice_header_in_scalable_extension() (§G.7.3.3.4) of a slice of NAL unit 20 with the SVC header
/// <paramref name="ext"/>; <paramref name="baseHeader"/> is the header of the layer with quality_id 0 of the same
/// dependency, from which a slice with quality_id above 0 takes its lists, weights and marking (§G.7.4.3.4).
/// </summary>
internal static SliceHeader ParseScalable(RbspReader r, NalUnit nal, SvcNalHeader ext, IReadOnlyDictionary<int, Sps> subsetSequences, IReadOnlyDictionary<int, Pps> pictures, SliceHeader? baseHeader, out Sps sps, out Pps pps)
{
var h = new SliceHeader { FirstMb = (int)r.ReadUe() };
var type = r.ReadUe(9);
h.Type = (SliceType)(type % 5);
if (h.Type is SliceType.SP or SliceType.SI)
{
throw new H264Exception("Tipo di slice non valido in SVC.");
}
h.PpsId = r.ReadUe(255);
if (!pictures.TryGetValue(h.PpsId, out pps!) || !subsetSequences.TryGetValue(pps.SpsId, out sps!) || sps.Svc is null)
{
throw new H264Exception("Slice SVC senza i suoi insiemi di parametri.");
}
var svc = new SvcSliceFields { Header = ext };
h.Svc = svc;
if (sps.SeparateColourPlane)
{
h.ColourPlaneId = (int)r.Read(2);
}
h.FrameNum = (int)r.Read(sps.Log2MaxFrameNum);
if (!sps.FrameMbsOnly)
{
h.FieldPic = r.ReadFlag();
if (h.FieldPic)
{
h.BottomField = r.ReadFlag();
}
}
if (ext.Idr)
{
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)
{
h.RedundantPicCnt = r.ReadUe(127);
}
if (ext.QualityId == 0)
{
if (h.IsB)
{
h.DirectSpatialMvPred = r.ReadFlag();
}
h.NumRefIdxActiveL0 = h.IsIntra ? 0 : pps.NumRefIdxL0DefaultActive;
h.NumRefIdxActiveL1 = h.IsB ? pps.NumRefIdxL1DefaultActive : 0;
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 ((pps.WeightedPred && h.IsP) || (pps.WeightedBipredIdc == 1 && h.IsB))
{
var fromBase = !ext.NoInterLayerPred && r.ReadFlag(); // base_pred_weight_table_flag
svc.BasePredWeightTable = fromBase;
if (!fromBase)
{
ParseWeights(r, h, sps);
}
}
if (nal.RefIdc != 0)
{
ParseMarking(r, h, ext.Idr);
if (!sps.Svc.SliceHeaderRestriction)
{
svc.StoreRefBasePic = r.ReadFlag();
if ((ext.UseRefBasePic || svc.StoreRefBasePic) && !ext.Idr)
{
svc.BaseMarking = true;
SkipBaseMarking(r);
}
}
}
}
else
{
// A quality refinement: the lists, the weights and the marking of the layer below (§G.7.4.3.4).
if (baseHeader is null)
{
throw new H264Exception("Strato di qualità senza il suo strato di base.");
}
h.DirectSpatialMvPred = baseHeader.DirectSpatialMvPred;
h.NumRefIdxActiveL0 = h.IsIntra ? 0 : baseHeader.NumRefIdxActiveL0;
h.NumRefIdxActiveL1 = h.IsB ? baseHeader.NumRefIdxActiveL1 : 0;
h.Modifications = baseHeader.Modifications;
h.LumaLog2WeightDenom = baseHeader.LumaLog2WeightDenom;
h.ChromaLog2WeightDenom = baseHeader.ChromaLog2WeightDenom;
h.Weights = baseHeader.Weights;
h.Offsets = baseHeader.Offsets;
}
if (pps.Cabac && !h.IsIntra)
{
h.CabacInitIdc = r.ReadUe(2);
}
h.QpDelta = r.ReadSe();
if (pps.DeblockingFilterControlPresent)
{
h.DisableDeblocking = r.ReadUe(6);
if (h.DisableDeblocking != 1)
{
h.AlphaOffset = r.ReadSe() * 2;
h.BetaOffset = r.ReadSe() * 2;
}
}
if (pps.NumSliceGroups > 1 && pps.SliceGroupMapType is >= 3 and <= 5)
{
var size = sps.WidthInMbs * sps.HeightInMapUnits;
var units = (size + pps.SliceGroupChangeRate - 1) / pps.SliceGroupChangeRate;
var bits = 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)units);
h.SliceGroupChangeCycle = (int)r.Read(bits);
}
var dqId = (ext.DependencyId << 4) + ext.QualityId;
svc.RefLayerDqId = ext.QualityId > 0 ? dqId - 1 : -1;
if (!ext.NoInterLayerPred && ext.QualityId == 0)
{
svc.RefLayerDqId = r.ReadUe(127);
if (sps.Svc.InterLayerDeblockingFilterControlPresent)
{
svc.DisableInterLayerDeblocking = r.ReadUe(6);
if (svc.DisableInterLayerDeblocking != 1)
{
svc.InterLayerAlphaOffset = r.ReadSe() * 2;
svc.InterLayerBetaOffset = r.ReadSe() * 2;
}
}
svc.ConstrainedIntraResampling = r.ReadFlag();
if (sps.Svc.ExtendedSpatialScalabilityIdc == 2)
{
if (sps.ChromaArrayType > 0)
{
r.Skip(3); // ref_layer_chroma_phase_x_plus1_flag, ref_layer_chroma_phase_y_plus1
}
svc.ScaledRefLayerOffsets = true;
for (var i = 0; i < 4; i++)
{
_ = r.ReadSe();
}
}
}
if (!ext.NoInterLayerPred)
{
svc.SliceSkip = r.ReadFlag();
if (svc.SliceSkip)
{
svc.NumMbsInSlice = (int)r.ReadUe() + 1;
}
else
{
svc.AdaptiveBaseMode = r.ReadFlag();
if (!svc.AdaptiveBaseMode)
{
svc.DefaultBaseMode = r.ReadFlag();
}
if (!svc.DefaultBaseMode)
{
svc.AdaptiveMotionPrediction = r.ReadFlag();
if (!svc.AdaptiveMotionPrediction)
{
svc.DefaultMotionPrediction = r.ReadFlag();
}
}
svc.AdaptiveResidualPrediction = r.ReadFlag();
if (!svc.AdaptiveResidualPrediction)
{
svc.DefaultResidualPrediction = r.ReadFlag();
}
}
if (sps.Svc.AdaptiveTcoeffLevelPrediction)
{
svc.TcoeffLevelPrediction = r.ReadFlag();
}
else
{
svc.TcoeffLevelPrediction = sps.Svc.SeqTcoeffLevelPrediction;
}
}
svc.ScanIdxEnd = 15;
if (!sps.Svc.SliceHeaderRestriction && !svc.SliceSkip)
{
svc.ScanIdxStart = (int)r.Read(4);
svc.ScanIdxEnd = (int)r.Read(4);
}
return h;
}
/// <summary>dec_ref_pic_marking() (§7.3.3.3) of an IDR picture or not.</summary>
private static void ParseMarking(RbspReader r, SliceHeader h, bool idr)
{
if (idr)
{
h.NoOutputOfPriorPics = r.ReadFlag();
h.LongTermReference = r.ReadFlag();
return;
}
if (!(h.AdaptiveMarking = r.ReadFlag()))
{
return;
}
for (var guard = 0; guard < 100; guard++)
{
var op = r.ReadUe(6);
if (op == 0)
{
return;
}
int a = 0, b = 0;
if (op is 1 or 2 or 3 or 4)
{
a = (int)r.ReadUe();
}
if (op is 3 or 6)
{
b = (int)r.ReadUe();
}
h.Mmco.Add((op, a, b));
}
}
/// <summary>dec_ref_base_pic_marking() (§G.7.3.3.5), skipped: base representations are not kept.</summary>
internal static void SkipBaseMarking(RbspReader r)
{
if (!r.ReadFlag())
{
return;
}
for (var guard = 0; guard < 100; guard++)
{
var op = r.ReadUe(3);
if (op == 0)
{
return;
}
_ = r.ReadUe();
}
}
private static void ParseWeights(RbspReader r, SliceHeader h, Sps sps)
{
h.LumaLog2WeightDenom = r.ReadUe(7);
+2 -1
View File
@@ -429,7 +429,8 @@ public sealed class VideoFrameDecoder
{
// Frames are matched to samples by the sample being decoded, not by the decoder's own count: a
// sample without a picture (only parameter sets, or damaged) must not shift the frames after it.
decoder = new H264Decoder { Wanted = _ => wanted.Contains(current) };
// Of an MVC stream only the base view: it is the 2D video, and the other views would add frames.
decoder = new H264Decoder { Wanted = _ => wanted.Contains(current), DecodeAllViews = false };
decoder.FrameDecoded += frame => found.TryAdd(current, frame);
next = key;
}