HEVC e HEIF: limiti di memoria contro i file danneggiati e correzioni della revisione (#58)

Un flusso HEVC di pochi byte poteva far allocare gigabyte: ora un SPS il cui
buffer supera il MaxDpbSize del livello 6.2 è rifiutato, il buffer non cresce
oltre quanto l'SPS dichiara e una sola immagine grigia, riusata, sta per ogni
riferimento mancante (il POC viaggia nelle liste). Nei file HEIF ogni immagine
deve avere la dimensione del suo ispe, controllata dal decodificatore prima di
allocare; i riquadri di una griglia devono coprire l'uscita senza traboccare,
i loro byte non superano il file né MaxTotalBytes, e ciò che va storto nei
riquadri decodificati in parallelo esce come HeifException.

Inoltre: SPS e PPS ripetuti identici dentro un'immagine sono accettati (7.4.2.4.4)
e uno cambiato vale dall'immagine dopo; le estensioni SCC sono rifiutate subito;
l'intervallo di luma_offset segue l'alta precisione; YCgCo convertito, le altre
matrici approssimate e documentate. «Oggetto» e «riquadro» al posto di
«elemento» e «tessera» per HEIF (glossario). Righe nuove in decisioni.md:
limiti, righe superate, consegne al binario dei documenti, piano per NSIS,
Node e tini.

Prove nuove su flussi HEVC scritti bit per bit con un codificatore CABAC di
prova, su file HEIF costruiti apposta e sulla conversione YCgCo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 18:23:05 +01:00
1 parent ac85d1baed
commit 7b10f4ad4c
16 files changed
+1389 -131

No files matched your search

@@ -0,0 +1,242 @@
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;
/// <summary>
/// The HEVC decoder on streams written for the purpose (<see cref="H265SyntheticStreams"/>): what bounds its memory
/// against damaged streams, parameter sets repeated inside a picture, the extensions it refuses, the range of weighted
/// prediction offsets.
/// </summary>
[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<H265Exception>(() => 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<byte[]> { 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<H265Exception>(() => 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<H265Exception>(() => 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<H265Exception>(() => 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<H265Frame>();
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<H265Exception>(() => refusing.DecodeAnnexB(big));
Assert.IsLessThan(1024L * 1024, GC.GetAllocatedBytesForCurrentThread() - before);
}
private static List<H265Frame> Decode(byte[] stream)
{
var frames = new List<H265Frame>();
var decoder = new H265Decoder();
decoder.FrameOutput += frames.Add;
decoder.DecodeAnnexB(stream);
return frames;
}
}
@@ -0,0 +1,497 @@
using Febe.Core.Codecs.H265;
using Lps = Febe.Core.Codecs.H264.CabacTables;
namespace Febe.Tests.Codecs.H265;
/// <summary>
/// Tiny HEVC streams written bit by bit from the syntax of ITU-T H.265 (§7.3), their slice data with a CABAC encoder
/// that mirrors the decoding engine of §9.3.4.3: 4:2:0 parameter sets with 16×16 coding tree blocks, I pictures whose
/// coding tree units are one intra coding unit predicted from nothing (every sample at the middle of its range) and P
/// pictures whose coding tree units are skipped. A picture can stop after its first coding tree unit, so pictures of
/// any size cost a few bytes. They reach what the conformance streams do not: missing references, reference picture
/// sets larger than the buffer, parameter sets repeated inside a picture, the screen content extensions, large weighted
/// prediction offsets.
/// </summary>
internal static class H265SyntheticStreams
{
internal const int Cra = 21;
internal const int TrailR = 1;
/// <summary>Settings of the sequence parameter set.</summary>
internal sealed record SequenceSettings(
int Width = 16,
int Height = 16,
int MaxDecPicBufferingMinus1 = 4,
int BitDepth = 8,
bool LongTermRefsPresent = false,
bool HighPrecisionOffsets = false,
bool SccExtension = false,
int ProfileIdc = 1);
/// <summary>Settings of the picture parameter set.</summary>
internal sealed record PictureSettings(
bool OutputFlagPresent = false,
bool WeightedPred = false,
bool SccExtension = false,
int InitQpMinus26 = 0);
/// <summary>A slice segment: its NAL unit type and the syntax elements of its header that the tests vary.</summary>
internal sealed record SliceSettings(int NalType, int PocLsb)
{
public bool First { get; init; } = true;
/// <summary>slice_segment_address of a segment that is not the first.</summary>
public int Address { get; init; }
/// <summary>Picture size in coding tree blocks (for the bits of the address and to know the last one).</summary>
public int CtbCount { get; init; } = 1;
/// <summary>Coding tree units coded in the segment, from its address; the slice ends after them.</summary>
public int Ctus { get; init; } = 1;
/// <summary>Coding tree blocks per row (for the contexts of cu_skip_flag).</summary>
public int WidthInCtbs { get; init; } = 1;
/// <summary>The negative deltas of the short-term set, each with used_by_curr_pic_s0_flag.</summary>
public (int Delta, bool Used)[] Negative { get; init; } = [];
/// <summary>poc_lsb_lt and used_by_curr_pic_lt_flag of the long-term entries (the SPS must allow them).</summary>
public (int PocLsb, bool Used)[] LongTerm { get; init; } = [];
/// <summary>num_ref_idx_l0_active_minus1 + 1, written with the override flag when it is not 1.</summary>
public int ActiveRefs { get; init; } = 1;
/// <summary>pic_output_flag, written when the PPS has output_flag_present_flag.</summary>
public bool? OutputFlag { get; init; }
/// <summary>luma_offset_l0 of reference 0, with a weight table, when the PPS has weighted_pred_flag.</summary>
public int? LumaOffset { get; init; }
}
/// <summary>A sequence parameter set NAL unit (§7.3.2.2), without start code.</summary>
internal static byte[] Sps(SequenceSettings s)
{
var bits = new BitWriter();
bits.Bits(0, 4); // sps_video_parameter_set_id
bits.Bits(0, 3); // sps_max_sub_layers_minus1
bits.Bits(1, 1); // sps_temporal_id_nesting_flag
// profile_tier_level(1, 0): space, tier, profile, 32 compatibility flags, 48 bits of constraints, level.
bits.Bits(0, 3);
bits.Bits((uint)s.ProfileIdc, 5);
bits.Bits(1u << (31 - s.ProfileIdc), 32);
bits.Bits(0, 24);
bits.Bits(0, 24);
bits.Bits(186, 8); // general_level_idc: 6.2
bits.Ue(0); // sps_seq_parameter_set_id
bits.Ue(1); // chroma_format_idc: 4:2:0
bits.Ue((uint)s.Width);
bits.Ue((uint)s.Height);
bits.Bits(0, 1); // conformance_window_flag
bits.Ue((uint)s.BitDepth - 8);
bits.Ue((uint)s.BitDepth - 8);
bits.Ue(4); // log2_max_pic_order_cnt_lsb_minus4: 8 bits
bits.Bits(1, 1); // sps_sub_layer_ordering_info_present_flag
bits.Ue((uint)s.MaxDecPicBufferingMinus1);
bits.Ue(0); // sps_max_num_reorder_pics
bits.Ue(0); // sps_max_latency_increase_plus1
bits.Ue(0); // log2_min_luma_coding_block_size_minus3: 8×8
bits.Ue(1); // log2_diff_max_min_luma_coding_block_size: 16×16 coding tree blocks
bits.Ue(0); // log2_min_luma_transform_block_size_minus2: 4×4
bits.Ue(2); // log2_diff_max_min_luma_transform_block_size: 16×16
bits.Ue(0); // max_transform_hierarchy_depth_inter
bits.Ue(0); // max_transform_hierarchy_depth_intra
bits.Bits(0, 1); // scaling_list_enabled_flag
bits.Bits(0, 1); // amp_enabled_flag
bits.Bits(0, 1); // sample_adaptive_offset_enabled_flag
bits.Bits(0, 1); // pcm_enabled_flag
bits.Ue(0); // num_short_term_ref_pic_sets
bits.Bits(s.LongTermRefsPresent ? 1u : 0u, 1);
if (s.LongTermRefsPresent)
{
bits.Ue(0); // num_long_term_ref_pics_sps
}
bits.Bits(0, 1); // sps_temporal_mvp_enabled_flag
bits.Bits(0, 1); // strong_intra_smoothing_enabled_flag
bits.Bits(0, 1); // vui_parameters_present_flag
var extension = s.HighPrecisionOffsets || s.SccExtension;
bits.Bits(extension ? 1u : 0u, 1);
if (extension)
{
bits.Bits(s.HighPrecisionOffsets ? 1u : 0u, 1); // sps_range_extension_flag
bits.Bits(0, 2); // sps_multilayer_extension_flag, sps_3d_extension_flag
bits.Bits(s.SccExtension ? 1u : 0u, 1);
bits.Bits(0, 4); // sps_extension_4bits
if (s.HighPrecisionOffsets)
{
// Range extension flags: only high_precision_offsets_enabled_flag (the seventh).
bits.Bits(0b0000_0010_0, 9);
}
// sps_scc_extension() is not written: the decoder refuses the stream before it would need it.
}
return Nal(33, bits);
}
/// <summary>A picture parameter set NAL unit (§7.3.2.3), without start code: deblocking off, no tiles or wavefronts.</summary>
internal static byte[] Pps(PictureSettings p)
{
var bits = new BitWriter();
bits.Ue(0); // pps_pic_parameter_set_id
bits.Ue(0); // pps_seq_parameter_set_id
bits.Bits(0, 1); // dependent_slice_segments_enabled_flag
bits.Bits(p.OutputFlagPresent ? 1u : 0u, 1);
bits.Bits(0, 3); // num_extra_slice_header_bits
bits.Bits(0, 1); // sign_data_hiding_enabled_flag
bits.Bits(0, 1); // cabac_init_present_flag
bits.Ue(0); // num_ref_idx_l0_default_active_minus1
bits.Ue(0); // num_ref_idx_l1_default_active_minus1
bits.Se(p.InitQpMinus26);
bits.Bits(0, 1); // constrained_intra_pred_flag
bits.Bits(0, 1); // transform_skip_enabled_flag
bits.Bits(0, 1); // cu_qp_delta_enabled_flag
bits.Se(0); // pps_cb_qp_offset
bits.Se(0); // pps_cr_qp_offset
bits.Bits(0, 1); // pps_slice_chroma_qp_offsets_present_flag
bits.Bits(p.WeightedPred ? 1u : 0u, 1);
bits.Bits(0, 1); // weighted_bipred_flag
bits.Bits(0, 1); // transquant_bypass_enabled_flag
bits.Bits(0, 1); // tiles_enabled_flag
bits.Bits(0, 1); // entropy_coding_sync_enabled_flag
bits.Bits(0, 1); // pps_loop_filter_across_slices_enabled_flag
bits.Bits(1, 1); // deblocking_filter_control_present_flag
bits.Bits(0, 1); // deblocking_filter_override_enabled_flag
bits.Bits(1, 1); // pps_deblocking_filter_disabled_flag
bits.Bits(0, 1); // pps_scaling_list_data_present_flag
bits.Bits(0, 1); // lists_modification_present_flag
bits.Ue(0); // log2_parallel_merge_level_minus2
bits.Bits(0, 1); // slice_segment_header_extension_present_flag
bits.Bits(p.SccExtension ? 1u : 0u, 1);
if (p.SccExtension)
{
bits.Bits(0, 3); // pps_range_extension_flag, pps_multilayer_extension_flag, pps_3d_extension_flag
bits.Bits(1, 1); // pps_scc_extension_flag
bits.Bits(0, 4); // pps_extension_4bits; pps_scc_extension() is not written
}
return Nal(34, bits);
}
/// <summary>A slice segment NAL unit (§7.3.6, §7.3.8), without start code, for the parameter sets above.</summary>
internal static byte[] Slice(SliceSettings s, SequenceSettings sequence, PictureSettings picture)
{
var bits = new BitWriter();
bits.Bits(s.First ? 1u : 0u, 1);
if (s.NalType is >= 16 and <= 23)
{
bits.Bits(0, 1); // no_output_of_prior_pics_flag
}
bits.Ue(0); // slice_pic_parameter_set_id
if (!s.First)
{
var addressBits = 0;
while ((1 << addressBits) < s.CtbCount)
{
addressBits++;
}
bits.Bits((uint)s.Address, addressBits);
}
var intra = s.NalType is >= 16 and <= 23;
bits.Ue(intra ? 2u : 1u); // slice_type: I or P
if (picture.OutputFlagPresent)
{
bits.Bits(s.OutputFlag ?? true ? 1u : 0u, 1);
}
bits.Bits((uint)s.PocLsb, 8);
bits.Bits(0, 1); // short_term_ref_pic_set_sps_flag: the set follows
bits.Ue((uint)s.Negative.Length);
bits.Ue(0); // num_positive_pics
var previous = 0;
foreach (var (delta, used) in s.Negative)
{
bits.Ue((uint)(previous - delta - 1)); // delta_poc_s0_minus1, from the previous entry
bits.Bits(used ? 1u : 0u, 1);
previous = delta;
}
if (sequence.LongTermRefsPresent)
{
bits.Ue((uint)s.LongTerm.Length);
foreach (var (pocLsb, used) in s.LongTerm)
{
bits.Bits((uint)pocLsb, 8);
bits.Bits(used ? 1u : 0u, 1);
bits.Bits(0, 1); // delta_poc_msb_present_flag
}
}
if (!intra)
{
bits.Bits(s.ActiveRefs != 1 ? 1u : 0u, 1); // num_ref_idx_active_override_flag
if (s.ActiveRefs != 1)
{
bits.Ue((uint)s.ActiveRefs - 1);
}
if (picture.WeightedPred)
{
bits.Ue(6); // luma_log2_weight_denom
bits.Se(0); // delta_chroma_log2_weight_denom
for (var i = 0; i < s.ActiveRefs; i++)
{
bits.Bits(i == 0 ? 1u : 0u, 1); // luma_weight_l0_flag
}
bits.Bits(0, s.ActiveRefs); // chroma_weight_l0_flag
bits.Se(0); // delta_luma_weight_l0
bits.Se(s.LumaOffset ?? 0);
}
bits.Ue(4); // five_minus_max_num_merge_cand: one candidate, no merge_idx
}
bits.Se(0); // slice_qp_delta
bits.Bits(1, 1); // byte_alignment()
bits.Align();
var cabac = new CabacWriter(bits, intra ? 0 : 1, 26 + picture.InitQpMinus26);
for (var k = 0; k < s.Ctus; k++)
{
var address = s.Address + k;
cabac.Decision(CabacTables.SplitCuFlag, 0);
if (intra)
{
cabac.Decision(CabacTables.PrevIntraLumaPredFlag, 1);
cabac.Bypass(0); // mpm_idx 0
cabac.Decision(CabacTables.IntraChromaPredMode, 0); // the luma mode
cabac.Decision(CabacTables.CbfChroma, 0);
cabac.Decision(CabacTables.CbfChroma, 0);
cabac.Decision(CabacTables.CbfLuma + 1, 0);
}
else
{
// cu_skip_flag: one more for each neighbour (left, above) of the same slice, all skipped.
var x = address % s.WidthInCtbs;
var y = address / s.WidthInCtbs;
var ctx = (x > 0 && address > s.Address ? 1 : 0) + (y > 0 && address - s.WidthInCtbs >= s.Address ? 1 : 0);
cabac.Decision(CabacTables.CuSkipFlag + ctx, 1);
}
cabac.Terminate(k == s.Ctus - 1 ? 1 : 0); // end_of_slice_segment_flag
}
bits.Align();
return Nal(s.NalType, bits, stopBit: false);
}
/// <summary>NAL units with start codes, one after the other.</summary>
internal static byte[] AnnexB(params byte[][] units) => [.. units.SelectMany(u => (byte[])[0, 0, 0, 1, .. u])];
private static byte[] Nal(int type, BitWriter bits, bool stopBit = true)
{
if (stopBit)
{
bits.Bits(1, 1); // rbsp_stop_one_bit
bits.Align();
}
return [(byte)(type << 1), 1, .. bits.ToArray()];
}
/// <summary>
/// The arithmetic encoder that matches the decoding engine bit for bit (the encoding flowcharts of ITU-T H.264
/// §9.3.4, whose arithmetic HEVC keeps), with the context variables initialised by the decoder's own code.
/// </summary>
private sealed class CabacWriter
{
private readonly BitWriter bits;
private readonly byte[] contexts;
private int low;
private int range = 510;
private int outstanding;
private bool firstBit = true;
public CabacWriter(BitWriter bits, int initType, int sliceQp)
{
this.bits = bits;
var engine = new CabacEngine();
engine.InitContexts(initType, sliceQp);
contexts = (byte[])engine.Contexts.Clone();
}
public void Decision(int ctx, int bin)
{
int s = contexts[ctx];
var p = s >> 1;
var mps = s & 1;
int lps = Lps.RangeLps[(p << 2) + ((range >> 6) & 3)];
range -= lps;
if (bin != mps)
{
low += range;
range = lps;
if (p == 0)
{
mps ^= 1;
}
contexts[ctx] = (byte)((Lps.NextStateLps[p] << 1) | mps);
}
else if (p < 62)
{
contexts[ctx] = (byte)(s + 2);
}
Renormalise();
}
public void Bypass(int bin)
{
low <<= 1;
if (bin != 0)
{
low += range;
}
if (low >= 1024)
{
Put(1);
low -= 1024;
}
else if (low < 512)
{
Put(0);
}
else
{
low -= 512;
outstanding++;
}
}
public void Terminate(int bin)
{
range -= 2;
if (bin == 0)
{
Renormalise();
return;
}
// EncodeFlush: the last bit written is the stop bit of the slice data.
low += range;
range = 2;
Renormalise();
Put((low >> 9) & 1);
bits.Bits((uint)(((low >> 7) & 3) | 1), 2);
}
private void Renormalise()
{
while (range < 256)
{
if (low < 256)
{
Put(0);
}
else if (low >= 512)
{
low -= 512;
Put(1);
}
else
{
low -= 256;
outstanding++;
}
range <<= 1;
low <<= 1;
}
}
private void Put(int bit)
{
if (firstBit)
{
firstBit = false;
}
else
{
bits.Bits((uint)bit, 1);
}
for (; outstanding > 0; outstanding--)
{
bits.Bits((uint)(1 - bit), 1);
}
}
}
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 void Se(int value) => Ue(value <= 0 ? (uint)(-2 * value) : (uint)((2 * value) - 1));
public void Align()
{
while (bits.Count % 8 != 0)
{
bits.Add(false);
}
}
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.2): 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];
}
}
}
@@ -341,6 +341,161 @@ public sealed class HeifDecoderTests
Assert.IsGreaterThan(0, decoded, "nessuna variante decodificata");
}
[TestMethod]
public void ACodedImageMustHaveTheSizeOfItsIspe()
{
// A 416×240 picture behind an ispe of 64×64: the decoder would allocate the picture the SPS says, however small
// the ispe, and the result was cut silently.
var picture = CodedPicture.First(Tiles[0]);
var builder = new HeifBuilder();
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
builder.Item(1, "hvc1", picture.Data, -hvcC, builder.Property(HeifBuilder.Ispe(64, 64)));
var file = builder.Build();
var ex = Assert.ThrowsExactly<HeifException>(() => HeifDecoder.Decode(file));
StringAssert.Contains(ex.Message, "dimensioni diverse");
using var bitmap = ImageDecoding.DecodeUpright(new MemoryStream(file));
Assert.IsNull(bitmap);
}
[TestMethod]
public void GridTilesMustHaveTheSizeOfTheirIspe()
{
// Tiles declared 208×120 that are pictures of 416×240, in a grid whose output the declared size covers.
var pictures = Tiles.Select(CodedPicture.First).ToArray();
var (tw, th) = (pictures[0].Frame.Width / 2, pictures[0].Frame.Height / 2);
var builder = new HeifBuilder();
var ispe = builder.Property(HeifBuilder.Ispe(tw, th));
builder.Item(1, "grid", HeifBuilder.GridData(2, 2, (2 * tw) - 4, (2 * th) - 4));
for (var i = 0; i < 4; i++)
{
builder.Item((uint)(10 + i), "hvc1", pictures[i].Data, -builder.Property(HeifBuilder.HvcCProperty(pictures[i].HvcC)), ispe);
}
builder.Reference("dimg", 1, 10, 11, 12, 13);
Assert.ThrowsExactly<HeifException>(() => HeifDecoder.Decode(builder.Build()));
}
[TestMethod]
[DataRow(0x5000_0000, 240)]
[DataRow(416, 0x5000_0000)]
[DataRow(100, 240)]
[DataRow(0, 240)]
public void TilesThatDoNotFitTheGridAreRefused(int tileWidth, int tileHeight)
{
// A row of four tiles for an image 800 wide: tiles 0x50000000 wide made the offset of the fourth overflow and
// the exception escaped the decoder from its parallel loop; 100 wide do not cover the image; 0 is no size.
var pictures = Tiles.Select(CodedPicture.First).ToArray();
var builder = new HeifBuilder();
var ispe = builder.Property(HeifBuilder.Ispe(tileWidth, tileHeight));
builder.Item(1, "grid", HeifBuilder.GridData(1, 4, 800, 240));
for (var i = 0; i < 4; i++)
{
builder.Item((uint)(10 + i), "hvc1", pictures[i].Data, -builder.Property(HeifBuilder.HvcCProperty(pictures[i].HvcC)), ispe);
}
builder.Reference("dimg", 1, 10, 11, 12, 13);
var file = builder.Build();
Assert.ThrowsExactly<HeifException>(() => HeifDecoder.Decode(file));
using var bitmap = ImageDecoding.DecodeUpright(new MemoryStream(file));
Assert.IsNull(bitmap, "nessuna eccezione fuori dalla decodifica");
}
[TestMethod]
public void TilesThatShareTheirBytesCannotMultiplyThem()
{
// Four tile items whose extents are the same bytes: read as four, they would be four times what the file holds
// (with thousands of tiles, gigabytes from a small file).
var picture = CodedPicture.First(Tiles[0]);
var (tw, th) = (picture.Frame.Width, picture.Frame.Height);
var shared = new HeifBuilder();
var hvcC = shared.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = shared.Property(HeifBuilder.Ispe(tw, th));
shared.Item(1, "grid", HeifBuilder.GridData(2, 2, 2 * tw, 2 * th)).Item(10, "hvc1", picture.Data, -hvcC, ispe);
for (var i = 1; i < 4; i++)
{
shared.ItemSharing((uint)(10 + i), "hvc1", 10, -hvcC, ispe);
}
shared.Reference("dimg", 1, 10, 11, 12, 13);
var ex = Assert.ThrowsExactly<HeifException>(() => HeifDecoder.Decode(shared.Build()));
StringAssert.Contains(ex.Message, "più dati");
// The same tile named four times is read once: the grid is that picture four times.
var repeated = new HeifBuilder();
hvcC = repeated.Property(HeifBuilder.HvcCProperty(picture.HvcC));
ispe = repeated.Property(HeifBuilder.Ispe(tw, th));
repeated.Item(1, "grid", HeifBuilder.GridData(2, 2, 2 * tw, 2 * th)).Item(10, "hvc1", picture.Data, -hvcC, ispe).Reference("dimg", 1, 10, 10, 10, 10);
var image = HeifDecoder.Decode(repeated.Build());
var tile = Rgba(picture.Frame);
for (var y = 0; y < 2 * th; y++)
{
for (var half = 0; half < 2; half++)
{
var row = image.Pixels.AsSpan(((y * 2 * tw) + (half * tw)) * 4, tw * 4);
Assert.IsTrue(row.SequenceEqual(tile.AsSpan(y % th * tw * 4, tw * 4)), $"riga {y}, metà {half}");
}
}
}
[TestMethod]
public void TheBytesOfAllTilesHaveALimit()
{
var pictures = Tiles.Select(CodedPicture.First).ToArray();
var (tw, th) = (pictures[0].Frame.Width, pictures[0].Frame.Height);
var builder = new HeifBuilder();
var ispe = builder.Property(HeifBuilder.Ispe(tw, th));
builder.Item(1, "grid", HeifBuilder.GridData(2, 2, 2 * tw, 2 * th));
for (var i = 0; i < 4; i++)
{
builder.Item((uint)(10 + i), "hvc1", pictures[i].Data, -builder.Property(HeifBuilder.HvcCProperty(pictures[i].HvcC)), ispe);
}
builder.Reference("dimg", 1, 10, 11, 12, 13);
var file = builder.Build();
long total = pictures.Sum(p => p.Data.Length);
Assert.AreEqual(2 * tw, HeifDecoder.Decode(file, new HeifLimits { MaxTotalBytes = total }).Width);
Assert.ThrowsExactly<HeifException>(() => HeifDecoder.Decode(file, new HeifLimits { MaxTotalBytes = total - 1 }));
}
[TestMethod]
[DataRow(6201)]
[DataRow(6202)]
public void DamagedTilesDecodedInParallelOnlyRaiseHeifException(int seed)
{
// The data of the tiles after the first, which are decoded on several threads: whatever goes wrong there leaves
// the decoder as a HeifException, not as the AggregateException of the parallel loop.
var pictures = Tiles.Select(CodedPicture.First).ToArray();
var (tw, th) = (pictures[0].Frame.Width, pictures[0].Frame.Height);
var builder = new HeifBuilder();
var ispe = builder.Property(HeifBuilder.Ispe(tw, th));
builder.Item(1, "grid", HeifBuilder.GridData(2, 2, 2 * tw, 2 * th));
for (var i = 0; i < 4; i++)
{
builder.Item((uint)(10 + i), "hvc1", pictures[i].Data, -builder.Property(HeifBuilder.HvcCProperty(pictures[i].HvcC)), ispe);
}
builder.Reference("dimg", 1, 10, 11, 12, 13);
var file = builder.Build();
var rest = pictures.Skip(1).Sum(p => p.Data.Length);
var random = new Random(seed);
for (var trial = 0; trial < 40; trial++)
{
var copy = (byte[])file.Clone();
for (var k = random.Next(1, 30); k > 0; k--)
{
copy[copy.Length - 1 - random.Next(rest)] = (byte)random.Next(256);
}
try
{
_ = HeifDecoder.Decode(copy);
}
catch (HeifException)
{
}
}
}
private static byte[] WithExif(CodedPicture picture, byte[] tiff)
{
var builder = new HeifBuilder();
+23 -6
View File
@@ -108,6 +108,13 @@ internal sealed class HeifBuilder
return this;
}
/// <summary>Adds an item whose only extent is that of item <paramref name="dataOf"/>: the same bytes of the file.</summary>
public HeifBuilder ItemSharing(uint id, string type, uint dataOf, params int[] properties)
{
items.Add(new Entry(id, type, [], properties) { SharesWith = dataOf });
return this;
}
/// <summary>Adds a property box and returns its 1-based index.</summary>
public int Property(byte[] box)
{
@@ -156,7 +163,7 @@ internal sealed class HeifBuilder
var meta = Meta(0);
var mdatStart = ftyp.Length + meta.Length + 8;
meta = Meta(mdatStart);
var payload = InIdat ? [] : items.SelectMany(i => i.Data).ToArray();
var payload = InIdat ? [] : items.Where(i => i.SharesWith is null).SelectMany(i => i.Data).ToArray();
return [.. ftyp, .. meta, .. Box("mdat", payload)];
}
@@ -171,15 +178,22 @@ internal sealed class HeifBuilder
var iloc = new List<byte> { 0x44, 0x00 };
iloc.AddRange(U16((ushort)items.Count));
var offset = InIdat ? 0 : mdatStart;
var extents = new Dictionary<uint, (int Offset, int Length)>();
foreach (var item in items.Where(i => i.SharesWith is null))
{
extents[item.Id] = (offset, item.Data.Length);
offset += item.Data.Length;
}
foreach (var item in items)
{
var (start, length) = extents[item.SharesWith ?? item.Id];
iloc.AddRange(U16((ushort)item.Id));
iloc.AddRange(U16(InIdat ? (ushort)1 : (ushort)0)); // construction_method
iloc.AddRange(U16(0));
iloc.AddRange(U16(1));
iloc.AddRange(U32((uint)offset));
iloc.AddRange(U32((uint)item.Data.Length));
offset += item.Data.Length;
iloc.AddRange(U32((uint)start));
iloc.AddRange(U32((uint)length));
}
var ipma = new List<byte>();
@@ -214,7 +228,7 @@ internal sealed class HeifBuilder
children.Add(iprp);
if (InIdat)
{
children.Add(Box("idat", [.. items.SelectMany(i => i.Data)]));
children.Add(Box("idat", [.. items.Where(i => i.SharesWith is null).SelectMany(i => i.Data)]));
}
return FullBox("meta", 0, [.. children.SelectMany(b => b)]);
@@ -235,5 +249,8 @@ internal sealed class HeifBuilder
private static byte[] U32(uint v) => [(byte)(v >> 24), (byte)(v >> 16), (byte)(v >> 8), (byte)v];
private sealed record Entry(uint Id, string Type, byte[] Data, int[] Properties);
private sealed record Entry(uint Id, string Type, byte[] Data, int[] Properties)
{
public uint? SharesWith { get; init; }
}
}
+37
View File
@@ -0,0 +1,37 @@
using Febe.Core.Codecs;
namespace Febe.Tests.Codecs;
/// <summary>The shared Y′CbCr to RGB conversion: the matrices that are not Y′CbCr ones.</summary>
[TestClass]
public sealed class YuvToRgbTests
{
[TestMethod]
[DataRow(128, 148, 128, true, 8, 108, 148, 108)]
[DataRow(100, 128, 150, true, 8, 122, 100, 78)]
[DataRow(200, 100, 160, true, 8, 255, 172, 196)]
[DataRow(512, 592, 512, true, 10, 108, 148, 108)]
[DataRow(16, 128, 128, false, 8, 0, 0, 0)]
[DataRow(235, 128, 128, false, 8, 255, 255, 255)]
[DataRow(126, 151, 128, false, 8, 102, 154, 102)]
public void YCgCoIsNotConvertedAsYCbCr(int y, int cg, int co, bool fullRange, int bitDepth, int r, int g, int b)
{
// matrix_coeffs 8 (H.273): G = Y + Cg, R = Y − Cg + Co, B = Y − Cg − Co, Cg and Co around the middle of their
// range and, in limited range, scaled as Cb and Cr are (224 steps), Y as luma (219 steps from 16).
var k = YuvToRgb.For(8, fullRange, bitDepth, bitDepth, 1080);
var planes = new YuvPlanes<ushort>([(ushort)y], [(ushort)cg], [(ushort)co], 1, 1, 0, 0, false, bitDepth, bitDepth);
var rgb = new byte[3];
YuvToRgb.Convert(planes, k, 1, rgb, 3, 3, 1, 1);
Assert.AreEqual((r, g, b), (rgb[0], rgb[1], rgb[2]));
}
[TestMethod]
public void YCgCoGreyStaysGrey()
{
var k = YuvToRgb.For(8, false, 8, 8, 1080);
var planes = new YuvPlanes<byte>([16, 126, 235], [128, 128, 128], [128, 128, 128], 3, 1, 0, 0, false, 8, 8);
var rgb = new byte[9];
YuvToRgb.Convert(planes, k, 1, rgb, 9, 3, 3, 1);
CollectionAssert.AreEqual(new byte[] { 0, 0, 0, 128, 128, 128, 255, 255, 255 }, rgb);
}
}