using System.Buffers.Binary;
using Chronos.Core.Metadata.Bmff;
using Chronos.Core.Metadata.Tiff;
using Chronos.Core.Metadata.Xmp;
namespace Chronos.Core.Metadata;
/// Formats with "minimal" metadata (BRIEF §8.1): GIF and BMP sizes; JPEG XR IFD (size, Exif, GPS, XMP);
/// JPEG XL size header plus the container's Exif and XML boxes.
internal static class MinimalFormatParser
{
private const ushort JxrImageWidth = 0xBC80;
private const ushort JxrImageHeight = 0xBC81;
public static void ParseGif(MetadataBuilder m)
{
Span h = stackalloc byte[10];
if (m.Stream.TryReadAt(0, h)) m.SetContainerSize(BinaryPrimitives.ReadUInt16LittleEndian(h[6..]), BinaryPrimitives.ReadUInt16LittleEndian(h[8..]));
else m.Warn("GIF header truncated");
}
/// BITMAPCOREHEADER (16-bit sizes) or BITMAPINFOHEADER and later (signed 32-bit; negative height = top-down).
public static void ParseBmp(MetadataBuilder m)
{
Span h = stackalloc byte[26];
if (!m.Stream.TryReadAt(0, h))
{
m.Warn("BMP header truncated");
return;
}
if (BinaryPrimitives.ReadUInt32LittleEndian(h[14..]) == 12)
{
m.SetContainerSize(BinaryPrimitives.ReadUInt16LittleEndian(h[18..]), BinaryPrimitives.ReadUInt16LittleEndian(h[20..]));
return;
}
var width = BinaryPrimitives.ReadInt32LittleEndian(h[18..]);
var height = BinaryPrimitives.ReadInt32LittleEndian(h[22..]);
if (height != int.MinValue) m.SetContainerSize(width, Math.Abs(height));
}
/// JPEG XR: a little-endian TIFF-like IFD (magic 0x01BC) with standard Make/Exif/GPS/XMP tags.
public static void ParseJpegXr(MetadataBuilder m)
{
Span h = stackalloc byte[8];
if (!m.Stream.TryReadAt(0, h))
{
m.Warn("JPEG XR header truncated");
return;
}
var r = TiffReader.ForEmbedded(m.Stream, 0, littleEndian: true);
if (r.ReadIfd(BinaryPrimitives.ReadUInt32LittleEndian(h[4..])) is { } ifd)
{
ExifParser.ReadTree(r, ifd, m, [ifd.Position]);
m.SetContainerSize(IfdValue.Int(r, ifd, JxrImageWidth) ?? 0, IfdValue.Int(r, ifd, JxrImageHeight) ?? 0);
}
m.AddWarnings(r.Warnings);
}
/// JPEG XL: bare codestream (FF 0A) or ISO-BMFF container with jxlc/jxlp, Exif and "xml " boxes.
public static void ParseJpegXl(MetadataBuilder m)
{
Span h = stackalloc byte[2];
if (m.Stream.TryReadAt(0, h) && h[0] == 0xFF && h[1] == 0x0A)
{
ReadSizeHeader(m, 0);
return;
}
var codestream = false;
foreach (var box in BmffReader.ReadChildren(m.Stream, 0, m.Length))
{
m.ThrowIfCancelled();
if (box.Is("Exif")) ExifParser.ParseOffsetPrefixed(m, box.PayloadStart, box.PayloadLength);
else if (box.Is("xml ")) m.AddXmp(m.Stream.ReadAt(box.PayloadStart, box.PayloadLength, XmpParser.MaxPacketBytes));
else if (!codestream && box.Is("jxlc")) codestream = ReadSizeHeader(m, box.PayloadStart);
else if (!codestream && box.Is("jxlp")) codestream = ReadSizeHeader(m, box.PayloadStart + 4);
}
}
/// Codestream SizeHeader (ISO/IEC 18181-1 §D.2): small sizes in multiples of 8, else U32 distributions;
/// width either explicit or derived from a fixed aspect ratio.
private static bool ReadSizeHeader(MetadataBuilder m, long position)
{
Span b = stackalloc byte[18];
var n = m.Stream.ReadUpTo(position, b);
if (n < 3 || b[0] != 0xFF || b[1] != 0x0A)
{
m.Warn("JPEG XL codestream signature missing");
return false;
}
b[n..].Clear();
var bits = new BitReader(BinaryPrimitives.ReadUInt128LittleEndian(b[2..]));
var small = bits.Read(1) == 1;
var height = small ? (bits.Read(5) + 1) * 8 : Distribution(ref bits) + 1;
var ratio = (int)bits.Read(3);
var width = ratio != 0
? height * (ulong)RatioNumerator[ratio] / (ulong)RatioDenominator[ratio]
: small ? (bits.Read(5) + 1) * 8 : Distribution(ref bits) + 1;
if (width <= int.MaxValue && height <= int.MaxValue) m.SetContainerSize((int)width, (int)height);
return true;
}
private static ReadOnlySpan RatioNumerator => [0, 1, 12, 4, 3, 16, 5, 2];
private static ReadOnlySpan RatioDenominator => [1, 1, 10, 3, 2, 9, 4, 1];
private static ulong Distribution(ref BitReader bits) => bits.Read(bits.Read(2) switch { 0 => 9, 1 => 13, 2 => 18, _ => 30 });
/// LSB-first bit reader over the 128 bits following the signature (a SizeHeader uses at most 68).
private struct BitReader(UInt128 value)
{
private UInt128 _value = value;
public ulong Read(int count)
{
var v = (ulong)(_value & ((UInt128.One << count) - 1));
_value >>= count;
return v;
}
}
}