HEVC nella catena dei media e foto HEIC/HEIF decodificate in casa (#58)

Le miniature e i fotogrammi dei video HEVC (i video dei telefoni) e le foto
HEIC non avevano un decodificatore: ora passano dal decodificatore HEVC
scritto in casa, senza componenti esterni.

- Contenitori: hvcC dai sample entry hvc1/hev1 dei file ISO e dalla
  CodecPrivate di Matroska V_MPEGH/ISO/HEVC (VideoTrack.HevcConfiguration);
  HEVC in AVI come Annex B. Lo scrittore MP4 sa scrivere anche hvc1.
- H265Decoder: fotogrammi in ordine di decodifica (FrameDecoded con Wanted),
  unità di accesso Annex B, punto d'accesso di un campione (IDR/BLA esatti,
  CRA vicino).
- VideoFrameDecoder sceglie H.264 o HEVC dal codec della traccia; il
  fotogramma da cui parte la corsa vale per un campione senza immagine
  (RASL di una CRA). Una sola conversione Y'CbCr->RGB (Codecs/YuvToRgb)
  per H.264, HEVC 8-12 bit 4:0:0/4:2:0/4:2:2/4:4:4 e HEIF.
- Febe.Core.Codecs.Heif (ISO/IEC 23008-12): meta, iinf, iloc (file e idat),
  iref, iprp/ipco/ipma; elemento hvc1 o griglia di tessere decodificate in
  parallelo, colr nclx/ICC, piano alfa, clap, irot/imir come orientamento
  EXIF, elemento Exif. Uscita HeifImage, con la stessa forma di RgbaImage
  del ramo funzione/codec-immagini (da unire).
- ImageDecoding manda gli HEIF al decodificatore di casa: miniature,
  impronte, dimensioni e anteprime valgono anche per gli HEIC;
  ExifDateReader legge la data dall'elemento Exif nei primi 512 KB.
- Prove su file costruiti dai flussi H.265.1 (MP4, frammentato, Matroska,
  AVI con e senza indice, Main 10, griglie, rotazioni, clap, alfa, nclx,
  Exif, file rovinati con semi fissi). Documenti: docker.md, LEGGIMI
  dell'importazione, una riga in decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 17:38:09 +01:00
1 parent 3cabd87316
commit ac85d1baed
21 files changed
+2695 -148

No files matched your search

@@ -0,0 +1,150 @@
using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.H265;
using Febe.Core.Library;
using Febe.Tests.Support;
namespace Febe.Tests.Codecs.Containers;
/// <summary>
/// HEVC videos through the containers and the frame decoder: the test videos are built from streams of the ITU-T H.265.1
/// set, so the frame expected is the one the decoder gives straight from the stream (itself bit exact on those streams).
/// </summary>
[TestClass]
public sealed class HevcVideoTests
{
private static readonly DateTimeOffset Now = new(2026, 11, 18, 12, 0, 0, TimeSpan.Zero);
/// <summary>416×240, 8 bit, 60 frames shown in another order than they are decoded.</summary>
private const string Moving = "INITQP_A_Sony_1";
[TestMethod]
[DataRow("mp4")]
[DataRow("mkv")]
[DataRow("avi")]
[DataRow("frammentato.mp4")]
[DataRow("senza-indice.avi")]
[DataRow("senza-indice-con-parametri.avi")]
public async Task TheFrameAtOneSecondIsTheOneTheStreamShowsThere(string kind)
{
var es = ElementaryStream.LoadHevc(Moving);
Assert.IsTrue(es.Rank.Where((r, i) => r != i).Any(), "il flusso deve riordinare i fotogrammi");
using var temp = new TempFolder("fotogramma-hevc");
var data = kind switch
{
"mkv" => TestVideos.Matroska(es),
"avi" => TestVideos.Avi(es),
"senza-indice.avi" => TestVideos.Avi(es, index: false),
"senza-indice-con-parametri.avi" => TestVideos.Avi(es.WithParameterSetsEverywhere(), index: false),
"frammentato.mp4" => TestVideos.FragmentedMp4(es),
_ => TestVideos.Mp4(es),
};
var path = TestVideos.Write(temp, "video." + kind, data);
var container = ContainerReader.ReadFile(path, Now);
Assert.AreEqual(VideoCodec.Hevc, container!.Video!.Codec);
Assert.AreEqual(kind.EndsWith("avi", StringComparison.Ordinal), container.Video.AnnexB);
if (!container.Video.AnnexB)
{
CollectionAssert.AreEqual(es.AvcC, container.Video.HevcConfiguration, "hvcC del contenitore");
}
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1));
Assert.IsNotNull(image);
// AVI has no presentation times: there frames are shown in decoding order.
var position = Math.Min(30, es.Count - 1);
var rank = kind.EndsWith("avi", StringComparison.Ordinal) ? es.Rank[position] : position;
var reference = VideoFrameDecoder.ToImage(Shown(Moving)[rank], 0, 0);
Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height));
CollectionAssert.AreEqual(reference.Rgb, image.Rgb);
}
[TestMethod]
[DataRow("INITQP_B_Main10_Sony_1")]
[DataRow("WPP_B_ericsson_MAIN10_2")]
public async Task Main10VideosGiveTheirFrame(string name)
{
var es = ElementaryStream.LoadHevc(name);
using var temp = new TempFolder("fotogramma-hevc-10");
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es, rotation: 270));
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.Zero);
Assert.IsNotNull(image);
var reference = VideoFrameDecoder.ToImage(Shown(name)[0], 270, 0);
Assert.AreEqual(10, Shown(name)[0].BitDepthLuma);
Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height));
Assert.AreEqual((es.Height, es.Width), (image.Width, image.Height), "ruotato di un quarto");
CollectionAssert.AreEqual(reference.Rgb, image.Rgb);
var bmp = await VideoFrameDecoder.Instance.ExtractImageAsync(path);
Assert.IsNotNull(bmp);
Assert.AreEqual((byte)'B', bmp[0]);
}
[TestMethod]
public async Task AnHevcVideoOfAStillPictureIsRecognisedAndOneThatMovesIsNot()
{
var es = ElementaryStream.LoadHevc(Moving);
using var temp = new TempFolder("fermo-hevc");
var still = TestVideos.Write(temp, "fermo.mp4", TestVideos.Mp4(es.FirstPictureRepeated(90)));
var result = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(still);
Assert.IsNotNull(result);
Assert.IsTrue(result.IsStill);
Assert.AreEqual(0, result.Difference);
var moving = TestVideos.Write(temp, "movimento.mkv", TestVideos.Matroska(ElementaryStream.LoadHevc("CAINIT_A_SHARP_4")));
var other = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(moving);
Assert.IsNotNull(other);
Assert.IsFalse(other.IsStill, $"differenza {other.Difference}");
}
[TestMethod]
public void AccessPointsAreTheIrapPictures()
{
var es = ElementaryStream.LoadHevc(Moving);
Assert.AreEqual(H265AccessPoint.Idr, H265Decoder.AccessPoint(es.LengthPrefixed(0), 4));
Assert.AreEqual(H265AccessPoint.Idr, H265Decoder.AccessPoint(es.WithStartCodes(0), 0));
var inter = Enumerable.Range(0, es.Count).First(i => !es.Key[i]);
Assert.AreEqual(H265AccessPoint.None, H265Decoder.AccessPoint(es.LengthPrefixed(inter), 4));
// A CRA picture (NAL unit type 21): decoding starts there, its RASL pictures are lost.
byte[] cra = [0, 0, 0, 3, 21 << 1, 1, 0x80];
Assert.AreEqual(H265AccessPoint.Cra, H265Decoder.AccessPoint(cra, 4));
Assert.AreEqual(H265AccessPoint.None, H265Decoder.AccessPoint([0, 0, 0, 2, 34 << 1, 1], 4), "solo parametri");
}
[TestMethod]
public void TenBitFramesAndOtherChromaFormatsBecomeTheRightColours()
{
static H265Frame Flat(ushort y, ushort c, int format, int bits, int matrix, bool full)
{
var chroma = format == 0 ? 0 : format == 3 ? 4 : format == 2 ? 2 : 1;
return new(2, 2, format, bits, bits, [y, y, y, y], [.. Enumerable.Repeat(c, chroma)], [.. Enumerable.Repeat(c, chroma)], 0, 0, matrix, full);
}
// Limited range at 10 bits: 64 is black, 940 white.
CollectionAssert.AreEqual(new byte[] { 0, 0, 0 }, VideoFrameDecoder.ToImage(Flat(64, 512, 1, 10, 1, false), 0, 0).Rgb[..3]);
CollectionAssert.AreEqual(new byte[] { 255, 255, 255 }, VideoFrameDecoder.ToImage(Flat(940, 512, 1, 10, 1, false), 0, 0).Rgb[..3]);
// The same grey at 8, 10 and 12 bits, in every chroma format (4:0:0 has no chroma at all).
var grey = VideoFrameDecoder.ToImage(Flat(128, 128, 1, 8, 6, true), 0, 0).Rgb;
foreach (var format in new[] { 0, 1, 2, 3 })
{
CollectionAssert.AreEqual(grey, VideoFrameDecoder.ToImage(Flat(512, 512, format, 10, 6, true), 0, 0).Rgb, $"formato {format}");
CollectionAssert.AreEqual(grey, VideoFrameDecoder.ToImage(Flat(2048, 2048, format, 12, 6, true), 0, 0).Rgb, $"formato {format}, 12 bit");
}
// Pure red of BT.601 at 10 bits (limited range): Y 324, Cb 360, Cr 960.
var red = VideoFrameDecoder.ToImage(new H265Frame(2, 2, 1, 10, 10, [324, 324, 324, 324], [360], [960], 0, 0, 6, false), 0, 0).Rgb;
Assert.IsTrue(red[0] >= 250 && red[1] <= 3 && red[2] <= 3, $"{red[0]} {red[1]} {red[2]}");
}
/// <summary>The frames of a conformance stream in output order, decoded straight from its Annex B form.</summary>
private static List<H265Frame> Shown(string name)
{
var frames = new List<H265Frame>();
var decoder = new H265Decoder();
decoder.FrameOutput += frames.Add;
decoder.DecodeAnnexB(File.ReadAllBytes(Codecs.H265.H265ConformanceStream.Load(name).BitstreamPath));
return frames;
}
}
@@ -21,6 +21,8 @@ public sealed class MalformedInputTests
[DataRow("frammentato.mp4")]
[DataRow("mkv")]
[DataRow("avi")]
[DataRow("hevc.mp4")]
[DataRow("hevc.mkv")]
public void TruncatedFilesNeverBreakTheReaders(string kind)
{
var file = Build(kind);
@@ -51,6 +53,9 @@ public sealed class MalformedInputTests
[DataRow("frammentato.mp4", 5812)]
[DataRow("mkv", 5813)]
[DataRow("avi", 5814)]
[DataRow("hevc.mp4", 5815)]
[DataRow("hevc.mkv", 5816)]
[DataRow("hevc.avi", 5817)]
public async Task GarbledFilesNeverBreakTheProbeOrTheFrameDecoder(string kind, int seed)
{
var file = Build(kind);
@@ -246,7 +251,10 @@ public sealed class MalformedInputTests
private static byte[] Build(string kind)
{
var es = ElementaryStream.Load("CABA3_SVA_B");
// «hevc.»: the same containers around an HEVC stream.
var hevc = kind.StartsWith("hevc.", StringComparison.Ordinal);
var es = hevc ? ElementaryStream.LoadHevc("INITQP_A_Sony_1") : ElementaryStream.Load("CABA3_SVA_B");
kind = hevc ? kind[5..] : kind;
return kind switch
{
"frammentato.mp4" => TestVideos.FragmentedMp4(es, perFragment: 6, defaults: true),
+69 -12
View File
@@ -13,7 +13,7 @@ namespace Febe.Tests.Codecs.Containers;
/// </summary>
internal sealed class ElementaryStream
{
private ElementaryStream(string name, List<List<byte[]>> units, int[] rank, bool[] key, byte[] avcC, int width, int height)
private ElementaryStream(string name, List<List<byte[]>> units, int[] rank, bool[] key, byte[] avcC, int width, int height, bool hevc = false)
{
Name = name;
Units = units;
@@ -22,10 +22,14 @@ internal sealed class ElementaryStream
AvcC = avcC;
Width = width;
Height = height;
Hevc = hevc;
}
public string Name { get; }
/// <summary>An HEVC stream (of the H.265.1 set): then <see cref="AvcC"/> holds its <c>hvcC</c> record.</summary>
public bool Hevc { get; }
/// <summary>The NAL units (without start codes) of each access unit, in decoding order.</summary>
public List<List<byte[]>> Units { get; }
@@ -119,22 +123,74 @@ internal sealed class ElementaryStream
return new ElementaryStream(name, units, rank, key, [.. avcC], frames[0].Width, frames[0].Height);
}
/// <summary>
/// An HEVC stream of the H.265.1 set cut into access units (§7.4.2.4.4: parameter sets, delimiters and prefix SEI
/// open the next one), with an <c>hvcC</c> record of its VPS, SPS and PPS. Every access unit must give one output
/// frame: streams with skipped RASL pictures or pic_output_flag 0 do not fit.
/// </summary>
public static ElementaryStream LoadHevc(string name)
{
var annexB = File.ReadAllBytes(H265.H265ConformanceStream.Load(name).BitstreamPath);
var units = new List<List<byte[]>>();
List<byte[]>? current = null;
var hasSlice = false;
foreach (var nal in SplitAnnexB(annexB))
{
var type = (nal[0] >> 1) & 63;
var startsPicture = type < 32 && nal.Length > 2 && (nal[2] & 0x80) != 0; // first_slice_segment_in_pic_flag
var beforePicture = type is (>= 32 and <= 35) or 39 or (>= 41 and <= 44) or (>= 48 and <= 55);
if (current is null || (hasSlice && (startsPicture || beforePicture)))
{
current = [];
units.Add(current);
hasSlice = false;
}
current.Add(nal);
hasSlice |= type < 32;
}
var key = units.Select(u => u.Any(n => ((n[0] >> 1) & 63) is >= 16 and <= 23)).ToArray();
var decoder = new Febe.Core.Codecs.H265.H265Decoder();
var frames = new List<Febe.Core.Codecs.H265.H265Frame>();
decoder.FrameOutput += frames.Add;
decoder.DecodeAnnexB(annexB);
Assert.AreEqual(units.Count, frames.Count, $"{name}: unità di accesso e fotogrammi");
var rank = new int[frames.Count];
for (var i = 0; i < frames.Count; i++)
{
rank[frames[i].DecodeIndex] = i; // FrameOutput comes in output order
}
var sets = units.SelectMany(u => u).Where(n => ((n[0] >> 1) & 63) is >= 32 and <= 34).DistinctBy(Convert.ToBase64String).ToList();
var hvcC = new List<byte>(new byte[21]) { 0xFC | 3, (byte)sets.Count };
hvcC[0] = 1;
foreach (var set in sets)
{
hvcC.AddRange([(byte)(0x80 | ((set[0] >> 1) & 63)), 0, 1, (byte)(set.Length >> 8), (byte)set.Length, .. set]);
}
return new ElementaryStream(name, units, rank, key, [.. hvcC], frames[0].Width, frames[0].Height, hevc: true);
}
private static bool IsParameterSet(byte[] nal, bool hevc) => hevc ? ((nal[0] >> 1) & 63) is >= 32 and <= 34 : (nal[0] & 0x1F) is 7 or 8;
/// <summary>The same stream with only its first access unit, repeated: a video of a still picture.</summary>
public ElementaryStream FirstPictureRepeated(int times)
{
var units = Enumerable.Repeat(Units[0], times).ToList();
return new ElementaryStream(Name + "-fermo", units, [.. Enumerable.Range(0, times)], [.. Enumerable.Repeat(true, times)], AvcC, Width, Height);
return new ElementaryStream(Name + "-fermo", units, [.. Enumerable.Range(0, times)], [.. Enumerable.Repeat(true, times)], AvcC, Width, Height, Hevc);
}
/// <summary>
/// The same stream with its SPS and PPS repeated in every access unit, as some cameras and recorders write them: a
/// The same stream with its parameter sets repeated in every access unit, as some cameras and recorders write them: a
/// decoder started at any of its P or B frames finds its parameter sets.
/// </summary>
public ElementaryStream WithParameterSetsEverywhere()
{
var sets = Units[0].Where(n => (n[0] & 0x1F) is 7 or 8).ToList();
var units = Units.Select(u => u.Any(n => (n[0] & 0x1F) == 7) ? u : [.. sets, .. u]).ToList();
return new ElementaryStream(Name + "-parametri", units, Rank, Key, AvcC, Width, Height);
var sets = Units[0].Where(n => IsParameterSet(n, Hevc)).ToList();
var units = Units.Select(u => u.Any(n => IsParameterSet(n, Hevc)) ? u : [.. sets, .. u]).ToList();
return new ElementaryStream(Name + "-parametri", units, Rank, Key, AvcC, Width, Height, Hevc);
}
/// <summary>An access unit with 4-byte length prefixes (MP4, Matroska).</summary>
@@ -227,7 +283,8 @@ internal static class TestVideos
Width = es.Width,
Height = es.Height,
Rotation = rotation,
AvcConfiguration = es.AvcC,
AvcConfiguration = es.Hevc ? null : es.AvcC,
HevcConfiguration = es.Hevc ? es.AvcC : null,
},
};
if (audio)
@@ -365,7 +422,7 @@ internal static class TestVideos
var video = Element(0xE0, Element(0xB0, U16((ushort)es.Width)), Element(0xBA, U16((ushort)es.Height)));
var track = Element(0xAE, Element(0xD7, [1]), Element(0x73C5, [7]), Element(0x83, [1]),
Element(0x86, "V_MPEG4/ISO/AVC"u8.ToArray()), Element(0x63A2, es.AvcC), video);
Element(0x86, es.Hevc ? "V_MPEGH/ISO/HEVC"u8.ToArray() : "V_MPEG4/ISO/AVC"u8.ToArray()), Element(0x63A2, es.AvcC), video);
var blocks = new List<byte[]> { Element(0xE7, [0]) };
for (var i = 0; i < es.Count; i++)
{
@@ -392,7 +449,7 @@ internal static class TestVideos
}
var strh = new List<byte>();
strh.AddRange("vidsH264"u8.ToArray());
strh.AddRange(es.Hevc ? "vidsHEVC"u8.ToArray() : "vidsH264"u8.ToArray());
foreach (var v in new uint[] { 0, 0, 0, scale, rate, 0, length ?? (uint)es.Count, 0, 0xFFFFFFFF, 0 })
{
strh.AddRange(Le32(v));
@@ -406,7 +463,7 @@ internal static class TestVideos
}
strf.AddRange([1, 0, 24, 0]);
strf.AddRange("H264"u8.ToArray());
strf.AddRange(es.Hevc ? "HEVC"u8.ToArray() : "H264"u8.ToArray());
strf.AddRange(new byte[20]);
var hdrl = new List<byte[]> { Chunk("avih", [.. avih]), List("strl", Chunk("strh", [.. strh]), Chunk("strf", [.. strf])) };
if (idit is not null)
@@ -445,9 +502,9 @@ internal static class TestVideos
return path;
}
private static byte[] Avc1(ElementaryStream es) => Box("avc1",
private static byte[] Avc1(ElementaryStream es) => Box(es.Hevc ? "hvc1" : "avc1",
[.. new byte[6], 0, 1, .. new byte[16], .. U16((ushort)es.Width), .. U16((ushort)es.Height), .. U32(0x00480000), .. U32(0x00480000),
.. U32(0), 0, 1, .. new byte[32], 0, 0x18, 0xFF, 0xFF, .. Box("avcC", es.AvcC)]);
.. U32(0), 0, 1, .. new byte[32], 0, 0x18, 0xFF, 0xFF, .. Box(es.Hevc ? "hvcC" : "avcC", es.AvcC)]);
private static byte[] Box(string type, params byte[][] children)
{
@@ -0,0 +1,368 @@
using Febe.Core.Codecs.H265;
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.Red, corner.Green, corner.Blue));
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 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");
}
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;
}
}
+239
View File
@@ -0,0 +1,239 @@
using System.Text;
using Febe.Core.Codecs.H264;
using Febe.Core.Codecs.H265;
using Febe.Tests.Codecs.H265;
namespace Febe.Tests.Codecs.Heif;
/// <summary>
/// The first picture of a stream of the ITU-T H.265.1 set, as a HEIF image item holds it: its parameter sets in an
/// <c>hvcC</c> record, its NAL units with 4-byte lengths; and the picture itself, decoded straight from the Annex B
/// stream (not through <c>hvcC</c>), to compare with.
/// </summary>
internal sealed class CodedPicture
{
private CodedPicture(byte[] hvcC, byte[] data, H265Frame frame)
{
HvcC = hvcC;
Data = data;
Frame = frame;
}
public byte[] HvcC { get; }
public byte[] Data { get; }
public H265Frame Frame { get; }
public static CodedPicture First(string name)
{
var annexB = File.ReadAllBytes(H265ConformanceStream.Load(name).BitstreamPath);
var sets = new List<byte[]>();
var picture = new List<byte[]>();
var position = 0;
var end = annexB.Length;
while (NalUnits.NextAnnexB(annexB, ref position, out var range))
{
var nal = annexB[range];
var type = (nal[0] >> 1) & 63;
if (type < 32 && (nal[2] & 0x80) != 0 && picture.Count > 0)
{
end = range.Start.Value;
break; // the second picture starts
}
if (type is >= 32 and <= 34)
{
if (picture.Count > 0)
{
end = range.Start.Value;
break;
}
sets.Add(nal);
}
else if (type < 32)
{
picture.Add(nal);
}
}
var hvcC = new List<byte>(new byte[21]) { 0xFC | 3, (byte)sets.Count };
hvcC[0] = 1;
foreach (var set in sets)
{
hvcC.AddRange([(byte)(0x80 | ((set[0] >> 1) & 63)), 0, 1, (byte)(set.Length >> 8), (byte)set.Length, .. set]);
}
var data = new List<byte>();
foreach (var nal in picture)
{
data.AddRange([(byte)(nal.Length >> 24), (byte)(nal.Length >> 16), (byte)(nal.Length >> 8), (byte)nal.Length, .. nal]);
}
H265Frame? first = null;
var decoder = new H265Decoder();
decoder.FrameDecoded += f => first ??= f;
decoder.DecodeAnnexB(annexB.AsSpan(0, end)); // the first picture only
return new CodedPicture([.. hvcC], [.. data], first!);
}
}
/// <summary>
/// A builder of HEIF files (ISO/IEC 23008-12) for the tests: <c>ftyp</c>, a <c>meta</c> box with <c>hdlr</c>,
/// <c>pitm</c>, <c>iinf</c>, <c>iloc</c> (version 1, offsets in the file or in <c>idat</c>), <c>iref</c> and
/// <c>iprp</c>, then one <c>mdat</c> with the data of the items.
/// </summary>
internal sealed class HeifBuilder
{
private readonly List<Entry> items = [];
private readonly List<byte[]> properties = [];
private readonly List<(string Type, uint From, uint[] To)> references = [];
public uint Primary { get; set; } = 1;
/// <summary>Major brand of the ftyp box.</summary>
public string Brand { get; set; } = "heic";
/// <summary>The item data goes into idat instead of mdat.</summary>
public bool InIdat { get; set; }
/// <summary>The ipma entries use 16-bit property indices (flags bit 0).</summary>
public bool WideIndices { get; set; }
/// <summary>Adds an item; <paramref name="properties"/> are indices from <see cref="Property"/>, negative for essential.</summary>
public HeifBuilder Item(uint id, string type, byte[] data, params int[] properties)
{
items.Add(new Entry(id, type, data, properties));
return this;
}
/// <summary>Adds a property box and returns its 1-based index.</summary>
public int Property(byte[] box)
{
properties.Add(box);
return properties.Count;
}
public HeifBuilder Reference(string type, uint from, params uint[] to)
{
references.Add((type, from, to));
return this;
}
public static byte[] HvcCProperty(byte[] hvcC) => Box("hvcC", hvcC);
public static byte[] Ispe(int width, int height) => FullBox("ispe", 0, [.. U32((uint)width), .. U32((uint)height)]);
public static byte[] Irot(int quarterTurnsAnticlockwise) => Box("irot", [(byte)quarterTurnsAnticlockwise]);
public static byte[] Imir(int axis) => Box("imir", [(byte)axis]);
public static byte[] Clap(int width, int height, int horizontalOffset, int verticalOffset) =>
Box("clap", [.. U32((uint)width), .. U32(1), .. U32((uint)height), .. U32(1), .. U32((uint)horizontalOffset), .. U32(1),
.. U32((uint)verticalOffset), .. U32(1)]);
public static byte[] Nclx(int matrix, bool fullRange) =>
Box("colr", [.. "nclx"u8, 0, 1, 0, 13, (byte)(matrix >> 8), (byte)matrix, fullRange ? (byte)0x80 : (byte)0]);
public static byte[] Icc(byte[] profile) => Box("colr", [.. "prof"u8, .. profile]);
public static byte[] AuxC(string type) => FullBox("auxC", 0, [.. Encoding.ASCII.GetBytes(type), 0]);
/// <summary>The data of a grid item (version 0): rows, columns, output size in 16 or 32 bits.</summary>
public static byte[] GridData(int rows, int columns, int width, int height, bool wide = false) => wide
? [0, 1, (byte)(rows - 1), (byte)(columns - 1), .. U32((uint)width), .. U32((uint)height)]
: [0, 0, (byte)(rows - 1), (byte)(columns - 1), (byte)(width >> 8), (byte)width, (byte)(height >> 8), (byte)height];
/// <summary>The data of an Exif item: the offset of the TIFF header after «Exif\0\0», then both.</summary>
public static byte[] ExifData(byte[] tiff) => [0, 0, 0, 6, .. "Exif\0\0"u8, .. tiff];
public byte[] Build()
{
var ftyp = Box("ftyp", [.. Encoding.ASCII.GetBytes(Brand), 0, 0, 0, 0, .. "mif1"u8, .. Encoding.ASCII.GetBytes(Brand)]);
// The meta box is built twice: the first time only to learn its size, so that the offsets into mdat are known.
var meta = Meta(0);
var mdatStart = ftyp.Length + meta.Length + 8;
meta = Meta(mdatStart);
var payload = InIdat ? [] : items.SelectMany(i => i.Data).ToArray();
return [.. ftyp, .. meta, .. Box("mdat", payload)];
}
private byte[] Meta(int mdatStart)
{
var hdlr = FullBox("hdlr", 0, [0, 0, 0, 0, .. "pict"u8, .. new byte[12], 0]);
var pitm = FullBox("pitm", 0, U16((ushort)Primary));
var infe = items.Select(i => FullBox("infe", 2u << 24, [.. U16((ushort)i.Id), 0, 0, .. Encoding.ASCII.GetBytes(i.Type), 0])).ToList();
var iinf = FullBox("iinf", 0, [.. U16((ushort)items.Count), .. infe.SelectMany(b => b)]);
// iloc version 1: offset_size 4, length_size 4, base_offset_size 0, index_size 0.
var iloc = new List<byte> { 0x44, 0x00 };
iloc.AddRange(U16((ushort)items.Count));
var offset = InIdat ? 0 : mdatStart;
foreach (var item in items)
{
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;
}
var ipma = new List<byte>();
var associated = items.Where(i => i.Properties.Length > 0).ToList();
ipma.AddRange(U32((uint)associated.Count));
foreach (var item in associated)
{
ipma.AddRange(U16((ushort)item.Id));
ipma.Add((byte)item.Properties.Length);
foreach (var p in item.Properties)
{
var index = Math.Abs(p);
if (WideIndices)
{
ipma.AddRange(U16((ushort)((p < 0 ? 0x8000 : 0) | index)));
}
else
{
ipma.Add((byte)((p < 0 ? 0x80 : 0) | index));
}
}
}
var iprp = Box("iprp", Box("ipco", [.. properties.SelectMany(b => b)]), FullBox("ipma", WideIndices ? 1u : 0u, [.. ipma]));
var children = new List<byte[]> { hdlr, pitm, FullBox("iloc", 1u << 24, [.. iloc]), iinf };
if (references.Count > 0)
{
var refs = references.Select(r => Box(r.Type, [.. U16((ushort)r.From), .. U16((ushort)r.To.Length), .. r.To.SelectMany(t => U16((ushort)t))]));
children.Add(FullBox("iref", 0, [.. refs.SelectMany(b => b)]));
}
children.Add(iprp);
if (InIdat)
{
children.Add(Box("idat", [.. items.SelectMany(i => i.Data)]));
}
return FullBox("meta", 0, [.. children.SelectMany(b => b)]);
}
private static byte[] Box(string type, params byte[][] children)
{
var body = children.SelectMany(c => c).ToArray();
return [.. U32((uint)(body.Length + 8)), .. Encoding.ASCII.GetBytes(type), .. body];
}
private static byte[] Box(string type, byte[] body) => [.. U32((uint)(body.Length + 8)), .. Encoding.ASCII.GetBytes(type), .. body];
/// <summary>A full box: <paramref name="versionAndFlags"/> holds the version in its top byte and the flags below.</summary>
private static byte[] FullBox(string type, uint versionAndFlags, byte[] body) => Box(type, [.. U32(versionAndFlags), .. body]);
private static byte[] U16(ushort v) => [(byte)(v >> 8), (byte)v];
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);
}