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

+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)
{