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

+9 -3
View File
@@ -19,7 +19,7 @@ public static class AviReader
start.Length >= 12 && start[..4].SequenceEqual("RIFF"u8) && start.Slice(8, 4).SequenceEqual("AVI "u8);
/// <summary>Reads a seekable stream from its start.</summary>
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(stream);
var state = new State();
@@ -29,6 +29,7 @@ public static class AviReader
var first = true;
while (position + 12 <= length)
{
ct.ThrowIfCancellationRequested();
stream.Position = position;
stream.ReadExactly(header);
if (!header[..4].SequenceEqual("RIFF"u8))
@@ -307,6 +308,9 @@ public static class AviReader
var tag = (Compression.Length == 4 ? Compression : VideoHandler).ToUpperInvariant();
var frames = VideoLength > 0 ? VideoLength : TotalFrames;
// Header values are taken as stored: a damaged one never gives an overflowing or negative duration.
var trackDuration = frames <= long.MaxValue / frameTicks ? frames * frameTicks : 0;
var video = VideoStream < 0 ? null : new VideoTrack
{
Codec = tag switch
@@ -322,7 +326,7 @@ public static class AviReader
Height = VideoHeight > 0 ? VideoHeight : Height,
AnnexB = true,
Timescale = timescale,
Duration = frames * frameTicks,
Duration = trackDuration,
Samples = samples,
};
@@ -353,7 +357,9 @@ public static class AviReader
};
}
TimeSpan? duration = video is { Duration: > 0 } ? TimeSpan.FromSeconds(video.Seconds(video.Duration)) : null;
// As the other readers: beyond what a video can last (a damaged header) there is no duration, and the rest stands.
var seconds = video is { Duration: > 0 } ? video.Seconds(video.Duration) : 0;
TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null;
return new MediaContainer { Format = ContainerFormat.Avi, CreatedAt = Created, Duration = duration, Video = video, Audio = audio };
}
@@ -24,9 +24,10 @@ public static class ContainerReader
/// <summary>
/// Reads a seekable stream; null when its format is not recognised. Damaged files raise
/// <see cref="ContainerException"/> (or <see cref="EndOfStreamException"/> when truncated).
/// <see cref="ContainerException"/> (or <see cref="EndOfStreamException"/> when truncated); <paramref name="ct"/> is
/// checked between the top-level boxes, elements and fragments.
/// </summary>
public static MediaContainer? Read(Stream stream, DateTimeOffset now, bool samples = true)
public static MediaContainer? Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(stream);
Span<byte> start = stackalloc byte[16];
@@ -35,18 +36,18 @@ public static class ContainerReader
stream.Position = 0;
return Detect(start[..read]) switch
{
ContainerFormat.Matroska => MatroskaReader.Read(stream, now, samples),
ContainerFormat.Avi => AviReader.Read(stream, now, samples),
ContainerFormat.IsoBmff => IsoBmffReader.Read(stream, now, samples),
ContainerFormat.Matroska => MatroskaReader.Read(stream, now, samples, ct),
ContainerFormat.Avi => AviReader.Read(stream, now, samples, ct),
ContainerFormat.IsoBmff => IsoBmffReader.Read(stream, now, samples, ct),
_ => null,
};
}
/// <summary>Reads a file (read-only, shared); null when its format is not recognised.</summary>
public static MediaContainer? ReadFile(string path, DateTimeOffset now, bool samples = true)
public static MediaContainer? ReadFile(string path, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
using var stream = OpenRead(path);
return Read(stream, now, samples);
return Read(stream, now, samples, ct);
}
/// <summary>Opens a file for reading without blocking other readers or writers.</summary>
@@ -27,8 +27,12 @@ public static class IsoBmffReader
/// <summary>Reads a seekable stream from its start.</summary>
/// <param name="stream">The file.</param>
/// <param name="now">Current time: later creation times are ignored.</param>
/// <param name="samples">False to stop at the metadata (no sample tables, no fragments).</param>
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
/// <param name="samples">
/// False to stop at the metadata: no sample tables, and fragments only when they alone tell the duration (then only
/// their durations are added up).
/// </param>
/// <param name="ct">Checked between the top-level boxes (each fragment of a fragmented file).</param>
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(stream);
var length = stream.Length;
@@ -38,6 +42,7 @@ public static class IsoBmffReader
var pending = new List<(long Start, byte[] Body)>();
for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++)
{
ct.ThrowIfCancellationRequested();
stream.Position = position;
stream.ReadExactly(header[..8]);
long size = BinaryPrimitives.ReadUInt32BigEndian(header);
@@ -137,7 +142,17 @@ public static class IsoBmffReader
movie.ParseMvhd(body, now);
break;
case "trak":
movie.ParseTrak(moov, start, count);
try
{
movie.ParseTrak(moov, start, count);
}
catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException
or ContainerException)
{
// A damaged track header, edit list or description (often of the audio track): that track is
// dropped, the others are still read.
}
break;
case "mvex":
movie.Fragmented = true;
@@ -406,6 +421,11 @@ public static class IsoBmffReader
var stz2 = false;
foreach (var (type, s, c) in Children(data, start, count))
{
if (!samples && type != "stsd")
{
continue; // metadata only: the tables are not even copied
}
switch (type)
{
case "stsd":
@@ -528,6 +548,11 @@ public static class IsoBmffReader
{
case 0x03: // ES_Descriptor
{
if (p + 3 > body.Length)
{
return null;
}
var flags = body[p + 2];
p += 3;
if ((flags & 0x80) != 0)
@@ -537,6 +562,11 @@ public static class IsoBmffReader
if ((flags & 0x40) != 0)
{
if (p >= body.Length)
{
return null;
}
p += 1 + body[p];
}
@@ -789,12 +819,22 @@ public static class IsoBmffReader
var bounded = perSample > 0
? (long)n * perSample <= body.Length - p
: (long)n * Math.Max(1u, defSize) <= fileLength;
if (n < 0 || !bounded || track.Samples.Count + n > MaxSamples)
if (n < 0 || !bounded || (samples && track.Samples.Count + n > MaxSamples))
{
throw new ContainerException("Troppi campioni.");
}
var dts = decodeTime ?? Math.Max(0, track.FragmentTime);
if (!samples)
{
// Metadata only: the fragments are read for the duration, so only durations add up.
var run = RunDuration(body[p..], flags, n, defDuration);
dts = run > (long.MaxValue / 2) - dts ? long.MaxValue / 2 : dts + run;
track.FragmentTime = dts;
decodeTime = dts;
break;
}
for (var i = 0; i < n; i++)
{
var duration = defDuration;
@@ -840,6 +880,24 @@ public static class IsoBmffReader
}
}
/// <summary>The total duration of the <paramref name="count"/> samples of a trun, from their fields after the header.</summary>
private static long RunDuration(ReadOnlySpan<byte> fields, uint flags, int count, uint defaultDuration)
{
if ((flags & 0x100) == 0)
{
return (long)count * defaultDuration;
}
var stride = 4 * (int)(((flags >> 8) & 1) + ((flags >> 9) & 1) + ((flags >> 10) & 1) + ((flags >> 11) & 1));
long total = 0;
for (var i = 0; i < count; i++)
{
total += BinaryPrimitives.ReadUInt32BigEndian(fields[(i * stride)..]); // the duration comes first
}
return total;
}
internal MediaContainer Build()
{
var video = tracks.Find(t => t.Handler == "vide");
@@ -34,7 +34,8 @@ public static class MatroskaReader
/// <param name="stream">The file.</param>
/// <param name="now">Current time: later creation times are ignored.</param>
/// <param name="samples">False to stop before the first cluster.</param>
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
/// <param name="ct">Checked between the top-level elements.</param>
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(stream);
var reader = new Reader(stream);
@@ -82,45 +83,55 @@ public static class MatroskaReader
var state = new State();
while (stream.Position < segmentEnd)
{
ct.ThrowIfCancellationRequested();
var elementStart = stream.Position;
if (segmentEnd - elementStart < 2)
{
break;
}
(id, size) = reader.Header();
var bodyEnd = size < 0 ? segmentEnd : stream.Position + size;
if (bodyEnd > segmentEnd)
try
{
bodyEnd = segmentEnd; // truncated file
}
(id, size) = reader.Header();
var bodyEnd = size < 0 ? segmentEnd : stream.Position + size;
if (bodyEnd > segmentEnd)
{
bodyEnd = segmentEnd; // truncated file
}
switch (id)
switch (id)
{
case InfoId:
ParseInfo(reader, bodyEnd, state, now);
break;
case TracksId:
ParseTracks(reader, bodyEnd, state);
break;
case ClusterId:
if (!samples)
{
return state.Build();
}
ParseCluster(reader, bodyEnd, size < 0, state);
continue; // the position is already past the cluster
default:
if (size < 0)
{
throw new ContainerException("Elemento Matroska di lunghezza ignota.");
}
break;
}
stream.Position = bodyEnd;
}
catch (Exception ex) when ((ex is ContainerException or EndOfStreamException) && state.HasSamples)
{
case InfoId:
ParseInfo(reader, bodyEnd, state, now);
break;
case TracksId:
ParseTracks(reader, bodyEnd, state);
break;
case ClusterId:
if (!samples)
{
return state.Build();
}
ParseCluster(reader, bodyEnd, size < 0, state);
continue; // the position is already past the cluster
default:
if (size < 0)
{
throw new ContainerException("Elemento Matroska di lunghezza ignota.");
}
break;
// A damaged or truncated block after the first ones, or more samples than the limit: what was read
// stands, as in the ISO reader.
break;
}
stream.Position = bodyEnd;
}
return state.Build();
@@ -377,7 +388,7 @@ public static class MatroskaReader
throw new ContainerException("Troppi campioni.");
}
var time = clusterTime + relative;
var time = state.ToUnits(clusterTime + relative);
var lacing = (flags >> 1) & 3;
var dataStart = stream.Position;
if (lacing == 0)
@@ -456,7 +467,7 @@ public static class MatroskaReader
}
var offset = dataBegin;
var frameDuration = target.DefaultDuration > 0 && state.TimecodeScale > 0 ? target.DefaultDuration / state.TimecodeScale : 0;
var frameDuration = target.DefaultDuration > 0 ? target.DefaultDuration / state.UnitNanoseconds : 0;
for (var i = 0; i < frames; i++)
{
if (sizes[i] < 0 || sizes[i] > int.MaxValue || offset + sizes[i] > end)
@@ -498,9 +509,53 @@ public static class MatroskaReader
internal TrackEntry? Video;
internal TrackEntry? Audio;
/// <summary>Nanoseconds of one unit of the sample times; fixed by the first block, 0 before.</summary>
private long unit;
internal bool HasSamples => Video?.Samples.Count > 0 || Audio?.Samples.Count > 0;
/// <summary>
/// Nanoseconds of one unit of the sample times: the greatest common divisor of TimecodeScale and a second, so
/// that the timescale of the tracks (a second in units) is exact for any TimecodeScale (3 ms gives units of
/// 1 ms, 2 s units of 1 s) and the block times are whole units.
/// </summary>
internal long UnitNanoseconds
{
get
{
if (unit == 0)
{
long a = Scale, b = 1_000_000_000;
while (b != 0)
{
(a, b) = (b, a % b);
}
unit = a;
}
return unit;
}
}
/// <summary>TimecodeScale (nanoseconds of a tick of the block times); the default for a damaged value.</summary>
private long Scale => TimecodeScale > 0 ? TimecodeScale : 1_000_000;
/// <summary>Units of <see cref="UnitNanoseconds"/> in a tick (at least 1, should Info come after the first block).</summary>
private long Factor => Math.Max(1, Scale / UnitNanoseconds);
/// <summary>A time in TimecodeScale ticks as a time in units of <see cref="UnitNanoseconds"/>.</summary>
internal long ToUnits(long ticks)
{
var limit = long.MaxValue / 4 / Factor;
return Math.Clamp(ticks, -limit, limit) * Factor; // a damaged cluster time stays a (wrong) number
}
internal MediaContainer Build()
{
var timescale = Math.Max(1, 1_000_000_000L / Math.Max(1, TimecodeScale));
var timescale = 1_000_000_000L / UnitNanoseconds;
var trackDuration = DurationTicks * Factor;
var trackUnits = trackDuration is > 0 and < long.MaxValue / 2 ? (long)trackDuration : 0;
VideoTrack? video = null;
if (Video is { } v)
{
@@ -541,7 +596,7 @@ public static class MatroskaReader
Rotation = roll is 90 or 180 or 270 ? roll : 0,
AvcConfiguration = v.CodecId == "V_MPEG4/ISO/AVC" ? v.CodecPrivate : null,
Timescale = timescale,
Duration = DurationTicks < long.MaxValue / 2 ? (long)DurationTicks : 0,
Duration = trackUnits,
Samples = samples,
};
}
@@ -565,7 +620,7 @@ public static class MatroskaReader
Channels = a.Channels,
AacConfiguration = a.CodecId == "A_AAC" ? a.CodecPrivate : null,
Timescale = timescale,
Duration = DurationTicks < long.MaxValue / 2 ? (long)DurationTicks : 0,
Duration = trackUnits,
Samples = a.Samples,
};
}