Files
Febe/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs
T
Alby96andClaude Opus 5.5 da84c79f7e Decodificatore H.264 per i formati dei profili High: 4:2:2, 4:4:4, piani separati, 4:0:0, da 8 a 14 bit, senza perdita (#58)
Il decodificatore rifiutava tutto ciò che non era 4:2:0 a 8 bit, così i video
4:2:2, monocromatici o a 10 bit restavano senza miniatura. Ora i campioni stanno
in piani di uno o due byte e i nuclei di predizione, trasformata e filtro sono
generici su byte e ushort, specializzati dal JIT: a 8 bit i tempi restano quelli
di prima (misurati sui flussi di conformità, 100,4%).

- 4:2:2: DC della crominanza 2x4 con qP + 3, tabelle CAVLC di nC -2, contesti
  CABAC per NumC8x8, predizione intra 8x16, vettore verticale a piena
  risoluzione, bordi della crominanza alle righe 4, 8 e 12.
- 4:4:4: Cb e Cr codificati come la luminanza in CAVLC, con le loro matrici
  e il filtro della luminanza; separate_colour_plane_flag come tre immagini
  monocromatiche con i propri dati di macroblocco e di moto.
- 4:0:0 senza sintassi della crominanza; in uscita la crominanza 4:2:0 al
  valore medio, come il file ufficiale.
- Profondità da 8 a 14 bit: QP da -QpBdOffset, soglie del deblocking e scarti
  dei pesi scalati; uscita a due byte little-endian.
- Senza perdita: qpprime_y_zero_transform_bypass_flag a QP'Y 0, con la DPCM
  della predizione intra orizzontale e verticale.
- VideoFrameDecoder converte in RGB alla profondità e al campionamento del
  fotogramma.

I dieci flussi 4:2:2 (8 e 10 bit) e 4:0:0 della serie ITU-T coincidono con la
ricostruzione ufficiale e passano fra i verificati. 4:4:4, piani separati,
senza perdita e 11-14 bit si provano con flussi sintetici (H264FormatTests).
Il CABAC in 4:4:4 con i piani insieme si rifiuta: mancano i contesti 460-1023.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 17:31:12 +01:00

261 lines
14 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 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<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);
}
}