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:
1 parent
6ffcb1bb18
commit
479c95f899
14 files changed
+787
-113
No files matched your search
@@ -0,0 +1,209 @@
|
||||
using System.Buffers.Binary;
|
||||
using Febe.Core.Codecs.Containers;
|
||||
using Febe.Core.Import;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Codecs.Containers;
|
||||
|
||||
/// <summary>
|
||||
/// Truncated and garbled videos: the container readers, the metadata probe and the frame decoder must survive every one
|
||||
/// of them with a <see cref="ContainerException"/> (or <see cref="EndOfStreamException"/>), a null result or a frame,
|
||||
/// and must never allocate much more than the file holds, whatever its damaged headers claim.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class MalformedInputTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 18, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("mp4")]
|
||||
[DataRow("frammentato.mp4")]
|
||||
[DataRow("mkv")]
|
||||
[DataRow("avi")]
|
||||
public void TruncatedFilesNeverBreakTheReaders(string kind)
|
||||
{
|
||||
var file = Build(kind);
|
||||
var step = Math.Max(1, file.Length / 300);
|
||||
for (var length = 0; length < file.Length; length += step)
|
||||
{
|
||||
AssertReadersSurvive(file[..length], $"{kind} troncato a {length}");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("mp4", 5801)]
|
||||
[DataRow("frammentato.mp4", 5802)]
|
||||
[DataRow("mkv", 5803)]
|
||||
[DataRow("avi", 5804)]
|
||||
public void GarbledFilesNeverBreakTheReaders(string kind, int seed)
|
||||
{
|
||||
var file = Build(kind);
|
||||
var random = new Random(seed);
|
||||
for (var trial = 0; trial < 400; trial++)
|
||||
{
|
||||
AssertReadersSurvive(Garble(file, random), $"{kind}, variante {trial} del seme {seed}");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("mp4", 5811)]
|
||||
[DataRow("frammentato.mp4", 5812)]
|
||||
[DataRow("mkv", 5813)]
|
||||
[DataRow("avi", 5814)]
|
||||
public async Task GarbledFilesNeverBreakTheProbeOrTheFrameDecoder(string kind, int seed)
|
||||
{
|
||||
var file = Build(kind);
|
||||
var random = new Random(seed);
|
||||
using var temp = new TempFolder("rovinati");
|
||||
var decoded = 0;
|
||||
for (var trial = 0; trial < 60; trial++)
|
||||
{
|
||||
var path = TestVideos.Write(temp, $"{trial}.{kind}", Garble(file, random));
|
||||
_ = ContainerVideoMetadataProbe.Probe(path, Now); // null or metadata, never an exception
|
||||
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1));
|
||||
var stillness = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(path);
|
||||
decoded += image is null ? 0 : 1;
|
||||
_ = stillness;
|
||||
}
|
||||
|
||||
// Most damage hits frame data, not headers: many variants still give a frame.
|
||||
Assert.IsGreaterThan(0, decoded, "nessuna variante ha dato un fotogramma");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AHugeSampleCountInATinyMp4AllocatesNothing()
|
||||
{
|
||||
var es = ElementaryStream.Load("CABA3_SVA_B");
|
||||
|
||||
// stsz with a fixed sample size of 1 and almost two million samples: far more than the file can hold.
|
||||
var file = TestVideos.Mp4(es);
|
||||
var stsz = IndexOf(file, "stsz"u8);
|
||||
BinaryPrimitives.WriteUInt32BigEndian(file.AsSpan(stsz + 8), 1);
|
||||
BinaryPrimitives.WriteUInt32BigEndian(file.AsSpan(stsz + 12), 1_999_999);
|
||||
var container = ReadMeasured(file, out var allocated);
|
||||
Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati");
|
||||
Assert.IsEmpty(container!.Video!.Samples, "una tabella impossibile non dà campioni");
|
||||
|
||||
// A trun of two billion samples without per-sample fields.
|
||||
var fragmented = TestVideos.FragmentedMp4(es, perFragment: 5);
|
||||
var trun = IndexOf(fragmented, "trun"u8);
|
||||
BinaryPrimitives.WriteUInt32BigEndian(fragmented.AsSpan(trun + 4), 0x000001); // only data_offset
|
||||
BinaryPrimitives.WriteUInt32BigEndian(fragmented.AsSpan(trun + 8), int.MaxValue);
|
||||
container = ReadMeasured(fragmented, out allocated);
|
||||
Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati");
|
||||
Assert.IsNotNull(container);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AMatroskaElementLargerThanTheFileAllocatesNothing()
|
||||
{
|
||||
var es = ElementaryStream.Load("BA1_Sony_D");
|
||||
var file = TestVideos.Matroska(es);
|
||||
|
||||
// CodecPrivate (0x63A2) with an eight-byte size: claim 60 MB in a file of a few kilobytes.
|
||||
var codecPrivate = IndexOf(file, [0x63, 0xA2, 0x01]);
|
||||
file[codecPrivate + 2] = 0x01;
|
||||
var size = new byte[8];
|
||||
BinaryPrimitives.WriteUInt64BigEndian(size, 60L * 1024 * 1024);
|
||||
size.AsSpan(1).CopyTo(file.AsSpan(codecPrivate + 3));
|
||||
long allocated = 0;
|
||||
Assert.ThrowsExactly<ContainerException>(() => ReadMeasured(file, out allocated));
|
||||
Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati");
|
||||
}
|
||||
|
||||
private static void AssertReadersSurvive(byte[] data, string what)
|
||||
{
|
||||
foreach (var samples in new[] { false, true })
|
||||
{
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
try
|
||||
{
|
||||
using var stream = new MemoryStream(data, writable: false);
|
||||
var container = ContainerReader.Read(stream, Now, samples);
|
||||
if (samples && container?.Video is { } video)
|
||||
{
|
||||
// Every sample listed is inside the file, or reading it says so.
|
||||
var buffer = Array.Empty<byte>();
|
||||
foreach (var sample in video.Samples.Take(50))
|
||||
{
|
||||
try
|
||||
{
|
||||
_ = ContainerReader.ReadSample(stream, sample, ref buffer);
|
||||
}
|
||||
catch (ContainerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (ContainerException)
|
||||
{
|
||||
}
|
||||
catch (EndOfStreamException)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Assert.Fail($"{what} (campioni: {samples}): {ex.GetType().Name} {ex.Message}\n{ex.StackTrace}");
|
||||
}
|
||||
|
||||
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
|
||||
Assert.IsLessThan((16L * 1024 * 1024) + (64L * data.Length), allocated, $"{what}: {allocated} byte allocati per {data.Length} byte di file");
|
||||
}
|
||||
}
|
||||
|
||||
private static MediaContainer? ReadMeasured(byte[] file, out long allocated)
|
||||
{
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
try
|
||||
{
|
||||
using var stream = new MemoryStream(file, writable: false);
|
||||
return ContainerReader.Read(stream, Now);
|
||||
}
|
||||
finally
|
||||
{
|
||||
allocated = GC.GetAllocatedBytesForCurrentThread() - before;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] Build(string kind)
|
||||
{
|
||||
var es = ElementaryStream.Load("CABA3_SVA_B");
|
||||
return kind switch
|
||||
{
|
||||
"frammentato.mp4" => TestVideos.FragmentedMp4(es, perFragment: 6, defaults: true),
|
||||
"mkv" => TestVideos.Matroska(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)),
|
||||
"avi" => TestVideos.Avi(es, "Thu Mar 04 05:06:07 2021"),
|
||||
_ => TestVideos.Mp4(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero), rotation: 90, audio: true),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A copy with a few bytes changed: mostly in the first kilobytes, where the headers are.</summary>
|
||||
private static byte[] Garble(byte[] file, Random random)
|
||||
{
|
||||
var copy = (byte[])file.Clone();
|
||||
var changes = 1 + random.Next(12);
|
||||
for (var k = 0; k < changes; k++)
|
||||
{
|
||||
var range = random.Next(3) == 0 ? copy.Length : Math.Min(copy.Length, 2048);
|
||||
var p = random.Next(range);
|
||||
copy[p] = random.Next(4) switch
|
||||
{
|
||||
0 => (byte)random.Next(256),
|
||||
1 => (byte)(copy[p] ^ (1 << random.Next(8))),
|
||||
2 => 0xFF,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
|
||||
return random.Next(5) == 0 ? copy[..random.Next(copy.Length)] : copy;
|
||||
}
|
||||
|
||||
private static int IndexOf(byte[] data, ReadOnlySpan<byte> pattern)
|
||||
{
|
||||
var index = data.AsSpan().IndexOf(pattern);
|
||||
Assert.IsGreaterThanOrEqualTo(0, index);
|
||||
return index;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user