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
@@ -30,15 +30,77 @@ public sealed class ContainerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("CABA3_SVA_B")]
|
||||
[DataRow("FRExt1_Panasonic_D")]
|
||||
public void AFragmentedMp4IsReadFromItsFragments(string name)
|
||||
[DataRow("CABA3_SVA_B", false)]
|
||||
[DataRow("FRExt1_Panasonic_D", false)]
|
||||
[DataRow("CABA3_SVA_B", true)]
|
||||
[DataRow("FRExt1_Panasonic_D", true)]
|
||||
public void AFragmentedMp4IsReadFromItsFragments(string name, bool defaults)
|
||||
{
|
||||
// With defaults: durations from trex and two runs per fragment, each with its data_offset from the moof.
|
||||
var es = ElementaryStream.Load(name);
|
||||
var file = TestVideos.FragmentedMp4(es, perFragment: 7);
|
||||
var file = TestVideos.FragmentedMp4(es, perFragment: 7, defaults: defaults);
|
||||
var container = Read(file);
|
||||
AssertTrack(es, container.Video!, startsAtZero: false); // no edit list: composition offsets stay
|
||||
CollectionAssert.AreEqual(ElementaryStream.Reference(name), DecodeAll(file, container.Video!));
|
||||
Assert.AreEqual(es.Count / 30.0, container.Duration!.Value.TotalSeconds, 0.05);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(false)]
|
||||
[DataRow(true)]
|
||||
public void TheProbeTellsTheDurationOfAFragmentedMp4(bool mehd)
|
||||
{
|
||||
// Without mehd only the fragments tell the duration: the metadata reading goes on through them.
|
||||
var es = ElementaryStream.Load("CABA3_SVA_B");
|
||||
using var temp = new TempFolder("sonda-frammentato");
|
||||
var path = TestVideos.Write(temp, "frammentato.mp4", TestVideos.FragmentedMp4(es, perFragment: 5, defaults: mehd));
|
||||
var meta = ContainerVideoMetadataProbe.Probe(path, Now);
|
||||
Assert.IsNotNull(meta);
|
||||
Assert.AreEqual(es.Count / 30.0, meta.Duration!.Value.TotalSeconds, 0.05);
|
||||
Assert.AreEqual((es.Width, es.Height), (meta.Width!.Value, meta.Height!.Value));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheMp4WriterKeepsTheOrderOfSamplesWithEqualTimes()
|
||||
{
|
||||
// An audio track without times (as AVI gives): every chunk starts at zero, and the order must still hold.
|
||||
var es = ElementaryStream.Load("BA1_Sony_D");
|
||||
var video = new Mp4OutputTrack
|
||||
{
|
||||
IsVideo = true,
|
||||
Timescale = TestVideos.Timescale,
|
||||
Samples = [.. Enumerable.Range(0, es.Count).Select(i => new Mp4OutputSample(es.LengthPrefixed(i).Length, (long)i * TestVideos.FrameTicks, (long)es.Rank[i] * TestVideos.FrameTicks, es.Key[i]))],
|
||||
WriteSample = (i, s) => s.Write(es.LengthPrefixed(i)),
|
||||
Width = es.Width,
|
||||
Height = es.Height,
|
||||
AvcConfiguration = es.AvcC,
|
||||
};
|
||||
const int Count = 40_000; // 40 chunks of 1024: enough for the sort to be an unstable one
|
||||
static byte[] Payload(int i) => [(byte)(i >> 8), (byte)i, 7];
|
||||
var audio = new Mp4OutputTrack
|
||||
{
|
||||
IsVideo = false,
|
||||
Timescale = 44100,
|
||||
Samples = [.. Enumerable.Range(0, Count).Select(_ => new Mp4OutputSample(3, 0, 0, true))],
|
||||
WriteSample = (i, s) => s.Write(Payload(i)),
|
||||
AacConfiguration = [0x12, 0x10],
|
||||
SampleRate = 44100,
|
||||
Channels = 2,
|
||||
};
|
||||
using var output = new MemoryStream();
|
||||
Mp4Writer.Write(output, [video, audio]);
|
||||
|
||||
var file = output.ToArray();
|
||||
var container = Read(file);
|
||||
Assert.AreEqual(Count, container.Audio!.Samples.Count);
|
||||
using var input = new MemoryStream(file);
|
||||
var buffer = Array.Empty<byte>();
|
||||
for (var i = 0; i < Count; i++)
|
||||
{
|
||||
CollectionAssert.AreEqual(Payload(i), ContainerReader.ReadSample(input, container.Audio.Samples[i], ref buffer).ToArray(), $"campione {i}");
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(ElementaryStream.Reference("BA1_Sony_D"), DecodeAll(file, container.Video!));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -240,8 +240,12 @@ internal static class TestVideos
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>A fragmented MP4 (empty sample tables in moov, then moof+mdat pairs of <paramref name="perFragment"/> frames).</summary>
|
||||
public static byte[] FragmentedMp4(ElementaryStream es, int perFragment = 10)
|
||||
/// <summary>
|
||||
/// A fragmented MP4 (empty sample tables in moov, then moof+mdat pairs of <paramref name="perFragment"/> frames).
|
||||
/// With <paramref name="defaults"/> the sample durations come from <c>trex</c>, each fragment has two runs that
|
||||
/// both give their <c>data_offset</c> from the start of the moof, and an <c>mehd</c> box tells the duration.
|
||||
/// </summary>
|
||||
public static byte[] FragmentedMp4(ElementaryStream es, int perFragment = 10, bool defaults = false)
|
||||
{
|
||||
var shift = 0;
|
||||
for (var i = 0; i < es.Count; i++)
|
||||
@@ -268,33 +272,52 @@ internal static class TestVideos
|
||||
var mvhd = FullBox("mvhd", 0, [.. new byte[8], .. U32(1000), .. U32(0), .. U32(0x10000), 1, 0, .. new byte[10],
|
||||
.. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x40000000),
|
||||
.. new byte[24], .. U32(2)]);
|
||||
var trex = FullBox("trex", 0, [.. U32(1), .. U32(1), .. U32(FrameTicks), .. U32(0), .. U32(0)]);
|
||||
output.Write(Box("moov", mvhd, Box("trak", tkhd, mdia), Box("mvex", trex)));
|
||||
// trex: track_ID, default_sample_description_index, default duration, size and flags (non-sync).
|
||||
var trex = FullBox("trex", 0, [.. U32(1), .. U32(1), .. U32(FrameTicks), .. U32(0), .. U32(0x01010000)]);
|
||||
var mvex = defaults
|
||||
? Box("mvex", FullBox("mehd", 0, U32((uint)(es.Count * 1000 / 30))), trex) // movie timescale 1000
|
||||
: Box("mvex", trex);
|
||||
output.Write(Box("moov", mvhd, Box("trak", tkhd, mdia), mvex));
|
||||
|
||||
for (int first = 0, sequence = 1; first < es.Count; first += perFragment, sequence++)
|
||||
{
|
||||
var count = Math.Min(perFragment, es.Count - first);
|
||||
var payloads = Enumerable.Range(first, count).Select(es.LengthPrefixed).ToList();
|
||||
byte[] Moof(int dataOffset)
|
||||
byte[] Run(int from, int length, int dataOffset)
|
||||
{
|
||||
var run = new List<byte>();
|
||||
run.AddRange(U32((uint)count));
|
||||
run.AddRange(U32((uint)length));
|
||||
run.AddRange(U32((uint)dataOffset));
|
||||
for (var k = 0; k < count; k++)
|
||||
for (var k = from; k < from + length; k++)
|
||||
{
|
||||
var i = first + k;
|
||||
run.AddRange(U32(FrameTicks));
|
||||
if (!defaults)
|
||||
{
|
||||
run.AddRange(U32(FrameTicks));
|
||||
}
|
||||
|
||||
run.AddRange(U32((uint)payloads[k].Length));
|
||||
run.AddRange(U32(es.Key[i] ? 0x02000000u : 0x01010000u));
|
||||
run.AddRange(U32((uint)((es.Rank[i] - i + shift) * FrameTicks)));
|
||||
}
|
||||
|
||||
// Without the duration field (0x100) every sample takes the trex default.
|
||||
return FullBox("trun", defaults ? 0x000E01u : 0x000F01u, [.. run]);
|
||||
}
|
||||
|
||||
var split = defaults ? (count + 1) / 2 : count;
|
||||
var secondData = payloads.Take(split).Sum(p => p.Length);
|
||||
byte[] Moof(int dataOffset)
|
||||
{
|
||||
var runs = new List<byte[]> { Run(0, split, dataOffset) };
|
||||
if (split < count)
|
||||
{
|
||||
runs.Add(Run(split, count - split, dataOffset + secondData));
|
||||
}
|
||||
|
||||
return Box("moof",
|
||||
FullBox("mfhd", 0, U32((uint)sequence)),
|
||||
Box("traf",
|
||||
FullBox("tfhd", 0x020000, U32(1)),
|
||||
FullBox("tfdt", 0, U32((uint)(first * FrameTicks))),
|
||||
FullBox("trun", 0x000F01, [.. run])));
|
||||
Box("traf", [FullBox("tfhd", 0x020000, U32(1)), FullBox("tfdt", 0, U32((uint)(first * FrameTicks))), .. runs]));
|
||||
}
|
||||
|
||||
var size = Moof(0).Length;
|
||||
|
||||
Reference in new issue
Block a user