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:
1 parent
ac85d1baed
commit
7b10f4ad4c
16 files changed
+1389
-131
No files matched your search
@@ -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();
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user