Revisione del lavoro in corso sui lettori in casa che sostituiscono ffmpeg e ffprobe. La corsa completa di tests/Febe.Tests ora è verde. Difetti corretti: - ISO BMFF frammentato: i valori di trex erano letti con i campi scambiati (la durata predefinita prendeva la dimensione, i flag andavano persi) e il data_offset di un secondo trun si sommava alla fine del primo invece che alla base del moof. - Mp4Writer: i blocchi di una traccia con tempi uguali (audio senza tempi, come da AVI) potevano uscire fuori ordine, perché l'ordinamento non è stabile; ora restano nell'ordine dei campioni. - Durata di un MP4 frammentato nella sola lettura dei metadati: da mehd o, se manca, dai frammenti (prima restava ignota). - File danneggiati: un stsz o un trun di pochi byte poteva chiedere centinaia di MB, un elemento Matroska più grande del file veniva allocato, un salto oltre i 2 GB faceva fallire MemoryStream, IndexOutOfRange e conversioni di date e durate uscivano come eccezioni non previste. Ora ogni tabella si controlla contro il file prima di allocare, al più 2.000.000 di campioni per traccia e 64 MB per campione, e una traccia MP4 con tabelle rovinate resta senza campioni senza togliere le altre. - H.264: un SPS oltre il MaxFS del livello 6.2 o con un ritaglio che non lascia immagine è rifiutato prima di allocare; mai più riferimenti di Max(max_num_ref_frames, 1); gli errori di deblocco e ritaglio escono come H264Exception. - VideoFrameDecoder: i fotogrammi si associano al campione decodificato, non al conteggio del decodificatore (un campione senza immagine non sposta più quelli dopo); un campione oltre la fine di un file troncato non toglie i fotogrammi già decodificati; il fotogramma per la miniatura è ridotto a 960 pixel sul lato lungo. Prove nuove: file troncati e rovinati con semi fissi per MP4, MP4 frammentato, Matroska e AVI (lettori, sonda e decodificatore dei fotogrammi, con limite di memoria allocata), flussi di conformità rovinati per il decodificatore H.264, SPS troppo grande e ritaglio non valido, MP4 frammentato con valori predefiniti e due trun, ordine dei blocchi con tempi uguali. Le prove nuove dei difetti falliscono sul codice di prima. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
168 lines
5.9 KiB
C#
168 lines
5.9 KiB
C#
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)]
|
||
public void DamagedStreamsGiveFramesOrAnH264Exception(string name, int seed)
|
||
{
|
||
var folder = Path.Combine(AppContext.BaseDirectory, "Media", "H264", "Conformita", name);
|
||
var data = File.ReadAllBytes(Directory.EnumerateFiles(folder).Single(f => Path.GetExtension(f) is ".264" or ".jsv" or ".avc"));
|
||
var random = new Random(seed);
|
||
for (var trial = 0; trial < 60; 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.
|
||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||
var error = Assert.ThrowsExactly<H264Exception>(() => new H264Decoder().DecodeAnnexB(Sps(widthInMbs: 1024, heightInMbs: 1024)));
|
||
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(Sps(widthInMbs: 512, heightInMbs: 272));
|
||
}
|
||
|
||
[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 NAL unit in Annex B form, written bit by bit (§7.3.2.1.1).</summary>
|
||
private static byte[] Sps(int widthInMbs, int heightInMbs, (int Left, int Right, int Top, int Bottom)? crop = null)
|
||
{
|
||
var bits = new BitWriter();
|
||
bits.Bits(66, 8); // profile_idc: Baseline
|
||
bits.Bits(0, 8); // constraint flags
|
||
bits.Bits(30, 8); // level_idc
|
||
bits.Ue(0); // seq_parameter_set_id
|
||
bits.Ue(0); // log2_max_frame_num_minus4
|
||
bits.Ue(2); // pic_order_cnt_type
|
||
bits.Ue(1); // max_num_ref_frames
|
||
bits.Bits(0, 1); // gaps_in_frame_num_value_allowed_flag
|
||
bits.Ue((uint)widthInMbs - 1);
|
||
bits.Ue((uint)heightInMbs - 1);
|
||
bits.Bits(1, 1); // frame_mbs_only_flag
|
||
bits.Bits(1, 1); // direct_8x8_inference_flag
|
||
bits.Bits(crop is null ? 0u : 1u, 1);
|
||
if (crop is { } c)
|
||
{
|
||
bits.Ue((uint)c.Left);
|
||
bits.Ue((uint)c.Right);
|
||
bits.Ue((uint)c.Top);
|
||
bits.Ue((uint)c.Bottom);
|
||
}
|
||
|
||
bits.Bits(0, 1); // vui_parameters_present_flag
|
||
bits.Bits(1, 1); // rbsp_stop_one_bit
|
||
return [0, 0, 0, 1, 0x67, .. bits.ToArray()];
|
||
}
|
||
|
||
private sealed class BitWriter
|
||
{
|
||
private readonly List<bool> bits = [];
|
||
|
||
public void Bits(uint value, int count)
|
||
{
|
||
for (var i = count - 1; i >= 0; i--)
|
||
{
|
||
bits.Add(((value >> i) & 1) != 0);
|
||
}
|
||
}
|
||
|
||
public void Ue(uint value)
|
||
{
|
||
var code = value + 1;
|
||
var length = 32 - System.Numerics.BitOperations.LeadingZeroCount(code);
|
||
Bits(0, length - 1);
|
||
Bits(code, length);
|
||
}
|
||
|
||
public byte[] ToArray()
|
||
{
|
||
var bytes = new byte[(bits.Count + 7) / 8];
|
||
for (var i = 0; i < bits.Count; i++)
|
||
{
|
||
if (bits[i])
|
||
{
|
||
bytes[i / 8] |= (byte)(0x80 >> (i % 8));
|
||
}
|
||
}
|
||
|
||
// Emulation prevention (§7.4.1): never two zero bytes followed by a byte up to 3.
|
||
var output = new List<byte>();
|
||
var zeros = 0;
|
||
foreach (var b in bytes)
|
||
{
|
||
if (zeros >= 2 && b <= 3)
|
||
{
|
||
output.Add(3);
|
||
zeros = 0;
|
||
}
|
||
|
||
output.Add(b);
|
||
zeros = b == 0 ? zeros + 1 : 0;
|
||
}
|
||
|
||
return [.. output];
|
||
}
|
||
}
|
||
}
|