using Febe.Core.Codecs.H265;
using static Febe.Tests.Codecs.H265.H265SyntheticStreams;
using Pps = Febe.Core.Codecs.H265.Pps;
using Sps = Febe.Core.Codecs.H265.Sps;
namespace Febe.Tests.Codecs.H265;
///
/// The HEVC decoder on streams written for the purpose (): what bounds its memory
/// against damaged streams, parameter sets repeated inside a picture, the extensions it refuses, the range of weighted
/// prediction offsets.
///
[TestClass]
public sealed class H265RobustnessTests
{
private static readonly SequenceSettings Small = new();
private static readonly PictureSettings Plain = new();
[TestMethod]
public void TheSyntheticStreamsDecode()
{
// The control for every test below: an I picture and three P pictures, each referring to the one before, all
// at the middle of the range (intra prediction from nothing, then skipped blocks).
var frames = Decode(AnnexB(
Sps(Small),
Pps(Plain),
Slice(new SliceSettings(Cra, 0), Small, Plain),
Slice(new SliceSettings(TrailR, 1) { Negative = [(-1, true)] }, Small, Plain),
Slice(new SliceSettings(TrailR, 2) { Negative = [(-1, true)] }, Small, Plain),
Slice(new SliceSettings(TrailR, 3) { Negative = [(-1, true)] }, Small, Plain)));
Assert.HasCount(4, frames);
foreach (var frame in frames)
{
Assert.AreEqual((16, 16), (frame.Width, frame.Height));
Assert.IsTrue(frame.Y.All(v => v == 128) && frame.Cb.All(v => v == 128) && frame.Cr.All(v => v == 128));
}
}
[TestMethod]
[DataRow(416, 240, 15, true)]
[DataRow(4096, 2160, 15, true)]
[DataRow(8192, 4320, 5, true)]
[DataRow(8192, 4320, 6, false)]
[DataRow(7680, 4320, 7, false)]
[DataRow(5120, 2880, 11, true)]
[DataRow(5120, 2880, 12, false)]
public void TheBufferMustFitTheLargestLevel(int width, int height, int maxDecPicBufferingMinus1, bool accepted)
{
// A.4.2 at level 6.2: 16 pictures up to a quarter of MaxLumaPs (8 912 896 samples), 12 up to half, 8 up to three
// quarters, then 6. Sixteen pictures of the largest size would be gigabytes.
var nal = Sps(new SequenceSettings(width, height, maxDecPicBufferingMinus1));
byte[]? buffer = null;
if (accepted)
{
var sps = Sps.Parse(H265NalUnit.Unescape(nal, ref buffer).Reader());
Assert.AreEqual(maxDecPicBufferingMinus1, sps.MaxDecPicBufferingMinus1[0]);
}
else
{
Assert.ThrowsExactly(() => Sps.Parse(H265NalUnit.Unescape(nal, ref buffer).Reader()));
}
}
[TestMethod]
public void MissingReferencesShareOneGeneratedPicture()
{
// A P picture whose 15 short-term and 16 long-term references are all missing: one generated picture stands for
// all of them, each entry of the lists keeping its own POC.
var sequence = new SequenceSettings(2048, 1024, LongTermRefsPresent: true);
var p = new SliceSettings(TrailR, 40)
{
Negative = [.. Enumerable.Range(1, 15).Select(d => (-d, true))],
LongTerm = [.. Enumerable.Range(100, 16).Select(lsb => (lsb, true))],
ActiveRefs = 15,
};
var decoder = new H265Decoder();
Picture? decoded = null;
decoder.PictureDecoded += picture => decoded = picture;
decoder.DecodeAccessUnitAnnexB(AnnexB(Sps(sequence), Pps(Plain), Slice(new SliceSettings(Cra, 0), sequence, Plain)));
var pictureBytes = (2048L * 1024 * 2 * 3 / 2) + (512L * 256 * 10);
var before = GC.GetAllocatedBytesForCurrentThread();
decoder.DecodeAccessUnitAnnexB(AnnexB(Slice(p, sequence, Plain)));
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
// The new picture and the generated one; one picture each would be 31 more.
Assert.IsLessThan(4 * pictureBytes, allocated, $"{allocated} byte per un'immagine P con 31 riferimenti mancanti");
Assert.IsNotNull(decoded);
Assert.AreEqual(40, decoded.Poc);
var list = decoded.Slices[0].RefPicList[0];
var generated = list[0];
Assert.IsTrue(generated.Generated);
for (var i = 0; i < 15; i++)
{
Assert.AreSame(generated, list[i], $"riferimento {i}");
Assert.AreEqual(40 - 1 - i, decoded.Slices[0].RefPoc[0][i], $"POC del riferimento {i}");
}
}
[TestMethod]
public void TheBufferDoesNotGrowBeyondTheSps()
{
// Room for two pictures, but every P picture keeps all those before it as references: from the fourth picture
// the buffer would have to hold more than it declares, which a damaged stream must not turn into memory.
var sequence = new SequenceSettings(MaxDecPicBufferingMinus1: 1);
var units = new List { Sps(sequence), Pps(Plain), Slice(new SliceSettings(Cra, 0), sequence, Plain) };
for (var poc = 1; poc < 40; poc++)
{
var negative = Enumerable.Range(1, Math.Min(poc, 16)).Select(d => (-d, d == 1)).ToArray();
units.Add(Slice(new SliceSettings(TrailR, poc) { Negative = negative }, sequence, Plain));
}
var decoder = new H265Decoder();
var output = 0;
decoder.FrameOutput += _ => output++;
var ex = Assert.ThrowsExactly(() => decoder.DecodeAnnexB(AnnexB([.. units])));
StringAssert.Contains(ex.Message, "buffer");
Assert.IsLessThan(6, decoder.PicturesDecoded, "rifiutato appena il buffer non basta");
// The same stream keeping only the picture before: every picture decodes.
units.RemoveRange(3, units.Count - 3);
for (var poc = 1; poc < 40; poc++)
{
units.Add(Slice(new SliceSettings(TrailR, poc) { Negative = [(-1, true)] }, sequence, Plain));
}
Assert.HasCount(40, Decode(AnnexB([.. units])));
}
[TestMethod]
public void ParameterSetsRepeatedInsideAPictureAreAccepted()
{
// Two slices of one picture (two coding tree blocks), the SPS and PPS sent again between them: §7.4.2.4.4 allows
// it as long as the content is the same.
var wide = new SequenceSettings(32, 16);
var first = new SliceSettings(Cra, 0) { CtbCount = 2, WidthInCtbs = 2 };
var second = first with { First = false, Address = 1 };
var frames = Decode(AnnexB(
Sps(wide),
Pps(Plain),
Slice(first, wide, Plain),
Sps(wide),
Pps(Plain),
Slice(second, wide, Plain)));
Assert.HasCount(1, frames);
Assert.IsTrue(frames[0].Y.All(v => v == 128));
}
[TestMethod]
public void AChangedPpsAppliesFromTheNextPicture()
{
// A PPS with the same ID and another content, between the slices of a picture (not allowed, but met in damaged
// streams) and between two pictures: the picture under way keeps its PPS, the next one takes the new one. Here
// the new PPS has output_flag_present_flag, and the P picture says pic_output_flag 0: it is not output.
var wide = new SequenceSettings(32, 16);
var flagged = new PictureSettings(OutputFlagPresent: true);
var first = new SliceSettings(Cra, 0) { CtbCount = 2, WidthInCtbs = 2 };
var second = first with { First = false, Address = 1 };
var p = new SliceSettings(TrailR, 1) { Negative = [(-1, true)], CtbCount = 2, WidthInCtbs = 2, Ctus = 2, OutputFlag = false };
var inside = Decode(AnnexB(Sps(wide), Pps(Plain), Slice(first, wide, Plain), Pps(flagged), Slice(second, wide, Plain), Slice(p, wide, flagged)));
Assert.HasCount(1, inside, "dentro l'immagine");
var between = Decode(AnnexB(Sps(wide), Pps(Plain), Slice(first, wide, Plain), Slice(second, wide, Plain), Pps(flagged), Slice(p, wide, flagged)));
Assert.HasCount(1, between, "fra due immagini");
}
[TestMethod]
[DataRow(true, false, 1)]
[DataRow(false, true, 1)]
[DataRow(false, false, 9)]
[DataRow(false, false, 11)]
public void ScreenContentCodingIsRefused(bool spsFlag, bool ppsFlag, int profile)
{
var sequence = new SequenceSettings(SccExtension: spsFlag, ProfileIdc: profile);
var picture = new PictureSettings(SccExtension: ppsFlag);
var stream = AnnexB(Sps(sequence), Pps(picture), Slice(new SliceSettings(Cra, 0), sequence, picture));
var ex = Assert.ThrowsExactly(() => new H265Decoder().DecodeAnnexB(stream));
StringAssert.Contains(ex.Message, "SCC");
}
[TestMethod]
[DataRow(10, true, 511, true, 511)]
[DataRow(10, true, -512, true, -512)]
[DataRow(10, true, 512, false, 0)]
[DataRow(12, true, 2047, true, 2047)]
[DataRow(12, true, -2049, false, 0)]
[DataRow(10, false, 127, true, 508)]
[DataRow(10, false, 128, false, 0)]
[DataRow(8, true, -128, true, -128)]
[DataRow(8, true, 128, false, 0)]
public void LumaOffsetsFollowTheirRange(int bitDepth, bool highPrecision, int offset, bool accepted, int expected)
{
// WpOffsetHalfRangeY (7-45): 1 << (BitDepthY − 1) with high_precision_offsets_enabled_flag, 128 without, when
// the offset is then scaled to the bit depth.
var sequence = new SequenceSettings(BitDepth: bitDepth, HighPrecisionOffsets: highPrecision);
var picture = new PictureSettings(WeightedPred: true);
byte[]? buffer = null;
var spss = new Sps?[16];
var ppss = new Pps?[64];
spss[0] = Sps.Parse(H265NalUnit.Unescape(Sps(sequence), ref buffer).Reader());
ppss[0] = Pps.Parse(H265NalUnit.Unescape(Pps(picture), ref buffer).Reader());
var slice = H265NalUnit.Unescape(Slice(new SliceSettings(TrailR, 1) { Negative = [(-1, true)], LumaOffset = offset }, sequence, picture), ref buffer);
if (accepted)
{
var header = SliceHeader.Parse(slice.Reader(), TrailR, spss, ppss, null, out _, out _);
Assert.AreEqual(expected, header.LumaOffset[0][0]);
}
else
{
Assert.ThrowsExactly(() => SliceHeader.Parse(slice.Reader(), TrailR, spss, ppss, null, out _, out _));
}
}
[TestMethod]
public void APictureOfAnotherSizeThanExpectedIsRefused()
{
var stream = AnnexB(Sps(Small), Pps(Plain), Slice(new SliceSettings(Cra, 0), Small, Plain));
var decoder = new H265Decoder { ExpectedFrameSize = (16, 16) };
var frames = new List();
decoder.FrameOutput += frames.Add;
decoder.DecodeAnnexB(stream);
Assert.HasCount(1, frames);
// 2048×1024 where 16×16 is expected: refused before its picture is allocated.
var large = new SequenceSettings(2048, 1024);
var big = AnnexB(Sps(large), Pps(Plain), Slice(new SliceSettings(Cra, 0), large, Plain));
var refusing = new H265Decoder { ExpectedFrameSize = (16, 16) };
var before = GC.GetAllocatedBytesForCurrentThread();
Assert.ThrowsExactly(() => refusing.DecodeAnnexB(big));
Assert.IsLessThan(1024L * 1024, GC.GetAllocatedBytesForCurrentThread() - before);
}
private static List Decode(byte[] stream)
{
var frames = new List();
var decoder = new H265Decoder();
decoder.FrameOutput += frames.Add;
decoder.DecodeAnnexB(stream);
return frames;
}
}