Files
Febe/tests/Febe.Tests/Media/Heif/HeifDecoderTests.cs
T
Alby96andClaude Opus 5.5 2068dd28f3 Correzioni della revisione della catena 0.3.0, ognuna con la sua prova
- Collegamento: corretta la SyntaxError di connection.js (una «let saved» dichiarata due
  volte nello stesso blocco fermava tutta la pagina). Nuova prova ScriptSyntaxTests con un
  controllo scritto in casa che legge ogni modulo di wwwroot: parentesi, dichiarazioni
  doppie nello stesso blocco, importazioni che il modulo di arrivo non esporta.
- HEIF: il riconoscimento dei formati prende ogni marchio che HeifDecoder accetta (mif2,
  MiHE, marchi solo compatibili), così rilevazione, decodifica, misure, miniatura e
  impronta concordano.
- Docker, lasciare la pagina del browser: un nuovo contratto del browser cancella l'uscita
  annotata (_leftAt) anche prima che la vista si riapra, e la copia della sessione aspetta
  un altro comando del collegamento al più LetGoWait invece che senza limite.
- JPEG e PNG: senza EOI o IEND la decodifica fallisce («File danneggiato o incompleto»),
  la sola lettura delle misure resta tollerante.
- Visualizzatore: IsDamaged legge prima l'intestazione e il file intero solo quando può
  servire, in modo asincrono e con una piccola memoria per file, così una scheda con
  molti file non blocca il server.
- Importazione (§9.3): le immagini danneggiate si importano come le altre ma si segnano
  nella revisione, nel resoconto e nel CSV.
- Pulizia: le prove con il limite di 5 minuti non corrono più in parallelo fra loro.
- Pila dei caratteri come l'appendice B, senza Liberation; testo di Informazioni sulle
  immagini fatte in casa; guida (Problemi comuni, Sicurezza) allineata all'uscita in
  Docker dalla pagina del browser.
- docs/decisioni.md: le righe del 25 novembre 2026 con i motivi, compresa l'unione 537517b
  tenuta così com'è.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:21:36 +01:00

587 lines
27 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Febe.Core.Codecs.H265;
using Febe.Core.Codecs.Images;
using Febe.Core.Codecs.Heif;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Codecs.Heif;
/// <summary>
/// HEIC/HEIF still images (ISO/IEC 23008-12) built from pictures of the ITU-T H.265.1 set: the pixels expected are those
/// of the picture decoded straight from its stream, converted to RGB as video frames are.
/// </summary>
[TestClass]
public sealed class HeifDecoderTests
{
/// <summary>416×240 streams, 8 bit, whose first picture is intra: tiles of a grid.</summary>
private static readonly string[] Tiles = ["INITQP_A_Sony_1", "AMVP_A_MTK_4", "RPS_A_docomo_5", "MERGE_A_TI_3"];
[TestMethod]
[DataRow("INITQP_A_Sony_1", false)]
[DataRow("INITQP_B_Main10_Sony_1", false)]
[DataRow("IPRED_C_Mitsubishi_3", true)]
[DataRow("GENERAL_8b_444_RExt_Sony_2", false)]
[DataRow("GENERAL_8b_400_RExt_Sony_1", true)]
public void ACodedImageIsItsPicture(string name, bool inIdat)
{
var picture = CodedPicture.First(name);
var builder = new HeifBuilder { InIdat = inIdat };
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height));
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe);
var file = builder.Build();
var image = HeifDecoder.Decode(file);
Assert.AreEqual((picture.Frame.Width, picture.Frame.Height), (image.Width, image.Height));
Assert.AreEqual(1, image.Orientation);
Assert.IsFalse(image.HasAlpha);
Assert.AreEqual(picture.Frame.BitDepthLuma, image.BitDepth);
CollectionAssert.AreEqual(Rgba(picture.Frame), image.Pixels);
using var stream = new MemoryStream(file);
Assert.AreEqual(new HeifInfo(image.Width, image.Height, 1, false, 1), HeifDecoder.ReadInfo(stream));
}
[TestMethod]
[DataRow(false)]
[DataRow(true)]
public void AGridIsItsTilesSideBySideCutToItsSize(bool wide)
{
// Four tiles of 416×240 in two rows of two, the output 20 and 12 pixels short of them: as phones cut their
// 512×512 tiles to the size of the photo.
var pictures = Tiles.Select(CodedPicture.First).ToArray();
var (tw, th) = (pictures[0].Frame.Width, pictures[0].Frame.Height);
var (width, height) = ((2 * tw) - 20, (2 * th) - 12);
var builder = new HeifBuilder { WideIndices = wide };
var ispe = builder.Property(HeifBuilder.Ispe(tw, th));
var gridIspe = builder.Property(HeifBuilder.Ispe(width, height));
builder.Item(1, "grid", HeifBuilder.GridData(2, 2, width, height, wide), gridIspe);
for (var i = 0; i < 4; i++)
{
var hvcC = builder.Property(HeifBuilder.HvcCProperty(pictures[i].HvcC));
builder.Item((uint)(10 + i), "hvc1", pictures[i].Data, -hvcC, ispe);
}
builder.Reference("dimg", 1, 10, 11, 12, 13);
var image = HeifDecoder.Decode(builder.Build());
Assert.AreEqual((width, height), (image.Width, image.Height));
var expected = new byte[width * height * 4];
for (var i = 0; i < 4; i++)
{
var tile = Rgba(pictures[i].Frame);
var (x0, y0) = (i % 2 * tw, i / 2 * th);
for (var y = 0; y < th && y0 + y < height; y++)
{
var w = Math.Min(tw, width - x0);
tile.AsSpan(y * tw * 4, w * 4).CopyTo(expected.AsSpan((((y0 + y) * width) + x0) * 4));
}
}
CollectionAssert.AreEqual(expected, image.Pixels);
using var stream = new MemoryStream(builder.Build());
Assert.AreEqual(4, HeifDecoder.ReadInfo(stream).Tiles);
}
[TestMethod]
[DataRow(new[] { "irot1" }, 8)]
[DataRow(new[] { "irot3" }, 6)]
[DataRow(new[] { "irot2" }, 3)]
[DataRow(new[] { "imir0" }, 2)]
[DataRow(new[] { "imir1" }, 4)]
[DataRow(new[] { "irot1", "imir0" }, 7)]
[DataRow(new[] { "irot3", "imir0" }, 5)]
[DataRow(new[] { "irot1", "imir1" }, 5)]
[DataRow(new[] { "irot2", "imir0" }, 4)]
[DataRow(new[] { "imir0", "imir1" }, 3)]
public void RotationsAndMirrorsBecomeOneOrientation(string[] transforms, int orientation)
{
var picture = CodedPicture.First(Tiles[0]);
var builder = new HeifBuilder();
var properties = new List<int>
{
-builder.Property(HeifBuilder.HvcCProperty(picture.HvcC)),
builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height)),
};
foreach (var t in transforms)
{
var value = t[^1] - '0';
properties.Add(-builder.Property(t.StartsWith("irot", StringComparison.Ordinal) ? HeifBuilder.Irot(value) : HeifBuilder.Imir(value)));
}
builder.Item(1, "hvc1", picture.Data, [.. properties]);
var file = builder.Build();
var image = HeifDecoder.Decode(file);
Assert.AreEqual(orientation, image.Orientation);
CollectionAssert.AreEqual(Rgba(picture.Frame), image.Pixels, "l'orientamento non tocca i pixel");
// Through the image decoding of the library: upright, so a quarter turn swaps the sides.
using var stream = new MemoryStream(file);
var size = ImageDecoding.ReadSize(stream);
var quarter = orientation >= 5;
Assert.AreEqual(quarter ? (image.Height, image.Width) : (image.Width, image.Height), size);
using var bitmap = ImageDecoding.DecodeUpright(new MemoryStream(file));
Assert.IsNotNull(bitmap);
Assert.AreEqual(size, (bitmap.Width, bitmap.Height));
}
[TestMethod]
public void TheLibraryTurnsTheImageUprightAndMakesItsThumbnail()
{
// irot 3: a quarter turn anticlockwise three times, i.e. 90° clockwise. The top-left pixel ends top right.
var picture = CodedPicture.First(Tiles[1]);
var builder = new HeifBuilder();
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height));
var irot = builder.Property(HeifBuilder.Irot(3));
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe, -irot);
var file = builder.Build();
var rgba = Rgba(picture.Frame);
using var bitmap = ImageDecoding.DecodeUpright(new MemoryStream(file));
Assert.IsNotNull(bitmap);
Assert.AreEqual((picture.Frame.Height, picture.Frame.Width), (bitmap.Width, bitmap.Height));
var corner = bitmap.GetPixel(bitmap.Width - 1, 0);
Assert.AreEqual((rgba[0], rgba[1], rgba[2]), (corner.R, corner.G, corner.B));
using var temp = new TempFolder("miniatura-heic");
var store = new ThumbnailStore(temp.Combine("miniature"));
var key = new string('a', 64);
Assert.IsTrue(store.Create(key, new MemoryStream(file)), "miniatura di un HEIC");
Assert.IsTrue(store.Exists(key));
Assert.IsNotNull(PerceptualHash.Compute(new MemoryStream(file)), "impronta visiva di un HEIC");
}
[TestMethod]
public void TheImageFacadeReadsAHeicAsAnyOtherPhoto()
{
// irot 1: a quarter turn anticlockwise. The facade gives the pixels as stored and the turn as the orientation.
var picture = CodedPicture.First(Tiles[0]);
var builder = new HeifBuilder();
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height));
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe, -builder.Property(HeifBuilder.Irot(1)));
var file = builder.Build();
var info = ImageDecoder.Identify(file);
Assert.AreEqual(ImageFormat.Heif, info.Format);
Assert.AreEqual((picture.Frame.Width, picture.Frame.Height, 8), (info.Width, info.Height, info.Metadata.Orientation));
using var image = ImageDecoder.Decode(file, out var decoded);
CollectionAssert.AreEqual(Rgba(picture.Frame), image.ToArray());
Assert.AreEqual(8, decoded.Metadata.Orientation);
Assert.ThrowsExactly<ImageLimitException>(() => ImageDecoder.Decode(file, ImageLimits.Default with { MaxPixels = 1000 }));
// Past the bytes ImageDecoding reads first, the size still comes from the boxes alone.
byte[] large = [.. file, 0, 4, 0x93, 0xE0, .. "free"u8, .. new byte[300_000 - 8]];
Assert.IsGreaterThan(ImageDecoding.HeaderBytes, large.Length);
using var stream = new MemoryStream(large);
Assert.AreEqual((picture.Frame.Height, picture.Frame.Width), ImageDecoding.ReadSize(stream));
}
[TestMethod]
[DataRow("mif2", null, DisplayName = "marca principale mif2")]
[DataRow("MiHE", null, DisplayName = "marca principale MiHE")]
[DataRow("isom", "heic", DisplayName = "heic solo fra le marche compatibili")]
public void TheImageFacadeTakesEveryBrandTheHeifDecoderTakes(string major, string? compatibleOnly)
{
// The facade picks the decoder from the first bytes: it must take every file HeifDecoder.Looks takes,
// or such a HEIC would lose its thumbnail, its fingerprint and its size.
var picture = CodedPicture.First(Tiles[0]);
var builder = new HeifBuilder { Brand = major };
if (compatibleOnly is not null)
{
builder.CompatibleBrands = ["isom", compatibleOnly];
}
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height));
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe);
var file = builder.Build();
Assert.IsTrue(HeifDecoder.Looks(file));
Assert.AreEqual(ImageFormat.Heif, ImageFormatSniffer.Detect(file));
using (var image = ImageDecoder.Decode(file, out _))
{
CollectionAssert.AreEqual(Rgba(picture.Frame), image.ToArray());
}
using (var stream = new MemoryStream(file))
{
Assert.AreEqual((picture.Frame.Width, picture.Frame.Height), ImageDecoding.ReadSize(stream));
}
using var temp = new TempFolder("marca-heic");
var store = new ThumbnailStore(temp.Combine("miniature"));
Assert.IsTrue(store.Create(new string('b', 64), new MemoryStream(file)), "miniatura");
Assert.IsNotNull(PerceptualHash.Compute(new MemoryStream(file)), "impronta visiva");
}
[TestMethod]
public void TheCleanApertureCutsThePicture()
{
var picture = CodedPicture.First(Tiles[2]);
var (w, h) = (picture.Frame.Width, picture.Frame.Height);
var builder = new HeifBuilder();
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = builder.Property(HeifBuilder.Ispe(w, h));
// 200×100 centred, then moved 10 right and 20 down: left = 10 + (w − 1)/2 − 99.5, top = 20 + (h − 1)/2 − 49.5.
var clap = builder.Property(HeifBuilder.Clap(200, 100, 10, 20));
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe, -clap);
var image = HeifDecoder.Decode(builder.Build());
Assert.AreEqual((200, 100), (image.Width, image.Height));
var left = (int)Math.Round(10 + ((w - 1) / 2.0) - 99.5);
var top = (int)Math.Round(20 + ((h - 1) / 2.0) - 49.5);
var full = Rgba(picture.Frame);
for (var y = 0; y < 100; y++)
{
CollectionAssert.AreEqual(full.AsSpan((((top + y) * w) + left) * 4, 800).ToArray(), image.Pixels.AsSpan(y * 800, 800).ToArray(), $"riga {y}");
}
}
[TestMethod]
public void TheAlphaPlaneFillsTheAlpha()
{
// The alpha plane is another picture of the same size: here the luma of the image itself.
var picture = CodedPicture.First(Tiles[0]);
var builder = new HeifBuilder();
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height));
var auxC = builder.Property(HeifBuilder.AuxC("urn:mpeg:hevc:2015:auxid:1"));
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe).Item(2, "hvc1", picture.Data, -hvcC, ispe, -auxC).Reference("auxl", 2, 1);
var file = builder.Build();
var image = HeifDecoder.Decode(file);
Assert.IsTrue(image.HasAlpha);
using (var stream = new MemoryStream(file))
{
Assert.IsTrue(HeifDecoder.ReadInfo(stream).HasAlpha);
}
var frame = picture.Frame;
var expected = Rgba(frame);
for (var i = 0; i < frame.Y.Length; i++)
{
var v = frame.FullRange ? frame.Y[i] : (((frame.Y[i] - 16) * (int)Math.Round(255.0 / 219.0 * 65536)) + 32768) >> 16;
expected[(i * 4) + 3] = (byte)Math.Clamp(v, 0, 255);
}
CollectionAssert.AreEqual(expected, image.Pixels);
using var bitmap = ImageDecoding.DecodeUpright(new MemoryStream(file));
Assert.IsNotNull(bitmap, "anche con la trasparenza");
}
[TestMethod]
public void ColourComesFromNclxWhenThereIsOne()
{
var picture = CodedPicture.First(Tiles[3]);
var builder = new HeifBuilder();
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height));
var colr = builder.Property(HeifBuilder.Nclx(9, true));
var icc = builder.Property(HeifBuilder.Icc([1, 2, 3, 4, 5]));
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe, colr, icc);
var image = HeifDecoder.Decode(builder.Build());
var asIf = picture.Frame with { MatrixCoefficients = 9, FullRange = true };
CollectionAssert.AreEqual(Rgba(asIf), image.Pixels);
CollectionAssert.AreNotEqual(Rgba(picture.Frame), image.Pixels, "BT.2020 a gamma piena non è il colore del VUI");
CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4, 5 }, image.IccProfile);
}
[TestMethod]
public void TheExifItemGivesItsBlockOrientationAndDate()
{
var picture = CodedPicture.First(Tiles[0]);
// A TIFF block with only an Orientation tag (6), big endian.
byte[] oriented = [.. "MM\0*"u8, 0, 0, 0, 8, 0, 1, 0x01, 0x12, 0, 3, 0, 0, 0, 1, 0, 6, 0, 0, 0, 0, 0, 0];
var image = HeifDecoder.Decode(WithExif(picture, oriented));
CollectionAssert.AreEqual(oriented, image.Exif);
Assert.AreEqual(6, image.ExifOrientation);
Assert.AreEqual(1, image.Orientation, "l'orientamento EXIF è solo informativo");
// The shooting date of an HEIC, as the import reads it from the first bytes of the file.
var dated = WithExif(picture, ImportTestFiles.Tiff("2023:07:08 09:10:11", offsetOriginal: "+02:00"));
var date = ExifDateReader.Read(dated, TimeZoneInfo.Utc);
Assert.AreEqual(new DateTimeOffset(2023, 7, 8, 9, 10, 11, TimeSpan.FromHours(2)), date);
Assert.IsNull(ExifDateReader.Read(dated.AsSpan(0, 200), TimeZoneInfo.Utc), "il blocco oltre i byte letti non si trova");
}
[TestMethod]
public void WhatIsNotAnHevcImageIsRefused()
{
var picture = CodedPicture.First(Tiles[0]);
// AVIF: an av01 primary item.
var avif = new HeifBuilder { Brand = "avif" };
avif.Item(1, "av01", [1, 2, 3]);
Assert.ThrowsExactly<HeifException>(() => HeifDecoder.Decode(avif.Build()));
// An essential property Febe does not know.
var unknown = new HeifBuilder();
var hvcC = unknown.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var odd = unknown.Property([0, 0, 0, 9, .. "zzzz"u8, 1]);
unknown.Item(1, "hvc1", picture.Data, -hvcC, -odd);
Assert.ThrowsExactly<HeifException>(() => HeifDecoder.Decode(unknown.Build()));
// A grid that names fewer tiles than its rows and columns.
var grid = new HeifBuilder();
var p = grid.Property(HeifBuilder.HvcCProperty(picture.HvcC));
grid.Item(1, "grid", HeifBuilder.GridData(1, 2, 100, 100)).Item(2, "hvc1", picture.Data, -p).Reference("dimg", 1, 2);
Assert.ThrowsExactly<HeifException>(() => HeifDecoder.Decode(grid.Build()));
// Not HEIF at all, and a picture whose HEVC data is cut.
Assert.IsFalse(HeifDecoder.Looks("not a heif file at all"u8));
Assert.ThrowsExactly<HeifException>(() => HeifDecoder.Decode([0, 0, 0, 16, .. "ftypheic"u8, 0, 0, 0, 0]));
var cut = new HeifBuilder();
var c = cut.Property(HeifBuilder.HvcCProperty(picture.HvcC));
cut.Item(1, "hvc1", picture.Data[..(picture.Data.Length / 3)], -c, cut.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height)));
Assert.ThrowsExactly<HeifException>(() => HeifDecoder.Decode(cut.Build()));
using var bitmap = ImageDecoding.DecodeUpright(new MemoryStream(cut.Build()));
Assert.IsNull(bitmap, "un HEIC rovinato non ha miniatura, senza eccezioni");
}
[TestMethod]
[DataRow(6101)]
[DataRow(6102)]
public void DamagedFilesOnlyRaiseHeifException(int seed)
{
var pictures = Tiles.Take(2).Select(CodedPicture.First).ToArray();
var builder = new HeifBuilder();
var ispe = builder.Property(HeifBuilder.Ispe(pictures[0].Frame.Width, pictures[0].Frame.Height));
var rot = builder.Property(HeifBuilder.Irot(1));
builder.Item(1, "grid", HeifBuilder.GridData(1, 2, 800, 240), -rot);
for (var i = 0; i < 2; i++)
{
builder.Item((uint)(10 + i), "hvc1", pictures[i].Data, -builder.Property(HeifBuilder.HvcCProperty(pictures[i].HvcC)), ispe);
}
builder.Reference("dimg", 1, 10, 11);
builder.Item(20, "Exif", HeifBuilder.ExifData(ImportTestFiles.Tiff("2020:01:02 03:04:05"))).Reference("cdsc", 20, 1);
var file = builder.Build();
var whole = HeifDecoder.Decode(file);
Assert.AreEqual((800, 240, 8), (whole.Width, whole.Height, whole.Orientation));
var random = new Random(seed);
var decoded = 0;
for (var trial = 0; trial < 150; trial++)
{
var copy = (byte[])file.Clone();
var changes = random.Next(1, 6);
for (var k = 0; k < changes; k++)
{
// Mostly in the boxes before the data, where a change hits the structure.
var at = random.Next(4) == 0 ? random.Next(copy.Length) : random.Next(Math.Min(copy.Length, 700));
copy[at] = (byte)random.Next(256);
}
if (random.Next(5) == 0)
{
copy = copy[..random.Next(copy.Length)];
}
try
{
_ = HeifDecoder.Decode(copy);
decoded++;
}
catch (HeifException)
{
}
using var stream = new MemoryStream(copy);
try
{
_ = HeifDecoder.ReadInfo(stream);
}
catch (HeifException)
{
}
_ = HeifDecoder.FindExif(copy); // null or a block, never an exception
_ = ExifDateReader.Read(copy, TimeZoneInfo.Utc);
}
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();
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height));
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe).Item(2, "Exif", HeifBuilder.ExifData(tiff)).Reference("cdsc", 2, 1);
return builder.Build();
}
/// <summary>The frame in RGBA, as the video frames are converted (the same coefficients, opaque).</summary>
private static byte[] Rgba(H265Frame frame)
{
var rgb = VideoFrameDecoder.ToImage(frame, 0, 0).Rgb;
var rgba = new byte[rgb.Length / 3 * 4];
for (int i = 0, o = 0; i < rgb.Length; i += 3, o += 4)
{
rgba[o] = rgb[i];
rgba[o + 1] = rgb[i + 1];
rgba[o + 2] = rgb[i + 2];
rgba[o + 3] = 255;
}
return rgba;
}
}