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:
Alby96andClaude Opus 5.5 committed 2026-11-18 14:13:45 +01:00
1 parent 479c95f899
commit b23632fc96
22 files changed
+1273 -282

No files matched your search

+118 -69
View File
@@ -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]));
}
}
}