Files
Febe/tests/Febe.Tests/Media/Heif/HeifFiles.cs
Alby96andClaude Opus 5.5 7b10f4ad4c 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>
2026-11-18 18:23:05 +01:00

257 lines
10 KiB
C#

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 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)
{
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.Where(i => i.SharesWith is null).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;
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)start));
iloc.AddRange(U32((uint)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.Where(i => i.SharesWith is null).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)
{
public uint? SharesWith { get; init; }
}
}