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,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));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user