Files
Febe/tests/Febe.Tests/Media/H264/H264RobustnessTests.cs
T
Alby96andClaude Opus 5.5 cdc3cc11b9 Correzioni dopo la revisione del decodificatore H.264, dei lettori FLV e della CI (#58)
- CI: le due prove MVC di FeaturesStillToDo finivano con «da verificare: …», che
  riepilogo-prove.sh contava come saltate: ogni verifica del ramo sarebbe fallita.
  Ora cominciano con «da fare: », e lo script esenta solo le inconclusive di
  FeaturesStillToDo il cui motivo comincia con «da fare: » subito dopo la cornice
  di MSTest (prima bastava la parola in qualunque punto di qualunque prova).
  PipelineTests prova lo script su .trx con le cornici inglese e italiana;
  processo.md, Sviluppo.md e verifica.yml descrivono la categoria.
- Partizionamento dei dati: una partizione B o C sperduta (partizione A persa)
  sovrascriveva il buffer delle partizioni della slice in attesa. Ora slice_id e
  redundant_pic_cnt si leggono prima di copiare, e contano l'ordine A, B, C.
- MVC: le viste tengono insieme al massimo 2 × MaxDpbMbs di immagini, e il
  decodificatore di una vista nuova si tiene solo dopo il controllo dell'SPS di
  sottoinsieme; Wanted vale per ogni vista.
- FLV: senza durata nei metadati la durata arriva alla fine dell'ultimo
  fotogramma, come per MPEG; «solo audio» solo con una prova vera nella testa
  (un onMetaData grande non fa più scartare un video).
- Flussi di conformità: tolti i 48 readme e schede di terzi (decisione di
  Alberto: nel repository solo flussi e MD5).
- Prove nuove: partizioni A perse, limite delle viste e Wanted in MVC, unità di
  estensione troncate, flussi rovinati 4:2:2, 10 bit, 4:0:0, SVC e MVC.
- Commenti sulla provenienza che citano i file di ricostruzione ufficiali e
  §8.7 invece del decodificatore di riferimento; commento di
  ImportEnvironment.VideoProbe aggiornato; righe nuove in decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 19:30:45 +01:00

142 lines
6.7 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.H264;
namespace Febe.Tests.Codecs.H264;
/// <summary>
/// Damaged H.264 streams: the decoder reads bytes of any file the library holds, so whatever they are it must end with
/// frames or an <see cref="H264Exception"/>, and a damaged parameter set must never make it allocate huge pictures.
/// </summary>
[TestClass]
public sealed class H264RobustnessTests
{
[TestMethod]
[DataRow("BA1_Sony_D", 2641)]
[DataRow("SVA_BA1_B", 2642)]
[DataRow("BA3_SVA_C", 2643)]
[DataRow("BASQP1_Sony_C", 2644)]
[DataRow("CI_MW_D", 2645)]
[DataRow("CABA1_SVA_B", 2646)]
[DataRow("CABA2_SVA_B", 2647)]
[DataRow("CABA3_SVA_B", 2648)]
[DataRow("CANL1_SVA_B", 2649)]
[DataRow("FRExt1_Panasonic_D", 2650)]
[DataRow("FRExt3_Panasonic_E", 2651)]
[DataRow("HCAFR1_HHI_C", 2652)]
[DataRow("FI1_Sony_E", 2653)]
[DataRow("CVMAQP3_Sony_D", 2654)]
[DataRow("CAMACI3_Sony_C", 2655)]
[DataRow("CAMASL3_Sony_B", 2656)]
[DataRow("MR6_BT_B", 2657)]
[DataRow("MR9_BT_B", 2658)]
[DataRow("CAPAMA3_Sand_F", 2659)]
[DataRow("FM2_SVA_C", 2660)]
[DataRow("FM1_FT_E", 2661)]
[DataRow("FM1_BT_B", 2662)]
[DataRow("sp1_bt_a", 2663)]
[DataRow("sp2_bt_b", 2664)]
public void DamagedStreamsGiveFramesOrAnH264Exception(string name, int seed) =>
AssertDamagedCopiesDecode(name, File.ReadAllBytes(H264ConformanceTests.StreamFile(H264ConformanceTests.Folder(name))), seed, trials: 60);
/// <summary>
/// The same for the formats of the High profiles beyond 4:2:0 at 8 bits (samples of two bytes, 4:2:2 and 4:0:0
/// layouts) and for the extensions, whose NAL units 14, 15 and 20 have headers of their own and whose layers or
/// views have arrays and decoders of their own; fewer copies each, since these streams are larger or decode twice.
/// </summary>
[TestMethod]
[DataRow("Hi422FR12_SONY_A", 2665)] // 4:2:2, 8 bit, slice B
[DataRow("Hi422FR13_SONY_A", 2666)] // 4:2:2, 10 bit: two bytes per sample
[DataRow("Hi422FR15_SONY_A", 2667)] // 4:2:2, 10 bit, slices P and B
[DataRow("FREXT2_TANDBERG_A", 2668)] // 4:2:2, CAVLC
[DataRow("HPCAMOLQ_BRCM_B", 2669)] // 4:0:0, CABAC
[DataRow("HPCVMOLQ_BRCM_B", 2670)] // 4:0:0, CAVLC
[DataRow("SVCBMT-13", 2671)] // SVC: MGS quality layers, NAL units 14 and 20
[DataRow("SVCBST-19", 2672)] // SVC: spatial layer left to the base
[DataRow("SVCBCT-1", 2673)] // SVC: CGS layer left to the base
[DataRow("MVCDS-4", 2674)] // MVC: two views, subset SPS, NAL units 14, 15 and 20
[DataRow("MVCNV-3", 2675)] // MVC: three views, inter-view prediction
public void DamagedStreamsOfOtherFormatsAndExtensionsGiveFramesOrAnH264Exception(string name, int seed) =>
AssertDamagedCopiesDecode(name, File.ReadAllBytes(H264ConformanceTests.StreamFile(H264ConformanceTests.Folder(name))), seed, trials: 20);
/// <summary>
/// Copies of <paramref name="data"/> with a few bytes changed (and some cut short), from a fixed seed: each must give
/// frames or an <see cref="H264Exception"/>, never another exception.
/// </summary>
internal static void AssertDamagedCopiesDecode(string name, byte[] data, int seed, int trials)
{
var random = new Random(seed);
for (var trial = 0; trial < trials; trial++)
{
var copy = (byte[])data.Clone();
var changes = 1 + random.Next(20);
for (var k = 0; k < changes; k++)
{
var p = random.Next(copy.Length);
copy[p] = random.Next(3) switch
{
0 => (byte)random.Next(256),
1 => (byte)(copy[p] ^ (1 << random.Next(8))),
_ => 0xFF,
};
}
if (random.Next(4) == 0)
{
copy = copy[..random.Next(copy.Length)];
}
try
{
var decoder = new H264Decoder();
decoder.FrameDecoded += _ => { };
decoder.DecodeAnnexB(copy);
}
catch (H264Exception)
{
}
catch (Exception ex)
{
Assert.Fail($"{name}, variante {trial} del seme {seed}: {ex.GetType().Name} {ex.Message}\n{ex.StackTrace}");
}
}
}
[TestMethod]
public void APictureLargerThanEveryLevelIsRefusedBeforeItIsAllocated()
{
// 1024 × 1024 macroblocks (16384 × 16384): what ue(v) allows, a hundred times what level 6.2 does. A PPS and the
// start of an IDR slice follow, so a decoder without the bound would really allocate its pictures.
var huge = new SyntheticStreams.SequenceSettings(WidthInMbs: 1024, HeightInMbs: 1024);
byte[] stream = [.. SyntheticStreams.Sps(huge), .. SyntheticStreams.Pps(), .. SyntheticStreams.Idr(huge, 100, macroblocks: 1)];
var before = GC.GetAllocatedBytesForCurrentThread();
var error = Assert.ThrowsExactly<H264Exception>(() => new H264Decoder().DecodeAnnexB(stream));
StringAssert.Contains(error.Message, "livello");
Assert.IsLessThan(1024L * 1024, GC.GetAllocatedBytesForCurrentThread() - before);
// The largest frame of level 6.2 is still accepted.
new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 512, HeightInMbs: 272)));
}
[TestMethod]
public void MoreReferenceFramesThanTheLargestBufferAreRefused()
{
// 8192 × 4352 with sixteen reference frames would be 1.4 GB of pictures; level 6.2 holds five of that size.
var error = Assert.ThrowsExactly<H264Exception>(() =>
new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 512, HeightInMbs: 272, MaxNumRefFrames: 16))));
StringAssert.Contains(error.Message, "riferimento");
new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 512, HeightInMbs: 272, MaxNumRefFrames: 5)));
new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 120, HeightInMbs: 68, MaxNumRefFrames: 16)));
}
[TestMethod]
public void ACropThatLeavesNoPictureIsRefused()
{
// 176 × 144 (11 × 9 macroblocks): crop units are two samples in 4:2:0 frames.
new H264Decoder().DecodeAnnexB(Sps(11, 9, crop: (4, 4, 2, 2)));
Assert.ThrowsExactly<H264Exception>(() => new H264Decoder().DecodeAnnexB(Sps(11, 9, crop: (44, 44, 0, 0))));
Assert.ThrowsExactly<H264Exception>(() => new H264Decoder().DecodeAnnexB(Sps(11, 9, crop: (0, 0, 8192, 0))));
}
/// <summary>A Baseline SPS of the given size and crop.</summary>
private static byte[] Sps(int widthInMbs, int heightInMbs, (int, int, int, int) crop) =>
SyntheticStreams.Sps(new(WidthInMbs: widthInMbs, HeightInMbs: heightInMbs, Crop: crop));
}