Fotogrammi e contenitori più robusti dopo la revisione: punto di partenza vero, limiti di tempo e di riferimenti, file rovinati tollerati (#58)
Corregge i difetti confermati dalla revisione del decodificatore H.264 e dei lettori di contenitori. - Fotogrammi: un AVI senza idx1 (o OpenDML oltre il primo GB) segna ogni campione come chiave; ora si parte dall'immagine IDR più vicina (entro 300 campioni), altrimenti da un'immagine di slice I o dal primo campione. Oltre 300 campioni vale il fotogramma del punto di partenza; ogni chiamata ha al più 30 secondi, come l'estrattore con ffmpeg che sostituisce. - H.264: una slice P/B senza riferimenti è un errore invece di una predizione da sé stessa; SPS con riferimenti oltre MaxDpbMbs del livello 6.2 rifiutato (1,4 GB da pochi byte); FrameNumOffset dei fotogrammi mancanti di un salto di frame_num; immagini ridondanti saltate e inizio d'immagine secondo §7.4.1.2.4; immagini non di riferimento non chieste non ricostruite; CABAC con finestra di 64 bit; unità NAL in un solo buffer. Il sommario non dice più verificato ciò che nessun MD5 verifica. - Matroska: un blocco rovinato o troncato ferma la lettura e i blocchi letti restano; scala dei tempi esatta per ogni TimecodeScale. - MP4: una traccia con tkhd/elst/mdhd/hdlr/esds rovinati si scarta senza perdere le altre; esds con limiti controllati; nei soli metadati niente copie delle tabelle né campioni dei frammenti. - AVI: durata impossibile ignota senza perdere la data. - Sonda dei metadati davvero asincrona, annullabile fra i frammenti. - Prove nuove: flussi H.264 sintetici scritti bit per bit (salto di frame_num, immagine ridondante, P senza riferimenti, immagini saltate, SPS enormi con PPS e slice), AVI senza indice, blocchi Matroska rovinati, audio MP4 rovinato, durata AVI, TimecodeScale di 3 ms, trun sotto il limite ma oltre il file, limite di run e di tempo, i due MP4 x264 del sito di prova, ffmpeg/ffprobe fuori dal Dockerfile. Provate contro il codice senza le correzioni: falliscono tutte. - decisioni.md: quattro righe del 18 novembre. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
479c95f899
commit
b23632fc96
22 files changed
+1273
-282
No files matched your search
@@ -1,17 +1,31 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Numerics;
|
||||
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>
|
||||
/// The arithmetic decoding engine of CABAC (§9.3.1.2 and §9.3.3.2), reading the slice data bit by bit, with the
|
||||
/// context variables of the slice.
|
||||
/// The arithmetic decoding engine of CABAC (§9.3.1.2 and §9.3.3.2), with the context variables of the slice. The slice
|
||||
/// data is read through a 64-bit window refilled four bytes at a time, and renormalisation shifts all its bits at once
|
||||
/// (the count of leading zeros of the range): the arithmetic is the one of the standard, bit for bit.
|
||||
/// </summary>
|
||||
internal sealed class CabacEngine
|
||||
{
|
||||
private readonly byte[] state = new byte[CabacTables.ContextCount];
|
||||
private readonly byte[] mps = new byte[CabacTables.ContextCount];
|
||||
private RbspReader reader = null!;
|
||||
private byte[] data = [];
|
||||
private int range;
|
||||
private int offset;
|
||||
|
||||
/// <summary>The next bits of the slice data, from the most significant bit.</summary>
|
||||
private ulong window;
|
||||
|
||||
/// <summary>Valid bits at the top of <see cref="window"/>.</summary>
|
||||
private int bits;
|
||||
|
||||
/// <summary>The next byte of <see cref="data"/> to load into the window.</summary>
|
||||
private int next;
|
||||
|
||||
/// <summary>Initialises the context variables (§9.3.1.1).</summary>
|
||||
internal void InitContexts(SliceHeader header, int sliceQp)
|
||||
{
|
||||
@@ -38,8 +52,18 @@ internal sealed class CabacEngine
|
||||
internal void Start(RbspReader source)
|
||||
{
|
||||
reader = source;
|
||||
data = source.Data;
|
||||
var position = source.Position;
|
||||
next = position >> 3;
|
||||
window = 0;
|
||||
bits = 0;
|
||||
Refill();
|
||||
var skip = position & 7;
|
||||
window <<= skip;
|
||||
bits -= skip;
|
||||
|
||||
range = 510;
|
||||
offset = (int)source.Read(9);
|
||||
offset = Take(9);
|
||||
if (offset >= range)
|
||||
{
|
||||
throw new H264Exception("Dati CABAC non validi.");
|
||||
@@ -73,10 +97,12 @@ internal sealed class CabacEngine
|
||||
}
|
||||
}
|
||||
|
||||
while (range < 256)
|
||||
if (range < 256)
|
||||
{
|
||||
range <<= 1;
|
||||
offset = (offset << 1) | reader.ReadBit();
|
||||
// RenormD (§9.3.3.2.2): as many single-bit steps as the range has leading zeros below bit 8.
|
||||
var shift = BitOperations.LeadingZeroCount((uint)range) - 23;
|
||||
range <<= shift;
|
||||
offset = (offset << shift) | Take(shift);
|
||||
}
|
||||
|
||||
return bin;
|
||||
@@ -84,7 +110,7 @@ internal sealed class CabacEngine
|
||||
|
||||
internal int Bypass()
|
||||
{
|
||||
offset = (offset << 1) | reader.ReadBit();
|
||||
offset = (offset << 1) | Take(1);
|
||||
if (offset >= range)
|
||||
{
|
||||
offset -= range;
|
||||
@@ -99,15 +125,45 @@ internal sealed class CabacEngine
|
||||
range -= 2;
|
||||
if (offset >= range)
|
||||
{
|
||||
// The end of the slice or an I_PCM macroblock: the reader goes on exactly after the bits read here.
|
||||
reader.Position = (next * 8) - bits;
|
||||
return 1;
|
||||
}
|
||||
|
||||
while (range < 256)
|
||||
if (range < 256)
|
||||
{
|
||||
range <<= 1;
|
||||
offset = (offset << 1) | reader.ReadBit();
|
||||
offset = (offset << 1) | Take(1);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>The next <paramref name="count"/> bits (1 to 32) of the slice data.</summary>
|
||||
private int Take(int count)
|
||||
{
|
||||
if (bits < count)
|
||||
{
|
||||
Refill();
|
||||
}
|
||||
|
||||
var value = (int)(window >> (64 - count));
|
||||
window <<= count;
|
||||
bits -= count;
|
||||
return value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads four bytes below the valid bits. Past the payload the buffer holds zero padding (see
|
||||
/// <see cref="RbspReader"/>); a damaged slice that reads beyond the padding fails as the bit reader would.
|
||||
/// </summary>
|
||||
private void Refill()
|
||||
{
|
||||
while (bits <= 32)
|
||||
{
|
||||
window |= (ulong)BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(next, 4)) << (32 - bits);
|
||||
next += 4;
|
||||
bits += 32;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -371,7 +371,8 @@ public sealed partial class H264Decoder
|
||||
}
|
||||
}
|
||||
|
||||
return cur!;
|
||||
// Never the picture itself: a frame predicted from its own unfinished samples is corrupt, not damaged.
|
||||
throw new H264Exception("Slice P o B senza immagini di riferimento.");
|
||||
}
|
||||
|
||||
private void PrepareWeights()
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>What an access unit offers to start decoding from (see <see cref="H264Decoder.AccessPoint"/>).</summary>
|
||||
public enum H264AccessPoint
|
||||
{
|
||||
/// <summary>A P or B picture, or no picture: decoding cannot start here.</summary>
|
||||
None,
|
||||
|
||||
/// <summary>A picture of I slices that is not IDR: the pictures after it may still refer to earlier ones.</summary>
|
||||
IntraPicture,
|
||||
|
||||
/// <summary>An IDR picture: nothing after it refers to anything before.</summary>
|
||||
Idr,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Main and High profiles for
|
||||
/// progressive frames in 4:2:0 with 8-bit samples — CAVLC and CABAC, I, P and B slices, 8×8 transform and scaling
|
||||
/// matrices, explicit and implicit weighted prediction, spatial and temporal direct prediction, multiple reference frames
|
||||
/// with list modification and memory management, deblocking. Not handled (an <see cref="H264Exception"/>): interlaced
|
||||
/// pictures (fields and MBAFF), slice groups, SP/SI slices, data partitioning, 4:2:2/4:4:4 and depths above 8 bits.
|
||||
/// matrices, spatial and temporal direct prediction, list modification, deblocking. Written from the standard but not
|
||||
/// yet checked against a conformance stream: explicit and implicit weighted prediction, memory management operations
|
||||
/// and long-term references, gaps in frame_num, picture order count type 1, I_PCM and CABAC pictures of several
|
||||
/// slices. Not handled (an <see cref="H264Exception"/>): interlaced pictures (fields and MBAFF), slice groups, SP/SI
|
||||
/// slices, data partitioning, 4:2:2/4:4:4 and depths above 8 bits. Redundant coded pictures are skipped.
|
||||
/// </summary>
|
||||
public sealed partial class H264Decoder
|
||||
{
|
||||
@@ -20,8 +35,12 @@ public sealed partial class H264Decoder
|
||||
private int picNalType;
|
||||
private int picRefIdc;
|
||||
private bool picMmco5;
|
||||
private bool picSkipped;
|
||||
private int sliceCounter;
|
||||
|
||||
/// <summary>The RBSP of the NAL unit being decoded: one buffer for the whole stream.</summary>
|
||||
private byte[]? rbsp;
|
||||
|
||||
private int prevPocMsb;
|
||||
private int prevPocLsb;
|
||||
private int prevFrameNumOffset;
|
||||
@@ -34,7 +53,10 @@ public sealed partial class H264Decoder
|
||||
private int period;
|
||||
private long decodeCounter;
|
||||
|
||||
/// <summary>Which frames to hand out, by decoding index; null hands out all of them.</summary>
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public Func<long, bool>? Wanted { get; set; }
|
||||
|
||||
/// <summary>Raised for each decoded frame that <see cref="Wanted"/> accepts, in decoding order.</summary>
|
||||
@@ -46,11 +68,7 @@ public sealed partial class H264Decoder
|
||||
/// <summary>Decodes a whole Annex B byte stream (start codes), then flushes the last picture.</summary>
|
||||
public void DecodeAnnexB(ReadOnlySpan<byte> stream)
|
||||
{
|
||||
foreach (var nal in NalUnits.SplitAnnexB(stream))
|
||||
{
|
||||
Decode(nal);
|
||||
}
|
||||
|
||||
DecodeUnitsAnnexB(stream);
|
||||
Flush();
|
||||
}
|
||||
|
||||
@@ -85,7 +103,7 @@ public sealed partial class H264Decoder
|
||||
throw new H264Exception("Configurazione avcC troncata.");
|
||||
}
|
||||
|
||||
Decode(NalUnits.Parse(avcC.Slice(offset, size)));
|
||||
Decode(NalUnits.Unescape(avcC.Slice(offset, size), ref rbsp));
|
||||
offset += size;
|
||||
}
|
||||
}
|
||||
@@ -96,9 +114,10 @@ public sealed partial class H264Decoder
|
||||
/// <summary>Decodes one access unit stored with length prefixes (an MP4 or Matroska sample) and finishes its picture.</summary>
|
||||
public void DecodeSample(ReadOnlySpan<byte> sample, int lengthSize)
|
||||
{
|
||||
foreach (var nal in NalUnits.SplitLengthPrefixed(sample, lengthSize))
|
||||
var position = 0;
|
||||
while (NalUnits.NextLengthPrefixed(sample, lengthSize, ref position, out var unit))
|
||||
{
|
||||
Decode(nal);
|
||||
Decode(NalUnits.Unescape(sample[unit], ref rbsp));
|
||||
}
|
||||
|
||||
FinishPicture();
|
||||
@@ -107,14 +126,59 @@ public sealed partial class H264Decoder
|
||||
/// <summary>Decodes one access unit in Annex B form and finishes its picture.</summary>
|
||||
public void DecodeAccessUnitAnnexB(ReadOnlySpan<byte> accessUnit)
|
||||
{
|
||||
foreach (var nal in NalUnits.SplitAnnexB(accessUnit))
|
||||
{
|
||||
Decode(nal);
|
||||
}
|
||||
|
||||
DecodeUnitsAnnexB(accessUnit);
|
||||
FinishPicture();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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. <paramref name="lengthSize"/>
|
||||
/// is the size of the NAL length fields, 0 for Annex B.
|
||||
/// </summary>
|
||||
public static H264AccessPoint AccessPoint(ReadOnlySpan<byte> 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:
|
||||
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 reader.ReadUe(9) % 5 == (int)SliceType.I ? H264AccessPoint.IntraPicture : H264AccessPoint.None;
|
||||
}
|
||||
catch (H264Exception)
|
||||
{
|
||||
return H264AccessPoint.None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void DecodeUnitsAnnexB(ReadOnlySpan<byte> stream)
|
||||
{
|
||||
var position = 0;
|
||||
while (NalUnits.NextAnnexB(stream, ref position, out var unit))
|
||||
{
|
||||
Decode(NalUnits.Unescape(stream[unit], ref rbsp));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Finishes the picture being decoded, if any.</summary>
|
||||
public void Flush() => FinishPicture();
|
||||
|
||||
@@ -194,15 +258,64 @@ public sealed partial class H264Decoder
|
||||
throw new H264Exception("La codifica senza perdita non è gestita.");
|
||||
}
|
||||
|
||||
if (header.FirstMb == 0 || cur is null)
|
||||
// A redundant coded picture (§7.4.3) repeats the primary one, which is decoded: it is skipped.
|
||||
if (header.RedundantPicCnt > 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (cur is null || picHeader is null || StartsNewPicture(header, nal) || (header.FirstMb == 0 && mbSlice[0] >= 0))
|
||||
{
|
||||
FinishPicture();
|
||||
StartPicture(nal, header, sps);
|
||||
}
|
||||
|
||||
if (picSkipped)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The first slice of a new primary picture (§7.4.1.2.4), compared with the first slice of the current one.</summary>
|
||||
private bool StartsNewPicture(SliceHeader h, NalUnit nal)
|
||||
{
|
||||
var p = picHeader!;
|
||||
if (h.FrameNum != p.FrameNum || h.PpsId != p.PpsId || (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,
|
||||
};
|
||||
}
|
||||
|
||||
private bool HasReference()
|
||||
{
|
||||
foreach (var p in dpb)
|
||||
{
|
||||
if (p.IsReference && !ReferenceEquals(p, cur))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void StartPicture(NalUnit nal, SliceHeader header, Sps sps)
|
||||
{
|
||||
if (activeSps is null || !ReferenceEquals(activeSps, sps))
|
||||
@@ -239,6 +352,9 @@ public sealed partial class H264Decoder
|
||||
sliceCounter = 0;
|
||||
sliceFilters.Clear();
|
||||
Array.Fill(mbSlice, -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 && Wanted is { } wanted && !wanted(cur.DecodeIndex);
|
||||
}
|
||||
|
||||
private Picture NewPicture(Sps sps)
|
||||
@@ -355,13 +471,16 @@ public sealed partial class H264Decoder
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Frames inferred for a gap in frame_num (§8.2.5.2): only their marking matters.</summary>
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private void FillFrameNumGap(int frameNum, Sps sps)
|
||||
{
|
||||
var max = sps.MaxFrameNum;
|
||||
var missing = ((frameNum - prevRefFrameNum - 1) % max + max) % max;
|
||||
var keep = Math.Max(1, sps.MaxNumRefFrames);
|
||||
var first = missing > keep ? (frameNum - keep + max) % max : (prevRefFrameNum + 1) % max;
|
||||
if (missing > keep)
|
||||
{
|
||||
foreach (var p in dpb)
|
||||
@@ -370,8 +489,24 @@ public sealed partial class H264Decoder
|
||||
}
|
||||
}
|
||||
|
||||
for (var n = first; n != frameNum; n = (n + 1) % max)
|
||||
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;
|
||||
@@ -381,12 +516,6 @@ public sealed partial class H264Decoder
|
||||
SlidingWindow(sps, n);
|
||||
gap.ShortTerm = true;
|
||||
dpb.Add(gap);
|
||||
prevRefFrameNum = n;
|
||||
prevFrameNum = n;
|
||||
if (sps.PocType != 0)
|
||||
{
|
||||
prevFrameNumOffset = frameNumOffset;
|
||||
}
|
||||
}
|
||||
|
||||
PruneDpb();
|
||||
@@ -401,7 +530,12 @@ public sealed partial class H264Decoder
|
||||
|
||||
var sps = activeSps;
|
||||
var picture = cur;
|
||||
Deblock(picture);
|
||||
var skipped = picSkipped;
|
||||
picSkipped = false;
|
||||
if (!skipped)
|
||||
{
|
||||
Deblock(picture);
|
||||
}
|
||||
|
||||
if (picRefIdc != 0)
|
||||
{
|
||||
@@ -437,7 +571,7 @@ public sealed partial class H264Decoder
|
||||
haveReference = true;
|
||||
}
|
||||
|
||||
if (Wanted?.Invoke(picture.DecodeIndex) ?? true)
|
||||
if (!skipped && (Wanted?.Invoke(picture.DecodeIndex) ?? true))
|
||||
{
|
||||
FrameDecoded?.Invoke(Crop(picture, sps));
|
||||
}
|
||||
|
||||
@@ -6,6 +6,9 @@ internal sealed class Sps
|
||||
/// <summary>MaxFS of level 6.2 (table A-1), in macroblocks: 8192×4320 fits.</summary>
|
||||
internal const int MaxFrameMbs = 139_264;
|
||||
|
||||
/// <summary>MaxDpbMbs of level 6.2 (table A-1): the largest decoded picture buffer of any level, in macroblocks.</summary>
|
||||
internal const int MaxDpbMbs = 696_320;
|
||||
|
||||
internal int ProfileIdc;
|
||||
internal int LevelIdc;
|
||||
internal int Id;
|
||||
@@ -105,6 +108,13 @@ internal sealed class Sps
|
||||
throw new H264Exception("Immagine più grande di ogni livello H.264.");
|
||||
}
|
||||
|
||||
// The reference frames must fit in the largest buffer of any level (MaxDpbMbs of level 6.2, table A-1; A.3.1
|
||||
// and A.3.2 bound max_num_ref_frames by it): sixteen frames of the largest size would be 1.4 GB.
|
||||
if ((long)s.MaxNumRefFrames * s.WidthInMbs * s.HeightInMbs > MaxDpbMbs)
|
||||
{
|
||||
throw new H264Exception("Troppe immagini di riferimento per ogni livello H.264.");
|
||||
}
|
||||
|
||||
s.Direct8x8Inference = r.ReadFlag();
|
||||
if (r.ReadFlag())
|
||||
{
|
||||
|
||||
@@ -129,105 +129,154 @@ internal readonly record struct NalUnit(int Type, int RefIdc, byte[] Rbsp, int L
|
||||
internal RbspReader Reader() => new(Rbsp, Length, 1);
|
||||
}
|
||||
|
||||
/// <summary>Splitting of byte streams (Annex B) and length-prefixed samples (ISO/IEC 14496-15) into NAL units.</summary>
|
||||
/// <summary>
|
||||
/// Splitting of byte streams (Annex B) and length-prefixed samples (ISO/IEC 14496-15) into NAL units, one at a time, and
|
||||
/// removal of their emulation prevention bytes into a buffer the caller keeps: decoding a sample allocates nothing.
|
||||
/// </summary>
|
||||
internal static class NalUnits
|
||||
{
|
||||
/// <summary>Removes the emulation prevention bytes (0x000003 → 0x0000) of one NAL unit (§7.4.1).</summary>
|
||||
/// <summary>Bytes of zero padding a buffer keeps past the payload (see <see cref="RbspReader"/>).</summary>
|
||||
internal const int Padding = 16;
|
||||
|
||||
/// <summary>Removes the emulation prevention bytes (0x000003 → 0x0000) of one NAL unit (§7.4.1) into a new buffer.</summary>
|
||||
internal static NalUnit Parse(ReadOnlySpan<byte> nal)
|
||||
{
|
||||
byte[]? buffer = null;
|
||||
return Unescape(nal, ref buffer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the emulation prevention bytes of one NAL unit into <paramref name="buffer"/>, grown when needed; the
|
||||
/// unit is valid until the buffer is used again.
|
||||
/// </summary>
|
||||
internal static NalUnit Unescape(ReadOnlySpan<byte> nal, ref byte[]? buffer)
|
||||
{
|
||||
if (nal.Length < 1)
|
||||
{
|
||||
throw new H264Exception("Unità NAL vuota.");
|
||||
}
|
||||
|
||||
var buffer = new byte[nal.Length + 16];
|
||||
var count = 0;
|
||||
var zeros = 0;
|
||||
for (var i = 0; i < nal.Length; i++)
|
||||
if (buffer is null || buffer.Length < nal.Length + Padding)
|
||||
{
|
||||
var b = nal[i];
|
||||
if (zeros >= 2 && b == 3)
|
||||
{
|
||||
zeros = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
buffer[count++] = b;
|
||||
zeros = b == 0 ? zeros + 1 : 0;
|
||||
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.
|
||||
ReadOnlySpan<byte> pattern = [0, 0, 3];
|
||||
var target = buffer.AsSpan();
|
||||
var count = 0;
|
||||
var rest = nal;
|
||||
while (true)
|
||||
{
|
||||
var i = rest.IndexOf(pattern);
|
||||
if (i < 0)
|
||||
{
|
||||
rest.CopyTo(target[count..]);
|
||||
count += rest.Length;
|
||||
break;
|
||||
}
|
||||
|
||||
rest[..(i + 2)].CopyTo(target[count..]);
|
||||
count += i + 2;
|
||||
rest = rest[(i + 3)..];
|
||||
}
|
||||
|
||||
target.Slice(count, Padding).Clear();
|
||||
return new NalUnit(nal[0] & 0x1F, (nal[0] >> 5) & 3, buffer, count);
|
||||
}
|
||||
|
||||
/// <summary>The NAL units of an Annex B byte stream (start codes 0x000001 or 0x00000001).</summary>
|
||||
/// <summary>
|
||||
/// The next NAL unit of an Annex B byte stream (start codes 0x000001 or 0x00000001) from <paramref name="position"/>,
|
||||
/// which moves past it; false when there is none left.
|
||||
/// </summary>
|
||||
internal static bool NextAnnexB(ReadOnlySpan<byte> stream, ref int position, out Range unit)
|
||||
{
|
||||
ReadOnlySpan<byte> startCode = [0, 0, 1];
|
||||
while (position < stream.Length)
|
||||
{
|
||||
var found = stream[position..].IndexOf(startCode);
|
||||
if (found < 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var start = position + found + 3;
|
||||
var next = start < stream.Length ? stream[start..].IndexOf(startCode) : -1;
|
||||
var end = next < 0 ? stream.Length : start + next;
|
||||
position = end;
|
||||
|
||||
// Zero bytes before the next start code belong to it (four-byte start codes, trailing_zero_8bits).
|
||||
var trimmed = end;
|
||||
while (trimmed > start && stream[trimmed - 1] == 0)
|
||||
{
|
||||
trimmed--;
|
||||
}
|
||||
|
||||
if (trimmed > start)
|
||||
{
|
||||
unit = start..trimmed;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
position = stream.Length;
|
||||
unit = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The next NAL unit of a sample whose units are each prefixed by a big-endian length, from
|
||||
/// <paramref name="position"/>; false at the end or at a damaged length (what was read stands).
|
||||
/// </summary>
|
||||
internal static bool NextLengthPrefixed(ReadOnlySpan<byte> sample, int lengthSize, ref int position, out Range unit)
|
||||
{
|
||||
unit = default;
|
||||
if (position + lengthSize > sample.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var size = 0;
|
||||
for (var k = 0; k < lengthSize; k++)
|
||||
{
|
||||
size = (size << 8) | sample[position + k];
|
||||
}
|
||||
|
||||
position += lengthSize;
|
||||
if (size <= 0 || size > sample.Length - position)
|
||||
{
|
||||
position = sample.Length;
|
||||
return false;
|
||||
}
|
||||
|
||||
unit = position..(position + size);
|
||||
position += size;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The NAL units of an Annex B byte stream, each in its own buffer (for tools and tests).</summary>
|
||||
internal static List<NalUnit> SplitAnnexB(ReadOnlySpan<byte> stream)
|
||||
{
|
||||
var units = new List<NalUnit>();
|
||||
var start = -1;
|
||||
var i = 0;
|
||||
while (i + 2 < stream.Length)
|
||||
var position = 0;
|
||||
while (NextAnnexB(stream, ref position, out var unit))
|
||||
{
|
||||
if (stream[i] == 0 && stream[i + 1] == 0 && stream[i + 2] == 1)
|
||||
{
|
||||
if (start >= 0)
|
||||
{
|
||||
AddTrimmed(units, stream[start..i]);
|
||||
}
|
||||
|
||||
i += 3;
|
||||
start = i;
|
||||
continue;
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
if (start >= 0 && start < stream.Length)
|
||||
{
|
||||
AddTrimmed(units, stream[start..]);
|
||||
units.Add(Parse(stream[unit]));
|
||||
}
|
||||
|
||||
return units;
|
||||
}
|
||||
|
||||
/// <summary>The NAL units of a sample whose units are each prefixed by a big-endian length.</summary>
|
||||
/// <summary>The NAL units of a length-prefixed sample, each in its own buffer (for tools and tests).</summary>
|
||||
internal static List<NalUnit> SplitLengthPrefixed(ReadOnlySpan<byte> sample, int lengthSize)
|
||||
{
|
||||
var units = new List<NalUnit>();
|
||||
var offset = 0;
|
||||
while (offset + lengthSize <= sample.Length)
|
||||
var position = 0;
|
||||
while (NextLengthPrefixed(sample, lengthSize, ref position, out var unit))
|
||||
{
|
||||
var size = 0;
|
||||
for (var k = 0; k < lengthSize; k++)
|
||||
{
|
||||
size = (size << 8) | sample[offset + k];
|
||||
}
|
||||
|
||||
offset += lengthSize;
|
||||
if (size <= 0 || size > sample.Length - offset)
|
||||
{
|
||||
break; // damaged: keep what was read
|
||||
}
|
||||
|
||||
units.Add(Parse(sample.Slice(offset, size)));
|
||||
offset += size;
|
||||
units.Add(Parse(sample[unit]));
|
||||
}
|
||||
|
||||
return units;
|
||||
}
|
||||
|
||||
private static void AddTrimmed(List<NalUnit> units, ReadOnlySpan<byte> nal)
|
||||
{
|
||||
// Zero bytes before the next start code belong to it (four-byte start codes, trailing_zero_8bits).
|
||||
var end = nal.Length;
|
||||
while (end > 0 && nal[end - 1] == 0)
|
||||
{
|
||||
end--;
|
||||
}
|
||||
|
||||
if (end > 0)
|
||||
{
|
||||
units.Add(Parse(nal[..end]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,10 @@ internal sealed class SliceHeader
|
||||
internal int DeltaPocBottom;
|
||||
internal int DeltaPoc0;
|
||||
internal int DeltaPoc1;
|
||||
|
||||
/// <summary>redundant_pic_cnt: 0 for the primary coded picture, above 0 for a redundant one.</summary>
|
||||
internal int RedundantPicCnt;
|
||||
|
||||
internal bool DirectSpatialMvPred;
|
||||
internal int NumRefIdxActiveL0;
|
||||
internal int NumRefIdxActiveL1;
|
||||
@@ -105,7 +109,7 @@ internal sealed class SliceHeader
|
||||
|
||||
if (pps.RedundantPicCntPresent)
|
||||
{
|
||||
r.ReadUe(); // redundant_pic_cnt
|
||||
h.RedundantPicCnt = r.ReadUe(127);
|
||||
}
|
||||
|
||||
if (h.IsB)
|
||||
|
||||
Reference in new issue
Block a user