Files
Febe/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs
T
Alby96andClaude Opus 5.5 b23632fc96 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>
2026-11-18 14:13:45 +01:00

223 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
/// <summary>The frame decoder that replaces ffmpeg for thumbnails, and the recognition of videos of a still picture.</summary>
[TestClass]
public sealed class VideoFrameDecoderTests
{
[TestMethod]
[DataRow("mp4")]
[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
};
var path = TestVideos.Write(temp, "video." + kind, data);
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1));
Assert.IsNotNull(image);
// 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.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);
}
[TestMethod]
public async Task ShortVideosGiveTheirFirstFrameAndTheBmpIsWellFormed()
{
var es = ElementaryStream.Load("BA1_Sony_D");
using var temp = new TempFolder("fotogramma-breve");
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es));
var bmp = await VideoFrameDecoder.Instance.ExtractImageAsync(path, TimeSpan.FromSeconds(3600), 0);
Assert.IsNotNull(bmp);
Assert.AreEqual((byte)'B', bmp[0]);
Assert.AreEqual((byte)'M', bmp[1]);
Assert.AreEqual(bmp.Length, BitConverter.ToInt32(bmp, 2));
Assert.AreEqual(es.Width, BitConverter.ToInt32(bmp, 18));
Assert.AreEqual(es.Height, BitConverter.ToInt32(bmp, 22));
Assert.AreEqual(24, BitConverter.ToInt16(bmp, 28));
var first = VideoFrameDecoder.ToImage(ShownFrame(es, 0), 0, 0);
CollectionAssert.AreEqual(first.ToBmp(), bmp);
}
[TestMethod]
public async Task RotationAndSizeLimitAreApplied()
{
var es = ElementaryStream.Load("BA1_Sony_D");
using var temp = new TempFolder("fotogramma-ruotato");
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es, rotation: 90));
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.Zero);
Assert.AreEqual((es.Height, es.Width), (image!.Width, image.Height));
var upright = VideoFrameDecoder.ToImage(ShownFrame(es, 0), 0, 0);
// Rotated clockwise: the top-left pixel of the frame ends at the top-right corner.
CollectionAssert.AreEqual(upright.Rgb[..3], image.Rgb[((image.Width - 1) * 3)..(image.Width * 3)]);
var small = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.Zero, maxLongSide: es.Width / 2);
Assert.AreEqual((es.Height / 2, es.Width / 2), (small!.Width, small.Height));
}
[TestMethod]
public void ColoursFollowTheMatrixAndTheRange()
{
static H264Frame Flat(byte y, byte cb, byte cr, int matrix, bool full) =>
new(2, 2, [y, y, y, y], [cb], [cr], 0, 0, 0, matrix, full);
CollectionAssert.AreEqual(new byte[] { 0, 0, 0 }, VideoFrameDecoder.ToImage(Flat(16, 128, 128, 1, false), 0, 0).Rgb[..3]);
CollectionAssert.AreEqual(new byte[] { 255, 255, 255 }, VideoFrameDecoder.ToImage(Flat(235, 128, 128, 1, false), 0, 0).Rgb[..3]);
CollectionAssert.AreEqual(new byte[] { 128, 128, 128 }, VideoFrameDecoder.ToImage(Flat(128, 128, 128, 6, true), 0, 0).Rgb[..3]);
// Pure red of BT.601 (limited range): Y 81, Cb 90, Cr 240.
var red = VideoFrameDecoder.ToImage(Flat(81, 90, 240, 6, false), 0, 0).Rgb;
Assert.IsTrue(red[0] >= 250 && red[1] <= 3 && red[2] <= 3, $"{red[0]} {red[1]} {red[2]}");
// The same values read as BT.709 are no longer pure red.
var other = VideoFrameDecoder.ToImage(Flat(81, 90, 240, 1, false), 0, 0).Rgb;
Assert.IsTrue(other[1] > 20, $"{other[0]} {other[1]} {other[2]}");
}
[TestMethod]
public async Task AVideoOfAStillPictureIsRecognised()
{
var es = ElementaryStream.Load("BA1_Sony_D");
using var temp = new TempFolder("fermo");
var still = TestVideos.Write(temp, "fermo.mp4", TestVideos.Mp4(es.FirstPictureRepeated(90)));
var result = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(still);
Assert.IsNotNull(result);
Assert.IsTrue(result.IsStill);
Assert.IsTrue(result.SampledFrames >= 2);
Assert.AreEqual(0, result.Difference);
}
[TestMethod]
[DataRow("CABA3_SVA_B")]
[DataRow("FRExt1_Panasonic_D")]
public async Task AVideoThatMovesIsNotStill(string name)
{
var es = ElementaryStream.Load(name);
using var temp = new TempFolder("movimento");
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es));
var result = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(path);
Assert.IsNotNull(result);
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()
{
using var temp = new TempFolder("illeggibile");
var junk = TestVideos.Write(temp, "rotto.mp4", [0, 0, 0, 16, .. "ftypisom"u8, 0, 0, 0, 0, 0, 0, 0, 9, .. "mdat"u8, 1]);
Assert.IsNull(await VideoFrameDecoder.Instance.ExtractImageAsync(junk));
Assert.IsNull(await VideoFrameDecoder.Instance.AnalyseStillnessAsync(junk));
Assert.IsNull(await VideoFrameDecoder.Instance.ExtractImageAsync(temp.Combine("non-esiste.mkv")));
}
/// <summary>The frame decoded at position <paramref name="index"/>, straight from the stream.</summary>
private static H264Frame DecodedFrame(ElementaryStream es, int index) => ShownFrame(es, es.Rank[index]);
/// <summary>The frame shown at position <paramref name="rank"/>, decoded straight from the stream.</summary>
private static H264Frame ShownFrame(ElementaryStream es, int rank)
{
var decoder = new H264Decoder();
var frames = new List<H264Frame>();
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(ElementaryStream.AnnexB(es.Name));
var index = Array.IndexOf(es.Rank, rank);
return frames.Single(f => f.DecodeIndex == index);
}
}