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;
/// The frame decoder that replaces ffmpeg for thumbnails, and the recognition of videos of a still picture.
[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")]
[DataRow("flv")]
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),
"flv" => LegacyTestVideos.Flv(es, audio: true),
_ => 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 void TenBitSamplesKeepTheirRange()
{
// 10 bits, two bytes each, little-endian: limited range has black at 64, white at 940, neutral chroma at 512.
static byte[] Samples(int count, int value) => [.. Enumerable.Range(0, count).SelectMany(_ => new[] { (byte)value, (byte)(value >> 8) })];
static H264Frame Flat(int y, int cb, int cr, bool full) =>
new(2, 2, Samples(4, y), Samples(1, cb), Samples(1, cr), 0, 0, 0, 1, full, ChromaFormat: 1, BitDepthLuma: 10, BitDepthChroma: 10);
CollectionAssert.AreEqual(new byte[] { 0, 0, 0 }, VideoFrameDecoder.ToImage(Flat(64, 512, 512, false), 0, 0).Rgb[..3]);
CollectionAssert.AreEqual(new byte[] { 255, 255, 255 }, VideoFrameDecoder.ToImage(Flat(940, 512, 512, false), 0, 0).Rgb[..3]);
CollectionAssert.AreEqual(new byte[] { 255, 255, 255 }, VideoFrameDecoder.ToImage(Flat(1023, 512, 512, true), 0, 0).Rgb[..3]);
// Pure red of BT.709 at 8 bits (Y 63, Cb 102, Cr 240) is the same colour at 10 bits (× 4).
var eight = VideoFrameDecoder.ToImage(new H264Frame(2, 2, [63, 63, 63, 63], [102], [240], 0, 0, 0, 1, false), 0, 0).Rgb[..3];
var ten = VideoFrameDecoder.ToImage(Flat(63 * 4, 102 * 4, 240 * 4, false), 0, 0).Rgb[..3];
for (var i = 0; i < 3; i++)
{
Assert.IsLessThanOrEqualTo(1, Math.Abs(eight[i] - ten[i]), $"componente {i}: {eight[i]} e {ten[i]}");
}
}
[TestMethod]
[DataRow(2)]
[DataRow(3)]
public void EveryChromaSamplingReachesItsOwnPixels(int chromaFormat)
{
// A 2×2 frame of grey luma; in 4:2:2 each row has its own chroma sample, in 4:4:4 each pixel. The top row is
// blue (Cb high), the bottom one red (Cr high).
var cw = chromaFormat == 3 ? 2 : 1;
byte[] cb = [.. Enumerable.Repeat((byte)200, cw), .. Enumerable.Repeat((byte)128, cw)];
byte[] cr = [.. Enumerable.Repeat((byte)128, cw), .. Enumerable.Repeat((byte)200, cw)];
var frame = new H264Frame(2, 2, [128, 128, 128, 128], cb, cr, 0, 0, 0, 1, true, ChromaFormat: chromaFormat);
var rgb = VideoFrameDecoder.ToImage(frame, 0, 0).Rgb;
Assert.IsGreaterThan(rgb[0] + 50, (int)rgb[2], "in alto prevale il blu");
Assert.IsGreaterThan(rgb[(2 * 3) + 2] + 50, (int)rgb[2 * 3], "in basso prevale il rosso");
CollectionAssert.AreEqual(rgb[..3], rgb[3..6], "la riga in alto è uniforme");
}
[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(() => 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")));
}
/// The frame decoded at position , straight from the stream.
private static H264Frame DecodedFrame(ElementaryStream es, int index) => ShownFrame(es, es.Rank[index]);
/// The frame shown at position , decoded straight from the stream.
private static H264Frame ShownFrame(ElementaryStream es, int rank)
{
var decoder = new H264Decoder();
var frames = new List();
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(ElementaryStream.AnnexB(es.Name));
var index = Array.IndexOf(es.Rank, rank);
return frames.Single(f => f.DecodeIndex == index);
}
}