Fotogrammi e contenitori più robusti dopo la revisione: punto di partenza vero, limiti di tempo e di riferimenti, file rovinati tollerati (#58)
Corregge i difetti confermati dalla revisione del decodificatore H.264 e dei lettori di contenitori. - Fotogrammi: un AVI senza idx1 (o OpenDML oltre il primo GB) segna ogni campione come chiave; ora si parte dall'immagine IDR più vicina (entro 300 campioni), altrimenti da un'immagine di slice I o dal primo campione. Oltre 300 campioni vale il fotogramma del punto di partenza; ogni chiamata ha al più 30 secondi, come l'estrattore con ffmpeg che sostituisce. - H.264: una slice P/B senza riferimenti è un errore invece di una predizione da sé stessa; SPS con riferimenti oltre MaxDpbMbs del livello 6.2 rifiutato (1,4 GB da pochi byte); FrameNumOffset dei fotogrammi mancanti di un salto di frame_num; immagini ridondanti saltate e inizio d'immagine secondo §7.4.1.2.4; immagini non di riferimento non chieste non ricostruite; CABAC con finestra di 64 bit; unità NAL in un solo buffer. Il sommario non dice più verificato ciò che nessun MD5 verifica. - Matroska: un blocco rovinato o troncato ferma la lettura e i blocchi letti restano; scala dei tempi esatta per ogni TimecodeScale. - MP4: una traccia con tkhd/elst/mdhd/hdlr/esds rovinati si scarta senza perdere le altre; esds con limiti controllati; nei soli metadati niente copie delle tabelle né campioni dei frammenti. - AVI: durata impossibile ignota senza perdere la data. - Sonda dei metadati davvero asincrona, annullabile fra i frammenti. - Prove nuove: flussi H.264 sintetici scritti bit per bit (salto di frame_num, immagine ridondante, P senza riferimenti, immagini saltate, SPS enormi con PPS e slice), AVI senza indice, blocchi Matroska rovinati, audio MP4 rovinato, durata AVI, TimecodeScale di 3 ms, trun sotto il limite ma oltre il file, limite di run e di tempo, i due MP4 x264 del sito di prova, ffmpeg/ffprobe fuori dal Dockerfile. Provate contro il codice senza le correzioni: falliscono tutte. - decisioni.md: quattro righe del 18 novembre. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
479c95f899
commit
b23632fc96
22 files changed
+1273
-282
No files matched your search
@@ -230,6 +230,23 @@ public sealed class ContainerTests
|
||||
Assert.AreEqual(2020, meta!.CreatedAt!.Value.Year);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(3_000_000u)]
|
||||
[DataRow(1_000_000u)]
|
||||
[DataRow(2_500_000u)]
|
||||
public void MatroskaTimesStayExactWithAnyTimecodeScale(uint timecodeScale)
|
||||
{
|
||||
// A TimecodeScale that does not divide a second (3 ms): the timescale of the track must not be rounded down
|
||||
// (333 ticks a second instead of 333.3), or every time drifts by 0.1% and disagrees with the duration.
|
||||
var es = ElementaryStream.Load("CI_MW_D");
|
||||
var container = Read(TestVideos.Matroska(es, timecodeScale: timecodeScale));
|
||||
var video = container.Video!;
|
||||
var tick = timecodeScale / 1e9;
|
||||
Assert.AreEqual(container.Duration!.Value.TotalSeconds, video.Seconds(video.Duration), 1.0 / video.Timescale, "durata della traccia e del file");
|
||||
var span = video.Samples.Max(s => s.PresentationTime) - video.Samples.Min(s => s.PresentationTime);
|
||||
Assert.AreEqual((es.Count - 1) / 30.0, video.Seconds(span), tick, "dal primo all'ultimo fotogramma");
|
||||
}
|
||||
|
||||
private static MediaContainer Read(byte[] file)
|
||||
{
|
||||
using var stream = new MemoryStream(file);
|
||||
|
||||
@@ -85,14 +85,91 @@ public sealed class MalformedInputTests
|
||||
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.
|
||||
// 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), int.MaxValue);
|
||||
BinaryPrimitives.WriteUInt32BigEndian(fragmented.AsSpan(trun + 8), 1_999_999);
|
||||
container = ReadMeasured(fragmented, out allocated);
|
||||
Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati");
|
||||
Assert.IsNotNull(container);
|
||||
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]
|
||||
|
||||
@@ -126,6 +126,17 @@ internal sealed class ElementaryStream
|
||||
return new ElementaryStream(Name + "-fermo", units, [.. Enumerable.Range(0, times)], [.. Enumerable.Repeat(true, times)], AvcC, Width, Height);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The same stream with its SPS and PPS repeated in every access unit, as some cameras and recorders write them: a
|
||||
/// decoder started at any of its P or B frames finds its parameter sets.
|
||||
/// </summary>
|
||||
public ElementaryStream WithParameterSetsEverywhere()
|
||||
{
|
||||
var sets = Units[0].Where(n => (n[0] & 0x1F) is 7 or 8).ToList();
|
||||
var units = Units.Select(u => u.Any(n => (n[0] & 0x1F) == 7) ? u : [.. sets, .. u]).ToList();
|
||||
return new ElementaryStream(Name + "-parametri", units, Rank, Key, AvcC, Width, Height);
|
||||
}
|
||||
|
||||
/// <summary>An access unit with 4-byte length prefixes (MP4, Matroska).</summary>
|
||||
public byte[] LengthPrefixed(int index)
|
||||
{
|
||||
@@ -328,8 +339,11 @@ internal static class TestVideos
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>A Matroska file with one video track of SimpleBlocks (times in milliseconds).</summary>
|
||||
public static byte[] Matroska(ElementaryStream es, DateTimeOffset? created = null, bool webm = false)
|
||||
/// <summary>
|
||||
/// A Matroska file with one video track of SimpleBlocks, in a single cluster; block times are in ticks of
|
||||
/// <paramref name="timecodeScale"/> nanoseconds (milliseconds by default).
|
||||
/// </summary>
|
||||
public static byte[] Matroska(ElementaryStream es, DateTimeOffset? created = null, bool webm = false, uint timecodeScale = 1_000_000)
|
||||
{
|
||||
var shift = 0;
|
||||
for (var i = 0; i < es.Count; i++)
|
||||
@@ -340,8 +354,9 @@ internal static class TestVideos
|
||||
var header = Element(0x1A45DFA3,
|
||||
Element(0x4286, [1]), Element(0x42F7, [1]), Element(0x42F2, [4]), Element(0x42F3, [8]),
|
||||
Element(0x4282, Encoding.ASCII.GetBytes(webm ? "webm" : "matroska")), Element(0x4287, [4]), Element(0x4285, [2]));
|
||||
var durationMs = es.Count * 1000.0 / 30;
|
||||
var info = new List<byte[]> { Element(0x2AD7B1, U32(1_000_000)), Element(0x4489, F64(durationMs)), Element(0x4D80, "febe-prove"u8.ToArray()) };
|
||||
var tickMs = timecodeScale / 1e6;
|
||||
var durationTicks = es.Count * 1000.0 / 30 / tickMs;
|
||||
var info = new List<byte[]> { Element(0x2AD7B1, U32(timecodeScale)), Element(0x4489, F64(durationTicks)), Element(0x4D80, "febe-prove"u8.ToArray()) };
|
||||
if (created is { } c)
|
||||
{
|
||||
var ns = (c - new DateTimeOffset(2001, 1, 1, 0, 0, 0, TimeSpan.Zero)).Ticks * 100;
|
||||
@@ -354,7 +369,7 @@ internal static class TestVideos
|
||||
var blocks = new List<byte[]> { Element(0xE7, [0]) };
|
||||
for (var i = 0; i < es.Count; i++)
|
||||
{
|
||||
var pts = (int)Math.Round((es.Rank[i] + shift) * 1000.0 / 30);
|
||||
var pts = (int)Math.Round((es.Rank[i] + shift) * 1000.0 / 30 / tickMs);
|
||||
var payload = es.LengthPrefixed(i);
|
||||
blocks.Add(Element(0xA3, [0x81, (byte)(pts >> 8), (byte)pts, es.Key[i] ? (byte)0x80 : (byte)0, .. payload]));
|
||||
}
|
||||
@@ -363,8 +378,12 @@ internal static class TestVideos
|
||||
return [.. header, .. segment];
|
||||
}
|
||||
|
||||
/// <summary>An AVI file with one H.264 stream in Annex B form, an idx1 index and, when given, an IDIT date.</summary>
|
||||
public static byte[] Avi(ElementaryStream es, string? idit = null, bool index = true)
|
||||
/// <summary>
|
||||
/// An AVI file with one H.264 stream in Annex B form, an idx1 index (unless <paramref name="index"/> is false, as in a
|
||||
/// recording cut short) and, when given, an IDIT date. The stream header says <paramref name="rate"/> /
|
||||
/// <paramref name="scale"/> frames per second and <paramref name="length"/> frames (default: the stream's).
|
||||
/// </summary>
|
||||
public static byte[] Avi(ElementaryStream es, string? idit = null, bool index = true, uint scale = 1, uint rate = 30, uint? length = null)
|
||||
{
|
||||
var avih = new List<byte>();
|
||||
foreach (var v in new uint[] { 33333, 0, 0, 0x10, (uint)es.Count, 0, 1, 0, (uint)es.Width, (uint)es.Height, 0, 0, 0, 0 })
|
||||
@@ -374,7 +393,7 @@ internal static class TestVideos
|
||||
|
||||
var strh = new List<byte>();
|
||||
strh.AddRange("vidsH264"u8.ToArray());
|
||||
foreach (var v in new uint[] { 0, 0, 0, 1, 30, 0, (uint)es.Count, 0, 0xFFFFFFFF, 0 })
|
||||
foreach (var v in new uint[] { 0, 0, 0, scale, rate, 0, length ?? (uint)es.Count, 0, 0xFFFFFFFF, 0 })
|
||||
{
|
||||
strh.AddRange(Le32(v));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
using Febe.Core.Codecs.Containers;
|
||||
using Febe.Core.Codecs.H264;
|
||||
using Febe.Core.Import;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Codecs.Containers;
|
||||
@@ -13,14 +16,22 @@ public sealed class VideoFrameDecoderTests
|
||||
[DataRow("mkv")]
|
||||
[DataRow("avi")]
|
||||
[DataRow("frammentato.mp4")]
|
||||
[DataRow("senza-indice.avi")]
|
||||
[DataRow("senza-indice-con-parametri.avi")]
|
||||
public async Task TheFrameAtOneSecondIsTheOneTheStreamShowsThere(string kind)
|
||||
{
|
||||
var es = ElementaryStream.Load("CABA3_SVA_B");
|
||||
using var temp = new TempFolder("fotogramma");
|
||||
|
||||
// Without idx1 (a recording cut short) every chunk counts as a key frame: decoding must still start from the
|
||||
// IDR picture, also when every chunk carries its own parameter sets (then a decoder started at the P frame itself
|
||||
// would give a corrupt picture rather than none).
|
||||
var data = kind switch
|
||||
{
|
||||
"mkv" => TestVideos.Matroska(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)),
|
||||
"avi" => TestVideos.Avi(es),
|
||||
"senza-indice.avi" => TestVideos.Avi(es, index: false),
|
||||
"senza-indice-con-parametri.avi" => TestVideos.Avi(es.WithParameterSetsEverywhere(), index: false),
|
||||
"frammentato.mp4" => TestVideos.FragmentedMp4(es),
|
||||
_ => TestVideos.Mp4(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)), // a dated file, as from a phone
|
||||
};
|
||||
@@ -32,7 +43,7 @@ public sealed class VideoFrameDecoderTests
|
||||
// The same frame straight from the decoder: the one shown at frame 30 (30 frames per second). AVI has no
|
||||
// presentation times: there frames are shown in decoding order.
|
||||
var position = Math.Min(30, es.Count - 1);
|
||||
var expected = kind == "avi" ? DecodedFrame(es, position) : ShownFrame(es, position);
|
||||
var expected = kind.EndsWith("avi", StringComparison.Ordinal) ? DecodedFrame(es, position) : ShownFrame(es, position);
|
||||
var reference = VideoFrameDecoder.ToImage(expected, 0, 0);
|
||||
Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height));
|
||||
CollectionAssert.AreEqual(reference.Rgb, image.Rgb);
|
||||
@@ -119,6 +130,72 @@ public sealed class VideoFrameDecoderTests
|
||||
Assert.IsFalse(result.IsStill, $"differenza {result.Difference}");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AFrameFarFromWhereDecodingCanStartGivesWayToTheFrameThere()
|
||||
{
|
||||
// At most five samples from the random access point: the frame at one second (sample 30, one IDR at sample 0)
|
||||
// is too far, the IDR picture stands for it instead of decoding the whole run (a damaged time table can put the
|
||||
// frame asked for two million samples after the only key frame).
|
||||
var es = ElementaryStream.Load("CABA3_SVA_B");
|
||||
using var temp = new TempFolder("fotogramma-lontano");
|
||||
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es));
|
||||
var decoder = new VideoFrameDecoder(VideoFrameDecoder.DefaultBudget, maxRun: 5);
|
||||
var image = await decoder.DecodeFrameAsync(path, TimeSpan.FromSeconds(1));
|
||||
CollectionAssert.AreEqual(VideoFrameDecoder.ToImage(DecodedFrame(es, 0), 0, 0).Rgb, image!.Rgb);
|
||||
Assert.IsNotNull(await decoder.AnalyseStillnessAsync(path), "anche l'analisi resta limitata e risponde");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task PastItsBudgetTheDecoderGivesNothingButTheCallerCanStillCancel()
|
||||
{
|
||||
var es = ElementaryStream.Load("CABA3_SVA_B");
|
||||
using var temp = new TempFolder("fotogramma-tempo");
|
||||
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es));
|
||||
var late = new VideoFrameDecoder(TimeSpan.Zero, maxRun: 300);
|
||||
Assert.IsNull(await late.DecodeFrameAsync(path, TimeSpan.FromSeconds(1)), "oltre il tempo concesso: nessun fotogramma");
|
||||
Assert.IsNull(await late.AnalyseStillnessAsync(path));
|
||||
|
||||
// A cancellation asked by the caller is not a missing frame: it stays a cancellation.
|
||||
using var cancelled = new CancellationTokenSource();
|
||||
await cancelled.CancelAsync();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1), 0, cancelled.Token));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("filmato-muto.mp4", false)]
|
||||
[DataRow("filmato-con-audio.mp4", true)]
|
||||
public async Task TheVideosOfARealEncoderAreReadAndDecoded(string name, bool audio)
|
||||
{
|
||||
// The two small MP4s of the test site come from a real muxer and encoder (libavformat, x264 High profile: the
|
||||
// shape of the videos Instagram serves); no official MD5 exists for them, so the frame is checked coarsely.
|
||||
var path = Repository.PathOf("tools", "Febe.SitoDiProva", "Risorse", name);
|
||||
var now = new DateTimeOffset(2026, 11, 18, 12, 0, 0, TimeSpan.Zero);
|
||||
var metadata = ContainerVideoMetadataProbe.Probe(path, now);
|
||||
Assert.IsNotNull(metadata);
|
||||
Assert.IsTrue(metadata.Width > 0 && metadata.Height > 0, $"{metadata.Width}×{metadata.Height}");
|
||||
Assert.IsTrue(metadata.Duration > TimeSpan.Zero && metadata.Duration < TimeSpan.FromMinutes(1), $"{metadata.Duration}");
|
||||
|
||||
var container = ContainerReader.ReadFile(path, now);
|
||||
Assert.AreEqual(VideoCodec.H264, container!.Video!.Codec);
|
||||
Assert.AreEqual(audio, container.Audio is not null);
|
||||
|
||||
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1));
|
||||
Assert.IsNotNull(image, "nessun fotogramma da un video di un codificatore vero");
|
||||
Assert.AreEqual((metadata.Width, metadata.Height), (image.Width, image.Height));
|
||||
|
||||
// A real picture: not a flat field of one value, not out of range.
|
||||
var luma = new double[image.Width * image.Height];
|
||||
for (var i = 0; i < luma.Length; i++)
|
||||
{
|
||||
luma[i] = (0.299 * image.Rgb[i * 3]) + (0.587 * image.Rgb[(i * 3) + 1]) + (0.114 * image.Rgb[(i * 3) + 2]);
|
||||
}
|
||||
|
||||
var mean = luma.Average();
|
||||
Assert.IsTrue(mean is > 2 and < 253, $"luminanza media {mean:F1}");
|
||||
var bmp = await VideoFrameDecoder.Instance.ExtractImageAsync(path);
|
||||
Assert.IsNotNull(bmp);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UnreadableFilesGiveNothing()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user