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;
///
/// Truncated and garbled videos: the container readers, the metadata probe and the frame decoder must survive every one
/// of them with a (or ), a null result or a frame,
/// and must never allocate much more than the file holds, whatever its damaged headers claim.
///
[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(() => 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();
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),
};
}
/// A copy with a few bytes changed: mostly in the first kilobytes, where the headers are.
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 pattern)
{
var index = data.AsSpan().IndexOf(pattern);
Assert.IsGreaterThanOrEqualTo(0, index);
return index;
}
}