Contenitori e decodificatore H.264 provati sui file rovinati; corretti trex, data_offset e ordine dei blocchi MP4 (#58)

Revisione del lavoro in corso sui lettori in casa che sostituiscono ffmpeg e ffprobe. La corsa completa di tests/Febe.Tests ora è verde.

Difetti corretti:
- ISO BMFF frammentato: i valori di trex erano letti con i campi scambiati (la durata predefinita prendeva la dimensione, i flag andavano persi) e il data_offset di un secondo trun si sommava alla fine del primo invece che alla base del moof.
- Mp4Writer: i blocchi di una traccia con tempi uguali (audio senza tempi, come da AVI) potevano uscire fuori ordine, perché l'ordinamento non è stabile; ora restano nell'ordine dei campioni.
- Durata di un MP4 frammentato nella sola lettura dei metadati: da mehd o, se manca, dai frammenti (prima restava ignota).
- File danneggiati: un stsz o un trun di pochi byte poteva chiedere centinaia di MB, un elemento Matroska più grande del file veniva allocato, un salto oltre i 2 GB faceva fallire MemoryStream, IndexOutOfRange e conversioni di date e durate uscivano come eccezioni non previste. Ora ogni tabella si controlla contro il file prima di allocare, al più 2.000.000 di campioni per traccia e 64 MB per campione, e una traccia MP4 con tabelle rovinate resta senza campioni senza togliere le altre.
- H.264: un SPS oltre il MaxFS del livello 6.2 o con un ritaglio che non lascia immagine è rifiutato prima di allocare; mai più riferimenti di Max(max_num_ref_frames, 1); gli errori di deblocco e ritaglio escono come H264Exception.
- VideoFrameDecoder: i fotogrammi si associano al campione decodificato, non al conteggio del decodificatore (un campione senza immagine non sposta più quelli dopo); un campione oltre la fine di un file troncato non toglie i fotogrammi già decodificati; il fotogramma per la miniatura è ridotto a 960 pixel sul lato lungo.

Prove nuove: file troncati e rovinati con semi fissi per MP4, MP4 frammentato, Matroska e AVI (lettori, sonda e decodificatore dei fotogrammi, con limite di memoria allocata), flussi di conformità rovinati per il decodificatore H.264, SPS troppo grande e ritaglio non valido, MP4 frammentato con valori predefiniti e due trun, ordine dei blocchi con tempi uguali. Le prove nuove dei difetti falliscono sul codice di prima.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 13:15:52 +01:00
1 parent 6ffcb1bb18
commit 479c95f899
14 files changed
+787 -113

No files matched your search

@@ -24,7 +24,7 @@ public static class MatroskaReader
private const uint ChaptersId = 0x1043A770;
private const uint SeekHeadId = 0x114D9B74;
private const long UnknownSize = -1;
private const int MaxSamples = 20_000_000;
private const int MaxSamples = IsoBmffReader.MaxSamples;
private const long MaxElementInMemory = 64L * 1024 * 1024;
/// <summary>True when the stream starts with an EBML header.</summary>
@@ -65,7 +65,7 @@ public static class MatroskaReader
throw new ContainerException("Documento EBML che non è Matroska.");
}
stream.Position = end;
stream.Position = Math.Min(end, stream.Length);
(id, size) = reader.Header();
while (id != SegmentId)
{
@@ -138,10 +138,15 @@ public static class MatroskaReader
state.TimecodeScale = (long)reader.Unsigned(size);
break;
case 0x4489:
state.DurationTicks = reader.Float(size);
break;
{
var ticks = reader.Float(size);
state.DurationTicks = double.IsFinite(ticks) && ticks > 0 ? ticks : 0;
break;
}
case 0x4461:
{
// Nanoseconds from 2001: about ±292 years, always inside the range of a date.
var ns = reader.Signed(size);
var instant = Epoch2001.AddTicks(ns / 100);
if (instant >= Earliest && instant <= now.AddDays(1))
@@ -171,6 +176,11 @@ public static class MatroskaReader
continue;
}
if (size < 0)
{
throw new ContainerException("Elemento Matroska di lunghezza ignota.");
}
var entryEnd = stream.Position + size;
var track = new TrackEntry();
while (stream.Position < entryEnd)
@@ -267,7 +277,7 @@ public static class MatroskaReader
}
}
stream.Position = entryEnd;
stream.Position = Math.Min(entryEnd, stream.Length);
if (track.Type == 1 && state.Video is null)
{
state.Video = track;
@@ -372,12 +382,23 @@ public static class MatroskaReader
var dataStart = stream.Position;
if (lacing == 0)
{
if (end - dataStart is <= 0 or > int.MaxValue)
{
throw new ContainerException("Blocco Matroska danneggiato.");
}
target.Samples.Add(new MediaSample(dataStart, (int)(end - dataStart), time, time, key));
return;
}
var frames = stream.ReadByte() + 1;
var sizes = new long[frames];
var count = stream.ReadByte();
if (count < 0 || dataStart >= end)
{
throw new ContainerException("Blocco Matroska troncato.");
}
var frames = count + 1;
Span<long> sizes = stackalloc long[frames];
switch (lacing)
{
case 1: // Xiph
@@ -438,12 +459,17 @@ public static class MatroskaReader
var frameDuration = target.DefaultDuration > 0 && state.TimecodeScale > 0 ? target.DefaultDuration / state.TimecodeScale : 0;
for (var i = 0; i < frames; i++)
{
if (sizes[i] < 0 || offset + sizes[i] > end)
if (sizes[i] < 0 || sizes[i] > int.MaxValue || offset + sizes[i] > end)
{
throw new ContainerException("Blocco Matroska danneggiato.");
}
var t = time + (i * frameDuration);
if (sizes[i] == 0)
{
continue; // an empty frame has nothing to decode (and costs no memory)
}
target.Samples.Add(new MediaSample(offset, (int)sizes[i], t, t, key));
offset += sizes[i];
}
@@ -515,7 +541,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 = (long)DurationTicks,
Duration = DurationTicks < long.MaxValue / 2 ? (long)DurationTicks : 0,
Samples = samples,
};
}
@@ -539,12 +565,13 @@ public static class MatroskaReader
Channels = a.Channels,
AacConfiguration = a.CodecId == "A_AAC" ? a.CodecPrivate : null,
Timescale = timescale,
Duration = (long)DurationTicks,
Duration = DurationTicks < long.MaxValue / 2 ? (long)DurationTicks : 0,
Samples = a.Samples,
};
}
TimeSpan? duration = DurationTicks > 0 ? TimeSpan.FromSeconds(DurationTicks * TimecodeScale / 1e9) : null;
var seconds = DurationTicks * TimecodeScale / 1e9;
TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null;
return new MediaContainer { Format = ContainerFormat.Matroska, CreatedAt = Created, Duration = duration, Video = video, Audio = audio };
}
}
@@ -654,6 +681,11 @@ public static class MatroskaReader
throw new ContainerException("Elemento Matroska troppo grande.");
}
if (size > stream.Length - stream.Position)
{
throw new ContainerException("File Matroska troncato."); // before allocating what the file cannot hold
}
var data = new byte[size];
stream.ReadExactly(data);
return data;
@@ -666,7 +698,8 @@ public static class MatroskaReader
throw new ContainerException("Elemento Matroska di lunghezza ignota.");
}
stream.Position += size;
// Past the end of a truncated or damaged file the reading simply ends there.
stream.Position = size > stream.Length - stream.Position ? stream.Length : stream.Position + size;
}
private int ReadByteOrThrow()