Files
Febe/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs
T
Alby96andClaude Opus 5.5 6c8b228333 Lettori in casa di WMV/ASF, FLV e MPEG: data, durata, dimensioni e codec anche per questi video (#58)
Finora MediaSniffer riconosceva WMV, FLV e MPEG ma la sonda dei metadati non ne sapeva nulla:
data, durata e dimensioni venivano solo dal nome e dalla data di modifica. Tre lettori nuovi,
scritti dalle specifiche pubbliche senza componenti esterni, stanno dietro ContainerReader e
quindi dietro ContainerVideoMetadataProbe e VideoFrameDecoder.

- AsfReader: proprietà del file (data FILETIME, durata meno il preroll, niente durata per le
  trasmissioni), proprietà dei flussi anche dentro l'estensione dell'intestazione, titolo della
  descrizione del contenuto, WM/EncodingTime quando manca la data. Nessun campione.
- FlvReader: onMetaData in AMF0 (durata, dimensioni, creationdate come testo o come data),
  dimensioni dall'SPS della sequenza AVC o dall'intestazione H.263 di Sorenson, durata
  dall'ultimo tag senza metadati, codec degli FLV «enhanced» dal FourCC; i tag H.264 sono
  campioni, così anche un FLV ha la miniatura.
- MpegPsReader: pacchetti MPEG-1 e MPEG-2, intestazione di sistema, mappa del flusso, PES; codec
  e dimensioni dall'intestazione di sequenza (con l'estensione di MPEG-2) o dall'SPS H.264, audio
  MPEG, ADTS, AC-3 e LPCM; durata dal primo all'ultimo PTS attraverso il giro dei 33 bit,
  leggendo solo i primi 2 MB e l'ultimo MB.
- H264StreamInfo: dimensioni ritagliate di un SPS, da un avcC o da un flusso Annex B.
- MediaSniffer: un WMA o un FLV di solo audio non è più un video, quando l'intestazione intera
  nei primi byte lo dimostra.

Prove con file costruiti dalle prove stesse (LegacyTestVideos, semi fissi): metadati, MD5
ufficiali dei fotogrammi da FLV, miniatura dell'FLV uguale a quella dell'MP4, file lunghi e giro
dell'orologio, file troncati e rovinati, AMF annidato senza fine e oggetti ASF più grandi del
file. LEGGIMI dell'importazione e una riga in decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:50:44 +01:00

364 lines
16 KiB
C#

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")]
[DataRow("wmv")]
[DataRow("flv")]
[DataRow("mpg")]
[DataRow("h264.mpg")]
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)]
[DataRow("wmv", 5805)]
[DataRow("flv", 5806)]
[DataRow("mpg", 5807)]
[DataRow("h264.mpg", 5808)]
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)]
[DataRow("wmv", 5815)]
[DataRow("flv", 5816)]
[DataRow("mpg", 5817)]
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. WMV and MPEG program streams have
// no samples Febe decodes, so no frame ever.
if (kind is "wmv" or "mpg")
{
Assert.AreEqual(0, decoded);
}
else
{
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 almost two million samples without per-sample fields: under the sample limit, but far more than the
// file can hold (the trex default size is 0, so each would take at least a byte). That fragment gives nothing,
// the others give their samples.
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), 1_999_999);
container = ReadMeasured(fragmented, out allocated);
Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati");
Assert.HasCount(es.Count - 5, container!.Video!.Samples, "nessun campione inventato");
}
[TestMethod]
public async Task AMatroskaFileWithADamagedOrTruncatedBlockKeepsTheBlocksBefore()
{
var es = ElementaryStream.Load("CI_MW_D");
var file = TestVideos.Matroska(es);
using var temp = new TempFolder("matroska-rovinato");
var intact = await VideoFrameDecoder.Instance.DecodeFrameAsync(TestVideos.Write(temp, "intero.mkv", file), TimeSpan.FromSeconds(1));
Assert.IsNotNull(intact);
// The blocks close the file: each is the ID, an eight-byte size, track, time, flags and the sample.
int StartOf(int block) => file.Length - Enumerable.Range(block, es.Count - block).Sum(i => 1 + 8 + 4 + es.LengthPrefixed(i).Length);
// Cut inside the fixed part of the last block.
var truncated = file[..(StartOf(es.Count - 1) + 1 + 8 + 2)];
Assert.HasCount(es.Count - 1, ReadMeasured(truncated, out _)!.Video!.Samples);
// Block 50 says it holds nothing but its own header: the blocks before it stand, the frame at one second too.
var damaged = (byte[])file.Clone();
var block = StartOf(50);
Assert.AreEqual(0xA3, damaged[block]);
damaged.AsSpan(block + 2, 7).Clear();
damaged[block + 8] = 4;
Assert.HasCount(50, ReadMeasured(damaged, out _)!.Video!.Samples);
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(TestVideos.Write(temp, "rovinato.mkv", damaged), TimeSpan.FromSeconds(1));
CollectionAssert.AreEqual(intact.Rgb, image!.Rgb);
}
[TestMethod]
public void ADamagedAudioTrackDoesNotCostTheVideo()
{
var es = ElementaryStream.Load("CABA3_SVA_B");
// The descriptors of the audio esds run to its very end: the ES_Descriptor starts at its last two bytes.
var file = TestVideos.Mp4(es, audio: true);
var esds = IndexOf(file, "esds"u8);
var length = (int)BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(esds - 4)) - 8;
var body = file.AsSpan(esds + 4, length);
body[4..].Clear();
body[4] = 0x7F; // an unknown descriptor that covers the body...
body[5] = (byte)(length - 8);
body[length - 2] = 0x03; // ...up to an ES_Descriptor with no room for its fields
var container = ReadMeasured(file, out _)!;
Assert.HasCount(es.Count, container.Video!.Samples);
Assert.IsNotNull(container.Audio);
Assert.IsNull(container.Audio.AacConfiguration);
// The audio track header claims version 1, whose fields lie past the end of the box: that track is dropped.
file = TestVideos.Mp4(es, audio: true);
var audioTkhd = file.AsSpan(IndexOf(file, "tkhd"u8) + 4).IndexOf("tkhd"u8) + IndexOf(file, "tkhd"u8) + 4;
file[audioTkhd + 4] = 1;
container = ReadMeasured(file, out _)!;
Assert.HasCount(es.Count, container.Video!.Samples);
Assert.IsNull(container.Audio);
using var temp = new TempFolder("audio-rovinato");
var metadata = ContainerVideoMetadataProbe.Probe(TestVideos.Write(temp, "video.mp4", file), Now);
Assert.AreEqual((es.Width, es.Height), (metadata!.Width, metadata.Height));
}
[TestMethod]
public void AnAviWithAnImpossibleDurationKeepsItsDate()
{
// One frame per million seconds for a million frames: 10¹² seconds, beyond what a TimeSpan holds.
var es = ElementaryStream.Load("BA1_Sony_D");
var file = TestVideos.Avi(es, "Thu Mar 04 05:06:07 2021", scale: 1_000_000, rate: 1, length: 1_000_000);
var container = ReadMeasured(file, out _)!;
Assert.IsNull(container.Duration);
Assert.AreEqual(2021, container.CreatedAt!.Value.Year);
using var temp = new TempFolder("avi-durata");
var metadata = ContainerVideoMetadataProbe.Probe(TestVideos.Write(temp, "video.avi", file), Now);
Assert.IsNotNull(metadata, "la data scritta nel file non va persa");
Assert.AreEqual(2021, metadata.CreatedAt!.Value.Year);
Assert.IsNull(metadata.Duration);
}
[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");
}
[TestMethod]
public void DeepOrEndlessFlvMetadataKeepsWhatCameBefore()
{
// onMetaData: a duration, then objects nested a hundred thousand deep (a stack overflow if followed blindly).
var deep = new List<byte> { 2, 0, 10 };
deep.AddRange("onMetaData"u8.ToArray());
deep.Add(3);
deep.AddRange([0, 8, .. "duration"u8, 0, .. Be64(5.0)]);
for (var i = 0; i < 100_000; i++)
{
deep.AddRange([0, 1, (byte)'a', 3]);
}
var container = ReadMeasured(LegacyTestVideos.FlvWithScript([.. deep]), out var allocated);
Assert.AreEqual(TimeSpan.FromSeconds(5), container!.Duration);
Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati");
// A strict array that claims four billion values, then a width: the array ends the reading, the duration stays.
List<byte> endless = [2, 0, 10, .. "onMetaData"u8, 8, 0, 0, 0, 2, 0, 8, .. "duration"u8, 0, .. Be64(7.0),
0, 4, .. "list"u8, 10, 0xFF, 0xFF, 0xFF, 0xFF, 0, .. Be64(1), 0, 5, .. "width"u8, 0, .. Be64(640)];
container = ReadMeasured(LegacyTestVideos.FlvWithScript([.. endless]), out _);
Assert.AreEqual(TimeSpan.FromSeconds(7), container!.Duration);
}
[TestMethod]
public void AnAsfObjectLargerThanItsFileAllocatesNothing()
{
var file = LegacyTestVideos.Asf(new AsfOptions { Title = "Prova" });
// The file properties object (the first after the 30 bytes of the header) claims a gigabyte.
BinaryPrimitives.WriteUInt64LittleEndian(file.AsSpan(30 + 16), 1L << 30);
var container = ReadMeasured(file, out var allocated);
Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati");
Assert.IsNull(container!.Duration, "nulla dopo l'oggetto rovinato");
// A header object smaller than its own fields.
file = LegacyTestVideos.Asf(new AsfOptions());
BinaryPrimitives.WriteUInt64LittleEndian(file.AsSpan(16), 12);
Assert.ThrowsExactly<ContainerException>(() => ReadMeasured(file, out _));
}
private static byte[] Be64(double value)
{
var bytes = new byte[8];
BinaryPrimitives.WriteDoubleBigEndian(bytes, value);
return bytes;
}
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"),
"wmv" => LegacyTestVideos.Asf(new AsfOptions
{
Created = new DateTimeOffset(2009, 6, 7, 8, 9, 10, TimeSpan.Zero),
EncodingTime = new DateTimeOffset(2009, 6, 7, 8, 9, 10, TimeSpan.Zero),
Title = "Prova",
VideoInExtension = true,
}),
"flv" => LegacyTestVideos.Flv(es, creationDate: "Thu Mar 04 05:06:07 2021", audio: true),
"mpg" => LegacyTestVideos.MpegPs(new PsOptions { Frames = 30, PictureBytes = 300, StreamMap = true }),
"h264.mpg" => LegacyTestVideos.MpegPs(new PsOptions { Video = "h264", Stream = es, Audio = "ac3" }),
_ => 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;
}
}