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

@@ -94,11 +94,11 @@ public sealed partial class H265Decoder
{
var entry = temp[h.ListModification[list] ? h.ListEntry[list][i] : i];
var longTerm = entry >= before + after;
var picture = entry < before ? refStCurrBefore[entry] : !longTerm ? refStCurrAfter[entry - before] : refLtCurr[entry - before - after];
var (picture, refPoc) = entry < before ? refStCurrBefore[entry] : !longTerm ? refStCurrAfter[entry - before] : refLtCurr[entry - before - after];
h.RefPicList[list][i] = picture;
h.RefPoc[list][i] = picture.Poc;
h.RefPoc[list][i] = refPoc;
h.RefIsLongTerm[list][i] = longTerm;
h.NoBackwardPred &= picture.Poc <= cur!.Poc;
h.NoBackwardPred &= refPoc <= cur!.Poc;
}
}
@@ -307,6 +307,7 @@ public sealed partial class H265Decoder
var motion = cur!.Motion;
var target = slice.RefPicList[x][refIdx];
var targetLongTerm = slice.RefIsLongTerm[x][refIdx];
var targetPoc = slice.RefPoc[x][refIdx];
var poc = cur.Poc;
// A: A0 then A1.
@@ -328,7 +329,7 @@ public sealed partial class H265Decoder
{
if (k == 0 ? availableA0 : availableA1)
{
flagA = ScaledCandidate(motion[Grid(xA0, k == 0 ? yA0 : yA1)], x, target, targetLongTerm, poc, out ax, out ay);
flagA = ScaledCandidate(motion[Grid(xA0, k == 0 ? yA0 : yA1)], x, targetPoc, targetLongTerm, poc, out ax, out ay);
}
}
@@ -361,7 +362,7 @@ public sealed partial class H265Decoder
{
if (k == 0 ? availableB0 : k == 1 ? availableB1 : availableB2)
{
flagB = ScaledCandidate(motion[Grid(k == 0 ? xB0 : k == 1 ? xB1 : xB2, yB)], x, target, targetLongTerm, poc, out bx, out by);
flagB = ScaledCandidate(motion[Grid(k == 0 ? xB0 : k == 1 ? xB1 : xB2, yB)], x, targetPoc, targetLongTerm, poc, out bx, out by);
}
}
}
@@ -434,7 +435,7 @@ public sealed partial class H265Decoder
/// The second conditions of §8.5.3.2.7: a neighbour whose reference is long-term exactly when the target is, its
/// vector scaled by the POC distances when both are short-term.
/// </summary>
private bool ScaledCandidate(in MvField n, int x, Picture target, bool targetLongTerm, int poc, out int mx, out int my)
private bool ScaledCandidate(in MvField n, int x, int targetPoc, bool targetLongTerm, int poc, out int mx, out int my)
{
for (var pass = 0; pass < 2; pass++)
{
@@ -450,7 +451,7 @@ public sealed partial class H265Decoder
if (!targetLongTerm)
{
var td = Math.Clamp(poc - slice.RefPoc[list][refIdx], -128, 127);
var tb = Math.Clamp(poc - target.Poc, -128, 127);
var tb = Math.Clamp(poc - targetPoc, -128, 127);
if (td != 0)
{
mx = ScaleMv(mx, td, tb);
+144 -30
View File
@@ -22,8 +22,10 @@ public enum H265AccessPoint
/// motion vector prediction, weighted prediction), deblocking and SAO, and the range extension tools (cross-component
/// prediction, implicit and explicit RDPCM, transform skip rotation and contexts, persistent Rice adaptation, chroma QP
/// offset lists, intra smoothing disabled, high precision offsets). Not handled (an <see cref="H265Exception"/>): extended
/// precision processing, the CABAC bypass alignment, separate colour planes, bit depths above 12; the layers above 0 of
/// scalable and multiview streams are ignored.
/// precision processing, the CABAC bypass alignment, the screen content coding extensions (SCC), separate colour planes,
/// bit depths above 12; the layers above 0 of scalable and multiview streams are ignored. Against damaged streams the
/// decoded picture buffer is bounded by the SPS (itself bounded by level 6.2) and one generated picture stands for every
/// missing reference.
/// </summary>
public sealed partial class H265Decoder
{
@@ -53,12 +55,31 @@ public sealed partial class H265Decoder
private bool skipping;
/// <summary>
/// The three lists of the reference picture set that the current picture uses (§8.3.2), a generated picture in place
/// of "no reference picture" (§8.3.3).
/// The three lists of the reference picture set that the current picture uses (§8.3.2), each picture with the POC the
/// set gives it; the generated picture <see cref="missing"/> in place of every "no reference picture" (§8.3.3).
/// </summary>
private readonly List<Picture> refStCurrBefore = [];
private readonly List<Picture> refStCurrAfter = [];
private readonly List<Picture> refLtCurr = [];
private readonly List<(Picture Picture, int Poc)> refStCurrBefore = [];
private readonly List<(Picture Picture, int Poc)> refStCurrAfter = [];
private readonly List<(Picture Picture, int Poc)> refLtCurr = [];
/// <summary>
/// The picture that stands for every missing reference (§8.3.3.2), made once for a size, chroma format and bit depth
/// and shared: a damaged stream that names dozens of missing references costs one picture, not one each.
/// </summary>
private Picture? missing;
/// <summary>
/// SPS and PPS that came, with an ID the current picture uses and a different content, between its slice segments:
/// they apply from the next picture (§7.4.2.4.4), and are installed when the current one is finished.
/// </summary>
private readonly List<Sps> pendingSps = [];
private readonly List<Pps> pendingPps = [];
/// <summary>
/// Pictures the DPB may hold beyond sps_max_dec_pic_buffering_minus1 + 1 before the stream is refused: a conforming
/// stream never needs it (C.5.2.2), a damaged one that keeps every picture as a reference cannot grow it further.
/// </summary>
private const int DpbMargin = 1;
/// <summary>Raised for each frame in output order (the bumping process of C.5.2.4), cropped.</summary>
public event Action<H265Frame>? FrameOutput;
@@ -79,6 +100,13 @@ public sealed partial class H265Decoder
/// <summary>Coded pictures met so far, also those skipped.</summary>
public long PicturesDecoded => codedPictures;
/// <summary>
/// The size every picture must have once cropped (a HEIF image of known <c>ispe</c>), or null for any size the
/// levels allow. A picture of another size, or coded much larger than it (a conformance window that throws most of
/// it away), is refused with an <see cref="H265Exception"/> before anything of its size is allocated.
/// </summary>
public (int Width, int Height)? ExpectedFrameSize { get; set; }
/// <summary>Decodes a whole Annex B byte stream, then outputs every picture left.</summary>
public void DecodeAnnexB(ReadOnlySpan<byte> stream)
{
@@ -232,18 +260,11 @@ public sealed partial class H265Decoder
DecodeSlice(H265NalUnit.Unescape(bytes, ref rbsp));
break;
case 33:
{
var sps = Sps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader());
spss[sps.Id] = sps;
break;
}
InstallSps(Sps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader()));
break;
case 34:
{
var pps = Pps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader());
ppss[pps.Id] = pps;
break;
}
InstallPps(Pps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader()));
break;
case 35: // access unit delimiter
FinishPicture();
@@ -284,7 +305,7 @@ public sealed partial class H265Decoder
return;
}
}
else if (!ReferenceEquals(s, sps) || !ReferenceEquals(p, pps))
else if (!s.SameContent(sps) || !p.SameContent(pps))
{
throw new H265Exception("Parametri diversi fra le slice di un'immagine.");
}
@@ -335,6 +356,21 @@ public sealed partial class H265Decoder
throw new H265Exception("La precisione estesa e l'allineamento CABAC delle estensioni di formato HEVC non sono gestiti.");
}
if (s.UsesScreenContentCoding || p.SccExtension)
{
throw new H265Exception("Le estensioni HEVC per i contenuti dello schermo (SCC) non sono gestite.");
}
if (ExpectedFrameSize is { } expected)
{
// A conformance window crops at most what pads the picture to its coding blocks (at most 63 samples).
int width = s.Width - s.ConfLeft - s.ConfRight, height = s.Height - s.ConfTop - s.ConfBottom;
if (width != expected.Width || height != expected.Height || s.Width - width > 63 || s.Height - height > 63)
{
throw new H265Exception("Immagine HEVC di dimensioni diverse da quelle attese.");
}
}
p.Activate(s);
// Picture order count (§8.3.1).
@@ -400,6 +436,13 @@ public sealed partial class H265Decoder
break;
}
}
// Nothing left to output and still no room: every picture is kept as a reference, which a conforming stream
// never does. Without this bound a damaged one would keep up to 48 pictures (16 short-term, 32 long-term).
if (dpb.Count > s.MaxDecPicBufferingMinus1[t] + DpbMargin)
{
throw new H265Exception("Più immagini di riferimento di quante ne tiene il buffer dell'SPS.");
}
}
firstPicture = false;
@@ -468,7 +511,7 @@ public sealed partial class H265Decoder
if (h.UsedByCurrPicLt[i])
{
refLtCurr.Add(found >= 0 ? dpb[found] : MissingReference(s, pocLt));
refLtCurr.Add(found >= 0 ? (dpb[found], dpb[found].Poc) : (MissingReference(s), pocLt));
}
}
@@ -479,7 +522,7 @@ public sealed partial class H265Decoder
var picture = FindShortTerm(poc + rps.DeltaPocS0[i], keep);
if (rps.UsedS0[i])
{
refStCurrBefore.Add(picture ?? MissingReference(s, poc + rps.DeltaPocS0[i]));
refStCurrBefore.Add((picture ?? MissingReference(s), poc + rps.DeltaPocS0[i]));
}
}
@@ -488,7 +531,7 @@ public sealed partial class H265Decoder
var picture = FindShortTerm(poc + rps.DeltaPocS1[i], keep);
if (rps.UsedS1[i])
{
refStCurrAfter.Add(picture ?? MissingReference(s, poc + rps.DeltaPocS1[i]));
refStCurrAfter.Add((picture ?? MissingReference(s), poc + rps.DeltaPocS1[i]));
}
}
}
@@ -504,19 +547,89 @@ public sealed partial class H265Decoder
}
/// <summary>
/// A picture for a reference that is not in the DPB (§8.3.3.2): every sample at the middle of its range, every block
/// intra. It is not put in the DPB and never output; only damaged or cut streams need one.
/// The picture for a reference that is not in the DPB (§8.3.3.2): every sample at the middle of its range, every block
/// intra. It is not put in the DPB and never output; only damaged or cut streams need one. One picture serves every
/// missing reference of the same size and bit depth (its POC travels in the reference lists, not in the picture):
/// it is never written, and a stream that names 48 missing references allocates it once.
/// </summary>
private static Picture MissingReference(Sps s, int poc)
private Picture MissingReference(Sps s)
{
var picture = new Picture(s) { Poc = poc, Generated = true };
picture.Planes[0].AsSpan().Fill((ushort)(1 << (s.BitDepthY - 1)));
picture.Planes[1].AsSpan().Fill((ushort)(1 << (s.BitDepthC - 1)));
picture.Planes[2].AsSpan().Fill((ushort)(1 << (s.BitDepthC - 1)));
picture.Motion.AsSpan().Fill(MvField.Intra);
var picture = missing;
if (picture is null || !picture.Fits(s) || picture.Sps.BitDepthY != s.BitDepthY || picture.Sps.BitDepthC != s.BitDepthC)
{
picture = new Picture(s) { Generated = true };
picture.Planes[0].AsSpan().Fill((ushort)(1 << (s.BitDepthY - 1)));
picture.Planes[1].AsSpan().Fill((ushort)(1 << (s.BitDepthC - 1)));
picture.Planes[2].AsSpan().Fill((ushort)(1 << (s.BitDepthC - 1)));
picture.Motion.AsSpan().Fill(MvField.Intra);
missing = picture;
}
picture.Sps = s;
return picture;
}
/// <summary>
/// Takes a new SPS. An identical copy of the one in place is dropped, so the active object stays (§7.4.2.4.4 lets a
/// stream repeat it anywhere in an access unit); one that carries the ID of the current picture's SPS waits until
/// that picture is finished.
/// </summary>
private void InstallSps(Sps s)
{
if (cur is not null && s.Id == sps.Id)
{
if (pendingSps.Count > 0 || !s.SameContent(spss[s.Id]))
{
pendingSps.RemoveAll(x => x.Id == s.Id);
pendingSps.Add(s);
}
return;
}
if (!s.SameContent(spss[s.Id]))
{
spss[s.Id] = s;
}
}
/// <summary>Takes a new PPS, as <see cref="InstallSps"/> does.</summary>
private void InstallPps(Pps p)
{
if (cur is not null && p.Id == pps.Id)
{
if (pendingPps.Count > 0 || !p.SameContent(ppss[p.Id]))
{
pendingPps.RemoveAll(x => x.Id == p.Id);
pendingPps.Add(p);
}
return;
}
if (!p.SameContent(ppss[p.Id]))
{
ppss[p.Id] = p;
}
}
/// <summary>Installs the parameter sets that waited for the end of the picture.</summary>
private void InstallPending()
{
foreach (var s in pendingSps)
{
spss[s.Id] = s;
}
foreach (var p in pendingPps)
{
ppss[p.Id] = p;
}
pendingSps.Clear();
pendingPps.Clear();
}
private Picture? FindShortTerm(int poc, Span<bool> keep)
{
for (var k = 0; k < dpb.Count; k++)
@@ -619,6 +732,7 @@ public sealed partial class H265Decoder
var picture = cur;
cur = null;
InstallPending();
picture.IntraOnly = true;
foreach (var header in slices)
{
+54 -4
View File
@@ -298,6 +298,9 @@ internal sealed class Sps
/// <summary>Largest width or height of any level: Sqrt(MaxLumaPs × 8).</summary>
internal const int MaxDimension = 16_888;
/// <summary>The RBSP after the NAL unit header, without trailing zero bytes: what "the same content" compares.</summary>
internal byte[] Raw = [];
internal int Id;
internal int MaxSubLayersMinus1;
internal int ProfileIdc;
@@ -372,12 +375,36 @@ internal sealed class Sps
internal int HighestTid => MaxSubLayersMinus1;
/// <summary>sps_scc_extension_flag: the screen content coding tools (palette, adaptive colour transform, ...).</summary>
internal bool SccExtension;
/// <summary>
/// The range extension tools the decoder does not handle: extended_precision_processing_flag and
/// cabac_bypass_alignment_enabled_flag, which only the 16-bit and High Throughput 4:4:4 profiles use.
/// </summary>
internal bool UsesUnsupportedTools => ExtendedPrecisionProcessing || CabacBypassAlignmentEnabled;
/// <summary>
/// The screen content coding extensions (§7.3.2.2.3; profiles 9, Screen-Extended, and 11, High Throughput
/// Screen-Extended, of A.3.7), whose coding units have a syntax the decoder does not read: palette mode, adaptive
/// colour transform, the current picture as a reference. The High Throughput 4:4:4 profiles (5) are not refused on
/// their own: their tools beyond RExt are those of <see cref="UsesUnsupportedTools"/>.
/// </summary>
internal bool UsesScreenContentCoding => SccExtension || ProfileIdc is 9 or 11;
/// <summary>
/// MaxDpbSize of A.4.2 for a picture of <paramref name="pictureSize"/> luma samples at level 6.2, the largest of any
/// level: 6 pictures of MaxLumaPs, up to 16 of a quarter of it (maxDpbPicBuf is 6).
/// </summary>
internal static int MaxDpbSize(long pictureSize) =>
pictureSize <= MaxLumaPs >> 2 ? 16 : pictureSize <= MaxLumaPs >> 1 ? 12 : pictureSize <= (3L * MaxLumaPs) >> 2 ? 8 : 6;
/// <summary>Whether <paramref name="other"/> is this SPS or one with the same content.</summary>
internal bool SameContent(Sps? other) => other is not null && (ReferenceEquals(this, other) || Raw.AsSpan().SequenceEqual(other.Raw));
/// <summary>The bytes <see cref="Raw"/> holds, read before parsing starts (the reader is past the NAL unit header).</summary>
internal static byte[] RawOf(BitReader r) => r.Data.AsSpan(r.Position >> 3, r.Length - (r.Position >> 3)).TrimEnd((byte)0).ToArray();
/// <summary>log2 of SubWidthC and SubHeightC (table 6-1).</summary>
internal int ChromaShiftX => SubWidthC - 1;
@@ -385,7 +412,7 @@ internal sealed class Sps
internal static Sps Parse(BitReader r)
{
var s = new Sps();
var s = new Sps { Raw = RawOf(r) };
r.Skip(4); // sps_video_parameter_set_id
s.MaxSubLayersMinus1 = r.ReadInt(3);
if (s.MaxSubLayersMinus1 > 6)
@@ -425,9 +452,17 @@ internal sealed class Sps
s.BitDepthC = r.ReadUe(8) + 8;
s.Log2MaxPocLsb = r.ReadUe(12) + 4;
var orderingInfo = r.ReadFlag();
var maxDpbSize = MaxDpbSize((long)s.Width * s.Height);
for (var i = orderingInfo ? 0 : s.MaxSubLayersMinus1; i <= s.MaxSubLayersMinus1; i++)
{
// The pictures the DPB holds must fit in the largest buffer of any level (A.4.2): with 16 pictures of the
// largest size a damaged SPS would make the decoder keep gigabytes.
s.MaxDecPicBufferingMinus1[i] = r.ReadUe(15);
if (s.MaxDecPicBufferingMinus1[i] + 1 > maxDpbSize)
{
throw new H265Exception("Buffer delle immagini più grande di ogni livello HEVC.");
}
s.MaxNumReorderPics[i] = r.ReadUe(s.MaxDecPicBufferingMinus1[i]);
s.MaxLatencyIncreasePlus1[i] = (int)Math.Min(r.ReadUe(), int.MaxValue);
}
@@ -503,7 +538,9 @@ internal sealed class Sps
if (r.ReadFlag())
{
var range = r.ReadFlag();
r.Skip(7); // sps_multilayer_extension_flag, sps_3d_extension_flag, sps_scc_extension_flag, sps_extension_4bits
r.Skip(2); // sps_multilayer_extension_flag, sps_3d_extension_flag
s.SccExtension = r.ReadFlag();
r.Skip(4); // sps_extension_4bits
if (range)
{
s.TransformSkipRotationEnabled = r.ReadFlag();
@@ -517,7 +554,8 @@ internal sealed class Sps
s.CabacBypassAlignmentEnabled = r.ReadFlag();
}
// Other extensions (multilayer, 3D, screen content) are not decoded: their data is ignored.
// The multilayer and 3D extensions only matter to layers above 0, which are ignored; their data and that
// of screen content coding (refused when the picture starts) are not read.
}
return s;
@@ -745,6 +783,15 @@ internal sealed class Pps
internal int Log2SaoOffsetScaleLuma;
internal int Log2SaoOffsetScaleChroma;
/// <summary>pps_scc_extension_flag: screen content coding, refused as for the SPS.</summary>
internal bool SccExtension;
/// <summary>The RBSP after the NAL unit header, without trailing zero bytes.</summary>
internal byte[] Raw = [];
/// <summary>Whether <paramref name="other"/> is this PPS or one with the same content.</summary>
internal bool SameContent(Pps? other) => other is not null && (ReferenceEquals(this, other) || Raw.AsSpan().SequenceEqual(other.Raw));
/// <summary>The tile layout of the SPS the arrays below were computed for.</summary>
private Sps? layoutSps;
@@ -763,6 +810,7 @@ internal sealed class Pps
{
var p = new Pps
{
Raw = Sps.RawOf(r),
Id = r.ReadUe(63),
SpsId = r.ReadUe(15),
DependentSliceSegmentsEnabled = r.ReadFlag(),
@@ -836,7 +884,9 @@ internal sealed class Pps
if (r.ReadFlag())
{
var range = r.ReadFlag();
r.Skip(7); // pps_multilayer_extension_flag, pps_3d_extension_flag, pps_scc_extension_flag, pps_extension_4bits
r.Skip(2); // pps_multilayer_extension_flag, pps_3d_extension_flag
p.SccExtension = r.ReadFlag();
r.Skip(4); // pps_extension_4bits
if (range)
{
if (p.TransformSkipEnabled)
+4 -1
View File
@@ -441,6 +441,9 @@ internal sealed class SliceHeader
var offsetShift = sps.HighPrecisionOffsetsEnabled ? 0 : sps.BitDepthY - 8;
var offsetShiftC = sps.HighPrecisionOffsetsEnabled ? 0 : sps.BitDepthC - 8;
// WpOffsetHalfRangeY and WpOffsetHalfRangeC (7-45, 7-46): with high_precision_offsets_enabled_flag the offsets
// are in units of the bit depth and range over half of it.
var wpOffsetHalfY = 1 << (sps.HighPrecisionOffsetsEnabled ? sps.BitDepthY - 1 : 7);
var wpOffsetHalfC = 1 << (sps.HighPrecisionOffsetsEnabled ? sps.BitDepthC - 1 : 7);
Span<bool> lumaFlags = stackalloc bool[16];
Span<bool> chromaFlags = stackalloc bool[16];
@@ -464,7 +467,7 @@ internal sealed class SliceHeader
if (lumaFlags[i])
{
LumaWeight[list][i] += r.ReadSe(-128, 127);
LumaOffset[list][i] = r.ReadSe(-128, 127) << offsetShift;
LumaOffset[list][i] = r.ReadSe(-wpOffsetHalfY, wpOffsetHalfY - 1) << offsetShift;
}
for (var j = 0; j < 2; j++)