feat(metadata): add ISO-BMFF walker with HEIF and CR3 parsers

BmffReader reads box headers only (32/64-bit and to-end sizes, uuid
user types, per-container count and path depth caps). HeifParser
handles hdlr/pitm/iinf (infe v2/v3)/iloc (v0-v2, multi-extent, idat)/
iprp: size from the primary item's ispe, bit depth from pixi, Exif and
XMP items; irot/imir define the orientation and override Exif because
HEIF decoders apply them. Cr3Parser reads CMT1-4 and THMB from the
Canon uuid box, PRVW, the XMP uuid, track 1's full-size JPEG through
the sample tables and the raw size from the CRAW/CMP1 header.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 10:01:21 +00:00
1 parent d12c0b41c5
commit 28c4d5ca7f
3 files changed
+567

No files matched your search

+282
View File
@@ -0,0 +1,282 @@
using System.Buffers.Binary;
using Titano.Core.Metadata.Tiff;
using Titano.Core.Metadata.Xmp;
namespace Titano.Core.Metadata.Bmff;
/// <summary>
/// HEIF / HEIC / AVIF: <c>meta</c> → <c>hdlr</c>, <c>pitm</c>, <c>iinf</c>/<c>infe</c> (v2/v3), <c>iloc</c> (v0–v2),
/// <c>iprp</c>/<c>ipco</c>/<c>ipma</c>. Main size from the primary item's <c>ispe</c>, bit depth from <c>pixi</c>,
/// Exif from the <c>Exif</c> item and XMP from the <c>application/rdf+xml</c> mime item.
/// </summary>
/// <remarks>
/// Orientation rule: when the primary item carries <c>irot</c> and/or <c>imir</c>, their composition (in association
/// order) defines <see cref="FrameMetadata.Orientation"/> and the Exif orientation is ignored — HEIF decoders apply those
/// transforms themselves (ISO/IEC 23008-12), so honouring Exif as well would rotate twice. Without them, Exif applies.
/// <c>imir</c> axis 0 mirrors top↔bottom and axis 1 left↔right (23008-12 2nd edition, as libheif).
/// </remarks>
internal static class HeifParser
{
private const int MaxPropertyBytes = 64;
private const int MaxTableBytes = 1024 * 1024;
private const int MaxInfeBytes = 4096;
private const int MaxExtentsPerItem = 1024;
private static readonly uint Exif = FourCC.From("Exif");
private static readonly uint Mime = FourCC.From("mime");
// Exif orientations 1–8 as integer matrices (a, b, c, d) mapping stored (x, y) to displayed (ax + by, cx + dy), y down.
private static readonly (int A, int B, int C, int D)[] Orientations =
[
(1, 0, 0, 1), (-1, 0, 0, 1), (-1, 0, 0, -1), (1, 0, 0, -1),
(0, 1, 1, 0), (0, -1, 1, 0), (0, -1, -1, 0), (0, 1, -1, 0),
];
public static void Parse(MetadataBuilder m)
{
var warnings = new List<string>();
var meta = BmffReader.Find(BmffReader.ReadChildren(m.Stream, 0, m.Length, warnings), "meta");
m.AddWarnings(warnings);
if (meta is { } box) ParseMeta(m, box);
else m.Warn("HEIF meta box not found");
}
private static void ParseMeta(MetadataBuilder m, BmffBox meta)
{
var s = m.Stream;
var warnings = new List<string>();
var children = BmffReader.ReadChildren(s, meta.PayloadStart + 4, meta.End, warnings);
var items = new Dictionary<uint, Item>();
uint? primary = null;
BmffBox? iprp = null;
long idat = -1;
foreach (var child in children)
{
m.ThrowIfCancelled();
if (child.Is("hdlr")) CheckHandler(m, child);
else if (child.Is("pitm")) primary = ReadPrimary(s, child);
else if (child.Is("iinf")) ReadItemInfo(m, child, items, warnings);
else if (child.Is("iloc")) ReadLocations(m, child, items);
else if (child.Is("iprp")) iprp = child;
else if (child.Is("idat")) idat = child.PayloadStart;
}
m.AddWarnings(warnings);
if (primary is { } id && iprp is { } properties) ReadPrimaryProperties(m, properties, id);
else m.Warn("HEIF primary item or properties missing");
foreach (var item in items.Values)
{
if (item.ConstructionMethod == 1 && idat < 0) continue;
var origin = item.ConstructionMethod == 1 ? idat : 0;
if (item.Type == Exif) ReadExifItem(m, item, origin);
else if (item.Type == Mime && item.ContentType == "application/rdf+xml") ReadXmpItem(m, item, origin);
}
}
private static void CheckHandler(MetadataBuilder m, BmffBox hdlr)
{
Span<byte> b = stackalloc byte[12];
if (!m.Stream.TryReadAt(hdlr.PayloadStart, b) || !b[8..].SequenceEqual("pict"u8)) m.Warn("HEIF handler is not 'pict'");
}
private static uint? ReadPrimary(Stream s, BmffBox pitm)
{
Span<byte> b = stackalloc byte[8];
var n = s.ReadUpTo(pitm.PayloadStart, b[..(int)Math.Min(b.Length, pitm.PayloadLength)]);
if (n < 6) return null;
return b[0] == 0 ? BinaryPrimitives.ReadUInt16BigEndian(b[4..]) : n >= 8 ? BinaryPrimitives.ReadUInt32BigEndian(b[4..]) : null;
}
/// <summary>iinf → infe v2/v3: item id, type and (for mime items) content type. Earlier infe versions carry no type.</summary>
private static void ReadItemInfo(MetadataBuilder m, BmffBox iinf, Dictionary<uint, Item> items, List<string> warnings)
{
Span<byte> head = stackalloc byte[1];
if (!m.Stream.TryReadAt(iinf.PayloadStart, head)) return;
var first = iinf.PayloadStart + (head[0] == 0 ? 6 : 8);
foreach (var infe in BmffReader.ReadChildren(m.Stream, first, iinf.End, warnings))
{
m.ThrowIfCancelled();
if (!infe.Is("infe") || m.Stream.ReadAt(infe.PayloadStart, Math.Min(infe.PayloadLength, MaxInfeBytes), MaxInfeBytes) is not { } data) continue;
var r = new SpanReader(data);
var version = r.U8();
r.Skip(3);
if (version < 2) continue;
var id = version == 2 ? r.U16() : r.U32();
r.Skip(2);
var type = r.U32();
if (!r.Ok) continue;
r.CString();
var item = Get(items, id);
item.Type = type;
if (type == Mime && r.Remaining > 0) item.ContentType = r.CString();
}
}
/// <summary>iloc v0–v2: offset/length/base-offset/index field sizes, construction methods 0 (file) and 1 (idat),
/// any number of extents.</summary>
private static void ReadLocations(MetadataBuilder m, BmffBox iloc, Dictionary<uint, Item> items)
{
if (m.Stream.ReadAt(iloc.PayloadStart, iloc.PayloadLength, MaxTableBytes) is not { } data)
{
m.Warn("HEIF iloc unreadable");
return;
}
var r = new SpanReader(data);
var version = r.U8();
r.Skip(3);
var sizes = r.U8();
var sizes2 = r.U8();
int offsetSize = sizes >> 4, lengthSize = sizes & 0xF, baseOffsetSize = sizes2 >> 4;
var indexSize = version is 1 or 2 ? sizes2 & 0xF : 0;
if (version > 2)
{
m.Warn($"HEIF iloc version {version} unsupported");
return;
}
var count = version < 2 ? r.U16() : r.U32();
for (uint i = 0; i < count && r.Ok; i++)
{
var id = version < 2 ? r.U16() : r.U32();
var method = version is 1 or 2 ? r.U16() & 0xF : 0;
r.Skip(2);
var baseOffset = r.Sized(baseOffsetSize);
var extents = r.U16();
var item = Get(items, id);
item.ConstructionMethod = method;
for (var e = 0; e < extents && r.Ok; e++)
{
r.Sized(indexSize);
var offset = baseOffset + r.Sized(offsetSize);
var length = r.Sized(lengthSize);
if (r.Ok && e < MaxExtentsPerItem && offset <= long.MaxValue && length <= long.MaxValue)
item.Extents.Add(((long)offset, (long)length));
}
}
if (!r.Ok) m.Warn("HEIF iloc truncated or malformed");
}
/// <summary>ispe, pixi, irot and imir associated with the primary item through ipma (1-based ipco indices).</summary>
private static void ReadPrimaryProperties(MetadataBuilder m, BmffBox iprp, uint primary)
{
var s = m.Stream;
var children = BmffReader.ReadChildren(s, iprp.PayloadStart, iprp.End);
if (BmffReader.Find(children, "ipco") is not { } ipco || BmffReader.Find(children, "ipma") is not { } ipma) return;
var properties = BmffReader.ReadChildren(s, ipco.PayloadStart, ipco.End);
var transform = Orientations[0];
var transformed = false;
foreach (var index in Associations(m, ipma, primary))
{
if (index < 1 || index > properties.Count) continue;
var p = properties[index - 1];
var data = s.ReadAt(p.PayloadStart, Math.Min(p.PayloadLength, MaxPropertyBytes), MaxPropertyBytes);
if (data is null) continue;
if (p.Is("ispe") && data.Length >= 12)
{
var width = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(4));
var height = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(8));
if (width <= int.MaxValue && height <= int.MaxValue) m.SetContainerSize((int)width, (int)height);
}
else if (p.Is("pixi") && data.Length >= 6 && data[4] > 0)
{
m.CodedBitsPerSample ??= data[5];
}
else if (p.Is("irot") && data.Length >= 1)
{
// Anticlockwise quarter turns: 1 → orientation 8, 2 → 3, 3 → 6.
transform = Multiply(Orientations[(data[0] & 3) switch { 1 => 7, 2 => 2, 3 => 5, _ => 0 }], transform);
transformed = true;
}
else if (p.Is("imir") && data.Length >= 1)
{
transform = Multiply(Orientations[(data[0] & 1) == 0 ? 3 : 1], transform);
transformed = true;
}
}
if (transformed) m.ContainerOrientation = Array.IndexOf(Orientations, transform) + 1;
}
private static List<int> Associations(MetadataBuilder m, BmffBox ipma, uint primary)
{
var result = new List<int>();
if (m.Stream.ReadAt(ipma.PayloadStart, ipma.PayloadLength, MaxTableBytes) is not { } data) return result;
var r = new SpanReader(data);
var version = r.U8();
r.Skip(2);
var wideIndex = (r.U8() & 1) != 0;
var count = r.U32();
for (uint i = 0; i < count && r.Ok; i++)
{
var id = version < 1 ? r.U16() : r.U32();
var associations = r.U8();
for (var a = 0; a < associations && r.Ok; a++)
{
var index = wideIndex ? r.U16() & 0x7FFF : r.U8() & 0x7F;
if (id == primary && r.Ok) result.Add(index);
}
}
if (!r.Ok) m.Warn("HEIF ipma truncated");
return result;
}
private static void ReadExifItem(MetadataBuilder m, Item item, long origin)
{
if (item.Extents.Count == 0) return;
var (start, length) = item.Extents[0];
for (var i = 1; i < item.Extents.Count; i++)
{
if (item.Extents[i].Offset != start + length)
{
m.Warn("Fragmented HEIF Exif item not supported");
return;
}
length += item.Extents[i].Length;
}
start += origin;
if (length == 0) length = m.Length - start;
if (start < 0 || length <= 0 || start > m.Length - length)
{
m.Warn("HEIF Exif item outside the file");
return;
}
ExifParser.ParseOffsetPrefixed(m, start, length);
}
private static void ReadXmpItem(MetadataBuilder m, Item item, long origin)
{
long total = 0;
foreach (var (_, length) in item.Extents) total += length;
if (total <= 0 || total > XmpParser.MaxPacketBytes)
{
m.Warn("HEIF XMP item empty or too large");
return;
}
var packet = new byte[total];
var at = 0;
foreach (var (offset, length) in item.Extents)
{
if (!m.Stream.TryReadAt(origin + offset, packet.AsSpan(at, (int)length)))
{
m.Warn("HEIF XMP item outside the file");
return;
}
at += (int)length;
}
m.AddXmp(packet);
}
private static (int, int, int, int) Multiply((int A, int B, int C, int D) x, (int A, int B, int C, int D) y) =>
(x.A * y.A + x.B * y.C, x.A * y.B + x.B * y.D, x.C * y.A + x.D * y.C, x.C * y.B + x.D * y.D);
private static Item Get(Dictionary<uint, Item> items, uint id)
{
if (!items.TryGetValue(id, out var item)) items[id] = item = new Item();
return item;
}
private sealed class Item
{
public uint Type { get; set; }
public string? ContentType { get; set; }
public int ConstructionMethod { get; set; }
public List<(long Offset, long Length)> Extents { get; } = [];
}
}