diff --git a/src/Titano.Core/Metadata/Bmff/BmffReader.cs b/src/Titano.Core/Metadata/Bmff/BmffReader.cs new file mode 100644 index 00000000..8f57a992 --- /dev/null +++ b/src/Titano.Core/Metadata/Bmff/BmffReader.cs @@ -0,0 +1,127 @@ +using System.Buffers.Binary; + +namespace Titano.Core.Metadata.Bmff; + +/// One ISO-BMFF box header: four-character type, absolute start, total size and header size +/// (8, 16 with a 64-bit size, plus 16 for a uuid user type). +public readonly record struct BmffBox(uint Type, long Start, long Size, int HeaderSize, Guid UserType) +{ + public long End => Start + Size; + public long PayloadStart => Start + HeaderSize; + public long PayloadLength => Size - HeaderSize; + + public bool Is(string fourCC) => Type == FourCC.From(fourCC); + + public override string ToString() => $"{FourCC.Format(Type)} @{Start} ({Size} bytes)"; +} + +/// Four-character codes as big-endian 32-bit integers. +public static class FourCC +{ + public static uint From(ReadOnlySpan code) + { + if (code.Length != 4) throw new ArgumentException("A four-character code has exactly four characters.", nameof(code)); + return (uint)(byte)code[0] << 24 | (uint)(byte)code[1] << 16 | (uint)(byte)code[2] << 8 | (byte)code[3]; + } + + public static string Format(uint code) => + string.Create(4, code, static (span, c) => + { + for (var i = 0; i < 4; i++) + { + var b = (char)((c >> (24 - 8 * i)) & 0xFF); + span[i] = b is >= ' ' and <= '~' ? b : '?'; + } + }); +} + +/// +/// Fuzz-safe ISO-BMFF box walker over a seekable stream: 32-bit, 64-bit (largesize) and to-end (size 0) boxes, +/// uuid user types, a cap on boxes per container and on descent depth. Only headers are read. +/// +public static class BmffReader +{ + public const int MaxBoxesPerContainer = 4096; + public const int MaxDepth = 16; + + private static readonly uint Uuid = FourCC.From("uuid"); + + /// Box headers inside [, ). Stops at the first malformed header; + /// a box running past is clamped so truncated files still expose their leading boxes. + public static IReadOnlyList ReadChildren(Stream stream, long start, long end, ICollection? warnings = null) + { + ArgumentNullException.ThrowIfNull(stream); + var boxes = new List(); + end = Math.Min(end, stream.Length); + Span h = stackalloc byte[32]; + var pos = Math.Max(0, start); + while (pos <= end - 8) + { + if (boxes.Count == MaxBoxesPerContainer) + { + warnings?.Add($"More than {MaxBoxesPerContainer} boxes at {start}; rest ignored"); + break; + } + var n = stream.ReadUpTo(pos, h[..(int)Math.Min(h.Length, end - pos)]); + if (n < 8) break; + long size = BinaryPrimitives.ReadUInt32BigEndian(h); + var type = BinaryPrimitives.ReadUInt32BigEndian(h[4..]); + var header = 8; + if (size == 1) + { + if (n < 16) break; + size = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(h[8..]), long.MaxValue); + header = 16; + } + else if (size == 0) + { + size = end - pos; + } + var userType = Guid.Empty; + if (type == Uuid) + { + if (n < header + 16) break; + userType = new Guid(h.Slice(header, 16), bigEndian: true); + header += 16; + } + if (size < header) + { + warnings?.Add($"Malformed box header at {pos}"); + break; + } + if (size > end - pos) + { + warnings?.Add($"Box '{FourCC.Format(type)}' at {pos} runs past its container"); + size = end - pos; + } + boxes.Add(new BmffBox(type, pos, size, header, userType)); + pos += size; + } + return boxes; + } + + /// First box of in , or null. + public static BmffBox? Find(IReadOnlyList boxes, string type) + { + var code = FourCC.From(type); + foreach (var b in boxes) + { + if (b.Type == code) return b; + } + return null; + } + + /// Follows a path of plain (non-full) container boxes from 's payload, + /// taking the first match at each level. + public static BmffBox? FindPath(Stream stream, BmffBox parent, params ReadOnlySpan path) + { + if (path.Length > MaxDepth) throw new ArgumentException($"Paths are limited to {MaxDepth} levels.", nameof(path)); + BmffBox? current = parent; + foreach (var type in path) + { + if (current is not { } box) return null; + current = Find(ReadChildren(stream, box.PayloadStart, box.End), type); + } + return current; + } +} diff --git a/src/Titano.Core/Metadata/Bmff/Cr3Parser.cs b/src/Titano.Core/Metadata/Bmff/Cr3Parser.cs new file mode 100644 index 00000000..a02d63ce --- /dev/null +++ b/src/Titano.Core/Metadata/Bmff/Cr3Parser.cs @@ -0,0 +1,158 @@ +using System.Buffers.Binary; +using Titano.Core.Metadata.Jpeg; +using Titano.Core.Metadata.MakerNotes; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Metadata.Xmp; + +namespace Titano.Core.Metadata.Bmff; + +/// +/// Canon CR3 (ISO-BMFF, brand crx ): the Canon uuid box in moov holds CMT1 (IFD0), CMT2 (Exif IFD), +/// CMT3 (Canon MakerNote), CMT4 (GPS IFD) as little TIFF files plus the THMB thumbnail; a top-level uuid holds the +/// PRVW preview and another the XMP packet. Track 1's first sample is the full-size JPEG; the main size and bit depth come +/// from the largest raw track (CRAW sample entry with a CMP1 header), else from CMT1. +/// +internal static class Cr3Parser +{ + private static readonly Guid CanonUuid = new("85c0b687-820f-11e0-8111-f4ce462b6a48"); + private static readonly Guid PreviewUuid = new("eaf42b5e-1c98-4b88-b9fb-b7dc406e4d16"); + private static readonly Guid XmpUuid = new("be7acfcb-97a9-42e8-9c71-999491e3afac"); + + /// Offset of the child boxes inside a CRAW visual sample entry (8-byte header + 78 bytes of fields). + private const int CrawChildrenOffset = 86; + + /// The JPEG of THMB and PRVW starts within this many bytes of the box payload. + private const int JpegSearchBytes = 32; + + public static void Parse(MetadataBuilder m) + { + var s = m.Stream; + var warnings = new List(); + var top = BmffReader.ReadChildren(s, 0, m.Length, warnings); + var trackIndex = 0; + (int Width, int Height, int Bits) raw = default; + foreach (var box in top) + { + m.ThrowIfCancelled(); + if (box.Is("moov")) + { + foreach (var child in BmffReader.ReadChildren(s, box.PayloadStart, box.End, warnings)) + { + m.ThrowIfCancelled(); + if (child.Is("uuid") && child.UserType == CanonUuid) ReadCanonBox(m, child, warnings); + else if (child.Is("trak")) ReadTrack(m, child, trackIndex++ == 0, ref raw); + } + } + else if (box.Is("uuid") && box.UserType == PreviewUuid) + { + ReadPreviewBox(m, box); + } + else if (box.Is("uuid") && box.UserType == XmpUuid) + { + m.AddXmp(s.ReadAt(box.PayloadStart, box.PayloadLength, XmpParser.MaxPacketBytes)); + } + } + m.AddWarnings(warnings); + if (raw.Width > 0) m.SetContainerSize(raw.Width, raw.Height, raw.Bits > 0 ? raw.Bits : null); + } + + private static void ReadCanonBox(MetadataBuilder m, BmffBox canon, List warnings) + { + foreach (var box in BmffReader.ReadChildren(m.Stream, canon.PayloadStart, canon.End, warnings)) + { + if (box.Is("THMB")) + { + AddJpeg(m, box); + continue; + } + if (!(box.Is("CMT1") || box.Is("CMT2") || box.Is("CMT3") || box.Is("CMT4"))) continue; + var r = TiffReader.Open(m.Stream, box.PayloadStart); + if (r?.ReadIfd(r.FirstIfdOffset) is not { } ifd) + { + m.Warn($"CR3 {FourCC.Format(box.Type)} is not a TIFF block"); + continue; + } + if (box.Is("CMT1")) + { + ExifParser.ReadIfd0(r, ifd, m); + m.AddRaster(IfdValue.Int(r, ifd, TiffTags.ImageWidth) ?? 0, IfdValue.Int(r, ifd, TiffTags.ImageLength) ?? 0, null, true); + } + else if (box.Is("CMT2")) + { + ExifParser.ReadExif(r, ifd, m); + } + else if (box.Is("CMT3")) + { + CanonMakerNote.Parse(r, ifd, m); + } + else + { + ExifParser.ReadGps(r, ifd, m); + } + m.AddWarnings(r.Warnings); + } + } + + /// Track 1's first sample is the full-size JPEG; any track whose CRAW entry has a CMP1 header is raw data. + private static void ReadTrack(MetadataBuilder m, BmffBox trak, bool first, ref (int Width, int Height, int Bits) raw) + { + var s = m.Stream; + if (BmffReader.FindPath(s, trak, "mdia", "minf", "stbl") is not { } stbl) return; + var tables = BmffReader.ReadChildren(s, stbl.PayloadStart, stbl.End); + if (BmffReader.Find(tables, "stsd") is { } stsd && FirstSampleEntry(s, stsd) is { } entry && entry.Is("CRAW") + && BmffReader.Find(BmffReader.ReadChildren(s, entry.Start + CrawChildrenOffset, entry.End), "CMP1") is { } cmp1) + { + // CMP1 (big-endian): +8 width, +12 height, +24 bits per sample. + Span h = stackalloc byte[25]; + if (s.TryReadAt(cmp1.PayloadStart, h)) + { + var width = BinaryPrimitives.ReadInt32BigEndian(h[8..]); + var height = BinaryPrimitives.ReadInt32BigEndian(h[12..]); + if (width > 0 && height > 0 && (long)width * height > (long)raw.Width * raw.Height) raw = (width, height, h[24]); + } + } + if (first && FirstSample(s, tables) is { } sample) JpegParser.AddPreview(m, sample.Offset, sample.Length, PreviewKind.FullSize); + } + + private static BmffBox? FirstSampleEntry(Stream s, BmffBox stsd) => + BmffReader.ReadChildren(s, stsd.PayloadStart + 8, stsd.End) is [var entry, ..] ? entry : null; + + /// Offset (stco/co64) and size (stsz) of a track's first sample. + private static (long Offset, long Length)? FirstSample(Stream s, IReadOnlyList tables) + { + Span b = stackalloc byte[16]; + if (BmffReader.Find(tables, "stsz") is not { } stsz || !s.TryReadAt(stsz.PayloadStart, b)) return null; + long size = BinaryPrimitives.ReadUInt32BigEndian(b[4..]); + if (size == 0) size = BinaryPrimitives.ReadUInt32BigEndian(b[8..]) > 0 ? BinaryPrimitives.ReadUInt32BigEndian(b[12..]) : 0; + long offset; + if (BmffReader.Find(tables, "co64") is { } co64 && s.TryReadAt(co64.PayloadStart, b)) + offset = BinaryPrimitives.ReadUInt32BigEndian(b[4..]) > 0 ? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(b[8..]), long.MaxValue) : 0; + else if (BmffReader.Find(tables, "stco") is { } stco && s.TryReadAt(stco.PayloadStart, b[..12])) + offset = BinaryPrimitives.ReadUInt32BigEndian(b[4..]) > 0 ? BinaryPrimitives.ReadUInt32BigEndian(b[8..]) : 0; + else + return null; + return offset > 0 && size > 0 ? (offset, size) : null; + } + + /// The preview uuid holds 8 bytes of header fields, then a PRVW box. + private static void ReadPreviewBox(MetadataBuilder m, BmffBox uuid) + { + if (BmffReader.Find(BmffReader.ReadChildren(m.Stream, uuid.PayloadStart + 8, uuid.End), "PRVW") is { } prvw) AddJpeg(m, prvw); + else m.Warn("CR3 PRVW box not found"); + } + + /// THMB/PRVW: a few header fields (version, size, dimensions) followed by the JPEG to the end of the box. + private static void AddJpeg(MetadataBuilder m, BmffBox box) + { + Span head = stackalloc byte[JpegSearchBytes]; + var n = m.Stream.ReadUpTo(box.PayloadStart, head[..(int)Math.Min(head.Length, box.PayloadLength)]); + var at = head[..n].IndexOf([(byte)0xFF, (byte)0xD8, (byte)0xFF]); + if (at < 0) + { + m.Warn($"CR3 {FourCC.Format(box.Type)} holds no JPEG"); + return; + } + var start = box.PayloadStart + at; + JpegParser.AddPreview(m, start, box.End - start); + } +} diff --git a/src/Titano.Core/Metadata/Bmff/HeifParser.cs b/src/Titano.Core/Metadata/Bmff/HeifParser.cs new file mode 100644 index 00000000..b29c5c70 --- /dev/null +++ b/src/Titano.Core/Metadata/Bmff/HeifParser.cs @@ -0,0 +1,282 @@ +using System.Buffers.Binary; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Metadata.Xmp; + +namespace Titano.Core.Metadata.Bmff; + +/// +/// HEIF / HEIC / AVIF: meta → hdlr, pitm, iinf/infe (v2/v3), iloc (v0–v2), +/// iprp/ipco/ipma. Main size from the primary item's ispe, bit depth from pixi, +/// Exif from the Exif item and XMP from the application/rdf+xml mime item. +/// +/// +/// Orientation rule: when the primary item carries irot and/or imir, their composition (in association +/// order) defines 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. +/// imir axis 0 mirrors top↔bottom and axis 1 left↔right (23008-12 2nd edition, as libheif). +/// +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(); + 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(); + var children = BmffReader.ReadChildren(s, meta.PayloadStart + 4, meta.End, warnings); + var items = new Dictionary(); + 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 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 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; + } + + /// iinf → infe v2/v3: item id, type and (for mime items) content type. Earlier infe versions carry no type. + private static void ReadItemInfo(MetadataBuilder m, BmffBox iinf, Dictionary items, List warnings) + { + Span 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(); + } + } + + /// iloc v0–v2: offset/length/base-offset/index field sizes, construction methods 0 (file) and 1 (idat), + /// any number of extents. + private static void ReadLocations(MetadataBuilder m, BmffBox iloc, Dictionary 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"); + } + + /// ispe, pixi, irot and imir associated with the primary item through ipma (1-based ipco indices). + 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 Associations(MetadataBuilder m, BmffBox ipma, uint primary) + { + var result = new List(); + 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 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; } = []; + } +} diff --git a/src/Titano.Core/Metadata/ExifWriter.cs b/src/Titano.Core/Metadata/ExifWriter.cs new file mode 100644 index 00000000..9fdd6416 --- /dev/null +++ b/src/Titano.Core/Metadata/ExifWriter.cs @@ -0,0 +1,254 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Text; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata; + +/// +/// Writes a minimal, valid little-endian Exif block for proxies and exports (BRIEF §8.5, §9): IFD0 (camera, orientation, +/// software, date, authorship), the Exif IFD (capture time with sub-seconds and offset, exposure, lens and body) and, +/// when known, the GPS IFD. Strings longer than UTF-8 bytes are truncated. +/// +public static class ExifWriter +{ + /// Longest string written, in UTF-8 bytes; keeps the APP1 segment far below its 64 KB limit. + public const int MaxStringBytes = 2000; + + private const int MaxShortIso = 65535; + private const uint GpsDegreeDenominator = 10_000_000; + + private static ReadOnlySpan ExifHeader => "Exif\0\0"u8; + + /// A complete TIFF structure ("II*\0" header, IFD0, Exif IFD, optional GPS IFD). + public static byte[] BuildTiff(FrameMetadata metadata) + { + ArgumentNullException.ThrowIfNull(metadata); + var m = metadata; + var date = m.CapturedAt?.ToString("yyyy':'MM':'dd HH':'mm':'ss", CultureInfo.InvariantCulture); + + var ifd0 = new IfdBuilder(); + ifd0.Ascii(TiffTags.Make, m.Make); + ifd0.Ascii(TiffTags.Model, m.Model); + ifd0.Short(TiffTags.Orientation, (ushort)(m.Orientation is >= 1 and <= 8 ? m.Orientation : 1)); + ifd0.Rational(TiffTags.XResolution, 72, 1); + ifd0.Rational(TiffTags.YResolution, 72, 1); + ifd0.Short(TiffTags.ResolutionUnit, 2); + ifd0.Ascii(TiffTags.Software, m.Software); + ifd0.Ascii(TiffTags.DateTime, date); + ifd0.Ascii(TiffTags.Artist, m.Artist); + ifd0.Short(TiffTags.YCbCrPositioning, 1); + ifd0.Ascii(TiffTags.Copyright, m.Copyright); + + var exif = new IfdBuilder(); + exif.Rational(TiffTags.ExposureTime, m.ExposureTime); + exif.Rational(TiffTags.FNumber, m.FNumber); + if (m.Iso is { } iso and > 0) + { + exif.Short(TiffTags.IsoSpeedRatings, (ushort)Math.Min(iso, MaxShortIso)); + if (iso >= MaxShortIso) + { + // ISOSpeedRatings saturates at 65535; SensitivityType 2 declares RecommendedExposureIndex as the value. + exif.Short(TiffTags.SensitivityType, 2); + exif.Long(TiffTags.RecommendedExposureIndex, (uint)iso); + } + } + exif.Undefined(TiffTags.ExifVersion, "0232"u8); + exif.Ascii(TiffTags.DateTimeOriginal, date); + if (m.CapturedAt is { } captured && captured.Ticks % TimeSpan.TicksPerSecond is > 0 and var fraction) + exif.Ascii(TiffTags.SubSecTimeOriginal, fraction.ToString("D7", CultureInfo.InvariantCulture).TrimEnd('0')); + if (m.UtcOffsetMinutes is { } offset && Math.Abs(offset) < 24 * 60) + exif.Ascii(TiffTags.OffsetTimeOriginal, $"{(offset < 0 ? '-' : '+')}{Math.Abs(offset) / 60:D2}:{Math.Abs(offset) % 60:D2}"); + exif.SRational(TiffTags.ExposureBiasValue, m.ExposureBias); + exif.Rational(TiffTags.FocalLength, m.FocalLength); + if (m.FocalLength35 is { } f35 and > 0 and < MaxShortIso) exif.Short(TiffTags.FocalLengthIn35mmFilm, (ushort)Math.Round(f35)); + exif.Ascii(TiffTags.BodySerialNumber, m.BodySerial); + exif.Ascii(TiffTags.LensModel, m.LensModel); + + var gps = m.Gps is { } position ? BuildGps(position) : null; + + // Pointers are fixed-size LONGs, so the IFD sizes are known before their offsets. + ifd0.Long(TiffTags.ExifIfd, 0); + if (gps is not null) ifd0.Long(TiffTags.GpsIfd, 0); + var exifOffset = 8 + ifd0.Size; + var gpsOffset = exifOffset + exif.Size; + ifd0.Long(TiffTags.ExifIfd, (uint)exifOffset); + if (gps is not null) ifd0.Long(TiffTags.GpsIfd, (uint)gpsOffset); + + var tiff = new byte[gpsOffset + (gps?.Size ?? 0)]; + "II*\0"u8.CopyTo(tiff); + BinaryPrimitives.WriteUInt32LittleEndian(tiff.AsSpan(4), 8); + ifd0.Write(tiff, 8); + exif.Write(tiff, exifOffset); + gps?.Write(tiff, gpsOffset); + return tiff; + } + + /// A complete JPEG APP1 segment: FF E1, big-endian length, "Exif\0\0", then . + public static byte[] BuildJpegApp1(FrameMetadata metadata) + { + var tiff = BuildTiff(metadata); + var segment = new byte[4 + ExifHeader.Length + tiff.Length]; + segment[0] = 0xFF; + segment[1] = 0xE1; + BinaryPrimitives.WriteUInt16BigEndian(segment.AsSpan(2), checked((ushort)(segment.Length - 2))); + ExifHeader.CopyTo(segment.AsSpan(4)); + tiff.CopyTo(segment, 4 + ExifHeader.Length); + return segment; + } + + /// Coordinates as decimal degrees (1e-7° resolution) in the degrees rational, minutes and seconds zero. + private static IfdBuilder BuildGps(GpsPosition gps) + { + var ifd = new IfdBuilder(); + ifd.Bytes(TiffTags.GpsVersionId, TiffType.Byte, [2, 3, 0, 0]); + if (double.IsFinite(gps.Latitude) && double.IsFinite(gps.Longitude)) + { + ifd.Ascii(TiffTags.GpsLatitudeRef, gps.Latitude < 0 ? "S" : "N"); + ifd.Rationals(TiffTags.GpsLatitude, [((uint)Math.Round(Math.Min(Math.Abs(gps.Latitude), 90) * GpsDegreeDenominator), GpsDegreeDenominator), (0, 1), (0, 1)]); + ifd.Ascii(TiffTags.GpsLongitudeRef, gps.Longitude < 0 ? "W" : "E"); + ifd.Rationals(TiffTags.GpsLongitude, [((uint)Math.Round(Math.Min(Math.Abs(gps.Longitude), 180) * GpsDegreeDenominator), GpsDegreeDenominator), (0, 1), (0, 1)]); + } + if (gps.Altitude is { } altitude && double.IsFinite(altitude)) + { + ifd.Bytes(TiffTags.GpsAltitudeRef, TiffType.Byte, [altitude < 0 ? (byte)1 : (byte)0]); + ifd.Rationals(TiffTags.GpsAltitude, [ToRational(Math.Abs(altitude))]); + } + if (gps.UtcTimestamp is { } utc) + { + var t = utc.TimeOfDay; + ifd.Rationals(TiffTags.GpsTimeStamp, [((uint)t.Hours, 1), ((uint)t.Minutes, 1), ((uint)Math.Round((t.Seconds + t.Milliseconds / 1000.0) * 1000), 1000)]); + ifd.Ascii(TiffTags.GpsDateStamp, utc.ToString("yyyy':'MM':'dd", CultureInfo.InvariantCulture)); + } + return ifd; + } + + /// Exact 1/n for exposure-style fractions, else a fixed denominator reduced by the GCD. + private static (uint Numerator, uint Denominator) ToRational(double value) + { + if (!double.IsFinite(value) || value <= 0) return (0, 1); + if (value < 1) + { + var inverse = Math.Round(1 / value); + if (inverse <= uint.MaxValue && Math.Abs(1 / inverse - value) <= value * 1e-6) return (1, (uint)inverse); + } + var denominator = value < 400_000 ? 10_000u : 1u; + var numerator = Math.Round(value * denominator); + if (numerator > uint.MaxValue) return (uint.MaxValue, 1); + var n = (uint)numerator; + var gcd = Gcd(n, denominator); + return (n / gcd, denominator / gcd); + } + + private static uint Gcd(uint a, uint b) + { + while (b != 0) (a, b) = (b, a % b); + return a == 0 ? 1 : a; + } + + /// Collects entries of one IFD and serialises them sorted by tag, values over 4 bytes word-aligned after it. + private sealed class IfdBuilder + { + private readonly SortedDictionary _entries = new(); + + /// Bytes taken by the IFD including its out-of-line values. + public int Size + { + get + { + var size = 2 + 12 * _entries.Count + 4; + foreach (var e in _entries.Values) + { + if (e.Data.Length > 4) size += e.Data.Length + (e.Data.Length & 1); + } + return size; + } + } + + public void Bytes(ushort tag, TiffType type, byte[] data) => _entries[tag] = (type, (uint)(data.Length / TiffTypeInfo.Size(type)), data); + + public void Undefined(ushort tag, ReadOnlySpan data) => Bytes(tag, TiffType.Undefined, data.ToArray()); + + public void Ascii(ushort tag, string? value) + { + if (string.IsNullOrWhiteSpace(value)) return; + var text = value.Trim(); + var nul = text.IndexOf('\0'); + if (nul >= 0) text = text[..nul]; + var bytes = Encoding.UTF8.GetBytes(text); + var length = Math.Min(bytes.Length, MaxStringBytes); + while (length < bytes.Length && length > 0 && (bytes[length] & 0xC0) == 0x80) length--; + var data = new byte[length + 1]; + bytes.AsSpan(0, length).CopyTo(data); + Bytes(tag, TiffType.Ascii, data); + } + + public void Short(ushort tag, ushort value) + { + var data = new byte[2]; + BinaryPrimitives.WriteUInt16LittleEndian(data, value); + Bytes(tag, TiffType.Short, data); + } + + public void Long(ushort tag, uint value) + { + var data = new byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(data, value); + Bytes(tag, TiffType.Long, data); + } + + public void Rational(ushort tag, double? value) + { + if (value is { } v and > 0 && double.IsFinite(v)) Rationals(tag, [ToRational(v)]); + } + + public void Rational(ushort tag, uint numerator, uint denominator) => Rationals(tag, [(numerator, denominator)]); + + public void Rationals(ushort tag, ReadOnlySpan<(uint Numerator, uint Denominator)> values) + { + var data = new byte[8 * values.Length]; + for (var i = 0; i < values.Length; i++) + { + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(8 * i), values[i].Numerator); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(8 * i + 4), values[i].Denominator); + } + Bytes(tag, TiffType.Rational, data); + } + + public void SRational(ushort tag, double? value) + { + if (value is not { } v || !double.IsFinite(v) || Math.Abs(v) >= 200_000) return; + var (n, d) = ToRational(Math.Abs(v)); + var data = new byte[8]; + BinaryPrimitives.WriteInt32LittleEndian(data, v < 0 ? -(int)n : (int)n); + BinaryPrimitives.WriteInt32LittleEndian(data.AsSpan(4), (int)d); + Bytes(tag, TiffType.SRational, data); + } + + public void Write(byte[] tiff, int offset) + { + var span = tiff.AsSpan(); + BinaryPrimitives.WriteUInt16LittleEndian(span[offset..], (ushort)_entries.Count); + var entry = offset + 2; + var data = offset + 2 + 12 * _entries.Count + 4; + foreach (var (tag, (type, count, bytes)) in _entries) + { + BinaryPrimitives.WriteUInt16LittleEndian(span[entry..], tag); + BinaryPrimitives.WriteUInt16LittleEndian(span[(entry + 2)..], (ushort)type); + BinaryPrimitives.WriteUInt32LittleEndian(span[(entry + 4)..], count); + if (bytes.Length <= 4) + { + bytes.CopyTo(span[(entry + 8)..]); + } + else + { + BinaryPrimitives.WriteUInt32LittleEndian(span[(entry + 8)..], (uint)data); + bytes.CopyTo(span[data..]); + data += bytes.Length + (bytes.Length & 1); + } + entry += 12; + } + BinaryPrimitives.WriteUInt32LittleEndian(span[entry..], 0); + } + } +} diff --git a/src/Titano.Core/Metadata/ImageSignature.cs b/src/Titano.Core/Metadata/ImageSignature.cs new file mode 100644 index 00000000..1b5becc2 --- /dev/null +++ b/src/Titano.Core/Metadata/ImageSignature.cs @@ -0,0 +1,149 @@ +using System.Buffers.Binary; +using Titano.Core.Imaging; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata; + +/// +/// Identifies a file's format from its leading bytes. TIFF-based files are refined by the CR2 marker, IFD0 +/// DNGVersion and Make; ISO-BMFF files by their ftyp brands. The file-name extension only breaks +/// ties between formats that share a container (NEF/NRW, ARW/SRF/SR2, 3FR/FFF, RW2/RWL/RAW, TIFF vs camera RAW). +/// +public static class ImageSignature +{ + private const int HeadBytes = 32; + private const int MaxFtypBytes = 256; + + private static ReadOnlySpan PngSignature => [0x89, (byte)'P', (byte)'N', (byte)'G', 0x0D, 0x0A, 0x1A, 0x0A]; + private static ReadOnlySpan JpegXrSignature => [(byte)'I', (byte)'I', 0xBC]; + private static ReadOnlySpan JpegXlBox => [0, 0, 0, 0x0C, (byte)'J', (byte)'X', (byte)'L', (byte)' ', 0x0D, 0x0A, 0x87, 0x0A]; + + private static readonly HashSet TiffBasedRaws = + [ + ImageFileFormat.Dng, ImageFileFormat.Cr2, ImageFileFormat.Nef, ImageFileFormat.Nrw, ImageFileFormat.Arw, + ImageFileFormat.Srf, ImageFileFormat.Sr2, ImageFileFormat.Orf, ImageFileFormat.Rw2, ImageFileFormat.Raw, + ImageFileFormat.Rwl, ImageFileFormat.Pef, ImageFileFormat.Srw, ImageFileFormat.ThreeFr, ImageFileFormat.Fff, + ImageFileFormat.Iiq, ImageFileFormat.Gpr, + ]; + + /// Detects the format of the bytes in (read from offset 0; the position is restored). + /// Optional name or path whose extension breaks ties; never overrides the signature. + /// when no known signature matches. + public static ImageFileFormat Detect(Stream stream, string? fileName) + { + ArgumentNullException.ThrowIfNull(stream); + if (!stream.CanSeek || !stream.CanRead) throw new ArgumentException("The stream must be readable and seekable.", nameof(stream)); + var position = stream.Position; + try + { + var extension = string.IsNullOrEmpty(fileName) ? ImageFileFormat.Unknown : ImageFormatInfo.FromPath(fileName).Format; + return DetectCore(stream, extension); + } + catch (IOException) + { + return ImageFileFormat.Unknown; + } + finally + { + stream.Position = position; + } + } + + private static ImageFileFormat DetectCore(Stream stream, ImageFileFormat extension) + { + Span buffer = stackalloc byte[HeadBytes]; + var h = buffer[..stream.ReadUpTo(0, buffer)]; + if (h.StartsWith((ReadOnlySpan)[0xFF, 0xD8, 0xFF])) return ImageFileFormat.Jpeg; + if (h.StartsWith(PngSignature)) return ImageFileFormat.Png; + if (h.StartsWith("GIF87a"u8) || h.StartsWith("GIF89a"u8)) return ImageFileFormat.Gif; + if (h.StartsWith("FUJIFILMCCD-RAW "u8)) return ImageFileFormat.Raf; + if (h.Length >= 12 && h.StartsWith("RIFF"u8) && h[8..12].SequenceEqual("WEBP"u8)) return ImageFileFormat.WebP; + if (h.StartsWith((ReadOnlySpan)[0xFF, 0x0A]) || h.StartsWith(JpegXlBox)) return ImageFileFormat.JpegXl; + if (h.Length >= 12 && h[4..8].SequenceEqual("ftyp"u8)) return FromBrands(stream, BinaryPrimitives.ReadUInt32BigEndian(h)); + if (h.Length >= 4 && h.StartsWith(JpegXrSignature) && h[3] <= 1) return ImageFileFormat.JpegXr; + if (h.Length >= 14 && h[6..14].SequenceEqual("HEAPCCDR"u8)) return ImageFileFormat.Crw; + if (h.StartsWith("IIRO"u8) || h.StartsWith("IIRS"u8) || h.StartsWith("MMOR"u8)) return ImageFileFormat.Orf; + if (h.StartsWith("IIU\0"u8)) return Panasonic(stream, extension); + if (h.StartsWith("II*\0"u8) || h.StartsWith("MM\0*"u8)) return Tiff(stream, h, extension); + if (h.Length >= 18 && h.StartsWith("BM"u8) && BinaryPrimitives.ReadUInt32LittleEndian(h[14..]) is 12 or 16 or 40 or 52 or 56 or 64 or 108 or 124) + return ImageFileFormat.Bmp; + return ImageFileFormat.Unknown; + } + + /// CR3 (crx), AVIF (avif/avis) or HEIF (heic, heix, hevc, hevx, heim, heis, mif1, msf1); major brand first. + private static ImageFileFormat FromBrands(Stream stream, uint ftypSize) + { + Span buffer = stackalloc byte[MaxFtypBytes]; + var n = stream.ReadUpTo(0, buffer[..(int)Math.Clamp(ftypSize, 16, MaxFtypBytes)]); + if (n < 12) return ImageFileFormat.Unknown; + var major = Brand(buffer[8..12]); + if (major == BrandKind.Cr3) return ImageFileFormat.Cr3; + if (major == BrandKind.Avif) return ImageFileFormat.Avif; + if (major == BrandKind.Heif) return ImageFileFormat.Heif; + var heif = major == BrandKind.Image; + for (var i = 16; i + 4 <= n; i += 4) + { + var brand = Brand(buffer.Slice(i, 4)); + if (brand == BrandKind.Avif) return ImageFileFormat.Avif; + heif |= brand is BrandKind.Heif or BrandKind.Image; + } + return heif ? ImageFileFormat.Heif : ImageFileFormat.Unknown; + } + + private enum BrandKind + { + Other, + Cr3, + Avif, + Heif, + Image, + } + + private static BrandKind Brand(ReadOnlySpan b) => + b.SequenceEqual("crx "u8) ? BrandKind.Cr3 + : b.SequenceEqual("avif"u8) || b.SequenceEqual("avis"u8) ? BrandKind.Avif + : b.SequenceEqual("heic"u8) || b.SequenceEqual("heix"u8) || b.SequenceEqual("hevc"u8) || b.SequenceEqual("hevx"u8) + || b.SequenceEqual("heim"u8) || b.SequenceEqual("heis"u8) ? BrandKind.Heif + : b.SequenceEqual("mif1"u8) || b.SequenceEqual("msf1"u8) ? BrandKind.Image + : BrandKind.Other; + + private static ImageFileFormat Panasonic(Stream stream, ImageFileFormat extension) + { + if (extension is ImageFileFormat.Rwl or ImageFileFormat.Raw) return extension; + return Make(stream)?.StartsWith("LEICA", StringComparison.OrdinalIgnoreCase) == true ? ImageFileFormat.Rwl : ImageFileFormat.Rw2; + } + + private static ImageFileFormat Tiff(Stream stream, ReadOnlySpan h, ImageFileFormat extension) + { + if (h.Length >= 10 && h[8..10].SequenceEqual("CR"u8)) return ImageFileFormat.Cr2; + var reader = TiffReader.Open(stream); + var ifd0 = reader?.ReadIfd(reader.FirstIfdOffset); + var make = reader is not null && ifd0 is not null ? IfdValue.String(reader, ifd0, TiffTags.Make) : null; + if (ifd0?.Has(TiffTags.DngVersion) == true) + return extension == ImageFileFormat.Gpr || make?.StartsWith("GoPro", StringComparison.OrdinalIgnoreCase) == true ? ImageFileFormat.Gpr : ImageFileFormat.Dng; + if (extension == ImageFileFormat.Tiff) return ImageFileFormat.Tiff; + var byMake = ByMake(make, extension); + if (byMake != ImageFileFormat.Unknown) return byMake; + return TiffBasedRaws.Contains(extension) ? extension : ImageFileFormat.Tiff; + } + + private static ImageFileFormat ByMake(string? make, ImageFileFormat extension) + { + if (make is null) return ImageFileFormat.Unknown; + bool Is(string prefix) => make.StartsWith(prefix, StringComparison.OrdinalIgnoreCase); + if (Is("NIKON")) return extension == ImageFileFormat.Nrw ? ImageFileFormat.Nrw : ImageFileFormat.Nef; + if (Is("SONY")) return extension is ImageFileFormat.Srf or ImageFileFormat.Sr2 ? extension : ImageFileFormat.Arw; + if (Is("PENTAX") || Is("RICOH")) return ImageFileFormat.Pef; + if (Is("SAMSUNG")) return ImageFileFormat.Srw; + if (Is("Hasselblad")) return extension == ImageFileFormat.Fff ? ImageFileFormat.Fff : ImageFileFormat.ThreeFr; + if (Is("Imacon")) return ImageFileFormat.Fff; + if (Is("Phase One") || Is("Leaf")) return ImageFileFormat.Iiq; + return ImageFileFormat.Unknown; + } + + private static string? Make(Stream stream) + { + var reader = TiffReader.Open(stream); + return reader?.ReadIfd(reader.FirstIfdOffset) is { } ifd ? IfdValue.String(reader, ifd, TiffTags.Make) : null; + } +} diff --git a/src/Titano.Core/Metadata/Jpeg/JpegParser.cs b/src/Titano.Core/Metadata/Jpeg/JpegParser.cs new file mode 100644 index 00000000..a5db9a65 --- /dev/null +++ b/src/Titano.Core/Metadata/Jpeg/JpegParser.cs @@ -0,0 +1,277 @@ +using System.Buffers.Binary; +using System.Text; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Metadata.Xmp; + +namespace Titano.Core.Metadata.Jpeg; + +/// Frame header (SOFn) of a JPEG. +internal readonly record struct JpegFrame(int Width, int Height, int Precision, bool Lossless); + +/// +/// JPEG marker scan: APP1 Exif, APP1 XMP and extended XMP (reassembled by GUID/offset), APP2 MPF large-thumbnail +/// entries, SOFn. Reads only segment headers and the payloads it parses, stops at SOS, and tolerates fill bytes and +/// garbage between segments. +/// +internal static class JpegParser +{ + /// Most bytes read while looking for an embedded JPEG's frame header. + public const int MaxFrameScanBytes = 64 * 1024; + + private const int MaxSegments = 1024; + private const int MaxGarbageBytes = 64 * 1024; + private const int MaxMpEntries = 64; + private const ushort MpEntryTag = 0xB002; + private const uint MpLargeThumbnailVga = 0x010001; + private const uint MpLargeThumbnailFullHd = 0x010002; + private const int ExtendedHeaderLength = 75; + + private static ReadOnlySpan ExifSignature => "Exif\0"u8; + private static ReadOnlySpan XmpSignature => "http://ns.adobe.com/xap/1.0/\0"u8; + private static ReadOnlySpan ExtendedXmpSignature => "http://ns.adobe.com/xmp/extension/\0"u8; + private static ReadOnlySpan MpfSignature => "MPF\0"u8; + + /// Scans the JPEG at [, ). A primary JPEG defines the main image + /// size; an embedded one (RAF, RW2 JpgFromRaw) contributes its Exif/XMP and is recorded as a preview. + public static void Parse(MetadataBuilder m, long start, long end, bool primary) + { + var scanner = new SegmentScanner(m.Stream, start, Math.Min(end, m.Length), long.MaxValue); + if (!scanner.StartsWithSoi()) + { + m.Warn("JPEG start-of-image marker not found"); + return; + } + JpegFrame? frame = null; + var exifSeen = false; + List? extended = null; + while (scanner.Next(out var segment)) + { + m.ThrowIfCancelled(); + if (segment.Marker is 0xDA or 0xD9) break; + if (segment.Marker == 0xE1) ReadApp1(m, segment, ref exifSeen, ref extended); + else if (segment.Marker == 0xE2) ReadMpf(m, segment); + else if (frame is null && IsFrameMarker(segment.Marker)) frame = ReadFrameHeader(m.Stream, segment); + } + if (scanner.Garbage) m.Warn("JPEG: garbage between segments skipped"); + if (scanner.Truncated) m.Warn("JPEG: truncated segment"); + if (frame is { } f) + { + if (primary) m.SetContainerSize(f.Width, f.Height, f.Precision); + else if (!f.Lossless && end <= m.Length) m.AddPreview(start, end - start, f.Width, f.Height); + } + else if (primary) + { + m.Warn("JPEG frame header not found"); + } + if (extended is not null) AssembleExtendedXmp(m, extended); + } + + /// Frame header of an embedded JPEG reading at most ; null when the bytes are + /// not a JPEG or no SOFn precedes the scan data. + public static JpegFrame? ReadFrame(Stream stream, long offset, long length) + { + if (offset < 0 || length < 4 || offset > stream.Length - length) return null; + var scanner = new SegmentScanner(stream, offset, offset + length, MaxFrameScanBytes); + if (!scanner.StartsWithSoi()) return null; + while (scanner.Next(out var segment)) + { + if (segment.Marker is 0xDA or 0xD9) return null; + if (IsFrameMarker(segment.Marker)) return ReadFrameHeader(stream, segment); + } + return null; + } + + /// Validates an embedded JPEG and records it as a preview unless it is lossless (raw data). + /// The frame header, or null when the range holds no readable JPEG. + public static JpegFrame? AddPreview(MetadataBuilder m, long offset, long length, PreviewKind? kind = null) + { + if (offset < 0 || length <= 0 || offset > m.Length - length) + { + m.Warn("Embedded JPEG outside the file"); + return null; + } + var frame = ReadFrame(m.Stream, offset, length); + if (frame is { Lossless: false } f) m.AddPreview(offset, length, f.Width, f.Height, kind); + return frame; + } + + private static bool IsFrameMarker(byte marker) => marker is >= 0xC0 and <= 0xCF and not (0xC4 or 0xC8 or 0xCC); + + private static JpegFrame? ReadFrameHeader(Stream stream, Segment segment) + { + Span sof = stackalloc byte[6]; + if (segment.Length < 6 || !stream.TryReadAt(segment.Payload, sof)) return null; + var lossless = segment.Marker is 0xC3 or 0xC7 or 0xCB or 0xCF; + return new JpegFrame(BinaryPrimitives.ReadUInt16BigEndian(sof[3..]), BinaryPrimitives.ReadUInt16BigEndian(sof[1..]), sof[0], lossless); + } + + private static void ReadApp1(MetadataBuilder m, Segment segment, ref bool exifSeen, ref List? extended) + { + Span head = stackalloc byte[ExtendedHeaderLength]; + var n = m.Stream.ReadUpTo(segment.Payload, head[..Math.Min(head.Length, segment.Length)]); + var h = head[..n]; + if (h.StartsWith(ExifSignature) && segment.Length > 6) + { + if (!exifSeen) ExifParser.ParseEmbedded(m, segment.Payload + 6); + exifSeen = true; + } + else if (h.StartsWith(XmpSignature)) + { + m.AddXmp(m.Stream.ReadAt(segment.Payload + XmpSignature.Length, segment.Length - XmpSignature.Length, XmpParser.MaxPacketBytes)); + } + else if (h.StartsWith(ExtendedXmpSignature) && n == ExtendedHeaderLength) + { + var guid = Encoding.ASCII.GetString(h.Slice(ExtendedXmpSignature.Length, 32)); + var full = BinaryPrimitives.ReadUInt32BigEndian(h[67..]); + var offset = BinaryPrimitives.ReadUInt32BigEndian(h[71..]); + (extended ??= []).Add(new ExtendedXmpChunk(guid, full, offset, segment.Payload + ExtendedHeaderLength, segment.Length - ExtendedHeaderLength)); + } + } + + /// APP2 Multi-Picture Format: secondary large thumbnails (type 0x010001/0x010002) become previews. Offsets are + /// relative to the MP header; other secondary types (disparity, gain maps…) are not previews. + private static void ReadMpf(MetadataBuilder m, Segment segment) + { + Span head = stackalloc byte[4]; + if (segment.Length < 16 || !m.Stream.TryReadAt(segment.Payload, head) || !head.SequenceEqual(MpfSignature)) return; + var mpBase = segment.Payload + 4; + var r = TiffReader.Open(m.Stream, mpBase); + if (r?.ReadIfd(r.FirstIfdOffset) is not { } index || !index.Entries.TryGetValue(MpEntryTag, out var entry)) return; + if (entry.Count % 16 != 0 || entry.Count > 16 * MaxMpEntries || r.ReadBytes(entry) is not { } entries) + { + m.Warn("MPF entry table malformed"); + return; + } + for (var i = 16; i + 16 <= entries.Length; i += 16) + { + var e = entries.AsSpan(i, 16); + var type = r.U32(e) & 0xFFFFFF; + var size = r.U32(e[4..]); + var offset = r.U32(e[8..]); + if (type is MpLargeThumbnailVga or MpLargeThumbnailFullHd && offset > 0 && size > 0) AddPreview(m, mpBase + offset, size); + } + m.AddWarnings(r.Warnings); + } + + private static void AssembleExtendedXmp(MetadataBuilder m, List chunks) + { + var guid = m.Xmp.ExtendedXmpGuid; + if (guid is null) + { + m.Warn("Extended XMP present but not referenced by the main packet"); + return; + } + uint full = 0; + long covered = 0; + foreach (var c in chunks) + { + if (!string.Equals(c.Guid, guid, StringComparison.OrdinalIgnoreCase)) continue; + if (full == 0) full = c.FullLength; + if (c.FullLength == full) covered += c.Length; + } + if (full == 0 || full > XmpParser.MaxPacketBytes || covered < full) + { + m.Warn("Extended XMP incomplete"); + return; + } + var buffer = new byte[full]; + foreach (var c in chunks) + { + if (!string.Equals(c.Guid, guid, StringComparison.OrdinalIgnoreCase) || c.FullLength != full || (long)c.Offset + c.Length > full) continue; + if (!m.Stream.TryReadAt(c.Position, buffer.AsSpan((int)c.Offset, c.Length))) + { + m.Warn("Extended XMP chunk unreadable"); + return; + } + } + m.AddXmp(buffer); + } + + private readonly record struct Segment(byte Marker, long Payload, int Length); + + private readonly record struct ExtendedXmpChunk(string Guid, uint FullLength, uint Offset, long Position, int Length); + + /// Walks marker segments of one JPEG, reading only marker and length bytes within a read budget. + private sealed class SegmentScanner(Stream stream, long start, long end, long readBudget) + { + private readonly byte[] _buffer = new byte[16]; + private long _position = start + 2; + private long _budget = readBudget; + private int _count; + + public bool Garbage { get; private set; } + + public bool Truncated { get; private set; } + + public bool StartsWithSoi() => Read(start, 2) == 2 && _buffer[0] == 0xFF && _buffer[1] == 0xD8; + + public bool Next(out Segment segment) + { + segment = default; + if (++_count > MaxSegments) return false; + long skipped = 0; + while (true) + { + var n = Read(_position, _buffer.Length); + if (n < 2) + { + if (_position < end) Truncated = true; + return false; + } + var i = 0; + while (i < n - 1 && !(_buffer[i] == 0xFF && _buffer[i + 1] is not (0xFF or 0x00))) i++; + if (i == n - 1) + { + Garbage |= _buffer.AsSpan(0, n - 1).ContainsAnyExcept((byte)0xFF); + _position += n - 1; + skipped += n - 1; + if (skipped > MaxGarbageBytes) return false; + continue; + } + Garbage |= _buffer.AsSpan(0, i).ContainsAnyExcept((byte)0xFF); + var marker = _buffer[i + 1]; + var markerPosition = _position + i + 1; + if (marker is 0xD8 or 0xD9 or 0x01 or (>= 0xD0 and <= 0xD7)) + { + _position = markerPosition + 1; + segment = new Segment(marker, _position, 0); + return true; + } + int length; + if (i + 3 < n) + { + length = _buffer[i + 2] << 8 | _buffer[i + 3]; + } + else if (Read(markerPosition + 1, 2) == 2) + { + length = _buffer[0] << 8 | _buffer[1]; + } + else + { + Truncated = true; + return false; + } + if (length < 2) + { + Garbage = true; + return false; + } + var payload = markerPosition + 3; + var available = (int)Math.Clamp(end - payload, 0, length - 2); + Truncated |= available < length - 2; + segment = new Segment(marker, payload, available); + _position = payload + length - 2; + return true; + } + } + + private int Read(long position, int count) + { + if (position >= end || _budget <= 0) return 0; + var n = (int)Math.Min(Math.Min(count, end - position), _budget); + n = stream.ReadUpTo(position, _buffer.AsSpan(0, n)); + _budget -= n; + return n; + } + } +} diff --git a/src/Titano.Core/Metadata/MakerNotes/CanonMakerNote.cs b/src/Titano.Core/Metadata/MakerNotes/CanonMakerNote.cs new file mode 100644 index 00000000..6c60030e --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/CanonMakerNote.cs @@ -0,0 +1,39 @@ +using System.Globalization; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.MakerNotes; + +/// Canon MakerNote: a bare IFD whose offsets are relative to the enclosing TIFF header (also CR3 CMT3). +internal static class CanonMakerNote +{ + private const ushort CameraSettings = 0x0001; + private const ushort SerialNumber = 0x000C; + private const ushort LensModel = 0x0095; + private const ushort InternalSerialNumber = 0x0096; + private const ushort ColorTemperature = 0x00AE; + private const int ImageStabilizationIndex = 34; + + public static void Parse(TiffReader r, Ifd ifd, MetadataBuilder m) + { + var v = m.MakerNote; + if (IfdValue.UInt(r, ifd, SerialNumber) is { } serial and > 0) + { + // Canon prints 6 digits on EOS-1D bodies and 10 elsewhere. + var digits = m.Model?.Contains("EOS-1D", StringComparison.OrdinalIgnoreCase) == true ? "D6" : "D10"; + v.BodySerial ??= serial.ToString(digits, CultureInfo.InvariantCulture); + } + v.BodySerial ??= IfdValue.String(r, ifd, InternalSerialNumber); + v.LensModel ??= IfdValue.String(r, ifd, LensModel); + v.ColorTemperature ??= IfdValue.Int(r, ifd, ColorTemperature) is { } kelvin and > 0 and < 65535 ? kelvin : null; + if (IfdValue.UInts(r, ifd, CameraSettings) is { Length: > ImageStabilizationIndex } settings) + { + // 0 Off, 1 On, 2 Shoot only, 3 Panning, 4 Dynamic; +256 for the "(2)" variants. + v.ImageStabilization ??= (settings[ImageStabilizationIndex] & 0xFF) switch + { + 0 => false, + >= 1 and <= 4 => true, + _ => null, + }; + } + } +} diff --git a/src/Titano.Core/Metadata/MakerNotes/FujifilmMakerNote.cs b/src/Titano.Core/Metadata/MakerNotes/FujifilmMakerNote.cs new file mode 100644 index 00000000..1b5f93e6 --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/FujifilmMakerNote.cs @@ -0,0 +1,31 @@ +using System.Buffers.Binary; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.MakerNotes; + +/// Fujifilm MakerNote: "FUJIFILM" + little-endian IFD offset, offsets relative to the MakerNote start, +/// always little-endian. +internal static class FujifilmMakerNote +{ + private const ushort SerialNumber = 0x0010; + private const ushort ColorTemperature = 0x1005; + private const ushort ImageStabilization = 0x1422; + + public static void Parse(MetadataBuilder m, long start, ReadOnlySpan header) + { + if (header.Length < 12) return; + var reader = TiffReader.ForEmbedded(m.Stream, start, littleEndian: true); + MakerNoteParser.Vendor(reader, BinaryPrimitives.ReadUInt32LittleEndian(header[8..]), m, ParseIfd); + m.AddWarnings(reader.Warnings); + } + + private static void ParseIfd(TiffReader r, Ifd ifd, MetadataBuilder m) + { + var v = m.MakerNote; + v.BodySerial ??= IfdValue.String(r, ifd, SerialNumber); + v.ColorTemperature ??= IfdValue.Int(r, ifd, ColorTemperature) is { } kelvin and > 0 and < 65535 ? kelvin : null; + // [0] type (0 none, 1 optical, 2 sensor-shift, …), [1] mode (0 off, 1/2 on). + if (IfdValue.UInts(r, ifd, ImageStabilization) is [var type, var mode, ..]) + v.ImageStabilization ??= type != 0 && mode != 0; + } +} diff --git a/src/Titano.Core/Metadata/MakerNotes/MakerNoteParser.cs b/src/Titano.Core/Metadata/MakerNotes/MakerNoteParser.cs new file mode 100644 index 00000000..578d1b6b --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/MakerNoteParser.cs @@ -0,0 +1,81 @@ +using System.Globalization; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.MakerNotes; + +/// +/// Locates the vendor IFD inside an Exif MakerNote (by header signature, then by camera make) and hands it to the +/// vendor parser. Best effort: unknown layouts are skipped, and every read goes through the bounds-checked +/// . +/// +internal static class MakerNoteParser +{ + private const int HeaderBytes = 16; + + /// Reader of the TIFF block holding the Exif IFD (base and byte order of relative offsets). + /// The Exif 0x927C entry. + public static void Parse(TiffReader exif, IfdEntry makerNote, MetadataBuilder m) + { + if (makerNote.IsInline || makerNote.ByteLength < 14) return; + var start = makerNote.ValuePosition(exif.Base); + if (start < exif.Base || start > m.Length - makerNote.ByteLength) + { + m.Warn("MakerNote outside the file"); + return; + } + Span head = stackalloc byte[HeaderBytes]; + var h = head[..m.Stream.ReadUpTo(start, head[..(int)Math.Min(HeaderBytes, makerNote.ByteLength)])]; + var make = m.Make ?? string.Empty; + var relative = (uint)(start - exif.Base); + + if (h.StartsWith("Nikon\0"u8)) + { + NikonMakerNote.Parse(exif, start, h, m); + } + else if (h.StartsWith("OLYMPUS\0"u8) || h.StartsWith("OM SYSTEM\0"u8) || h.StartsWith("OLYMP\0"u8)) + { + OlympusMakerNote.Parse(exif, start, h, m); + } + else if (h.StartsWith("FUJIFILM"u8)) + { + FujifilmMakerNote.Parse(m, start, h); + } + else if (h.StartsWith("Panasonic\0"u8)) + { + Vendor(exif, relative + 12, m, PanasonicMakerNote.Parse); + } + else if (h.StartsWith("SONY"u8)) + { + Vendor(exif, relative + 12, m, SonyMakerNote.Parse); + } + else if (make.StartsWith("Canon", StringComparison.OrdinalIgnoreCase)) + { + Vendor(exif, relative, m, CanonMakerNote.Parse); + } + else if (make.StartsWith("NIKON", StringComparison.OrdinalIgnoreCase)) + { + Vendor(exif, relative, m, NikonMakerNote.ParseIfd); + } + else if (make.StartsWith("SONY", StringComparison.OrdinalIgnoreCase)) + { + Vendor(exif, relative, m, SonyMakerNote.Parse); + } + } + + /// Reads the IFD at a base-relative offset with and runs on it. + internal static void Vendor(TiffReader reader, uint offset, MetadataBuilder m, Action parse) + { + if (reader.ReadIfd(offset) is { } ifd) parse(reader, ifd, m); + else m.Warn("MakerNote IFD unreadable"); + } + + /// "24-70mm f/2.8", "50mm f/1.8" or "18-55mm F3.5-5.6" from focal-length and aperture ranges. + internal static string FormatLens(double minFocal, double maxFocal, double minAperture, double maxAperture, string aperturePrefix) + { + static string N(double v) => Math.Round(v, 1).ToString("0.#", CultureInfo.InvariantCulture); + var focal = maxFocal > minFocal ? $"{N(minFocal)}-{N(maxFocal)}mm" : $"{N(minFocal)}mm"; + if (minAperture <= 0) return focal; + var aperture = maxAperture > minAperture ? $"{N(minAperture)}-{N(maxAperture)}" : N(minAperture); + return $"{focal} {aperturePrefix}{aperture}"; + } +} diff --git a/src/Titano.Core/Metadata/MakerNotes/MakerNoteValues.cs b/src/Titano.Core/Metadata/MakerNotes/MakerNoteValues.cs new file mode 100644 index 00000000..9d2625b9 --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/MakerNoteValues.cs @@ -0,0 +1,12 @@ +namespace Titano.Core.Metadata.MakerNotes; + +/// Values recovered from a vendor MakerNote. They fill a field only when the standard tags left it empty. +internal sealed class MakerNoteValues +{ + public string? BodySerial { get; set; } + public string? LensModel { get; set; } + public long? ShutterCount { get; set; } + public bool? ImageStabilization { get; set; } + public int? Iso { get; set; } + public int? ColorTemperature { get; set; } +} diff --git a/src/Titano.Core/Metadata/MakerNotes/NikonMakerNote.cs b/src/Titano.Core/Metadata/MakerNotes/NikonMakerNote.cs new file mode 100644 index 00000000..a7e50bb7 --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/NikonMakerNote.cs @@ -0,0 +1,54 @@ +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.MakerNotes; + +/// Nikon MakerNote. Type 3 ("Nikon\0" + version 2.x) embeds its own TIFF header 10 bytes in; type 1 +/// ("Nikon\0" + version 1) has an IFD at +8 and headerless type 2 an IFD at +0, both relative to the Exif TIFF. +internal static class NikonMakerNote +{ + private const ushort Iso = 0x0002; + private const ushort SerialNumber = 0x001D; + private const ushort VrInfo = 0x001F; + private const ushort Lens = 0x0084; + private const ushort ShutterCount = 0x00A7; + + public static void Parse(TiffReader exif, long start, ReadOnlySpan header, MetadataBuilder m) + { + if (header.Length > 6 && header[6] == 2) + { + if (TiffReader.Open(m.Stream, start + 10) is { } inner) + { + MakerNoteParser.Vendor(inner, inner.FirstIfdOffset, m, ParseIfd); + m.AddWarnings(inner.Warnings); + } + else + { + m.Warn("Nikon MakerNote TIFF header missing"); + } + } + else + { + MakerNoteParser.Vendor(exif, (uint)(start - exif.Base + 8), m, ParseIfd); + } + } + + public static void ParseIfd(TiffReader r, Ifd ifd, MetadataBuilder m) + { + var v = m.MakerNote; + v.BodySerial ??= IfdValue.String(r, ifd, SerialNumber); + v.ShutterCount ??= IfdValue.UInt(r, ifd, ShutterCount); + v.Iso ??= IfdValue.UInts(r, ifd, Iso) is [_, var iso, ..] && iso is > 0 and <= int.MaxValue ? (int)iso : null; + if (IfdValue.Doubles(r, ifd, Lens, 4) is [var minFocal, var maxFocal, var minAperture, var maxAperture, ..] && minFocal > 0) + v.LensModel ??= MakerNoteParser.FormatLens(minFocal, maxFocal, minAperture, maxAperture, "f/"); + if (ifd.Entries.TryGetValue(VrInfo, out var vr) && vr.Count is >= 5 and <= 64 && r.ReadBytes(vr) is { } bytes) + { + // Byte 4: 1 = on, 2 = off. + v.ImageStabilization ??= bytes[4] switch + { + 1 => true, + 2 => false, + _ => null, + }; + } + } +} diff --git a/src/Titano.Core/Metadata/MakerNotes/OlympusMakerNote.cs b/src/Titano.Core/Metadata/MakerNotes/OlympusMakerNote.cs new file mode 100644 index 00000000..e00e90b5 --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/OlympusMakerNote.cs @@ -0,0 +1,66 @@ +using Titano.Core.Metadata.Jpeg; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.MakerNotes; + +/// +/// Olympus / OM System MakerNote. "OLYMPUS\0II\3\0" (IFD at +12) and "OM SYSTEM\0\0\0II\4\0" (IFD at +16) use offsets +/// relative to the MakerNote start and their own byte order; legacy "OLYMP\0" has its IFD at +8 relative to the +/// Exif TIFF. Equipment (0x2010) gives serial and lens; CameraSettings (0x2020) gives the ORF preview and stabiliser. +/// +internal static class OlympusMakerNote +{ + private const ushort Equipment = 0x2010; + private const ushort CameraSettings = 0x2020; + private const ushort EquipmentSerialNumber = 0x0101; + private const ushort EquipmentLensModel = 0x0203; + private const ushort PreviewImageValid = 0x0100; + private const ushort PreviewImageStart = 0x0101; + private const ushort PreviewImageLength = 0x0102; + private const ushort ImageStabilization = 0x0604; + + public static void Parse(TiffReader exif, long start, ReadOnlySpan header, MetadataBuilder m) + { + if (header.StartsWith("OLYMP\0"u8)) + { + MakerNoteParser.Vendor(exif, (uint)(start - exif.Base + 8), m, ParseIfd); + return; + } + var orderAt = header.StartsWith("OM SYSTEM\0"u8) ? 12 : 8; + if (header.Length < orderAt + 4 || header[orderAt] != header[orderAt + 1] || header[orderAt] is not ((byte)'I' or (byte)'M')) + { + m.Warn("Olympus MakerNote header malformed"); + return; + } + var reader = TiffReader.ForEmbedded(m.Stream, start, header[orderAt] == 'I'); + MakerNoteParser.Vendor(reader, (uint)(orderAt + 4), m, ParseIfd); + m.AddWarnings(reader.Warnings); + } + + private static void ParseIfd(TiffReader r, Ifd ifd, MetadataBuilder m) + { + var v = m.MakerNote; + if (SubIfd(r, ifd, Equipment) is { } equipment) + { + v.BodySerial ??= IfdValue.String(r, equipment, EquipmentSerialNumber); + v.LensModel ??= IfdValue.String(r, equipment, EquipmentLensModel); + } + if (SubIfd(r, ifd, CameraSettings) is not { } settings) return; + v.ImageStabilization ??= IfdValue.UInt(r, settings, ImageStabilization) switch + { + 0 => false, + >= 1 and <= 4 => true, + _ => null, + }; + if (IfdValue.UInt(r, settings, PreviewImageValid) != 0 + && IfdValue.UInt(r, settings, PreviewImageStart) is { } offset and > 0 + && IfdValue.UInt(r, settings, PreviewImageLength) is { } length and > 0) + { + JpegParser.AddPreview(m, r.Base + offset, length); + } + } + + /// Sub-IFD stored either as an IFD/LONG pointer or as an UNDEFINED block; both resolve to the value offset. + private static Ifd? SubIfd(TiffReader r, Ifd ifd, ushort tag) => + ifd.Entries.TryGetValue(tag, out var e) && !(e.IsInline && e.Type == TiffType.Undefined) ? r.ReadIfd(e.ValueOffset) : null; +} diff --git a/src/Titano.Core/Metadata/MakerNotes/PanasonicMakerNote.cs b/src/Titano.Core/Metadata/MakerNotes/PanasonicMakerNote.cs new file mode 100644 index 00000000..9709903c --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/PanasonicMakerNote.cs @@ -0,0 +1,27 @@ +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.MakerNotes; + +/// Panasonic MakerNote: "Panasonic\0\0\0" then an IFD whose offsets are relative to the Exif TIFF. +internal static class PanasonicMakerNote +{ + private const ushort ImageStabilization = 0x001A; + private const ushort InternalSerialNumber = 0x0025; + private const ushort ColorTempKelvin = 0x0044; + private const ushort LensType = 0x0051; + + public static void Parse(TiffReader r, Ifd ifd, MetadataBuilder m) + { + var v = m.MakerNote; + v.BodySerial ??= IfdValue.String(r, ifd, InternalSerialNumber); + v.LensModel ??= IfdValue.String(r, ifd, LensType); + v.ColorTemperature ??= IfdValue.Int(r, ifd, ColorTempKelvin) is { } kelvin and > 0 and < 65535 ? kelvin : null; + // 3 = off; 2, 4–7, 9–12 = optical/body/dual IS modes. + v.ImageStabilization ??= IfdValue.UInt(r, ifd, ImageStabilization) switch + { + 3 => false, + 2 or (>= 4 and <= 7) or (>= 9 and <= 12) => true, + _ => null, + }; + } +} diff --git a/src/Titano.Core/Metadata/MakerNotes/SonyMakerNote.cs b/src/Titano.Core/Metadata/MakerNotes/SonyMakerNote.cs new file mode 100644 index 00000000..692a129b --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/SonyMakerNote.cs @@ -0,0 +1,46 @@ +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.MakerNotes; + +/// Sony MakerNote ("SONY DSC/CAM" 12-byte header or headerless; offsets relative to the Exif TIFF). +/// Lens: the unencrypted LensSpec (BCD focal/aperture range); numeric LensType tables are not shipped. +internal static class SonyMakerNote +{ + private const ushort ColorTemperature = 0xB021; + private const ushort ImageStabilization = 0xB026; + private const ushort LensSpec = 0xB02A; + + public static void Parse(TiffReader r, Ifd ifd, MetadataBuilder m) + { + var v = m.MakerNote; + if (ifd.Entries.TryGetValue(LensSpec, out var spec) && spec.Count == 8 && r.ReadBytes(spec) is { } bytes) + v.LensModel ??= DecodeLensSpec(bytes); + v.ColorTemperature ??= IfdValue.UInt(r, ifd, ColorTemperature) is { } kelvin and > 0 and < 65535 ? (int)kelvin : null; + v.ImageStabilization ??= IfdValue.UInt(r, ifd, ImageStabilization) switch + { + 0 => false, + 1 => true, + _ => null, + }; + } + + /// Bytes 1–2 short focal, 3–4 long focal (BCD mm), 5–6 apertures (BCD ×10); flags 0 and 7 are not decoded. + private static string? DecodeLensSpec(ReadOnlySpan s) + { + if (!TryBcd(s.Slice(1, 2), out var minFocal) || !TryBcd(s.Slice(3, 2), out var maxFocal) + || !TryBcd(s.Slice(5, 1), out var minAperture) || !TryBcd(s.Slice(6, 1), out var maxAperture) || minFocal == 0) + return null; + return MakerNoteParser.FormatLens(minFocal, maxFocal, minAperture / 10.0, maxAperture / 10.0, "F"); + } + + private static bool TryBcd(ReadOnlySpan bytes, out int value) + { + value = 0; + foreach (var b in bytes) + { + if (b >> 4 > 9 || (b & 0xF) > 9) return false; + value = value * 100 + (b >> 4) * 10 + (b & 0xF); + } + return true; + } +} diff --git a/src/Titano.Core/Metadata/MetadataBuilder.cs b/src/Titano.Core/Metadata/MetadataBuilder.cs new file mode 100644 index 00000000..f55fe60e --- /dev/null +++ b/src/Titano.Core/Metadata/MetadataBuilder.cs @@ -0,0 +1,250 @@ +using Titano.Core.Imaging; +using Titano.Core.Metadata.MakerNotes; +using Titano.Core.Metadata.Xmp; +using Titano.Core.Model; + +namespace Titano.Core.Metadata; + +/// +/// Mutable accumulator shared by the container parsers. Parsers assign standard values with ??= in the order +/// of authority (so the first source wins); MakerNote and XMP values are kept apart and applies +/// every fallback chain in one place. +/// +internal sealed class MetadataBuilder +{ + private const int MaxWarnings = 64; + private const int MaxPreviews = 32; + private const int MaxRasters = 64; + private const int ThumbnailLongEdge = 640; + private const double FullSizeRatio = 0.9; + private const int SaturatedIso = 65535; + + private readonly List _warnings = []; + private readonly List _previews = []; + private readonly List _rasters = []; + private Raster? _container; + + public MetadataBuilder(Stream stream, CancellationToken cancellation) + { + Stream = stream; + Length = stream.Length; + Cancellation = cancellation; + } + + public Stream Stream { get; } + public long Length { get; } + public CancellationToken Cancellation { get; } + public ImageFileFormat Format { get; set; } + + public string? Make { get; set; } + public string? Model { get; set; } + public string? BodySerial { get; set; } + public string? LensModel { get; set; } + public string? Software { get; set; } + public string? Artist { get; set; } + public string? Copyright { get; set; } + public CaptureStamp? DateTimeOriginal { get; set; } + public CaptureStamp? DateTimeDigitized { get; set; } + public double? ExposureTime { get; set; } + public double? FNumber { get; set; } + + /// Exif ISOSpeedRatings (first value); 65535 means "at least 65535". + public int? IsoSpeedRatings { get; set; } + + /// RecommendedExposureIndex, StandardOutputSensitivity, ISOSpeed or a RAW-header ISO. + public int? IsoFallback { get; set; } + + public double? FocalLength { get; set; } + public double? FocalLength35 { get; set; } + public double? ExposureBias { get; set; } + public int? ExposureProgram { get; set; } + public int? MeteringMode { get; set; } + public int? WhiteBalanceMode { get; set; } + public int? Flash { get; set; } + + /// Raw Exif/TIFF orientation value (validated in ). + public int? ExifOrientation { get; set; } + + /// Orientation implied by container transforms (HEIF irot/imir); overrides Exif. + public int? ContainerOrientation { get; set; } + + public int? PixelXDimension { get; set; } + public int? PixelYDimension { get; set; } + + /// Bit depth of the coded main image when the container states it apart from the raster size (CR2 lossless-JPEG + /// SOF3, RAF FujiIFD, HEIF pixi); preferred over IFD BitsPerSample. + public int? CodedBitsPerSample { get; set; } + + /// GPS position without its timestamp (merged in ). + public GpsPosition? Gps { get; set; } + + public DateTime? GpsUtc { get; set; } + public int? ExifRating { get; set; } + public MakerNoteValues MakerNote { get; } = new(); + public XmpValues Xmp { get; } = new(); + public IReadOnlyList Warnings => _warnings; + + public void Warn(string message) + { + if (_warnings.Count < MaxWarnings && !_warnings.Contains(message)) _warnings.Add(message); + } + + public void AddWarnings(IEnumerable messages) + { + foreach (var message in messages) Warn(message); + } + + public void ThrowIfCancelled() => Cancellation.ThrowIfCancellationRequested(); + + /// Main-image size defined by the container itself (JPEG SOF, PNG IHDR, HEIF ispe, RAF header…); first call wins + /// and it overrides TIFF raster IFDs. + public void SetContainerSize(int width, int height, int? bitsPerSample = null) + { + if (_container is null && width > 0 && height > 0) _container = new Raster(width, height, bitsPerSample, true); + } + + /// A raster IFD; is false for reduced-resolution images (NewSubfileType bit 0). + public void AddRaster(int width, int height, int? bitsPerSample, bool primary) + { + if (width > 0 && height > 0 && _rasters.Count < MaxRasters) _rasters.Add(new Raster(width, height, bitsPerSample, primary)); + } + + /// Records a validated embedded JPEG; duplicates (same offset) keep the first. + public void AddPreview(long offset, long length, int width, int height, PreviewKind? kind = null) + { + if (width <= 0 || height <= 0 || length <= 0 || _previews.Count >= MaxPreviews) return; + foreach (var p in _previews) + { + if (p.Offset == offset) return; + } + _previews.Add(new PreviewCandidate(offset, length, width, height, kind)); + } + + public void AddXmp(byte[]? packet) + { + if (packet is not null && XmpParser.Parse(packet, Xmp) is { } problem) Warn(problem); + } + + /// Applies the fallback rules and produces the immutable result. + /// File modification time; used when no capture time is recorded. + public FrameMetadata Build(DateTime? fileModified) + { + var main = _container ?? BestRaster() ?? (PixelXDimension is > 0 && PixelYDimension is > 0 + ? new Raster(PixelXDimension.Value, PixelYDimension.Value, null, true) + : default(Raster?)); + var (captured, offset, source) = ResolveCaptureTime(fileModified); + var orientation = ResolveOrientation(); + return new FrameMetadata + { + Format = Format, + Make = Make, + Model = Model, + BodySerial = BodySerial ?? MakerNote.BodySerial ?? Xmp.BodySerial, + LensModel = LensModel ?? MakerNote.LensModel ?? Xmp.Lens, + Software = Software, + Artist = Artist, + Copyright = Copyright, + CapturedAt = captured, + UtcOffsetMinutes = offset, + TimestampSource = source, + ExposureTime = ExposureTime, + FNumber = FNumber, + Iso = ResolveIso(), + FocalLength = FocalLength, + FocalLength35 = FocalLength35, + ExposureBias = ExposureBias, + ExposureProgram = ExposureProgram, + MeteringMode = MeteringMode, + WhiteBalanceMode = WhiteBalanceMode, + ColorTemperature = MakerNote.ColorTemperature, + Flash = Flash, + Orientation = orientation, + Width = main?.Width ?? 0, + Height = main?.Height ?? 0, + BitsPerSample = CodedBitsPerSample ?? main?.Bits, + Gps = Gps is { } g ? g with { UtcTimestamp = GpsUtc } : null, + Rating = Xmp.Rating ?? (ExifRating is >= -1 and <= 5 ? ExifRating : null), + Label = Xmp.Label, + ShutterCount = MakerNote.ShutterCount, + ImageStabilization = MakerNote.ImageStabilization, + Previews = ResolvePreviews(main is { } m ? Math.Max(m.Width, m.Height) : 0), + Warnings = _warnings.ToArray(), + }; + } + + /// Largest full-resolution raster (NewSubfileType bit 0 clear); any raster when none is full-resolution. + private Raster? BestRaster() + { + Raster? best = null; + foreach (var r in _rasters) + { + if (best is not { } b || (r.Primary && !b.Primary) || (r.Primary == b.Primary && r.Area > b.Area)) best = r; + } + return best; + } + + /// Exif original → Exif digitized → XMP → GPS (UTC) → file time. + private (DateTime? Value, int? Offset, TimestampSource Source) ResolveCaptureTime(DateTime? fileModified) + { + if (DateTimeOriginal is { } original) return (original.Value, original.OffsetMinutes, TimestampSource.ExifOriginal); + if (DateTimeDigitized is { } digitized) return (digitized.Value, digitized.OffsetMinutes, TimestampSource.ExifCreate); + if (Xmp.CaptureTime is { } xmp) return (xmp.Value, xmp.OffsetMinutes, TimestampSource.Xmp); + if (GpsUtc is { } utc) return (DateTime.SpecifyKind(utc, DateTimeKind.Unspecified), 0, TimestampSource.Gps); + if (fileModified is { } file) + { + int? fileOffset = file.Kind switch + { + DateTimeKind.Local => (int)TimeZoneInfo.Local.GetUtcOffset(file).TotalMinutes, + DateTimeKind.Utc => 0, + _ => null, + }; + return (DateTime.SpecifyKind(file, DateTimeKind.Unspecified), fileOffset, TimestampSource.FileSystem); + } + return (null, null, TimestampSource.Unknown); + } + + /// ISOSpeedRatings unless absent or saturated (65535), then REI/SOS/ISOSpeed, then the MakerNote. + private int? ResolveIso() + { + if (IsoSpeedRatings is > 0 and < SaturatedIso) return IsoSpeedRatings; + return (IsoFallback is > 0 ? IsoFallback : null) + ?? (MakerNote.Iso is > 0 ? MakerNote.Iso : null) + ?? (IsoSpeedRatings is > 0 ? IsoSpeedRatings : null); + } + + private int ResolveOrientation() + { + if (ContainerOrientation is >= 1 and <= 8) return ContainerOrientation.Value; + if (ExifOrientation is >= 1 and <= 8) return ExifOrientation.Value; + if (ExifOrientation is { } invalid) Warn($"Invalid orientation {invalid} ignored"); + return Xmp.Orientation ?? 1; + } + + /// Largest first; kinds by long edge: < 640 px thumbnail, ≥ 90 % of the main image full size. + private EmbeddedPreview[] ResolvePreviews(int mainLongEdge) + { + var result = new EmbeddedPreview[_previews.Count]; + for (var i = 0; i < result.Length; i++) + { + var p = _previews[i]; + var longEdge = Math.Max(p.Width, p.Height); + var kind = p.Kind ?? (longEdge < ThumbnailLongEdge ? PreviewKind.Thumbnail + : mainLongEdge > 0 && longEdge >= FullSizeRatio * mainLongEdge ? PreviewKind.FullSize + : PreviewKind.Preview); + result[i] = new EmbeddedPreview(p.Offset, p.Length, p.Width, p.Height, kind); + } + Array.Sort(result, static (a, b) => + { + var byArea = ((long)b.Width * b.Height).CompareTo((long)a.Width * a.Height); + return byArea != 0 ? byArea : b.Length.CompareTo(a.Length); + }); + return result; + } + + private readonly record struct Raster(int Width, int Height, int? Bits, bool Primary) + { + public long Area => (long)Width * Height; + } + + private readonly record struct PreviewCandidate(long Offset, long Length, int Width, int Height, PreviewKind? Kind); +} diff --git a/src/Titano.Core/Metadata/MetadataDates.cs b/src/Titano.Core/Metadata/MetadataDates.cs new file mode 100644 index 00000000..77d38baf --- /dev/null +++ b/src/Titano.Core/Metadata/MetadataDates.cs @@ -0,0 +1,112 @@ +namespace Titano.Core.Metadata; + +/// Camera wall-clock time (DateTimeKind.Unspecified) plus the UTC offset when the file records one. +internal readonly record struct CaptureStamp(DateTime Value, int? OffsetMinutes); + +/// Parsers for Exif ("YYYY:MM:DD HH:MM:SS"), sub-second, UTC-offset, GPS-date and XMP (ISO 8601) strings. +/// Blank, zeroed or out-of-range values yield null rather than a guess. +internal static class MetadataDates +{ + private const int MaxOffsetMinutes = 14 * 60; + + /// Exif date-time; separators are not checked so "YYYY-MM-DD HH:MM:SS" also parses. + public static DateTime? ParseExif(string? text) + { + if (text is null) return null; + var s = text.AsSpan().Trim(); + if (s.Length < 19) return null; + return Number(s, 0, 4) is { } y && Number(s, 5, 2) is { } mo && Number(s, 8, 2) is { } d + && Number(s, 11, 2) is { } h && Number(s, 14, 2) is { } mi && Number(s, 17, 2) is { } sec + ? Create(y, mo, d, h, mi, sec, 0) + : null; + } + + /// Exif date ("YYYY:MM:DD", e.g. GPSDateStamp) at midnight. + public static DateTime? ParseDate(string? text) + { + if (text is null) return null; + var s = text.AsSpan().Trim(); + if (s.Length < 10) return null; + return Number(s, 0, 4) is { } y && Number(s, 5, 2) is { } mo && Number(s, 8, 2) is { } d ? Create(y, mo, d, 0, 0, 0, 0) : null; + } + + /// SubSecTime digits as a fraction of a second in ticks ("5" → 0.5 s, "123" → 0.123 s). + public static long SubSecondTicks(string? text) + { + if (text is null) return 0; + long ticks = 0; + var digits = 0; + foreach (var c in text.AsSpan().Trim()) + { + if (c is < '0' or > '9' || digits == 7) break; + ticks = ticks * 10 + (c - '0'); + digits++; + } + if (digits == 0) return 0; + for (; digits < 7; digits++) ticks *= 10; + return ticks; + } + + /// "+HH:MM", "-HH:MM", "+HHMM" or "Z" as minutes east of UTC. + public static int? ParseOffset(ReadOnlySpan text) + { + var s = text.Trim(); + if (s is "Z") return 0; + if (s.Length < 5 || s[0] is not ('+' or '-')) return null; + var minuteStart = s[3] == ':' ? 4 : 3; + if (Number(s, 1, 2) is not { } h || Number(s, minuteStart, 2) is not { } m || m > 59) return null; + var total = h * 60 + m; + if (total > MaxOffsetMinutes) return null; + return s[0] == '-' ? -total : total; + } + + public static int? ParseOffset(string? text) => text is null ? null : ParseOffset(text.AsSpan()); + + /// XMP date "YYYY-MM-DDThh:mm[:ss[.f…]][Z|±hh:mm]"; Exif-style ':' date separators are tolerated. + /// Date-only values return null because midnight would be a fabricated capture time. + public static CaptureStamp? ParseIso8601(string? text) + { + if (text is null) return null; + var s = text.AsSpan().Trim(); + if (s.Length < 16 || s[10] is not ('T' or ' ')) return null; + if (Number(s, 0, 4) is not { } y || Number(s, 5, 2) is not { } mo || Number(s, 8, 2) is not { } d + || Number(s, 11, 2) is not { } h || Number(s, 14, 2) is not { } mi) + return null; + var pos = 16; + var sec = 0; + long ticks = 0; + if (pos < s.Length && s[pos] == ':') + { + if (Number(s, 17, 2) is not { } parsed) return null; + sec = parsed; + pos = 19; + if (pos < s.Length && s[pos] is '.' or ',') + { + var end = pos + 1; + while (end < s.Length && char.IsAsciiDigit(s[end])) end++; + ticks = SubSecondTicks(s[(pos + 1)..end].ToString()); + pos = end; + } + } + var offset = pos < s.Length ? ParseOffset(s[pos..]) : null; + return Create(y, mo, d, h, mi, sec, ticks) is { } value ? new CaptureStamp(value, offset) : null; + } + + private static int? Number(ReadOnlySpan s, int start, int length) + { + if (start + length > s.Length) return null; + var value = 0; + foreach (var c in s.Slice(start, length)) + { + if (!char.IsAsciiDigit(c)) return null; + value = value * 10 + (c - '0'); + } + return value; + } + + private static DateTime? Create(int y, int mo, int d, int h, int mi, int s, long ticks) + { + if (y < 1 || mo is < 1 or > 12 || d < 1 || d > DateTime.DaysInMonth(y, mo) || h > 23 || mi > 59 || s > 59) return null; + return new DateTime(y, mo, d, h, mi, s, DateTimeKind.Unspecified).AddTicks(ticks); + } +} diff --git a/src/Titano.Core/Metadata/MetadataReader.cs b/src/Titano.Core/Metadata/MetadataReader.cs new file mode 100644 index 00000000..74bca4df --- /dev/null +++ b/src/Titano.Core/Metadata/MetadataReader.cs @@ -0,0 +1,110 @@ +using Titano.Core.Diagnostics; +using Titano.Core.Imaging; +using Titano.Core.Metadata.Bmff; +using Titano.Core.Metadata.Jpeg; +using Titano.Core.Metadata.Png; +using Titano.Core.Metadata.Raf; +using Titano.Core.Metadata.Riff; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata; + +/// +/// Reads from any supported photo (BRIEF §9). Detects the container by signature, then +/// reads only the structures it needs through bounded seeks (a RAW's image data is never read). Malformed input never +/// throws: the result carries whatever was readable plus . +/// +public static class MetadataReader +{ + private const string LogCategory = "Metadata"; + private const int FileBufferSize = 4096; + + /// Reads the file at ; its modification time is the last-resort capture time. + /// The file cannot be opened (missing or locked). + /// Access to the file is denied. + public static FrameMetadata Read(string path, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrEmpty(path); + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileBufferSize, FileOptions.RandomAccess); + return Read(stream, Path.GetFileName(path), File.GetLastWriteTime(path), cancellationToken); + } + + /// Reads metadata from a readable, seekable stream (the position is left undefined). + /// Name used only to break signature ties (see ). + /// File time used when no capture time is recorded (); + /// its UTC offset is taken from the local zone for values. + /// Cancelled through . + public static FrameMetadata Read(Stream stream, string? fileName, DateTime? fileModifiedLocal = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(stream); + if (!stream.CanSeek || !stream.CanRead) throw new ArgumentException("The stream must be readable and seekable.", nameof(stream)); + cancellationToken.ThrowIfCancellationRequested(); + var m = new MetadataBuilder(stream, cancellationToken); + try + { + m.Format = ImageSignature.Detect(stream, fileName); + Parse(m); + } + catch (OperationCanceledException) + { + throw; + } + catch (IOException ex) + { + m.Warn("I/O error: " + ex.Message); + } + catch (Exception ex) + { + // Safety net: parsers are written not to throw, but a defect must cost one file's metadata, not the import. + m.Warn($"Parser fault: {ex.GetType().Name}: {ex.Message}"); + Log.Warning(LogCategory, $"Metadata parser fault in {fileName ?? "stream"}", ex); + } + return m.Build(fileModifiedLocal); + } + + private static void Parse(MetadataBuilder m) + { + switch (m.Format) + { + case ImageFileFormat.Jpeg: + JpegParser.Parse(m, 0, m.Length, primary: true); + break; + case ImageFileFormat.Png: + PngParser.Parse(m); + break; + case ImageFileFormat.WebP: + WebPParser.Parse(m); + break; + case ImageFileFormat.Heif or ImageFileFormat.Avif: + HeifParser.Parse(m); + break; + case ImageFileFormat.Cr3: + Cr3Parser.Parse(m); + break; + case ImageFileFormat.Raf: + RafParser.Parse(m); + break; + case ImageFileFormat.Gif: + MinimalFormatParser.ParseGif(m); + break; + case ImageFileFormat.Bmp: + MinimalFormatParser.ParseBmp(m); + break; + case ImageFileFormat.JpegXr: + MinimalFormatParser.ParseJpegXr(m); + break; + case ImageFileFormat.JpegXl: + MinimalFormatParser.ParseJpegXl(m); + break; + case ImageFileFormat.Crw: + m.Warn("CRW (CIFF) metadata is not supported"); + break; + case ImageFileFormat.Unknown: + m.Warn("Unrecognised file signature"); + break; + default: + ExifParser.ParseFile(m); + break; + } + } +} diff --git a/src/Titano.Core/Metadata/MinimalFormatParser.cs b/src/Titano.Core/Metadata/MinimalFormatParser.cs new file mode 100644 index 00000000..7b561690 --- /dev/null +++ b/src/Titano.Core/Metadata/MinimalFormatParser.cs @@ -0,0 +1,119 @@ +using System.Buffers.Binary; +using Titano.Core.Metadata.Bmff; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Metadata.Xmp; + +namespace Titano.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; + } + } +} diff --git a/src/Titano.Core/Metadata/Png/PngParser.cs b/src/Titano.Core/Metadata/Png/PngParser.cs new file mode 100644 index 00000000..af7ff78e --- /dev/null +++ b/src/Titano.Core/Metadata/Png/PngParser.cs @@ -0,0 +1,111 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Metadata.Xmp; + +namespace Titano.Core.Metadata.Png; + +/// PNG chunks: IHDR (size, bit depth), eXIf (TIFF), iTXt/tEXt "XML:com.adobe.xmp" (XMP, zlib-compressed iTXt +/// supported). Image data chunks are skipped by seeking; CRCs are not verified. +internal static class PngParser +{ + private const int MaxChunks = 4096; + private const int KeywordProbeBytes = 80; + private static ReadOnlySpan XmpKeyword => "XML:com.adobe.xmp\0"u8; + + public static void Parse(MetadataBuilder m) + { + var s = m.Stream; + Span head = stackalloc byte[8 + 13]; + long pos = 8; + for (var i = 0; i < MaxChunks; i++) + { + m.ThrowIfCancelled(); + var n = s.ReadUpTo(pos, head); + if (n < 8) + { + m.Warn("PNG truncated before IEND"); + return; + } + var length = BinaryPrimitives.ReadUInt32BigEndian(head); + var type = head.Slice(4, 4); + var data = pos + 8; + if (length > int.MaxValue || data > m.Length - length) + { + m.Warn("PNG chunk runs past the end of the file"); + return; + } + if (type.SequenceEqual("IHDR"u8) && length >= 13 && n == head.Length) + { + var width = BinaryPrimitives.ReadUInt32BigEndian(head[8..]); + var height = BinaryPrimitives.ReadUInt32BigEndian(head[12..]); + if (width <= int.MaxValue && height <= int.MaxValue) m.SetContainerSize((int)width, (int)height, head[16]); + } + else if (type.SequenceEqual("eXIf"u8) && length >= 8) + { + var exif = n >= 14 && head[8..].StartsWith("Exif\0\0"u8) ? data + 6 : data; + ExifParser.ParseEmbedded(m, exif); + } + else if (type.SequenceEqual("iTXt"u8) || type.SequenceEqual("tEXt"u8)) + { + ReadText(m, data, (int)length, international: type[0] == 'i'); + } + else if (type.SequenceEqual("IEND"u8)) + { + return; + } + pos = data + length + 4; + } + m.Warn("PNG has too many chunks; rest ignored"); + } + + /// XMP text chunk: keyword "XML:com.adobe.xmp"; iTXt adds compression flag/method, language and translated keyword. + private static void ReadText(MetadataBuilder m, long data, int length, bool international) + { + Span probe = stackalloc byte[XmpKeyword.Length]; + if (length < probe.Length || !m.Stream.TryReadAt(data, probe) || !probe.SequenceEqual(XmpKeyword)) return; + if (m.Stream.ReadAt(data, length, XmpParser.MaxPacketBytes + KeywordProbeBytes) is not { } chunk) + { + m.Warn("PNG XMP chunk too large"); + return; + } + var r = new SpanReader(chunk); + r.Skip(XmpKeyword.Length); + var compressed = false; + if (international) + { + compressed = r.U8() == 1; + r.Skip(1); + r.CString(); + r.CString(); + } + if (!r.Ok) return; + var text = chunk.AsMemory(r.Position); + if (!compressed) + { + m.AddXmp(text.ToArray()); + return; + } + try + { + using var z = new ZLibStream(new MemoryStream(chunk, r.Position, text.Length, writable: false), CompressionMode.Decompress); + using var packet = new MemoryStream(); + var buffer = new byte[16 * 1024]; + int read; + while ((read = z.Read(buffer)) > 0) + { + if (packet.Length + read > XmpParser.MaxPacketBytes) + { + m.Warn("PNG XMP larger than 4 MB ignored"); + return; + } + packet.Write(buffer, 0, read); + } + m.AddXmp(packet.ToArray()); + } + catch (InvalidDataException) + { + m.Warn("PNG compressed XMP is corrupt"); + } + } +} diff --git a/src/Titano.Core/Metadata/Raf/RafParser.cs b/src/Titano.Core/Metadata/Raf/RafParser.cs new file mode 100644 index 00000000..ac4631e6 --- /dev/null +++ b/src/Titano.Core/Metadata/Raf/RafParser.cs @@ -0,0 +1,81 @@ +using System.Buffers.Binary; +using System.Text; +using Titano.Core.Metadata.Jpeg; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.Raf; + +/// +/// Fujifilm RAF: "FUJIFILMCCD-RAW " header with a big-endian directory (0x54 JPEG offset/length, 0x5C RAF-directory +/// offset/length, 0x64 CFA offset/length). Camera fields come from the embedded JPEG's Exif, which is also the +/// preview; the main size from the RAF directory records (0x0111 cropped, else 0x0100 full), bit depth from the +/// FujiIFD at the CFA offset when that is a TIFF block. +/// +internal static class RafParser +{ + private const int HeaderLength = 0x6C; + private const int MaxDirectoryBytes = 64 * 1024; + private const int MaxRecords = 512; + private const ushort RawImageFullSize = 0x0100; + private const ushort RawImageCroppedSize = 0x0111; + private const ushort FujiIfd = 0xF000; + private const ushort FujiRawWidth = 0xF001; + private const ushort FujiRawHeight = 0xF002; + private const ushort FujiBitsPerSample = 0xF003; + + public static void Parse(MetadataBuilder m) + { + var header = m.Stream.ReadAt(0, HeaderLength, HeaderLength); + if (header is null) + { + m.Warn("RAF header truncated"); + return; + } + var h = header.AsSpan(); + var jpegOffset = BinaryPrimitives.ReadUInt32BigEndian(h[0x54..]); + var jpegLength = BinaryPrimitives.ReadUInt32BigEndian(h[0x58..]); + if (jpegOffset >= HeaderLength && jpegLength > 0 && jpegOffset <= m.Length - jpegLength) + JpegParser.Parse(m, jpegOffset, (long)jpegOffset + jpegLength, primary: false); + else + m.Warn("RAF embedded JPEG missing"); + ReadDirectory(m, BinaryPrimitives.ReadUInt32BigEndian(h[0x5C..]), BinaryPrimitives.ReadUInt32BigEndian(h[0x60..])); + ReadFujiIfd(m, BinaryPrimitives.ReadUInt32BigEndian(h[0x64..])); + m.Make ??= "FUJIFILM"; + m.Model ??= Ascii(h.Slice(0x1C, 32)); + } + + /// RAF directory: u32 count, then (u16 tag, u16 size, data) records; sizes are (height, width) pairs. + private static void ReadDirectory(MetadataBuilder m, uint offset, uint length) + { + if (offset == 0 || m.Stream.ReadAt(offset, Math.Min(length, MaxDirectoryBytes), MaxDirectoryBytes) is not { } data) return; + var r = new SpanReader(data); + var count = Math.Min(r.U32(), MaxRecords); + (int Width, int Height) full = default, cropped = default; + for (var i = 0; i < count && r.Ok; i++) + { + var tag = r.U16(); + var record = r.Take(r.U16()); + if (!r.Ok || record.Length < 4) continue; + var size = (BinaryPrimitives.ReadUInt16BigEndian(record[2..]), BinaryPrimitives.ReadUInt16BigEndian(record)); + if (tag == RawImageFullSize) full = size; + else if (tag == RawImageCroppedSize) cropped = size; + } + var best = cropped.Width > 0 && cropped.Height > 0 ? cropped : full; + m.SetContainerSize(best.Width, best.Height); + } + + private static void ReadFujiIfd(MetadataBuilder m, uint offset) + { + if (offset == 0 || TiffReader.Open(m.Stream, offset) is not { } r) return; + if (r.ReadIfd(r.FirstIfdOffset) is not { } ifd0 || IfdValue.UInt(r, ifd0, FujiIfd) is not { } sub || r.ReadIfd(sub) is not { } fuji) return; + m.CodedBitsPerSample ??= IfdValue.Int(r, fuji, FujiBitsPerSample); + m.AddRaster(IfdValue.Int(r, fuji, FujiRawWidth) ?? 0, IfdValue.Int(r, fuji, FujiRawHeight) ?? 0, null, true); + } + + private static string? Ascii(ReadOnlySpan field) + { + var end = field.IndexOf((byte)0); + var s = Encoding.ASCII.GetString(end < 0 ? field : field[..end]).Trim(); + return s.Length > 0 && !s.Any(char.IsControl) ? s : null; + } +} diff --git a/src/Titano.Core/Metadata/Riff/WebPParser.cs b/src/Titano.Core/Metadata/Riff/WebPParser.cs new file mode 100644 index 00000000..89932943 --- /dev/null +++ b/src/Titano.Core/Metadata/Riff/WebPParser.cs @@ -0,0 +1,63 @@ +using System.Buffers.Binary; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Metadata.Xmp; + +namespace Titano.Core.Metadata.Riff; + +/// RIFF/WebP: canvas size from VP8X, else the VP8 key-frame or VP8L header; Exif from "EXIF" (with or without +/// an "Exif\0\0" prefix) and XMP from "XMP ". Image data is skipped by seeking. +internal static class WebPParser +{ + private const int MaxChunks = 1024; + + public static void Parse(MetadataBuilder m) + { + var s = m.Stream; + Span h = stackalloc byte[8 + 10]; + if (!s.TryReadAt(0, h[..12])) + { + m.Warn("WebP header truncated"); + return; + } + var end = Math.Min(m.Length, 8 + (long)BinaryPrimitives.ReadUInt32LittleEndian(h[4..])); + long pos = 12; + for (var i = 0; i < MaxChunks && pos <= end - 8; i++) + { + m.ThrowIfCancelled(); + var n = s.ReadUpTo(pos, h); + var size = BinaryPrimitives.ReadUInt32LittleEndian(h[4..]); + var data = pos + 8; + var payload = h[8..n]; + if (size > end - data) + { + m.Warn("WebP chunk runs past the end of the file"); + size = (uint)(end - data); + } + var fourCC = h[..4]; + if (fourCC.SequenceEqual("VP8X"u8) && payload.Length >= 10) + { + m.SetContainerSize(1 + UInt24(payload[4..]), 1 + UInt24(payload[7..]), 8); + } + else if (fourCC.SequenceEqual("VP8 "u8) && payload.Length >= 10 && payload[3..6].SequenceEqual((ReadOnlySpan)[0x9D, 0x01, 0x2A])) + { + m.SetContainerSize(BinaryPrimitives.ReadUInt16LittleEndian(payload[6..]) & 0x3FFF, BinaryPrimitives.ReadUInt16LittleEndian(payload[8..]) & 0x3FFF, 8); + } + else if (fourCC.SequenceEqual("VP8L"u8) && payload.Length >= 5 && payload[0] == 0x2F) + { + var bits = BinaryPrimitives.ReadUInt32LittleEndian(payload[1..]); + m.SetContainerSize((int)(bits & 0x3FFF) + 1, (int)((bits >> 14) & 0x3FFF) + 1, 8); + } + else if (fourCC.SequenceEqual("EXIF"u8) && size >= 8) + { + ExifParser.ParseEmbedded(m, payload.StartsWith("Exif\0\0"u8) ? data + 6 : data); + } + else if (fourCC.SequenceEqual("XMP "u8)) + { + m.AddXmp(s.ReadAt(data, size, XmpParser.MaxPacketBytes)); + } + pos = data + size + (size & 1); + } + } + + private static int UInt24(ReadOnlySpan b) => b[0] | b[1] << 8 | b[2] << 16; +} diff --git a/src/Titano.Core/Metadata/SpanReader.cs b/src/Titano.Core/Metadata/SpanReader.cs new file mode 100644 index 00000000..9f2c5cf8 --- /dev/null +++ b/src/Titano.Core/Metadata/SpanReader.cs @@ -0,0 +1,88 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Titano.Core.Metadata; + +/// +/// Forward-only reader over bytes already in memory. Reading past the end returns zeros and clears , +/// so a parser can read a whole structure and validate once. +/// +internal ref struct SpanReader +{ + private readonly ReadOnlySpan _data; + private readonly bool _bigEndian; + private int _position; + + public SpanReader(ReadOnlySpan data, bool bigEndian = true) + { + _data = data; + _bigEndian = bigEndian; + Ok = true; + } + + public bool Ok { get; private set; } + + public readonly int Position => _position; + + public readonly int Remaining => _data.Length - _position; + + public byte U8() => Take(1) is [var b] ? b : (byte)0; + + public ushort U16() + { + var s = Take(2); + return s.Length < 2 ? (ushort)0 : _bigEndian ? BinaryPrimitives.ReadUInt16BigEndian(s) : BinaryPrimitives.ReadUInt16LittleEndian(s); + } + + public uint U32() + { + var s = Take(4); + return s.Length < 4 ? 0 : _bigEndian ? BinaryPrimitives.ReadUInt32BigEndian(s) : BinaryPrimitives.ReadUInt32LittleEndian(s); + } + + public ulong U64() + { + var s = Take(8); + return s.Length < 8 ? 0 : _bigEndian ? BinaryPrimitives.ReadUInt64BigEndian(s) : BinaryPrimitives.ReadUInt64LittleEndian(s); + } + + /// Unsigned integer stored in 0, 4 or 8 bytes (ISO-BMFF iloc field sizes); other sizes fail. + public ulong Sized(int bytes) + { + switch (bytes) + { + case 0: return 0; + case 4: return U32(); + case 8: return U64(); + default: + Ok = false; + return 0; + } + } + + public void Skip(int count) => Take(count); + + /// The next bytes; empty (and cleared) when fewer remain. + public ReadOnlySpan Take(int count) + { + if (count < 0 || count > Remaining) + { + Ok = false; + _position = _data.Length; + return default; + } + var s = _data.Slice(_position, count); + _position += count; + return s; + } + + /// NUL-terminated UTF-8 string (the terminator is consumed); the rest of the data when unterminated. + public string CString() + { + var rest = _data[_position..]; + var end = rest.IndexOf((byte)0); + var length = end < 0 ? rest.Length : end; + _position += end < 0 ? length : length + 1; + return Encoding.UTF8.GetString(rest[..length]); + } +} diff --git a/src/Titano.Core/Metadata/StreamExtensions.cs b/src/Titano.Core/Metadata/StreamExtensions.cs new file mode 100644 index 00000000..6a9c476e --- /dev/null +++ b/src/Titano.Core/Metadata/StreamExtensions.cs @@ -0,0 +1,30 @@ +namespace Titano.Core.Metadata; + +/// Bounds-checked positional reads shared by the container parsers (windowed access, never whole files). +internal static class StreamExtensions +{ + /// Fills from ; false when the range leaves the stream. + public static bool TryReadAt(this Stream stream, long position, Span buffer) + { + if (position < 0 || position > stream.Length - buffer.Length) return false; + stream.Position = position; + return stream.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) == buffer.Length; + } + + /// Reads bytes at ; null when out of range or above . + public static byte[]? ReadAt(this Stream stream, long position, long length, long maxLength) + { + if (length < 0 || length > maxLength || position < 0 || position > stream.Length - length) return null; + var buffer = new byte[length]; + return stream.TryReadAt(position, buffer) ? buffer : null; + } + + /// Reads up to .Length bytes at ; returns the count read. + public static int ReadUpTo(this Stream stream, long position, Span buffer) + { + if (position < 0 || position >= stream.Length) return 0; + var n = (int)Math.Min(buffer.Length, stream.Length - position); + stream.Position = position; + return stream.ReadAtLeast(buffer[..n], n, throwOnEndOfStream: false); + } +} diff --git a/src/Titano.Core/Metadata/Tiff/ExifParser.cs b/src/Titano.Core/Metadata/Tiff/ExifParser.cs new file mode 100644 index 00000000..a0ba6fa8 --- /dev/null +++ b/src/Titano.Core/Metadata/Tiff/ExifParser.cs @@ -0,0 +1,247 @@ +using System.Buffers.Binary; +using Titano.Core.Imaging; +using Titano.Core.Metadata.Jpeg; +using Titano.Core.Metadata.MakerNotes; +using Titano.Core.Metadata.Xmp; + +namespace Titano.Core.Metadata.Tiff; + +/// +/// Maps TIFF/Exif structures onto a : IFD0, Exif IFD, GPS IFD, MakerNote, the 0x02BC XMP +/// packet, raster IFDs (main-image selection across the IFD chain and SubIFDs) and embedded JPEG previews. +/// +internal static class ExifParser +{ + private const int MaxImageIfds = 64; + private const int MaxSubIfdDepth = 4; + private const uint MaxSubIfdsPerIfd = 16; + private const uint PhotometricCfa = 32803; + private const uint PhotometricLinearRaw = 34892; + + // Panasonic RW2/RWL IFD0 (PanasonicRaw) tags. + private const ushort PanasonicSensorWidth = 0x0002; + private const ushort PanasonicSensorHeight = 0x0003; + private const ushort PanasonicSensorTop = 0x0004; + private const ushort PanasonicSensorLeft = 0x0005; + private const ushort PanasonicSensorBottom = 0x0006; + private const ushort PanasonicSensorRight = 0x0007; + private const ushort PanasonicBitsPerSample = 0x000A; + private const ushort PanasonicIso = 0x0017; + private const ushort PanasonicJpgFromRaw = 0x002E; + + /// Parses a TIFF-based file (TIFF, DNG, TIFF-like RAWs) whose header is at offset 0. + public static void ParseFile(MetadataBuilder m) => Walk(m, 0, isFile: true); + + /// Parses an Exif TIFF block embedded in another container (JPEG APP1, PNG eXIf, WebP EXIF, HEIF item…). + /// Its IFD1 thumbnail is reported as a preview; raster IFDs do not compete for the main image size. + public static void ParseEmbedded(MetadataBuilder m, long tiffBase) => Walk(m, tiffBase, isFile: false); + + /// Exif data prefixed by a 4-byte big-endian TIFF-header offset (HEIF Exif item, JPEG XL Exif box). + /// Falls back to searching the first bytes for a TIFF header when the offset is wrong. + public static void ParseOffsetPrefixed(MetadataBuilder m, long start, long length) + { + Span head = stackalloc byte[40]; + var n = m.Stream.ReadUpTo(start, head[..(int)Math.Min(head.Length, Math.Max(0, length))]); + if (n < 12) + { + m.Warn("Exif item too short"); + return; + } + var declared = BinaryPrimitives.ReadUInt32BigEndian(head); + if (declared < length - 12 && TiffReader.Open(m.Stream, start + 4 + declared) is not null) + { + ParseEmbedded(m, start + 4 + declared); + return; + } + for (var i = 4; i + 4 <= n; i++) + { + if (head[i..].StartsWith("II*\0"u8) || head[i..].StartsWith("MM\0*"u8)) + { + ParseEmbedded(m, start + i); + return; + } + } + m.Warn("Exif item has no TIFF header"); + } + + /// IFD0 fields plus the Exif and GPS sub-IFDs it points to. + public static void ReadTree(TiffReader r, Ifd ifd0, MetadataBuilder m, HashSet visited) + { + ReadIfd0(r, ifd0, m); + if (Pointer(r, ifd0, TiffTags.ExifIfd, visited) is { } exif) ReadExif(r, exif, m); + if (Pointer(r, ifd0, TiffTags.GpsIfd, visited) is { } gps) ReadGps(r, gps, m); + } + + /// Camera identity, authorship, orientation, rating and XMP from IFD0. + public static void ReadIfd0(TiffReader r, Ifd ifd, MetadataBuilder m) + { + m.Make ??= IfdValue.String(r, ifd, TiffTags.Make); + m.Model ??= IfdValue.String(r, ifd, TiffTags.Model); + m.Software ??= IfdValue.String(r, ifd, TiffTags.Software); + m.Artist ??= IfdValue.String(r, ifd, TiffTags.Artist); + m.Copyright ??= IfdValue.String(r, ifd, TiffTags.Copyright); + m.ExifOrientation ??= IfdValue.Int(r, ifd, TiffTags.Orientation); + m.ExifRating ??= IfdValue.Int(r, ifd, TiffTags.Rating); + if (ifd.Entries.TryGetValue(TiffTags.Xmp, out var xmp)) m.AddXmp(r.ReadBytes(xmp, XmpParser.MaxPacketBytes)); + } + + /// Exposure, capture time, lens/body identity and the MakerNote from an Exif IFD. + public static void ReadExif(TiffReader r, Ifd ifd, MetadataBuilder m) + { + m.ExposureTime ??= Positive(IfdValue.Double(r, ifd, TiffTags.ExposureTime)) + ?? (IfdValue.Double(r, ifd, TiffTags.ShutterSpeedValue) is { } tv and > -32 and < 32 ? Math.Pow(2, -tv) : (double?)null); + m.FNumber ??= Positive(IfdValue.Double(r, ifd, TiffTags.FNumber)) + ?? (IfdValue.Double(r, ifd, TiffTags.ApertureValue) is { } av and >= 0 and < 64 ? Math.Pow(2, av / 2) : (double?)null); + m.IsoSpeedRatings ??= IfdValue.Int(r, ifd, TiffTags.IsoSpeedRatings); + m.IsoFallback ??= IfdValue.Int(r, ifd, TiffTags.RecommendedExposureIndex) + ?? IfdValue.Int(r, ifd, TiffTags.StandardOutputSensitivity) + ?? IfdValue.Int(r, ifd, TiffTags.IsoSpeed); + var commonOffset = IfdValue.String(r, ifd, TiffTags.OffsetTime); + m.DateTimeOriginal ??= Stamp(r, ifd, TiffTags.DateTimeOriginal, TiffTags.SubSecTimeOriginal, TiffTags.OffsetTimeOriginal, commonOffset); + m.DateTimeDigitized ??= Stamp(r, ifd, TiffTags.DateTimeDigitized, TiffTags.SubSecTimeDigitized, TiffTags.OffsetTimeDigitized, commonOffset); + m.FocalLength ??= Positive(IfdValue.Double(r, ifd, TiffTags.FocalLength)); + m.FocalLength35 ??= Positive(IfdValue.Double(r, ifd, TiffTags.FocalLengthIn35mmFilm)); + m.ExposureBias ??= IfdValue.Double(r, ifd, TiffTags.ExposureBiasValue) is { } bias and > -64 and < 64 ? bias : (double?)null; + m.ExposureProgram ??= IfdValue.Int(r, ifd, TiffTags.ExposureProgram); + m.MeteringMode ??= IfdValue.Int(r, ifd, TiffTags.MeteringMode); + m.WhiteBalanceMode ??= IfdValue.Int(r, ifd, TiffTags.WhiteBalance); + m.Flash ??= IfdValue.Int(r, ifd, TiffTags.Flash); + m.PixelXDimension ??= IfdValue.Int(r, ifd, TiffTags.PixelXDimension); + m.PixelYDimension ??= IfdValue.Int(r, ifd, TiffTags.PixelYDimension); + m.BodySerial ??= IfdValue.String(r, ifd, TiffTags.BodySerialNumber); + m.LensModel ??= IfdValue.String(r, ifd, TiffTags.LensModel); + if (ifd.Entries.TryGetValue(TiffTags.MakerNote, out var makerNote)) MakerNoteParser.Parse(r, makerNote, m); + } + + /// Position (status "V" = void is ignored), altitude and the UTC date/time stamp from a GPS IFD. + public static void ReadGps(TiffReader r, Ifd ifd, MetadataBuilder m) + { + if (m.Gps is null && IfdValue.String(r, ifd, TiffTags.GpsStatus) != "V" + && Degrees(r, ifd, TiffTags.GpsLatitude, TiffTags.GpsLatitudeRef, 'S', 90) is { } lat + && Degrees(r, ifd, TiffTags.GpsLongitude, TiffTags.GpsLongitudeRef, 'W', 180) is { } lon) + { + var altitude = IfdValue.Double(r, ifd, TiffTags.GpsAltitude) is { } alt and >= 0 and < 1e6 + ? IfdValue.Int(r, ifd, TiffTags.GpsAltitudeRef) == 1 ? -alt : alt + : (double?)null; + m.Gps = new GpsPosition(lat, lon, altitude, null); + } + if (m.GpsUtc is null + && MetadataDates.ParseDate(IfdValue.String(r, ifd, TiffTags.GpsDateStamp)) is { } date + && IfdValue.Doubles(r, ifd, TiffTags.GpsTimeStamp, 3) is [var h, var min, var sec, ..] + && h is >= 0 and < 24 && min is >= 0 and < 60 && sec is >= 0 and < 61) + { + m.GpsUtc = DateTime.SpecifyKind(date.AddSeconds(h * 3600 + min * 60 + sec), DateTimeKind.Utc); + } + } + + private static void Walk(MetadataBuilder m, long tiffBase, bool isFile) + { + var r = TiffReader.Open(m.Stream, tiffBase); + if (r is null) + { + m.Warn(isFile ? "TIFF header not found" : "Exif TIFF header not found"); + return; + } + var chain = r.ReadChain(); + if (chain.Count == 0) + { + m.Warn("No readable IFD"); + } + else + { + var visited = new HashSet(); + foreach (var ifd in chain) visited.Add(ifd.Position); + ReadTree(r, chain[0], m, visited); + if (isFile && m.Format is ImageFileFormat.Rw2 or ImageFileFormat.Rwl or ImageFileFormat.Raw) ReadPanasonicRaw(r, chain[0], m); + var budget = MaxImageIfds; + foreach (var ifd in chain) VisitImage(r, ifd, m, visited, 0, isFile, ref budget); + // DNG CameraSerialNumber ranks after Exif BodySerialNumber and before the MakerNote. + if (isFile) m.BodySerial ??= IfdValue.String(r, chain[0], TiffTags.CameraSerialNumber); + } + m.AddWarnings(r.Warnings); + } + + /// Raster candidate, embedded previews and SubIFDs (depth- and count-capped) of one image IFD. + private static void VisitImage(TiffReader r, Ifd ifd, MetadataBuilder m, HashSet visited, int depth, bool isFile, ref int budget) + { + if (--budget < 0) return; + m.ThrowIfCancelled(); + if (isFile) + { + var width = IfdValue.Int(r, ifd, TiffTags.ImageWidth) ?? 0; + var height = IfdValue.Int(r, ifd, TiffTags.ImageLength) ?? 0; + var primary = ((IfdValue.UInt(r, ifd, TiffTags.NewSubfileType) ?? 0) & 1) == 0; + m.AddRaster(width, height, IfdValue.Int(r, ifd, TiffTags.BitsPerSample), primary); + } + AddPreviews(r, ifd, m, isFile); + if (depth >= MaxSubIfdDepth || !ifd.Entries.TryGetValue(TiffTags.SubIfds, out var sub) || sub.Count > MaxSubIfdsPerIfd) return; + foreach (var offset in r.GetUInts(sub) ?? []) + { + if (r.ReadIfd(offset, visited) is { } child) VisitImage(r, child, m, visited, depth + 1, isFile, ref budget); + } + } + + /// JPEGInterchangeFormat thumbnails/previews and single-strip/tile JPEG images (Compression 6/7, not CFA). + private static void AddPreviews(TiffReader r, Ifd ifd, MetadataBuilder m, bool isFile) + { + if (IfdValue.UInt(r, ifd, TiffTags.JpegInterchangeFormat) is { } offset and > 0 + && IfdValue.UInt(r, ifd, TiffTags.JpegInterchangeFormatLength) is { } length and > 0) + { + JpegParser.AddPreview(m, r.Base + offset, length); + } + if (IfdValue.UInt(r, ifd, TiffTags.Compression) is not (6 or 7) + || IfdValue.UInt(r, ifd, TiffTags.PhotometricInterpretation) is PhotometricCfa or PhotometricLinearRaw) + return; + var (offsetTag, countTag) = ifd.Has(TiffTags.StripOffsets) + ? (TiffTags.StripOffsets, TiffTags.StripByteCounts) + : (TiffTags.TileOffsets, TiffTags.TileByteCounts); + if (ifd.Entries.TryGetValue(offsetTag, out var e) && e.Count == 1 + && IfdValue.UInt(r, ifd, offsetTag) is { } dataOffset + && IfdValue.UInt(r, ifd, countTag) is { } dataLength and > 0 + && JpegParser.AddPreview(m, r.Base + dataOffset, dataLength) is { Lossless: true } raw + && isFile) + { + m.CodedBitsPerSample ??= raw.Precision; + } + } + + /// Panasonic RW2 header: sensor crop size, bit depth, ISO and the JpgFromRaw that carries the Exif block. + private static void ReadPanasonicRaw(TiffReader r, Ifd ifd0, MetadataBuilder m) + { + var top = IfdValue.Int(r, ifd0, PanasonicSensorTop) ?? 0; + var left = IfdValue.Int(r, ifd0, PanasonicSensorLeft) ?? 0; + var bottom = IfdValue.Int(r, ifd0, PanasonicSensorBottom) ?? 0; + var right = IfdValue.Int(r, ifd0, PanasonicSensorRight) ?? 0; + var (width, height) = right > left && bottom > top + ? (right - left, bottom - top) + : (IfdValue.Int(r, ifd0, PanasonicSensorWidth) ?? 0, IfdValue.Int(r, ifd0, PanasonicSensorHeight) ?? 0); + m.SetContainerSize(width, height, IfdValue.Int(r, ifd0, PanasonicBitsPerSample)); + m.IsoFallback ??= IfdValue.Int(r, ifd0, PanasonicIso); + if (ifd0.Entries.TryGetValue(PanasonicJpgFromRaw, out var jpeg) && !jpeg.IsInline) + { + var start = jpeg.ValuePosition(r.Base); + JpegParser.Parse(m, start, start + jpeg.ByteLength, primary: false); + } + } + + private static Ifd? Pointer(TiffReader r, Ifd ifd, ushort tag, HashSet visited) => + IfdValue.UInt(r, ifd, tag) is { } offset and > 0 ? r.ReadIfd(offset, visited) : null; + + private static CaptureStamp? Stamp(TiffReader r, Ifd ifd, ushort dateTag, ushort subSecTag, ushort offsetTag, string? fallbackOffset) + { + if (MetadataDates.ParseExif(IfdValue.String(r, ifd, dateTag)) is not { } value) return null; + var ticks = MetadataDates.SubSecondTicks(IfdValue.String(r, ifd, subSecTag)); + var offset = MetadataDates.ParseOffset(IfdValue.String(r, ifd, offsetTag)) ?? MetadataDates.ParseOffset(fallbackOffset); + return new CaptureStamp(value.AddTicks(ticks), offset); + } + + private static double? Degrees(TiffReader r, Ifd ifd, ushort tag, ushort refTag, char negative, double limit) + { + if (IfdValue.Doubles(r, ifd, tag, 3) is not [var d, var min, var sec, ..]) return null; + var value = d + min / 60 + sec / 3600; + if (!(value >= 0 && value <= limit)) return null; + return IfdValue.String(r, ifd, refTag) is { Length: > 0 } reference && char.ToUpperInvariant(reference[0]) == negative ? -value : value; + } + + private static double? Positive(double? value) => value is > 0 ? value : null; +} diff --git a/src/Titano.Core/Metadata/Tiff/IfdValue.cs b/src/Titano.Core/Metadata/Tiff/IfdValue.cs new file mode 100644 index 00000000..53c7f14c --- /dev/null +++ b/src/Titano.Core/Metadata/Tiff/IfdValue.cs @@ -0,0 +1,45 @@ +namespace Titano.Core.Metadata.Tiff; + +/// Single-value accessors over that refuse oversized counts, so a corrupt +/// count can never trigger a large read when only the first value is needed. +internal static class IfdValue +{ + /// Largest value count read for scalar/array tags (GPS triples, lens info, Canon camera settings…). + public const uint MaxCount = 256; + + public static uint? UInt(TiffReader r, Ifd ifd, ushort tag) => + ifd.Entries.TryGetValue(tag, out var e) && e.Count is > 0 and <= MaxCount && r.GetUInts(e) is [var v, ..] ? v : null; + + public static int? Int(TiffReader r, Ifd ifd, ushort tag) => UInt(r, ifd, tag) is { } v && v <= int.MaxValue ? (int)v : null; + + public static uint[]? UInts(TiffReader r, Ifd ifd, ushort tag) => + ifd.Entries.TryGetValue(tag, out var e) && e.Count is > 0 and <= MaxCount ? r.GetUInts(e) : null; + + /// First value as a finite double (rationals divided). + public static double? Double(TiffReader r, Ifd ifd, ushort tag) => Doubles(r, ifd, tag, 1) is [var v, ..] ? v : null; + + /// All values when at least are present and every one is finite. + public static double[]? Doubles(TiffReader r, Ifd ifd, ushort tag, int minCount) + { + if (!ifd.Entries.TryGetValue(tag, out var e) || e.Count < minCount || e.Count > MaxCount) return null; + var values = r.GetDoubles(e); + if (values is null) return null; + foreach (var v in values) + { + if (!double.IsFinite(v)) return null; + } + return values; + } + + /// Text value with control characters removed; null when empty. + public static string? String(TiffReader r, Ifd ifd, ushort tag) + { + var s = r.GetString(ifd, tag); + if (s is null) return null; + if (s.AsSpan().IndexOfAnyInRange('\0', '\u001F') >= 0) + { + s = string.Concat(s.Where(c => !char.IsControl(c))).Trim(); + } + return s.Length == 0 ? null : s; + } +} diff --git a/src/Titano.Core/Metadata/Tiff/TiffTags.cs b/src/Titano.Core/Metadata/Tiff/TiffTags.cs index e279e5a1..a1ca5a26 100644 --- a/src/Titano.Core/Metadata/Tiff/TiffTags.cs +++ b/src/Titano.Core/Metadata/Tiff/TiffTags.cs @@ -37,6 +37,7 @@ public static class TiffTags public const ushort JpegInterchangeFormat = 0x0201; public const ushort JpegInterchangeFormatLength = 0x0202; public const ushort YCbCrSubSampling = 0x0212; + public const ushort YCbCrPositioning = 0x0213; public const ushort Rating = 0x4746; public const ushort Xmp = 0x02BC; public const ushort Copyright = 0x8298; @@ -50,7 +51,9 @@ public static class TiffTags public const ushort ExposureProgram = 0x8822; public const ushort IsoSpeedRatings = 0x8827; public const ushort SensitivityType = 0x8830; + public const ushort StandardOutputSensitivity = 0x8831; public const ushort RecommendedExposureIndex = 0x8832; + public const ushort IsoSpeed = 0x8833; public const ushort ExifVersion = 0x9000; public const ushort DateTimeOriginal = 0x9003; public const ushort DateTimeDigitized = 0x9004; @@ -78,6 +81,7 @@ public static class TiffTags public const ushort LensModel = 0xA434; // GPS + public const ushort GpsVersionId = 0x0000; public const ushort GpsLatitudeRef = 0x0001; public const ushort GpsLatitude = 0x0002; public const ushort GpsLongitudeRef = 0x0003; @@ -85,6 +89,7 @@ public static class TiffTags public const ushort GpsAltitudeRef = 0x0005; public const ushort GpsAltitude = 0x0006; public const ushort GpsTimeStamp = 0x0007; + public const ushort GpsStatus = 0x0009; public const ushort GpsDateStamp = 0x001D; // DNG diff --git a/src/Titano.Core/Metadata/Xmp/XmpParser.cs b/src/Titano.Core/Metadata/Xmp/XmpParser.cs new file mode 100644 index 00000000..7d62054a --- /dev/null +++ b/src/Titano.Core/Metadata/Xmp/XmpParser.cs @@ -0,0 +1,171 @@ +using System.Globalization; +using System.Xml; + +namespace Titano.Core.Metadata.Xmp; + +/// +/// Streaming XMP reader (no DTDs, no external resolution, 4 MB cap). Reads both the attribute form +/// (<rdf:Description xmp:Rating="5"/>) and the element form (<xmp:Rating>5</xmp:Rating>, +/// including values nested in rdf:Alt/rdf:Seq) of the properties in . +/// +internal static class XmpParser +{ + public const int MaxPacketBytes = 4 * 1024 * 1024; + + private const string NsXmp = "http://ns.adobe.com/xap/1.0/"; + private const string NsExif = "http://ns.adobe.com/exif/1.0/"; + private const string NsAux = "http://ns.adobe.com/exif/1.0/aux/"; + private const string NsExifEx = "http://cipa.jp/exif/1.0/"; + private const string NsPhotoshop = "http://ns.adobe.com/photoshop/1.0/"; + private const string NsTiff = "http://ns.adobe.com/tiff/1.0/"; + private const string NsXmpNote = "http://ns.adobe.com/xmp/note/"; + + private static readonly XmlReaderSettings Settings = new() + { + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null, + IgnoreComments = true, + IgnoreProcessingInstructions = true, + IgnoreWhitespace = true, + MaxCharactersInDocument = MaxPacketBytes, + CloseInput = true, + }; + + private enum Property + { + None, + Rating, + Label, + DateTimeOriginal, + DateCreated, + CreateDate, + Orientation, + AuxSerialNumber, + BodySerialNumber, + AuxLens, + LensModel, + HasExtendedXmp, + } + + /// Parses one packet into , keeping values that are already set. + /// Null on success; otherwise why parsing stopped (values read before the problem are kept). + public static string? Parse(byte[] packet, XmpValues values) + { + var length = packet.Length; + while (length > 0 && packet[length - 1] == 0) length--; + if (length == 0) return "Empty XMP packet"; + if (length > MaxPacketBytes) return "XMP packet larger than 4 MB ignored"; + try + { + using var reader = XmlReader.Create(new MemoryStream(packet, 0, length, writable: false), Settings); + var pending = Property.None; + var pendingDepth = 0; + while (reader.Read()) + { + switch (reader.NodeType) + { + case XmlNodeType.Element: + if (reader.MoveToFirstAttribute()) + { + do Assign(values, Lookup(reader.NamespaceURI, reader.LocalName), reader.Value); + while (reader.MoveToNextAttribute()); + reader.MoveToElement(); + } + if (pending == Property.None && !reader.IsEmptyElement) + { + pending = Lookup(reader.NamespaceURI, reader.LocalName); + pendingDepth = reader.Depth; + } + break; + case XmlNodeType.Text or XmlNodeType.CDATA: + if (pending != Property.None) + { + Assign(values, pending, reader.Value); + pending = Property.None; + } + break; + case XmlNodeType.EndElement: + if (reader.Depth <= pendingDepth) pending = Property.None; + break; + } + } + return null; + } + catch (XmlException ex) + { + return "Malformed XMP: " + ex.Message; + } + } + + private static Property Lookup(string ns, string name) => ns switch + { + NsXmp => name switch + { + "Rating" => Property.Rating, + "Label" => Property.Label, + "CreateDate" => Property.CreateDate, + _ => Property.None, + }, + NsExif when name == "DateTimeOriginal" => Property.DateTimeOriginal, + NsPhotoshop when name == "DateCreated" => Property.DateCreated, + NsTiff when name == "Orientation" => Property.Orientation, + NsAux => name switch + { + "SerialNumber" => Property.AuxSerialNumber, + "Lens" => Property.AuxLens, + _ => Property.None, + }, + NsExifEx => name switch + { + "BodySerialNumber" => Property.BodySerialNumber, + "LensModel" => Property.LensModel, + _ => Property.None, + }, + NsXmpNote when name == "HasExtendedXMP" => Property.HasExtendedXmp, + _ => Property.None, + }; + + private static void Assign(XmpValues v, Property property, string raw) + { + var text = raw.Trim(); + if (property == Property.None || text.Length == 0) return; + switch (property) + { + case Property.Rating: + if (double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var rating) && rating is >= -1 and <= 5) + v.Rating ??= (int)Math.Round(rating); + break; + case Property.Label: + v.Label ??= text; + break; + case Property.DateTimeOriginal: + v.DateTimeOriginal ??= MetadataDates.ParseIso8601(text); + break; + case Property.DateCreated: + v.DateCreated ??= MetadataDates.ParseIso8601(text); + break; + case Property.CreateDate: + v.CreateDate ??= MetadataDates.ParseIso8601(text); + break; + case Property.Orientation: + if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var o) && o is >= 1 and <= 8) + v.Orientation ??= o; + break; + case Property.AuxSerialNumber: + v.AuxSerialNumber ??= text; + break; + case Property.BodySerialNumber: + v.BodySerialNumber ??= text; + break; + case Property.AuxLens: + v.AuxLens ??= text; + break; + case Property.LensModel: + v.LensModel ??= text; + break; + case Property.HasExtendedXmp: + v.ExtendedXmpGuid ??= text; + break; + } + } +} diff --git a/src/Titano.Core/Metadata/Xmp/XmpValues.cs b/src/Titano.Core/Metadata/Xmp/XmpValues.cs new file mode 100644 index 00000000..2a258592 --- /dev/null +++ b/src/Titano.Core/Metadata/Xmp/XmpValues.cs @@ -0,0 +1,41 @@ +namespace Titano.Core.Metadata.Xmp; + +/// The XMP properties Titano reads. Each is set by the first packet that carries it. +internal sealed class XmpValues +{ + public int? Rating { get; set; } + public string? Label { get; set; } + + /// exif:DateTimeOriginal. + public CaptureStamp? DateTimeOriginal { get; set; } + + /// photoshop:DateCreated. + public CaptureStamp? DateCreated { get; set; } + + /// xmp:CreateDate. + public CaptureStamp? CreateDate { get; set; } + + public int? Orientation { get; set; } + + /// aux:SerialNumber. + public string? AuxSerialNumber { get; set; } + + /// exifEX:BodySerialNumber. + public string? BodySerialNumber { get; set; } + + /// aux:Lens. + public string? AuxLens { get; set; } + + /// exifEX:LensModel. + public string? LensModel { get; set; } + + /// xmpNote:HasExtendedXMP: GUID of the extended packet split across JPEG APP1 segments. + public string? ExtendedXmpGuid { get; set; } + + /// Capture time in MWG order: DateTimeOriginal, DateCreated, CreateDate. + public CaptureStamp? CaptureTime => DateTimeOriginal ?? DateCreated ?? CreateDate; + + public string? BodySerial => BodySerialNumber ?? AuxSerialNumber; + + public string? Lens => LensModel ?? AuxLens; +} diff --git a/tests/Titano.Core.Tests/Metadata/BmffTests.cs b/tests/Titano.Core.Tests/Metadata/BmffTests.cs new file mode 100644 index 00000000..c122240f --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/BmffTests.cs @@ -0,0 +1,127 @@ +using Titano.Core.Imaging; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Bmff; +using Titano.Core.Model; +using Titano.Core.Tests.Metadata.Builders; +using Titano.Testing; +using static Titano.Core.Tests.Metadata.MetadataTestHelpers; + +namespace Titano.Core.Tests.Metadata; + +public sealed class BmffTests +{ + [Test] + public void Cr3() + { + var m = Read(Fixtures.Cr3(), "IMG_0001.CR3"); + AssertNoFault(m); + Assert.Empty(m.Warnings); + Assert.Equal(ImageFileFormat.Cr3, m.Format); + Assert.Equal("Canon", m.Make); + Assert.Equal("Canon EOS R5", m.Model); + Assert.Equal(8, m.Orientation); + Assert.Equal((8352, 5586), (m.Width, m.Height)); + Assert.Equal(14, m.BitsPerSample); + AssertPreviews(m, (8192, 5464, PreviewKind.FullSize), (1620, 1080, PreviewKind.Preview), (160, 120, PreviewKind.Thumbnail)); + Assert.Equal(new DateTime(2024, 6, 1, 8, 0, 0, 500), m.CapturedAt); + Assert.Equal(-240, m.UtcOffsetMinutes); + Assert.Equal(TimestampSource.ExifOriginal, m.TimestampSource); + Assert.Approximately(0.01, m.ExposureTime!.Value, 1e-12); + Assert.Approximately(4, m.FNumber!.Value, 1e-12); + Assert.Equal(100, m.Iso); + Assert.Equal("0000098765", m.BodySerial); + Assert.Equal("RF24-105mm F4 L IS USM", m.LensModel); + Assert.Approximately(-9.26, m.Gps!.Longitude, 1e-9); + } + + [Test] + public void Cr3FullSizeJpegIsTrackOneSample() + { + var bytes = Fixtures.Cr3(out var mdatStart); + var full = Read(bytes).Previews[0]; + Assert.Equal(mdatStart + 8L, full.Offset); + Assert.Equal(0xFF, bytes[full.Offset]); + Assert.Equal(0xD9, bytes[full.Offset + full.Length - 1]); + } + + [Theory] + [Case(false, false, 6, Name = "no transforms: Exif orientation applies")] + [Case(true, false, 8, Name = "irot 90° anticlockwise")] + [Case(true, true, 7, Name = "irot then imir left-right")] + [Case(false, true, 2, Name = "imir left-right only")] + public void HeifTransformsOverrideExifOrientation(bool rotate, bool mirror, int expected) => + Assert.Equal(expected, Read(Fixtures.Heic(rotate, mirror), "IMG_0001.HEIC").Orientation); + + [Test] + public void Heic() + { + var m = Read(Fixtures.Heic(), "IMG_0001.HEIC"); + AssertNoFault(m); + Assert.Empty(m.Warnings); + Assert.Equal(ImageFileFormat.Heif, m.Format); + Assert.Equal((4032, 3024), (m.Width, m.Height)); + Assert.Equal(10, m.BitsPerSample); + Assert.Equal(Fixtures.Make, m.Make); + Assert.Equal(Fixtures.Captured, m.CapturedAt); + Assert.Equal(400, m.Iso); + Assert.Equal(4, m.Rating); + Assert.Equal("Red", m.Label); + AssertPreviews(m, (160, 120, PreviewKind.Thumbnail)); + } + + [Test] + public void Avif() + { + var m = Read(Fixtures.Heic(major: "avif"), "a.avif"); + Assert.Equal(ImageFileFormat.Avif, m.Format); + Assert.Equal((4032, 3024), (m.Width, m.Height)); + Assert.Equal("Red", m.Label); + } + + [Test] + public void WalksLargeSizeToEndAndUuidBoxes() + { + var guid = Guid.NewGuid(); + byte[] large = [.. Box.U32(1), .. Box.Ascii("free"), .. Box.U64(20), 1, 2, 3, 4]; + byte[] data = [.. Box.Make("ftyp", Box.Ascii("heic")), .. large, .. Box.Uuid(guid, [9, 9]), .. Box.U32(0), .. Box.Ascii("mdat"), 7, 7, 7]; + var boxes = BmffReader.ReadChildren(new MemoryStream(data), 0, data.Length); + Assert.Equal(4, boxes.Count); + Assert.True(boxes[1].Is("free")); + Assert.Equal(16, boxes[1].HeaderSize); + Assert.Equal(20L, boxes[1].Size); + Assert.Equal(guid, boxes[2].UserType); + Assert.Equal(24, boxes[2].HeaderSize); + Assert.True(boxes[3].Is("mdat")); + Assert.Equal((long)data.Length, boxes[3].End); + } + + [Test] + public void StopsAtMalformedAndClampsTruncatedBoxes() + { + var warnings = new List(); + byte[] truncated = [.. Box.Make("ftyp", Box.Ascii("heic")), .. Box.U32(1000), .. Box.Ascii("moov"), 0, 0]; + var boxes = BmffReader.ReadChildren(new MemoryStream(truncated), 0, truncated.Length, warnings); + Assert.Equal(2, boxes.Count); + Assert.Equal((long)truncated.Length, boxes[1].End); + Assert.Contains("Box 'moov' at 12 runs past its container", warnings); + + byte[] malformed = [.. Box.Make("ftyp", Box.Ascii("heic")), .. Box.U32(4), .. Box.Ascii("bad!"), .. Box.Make("free")]; + Assert.Equal(1, BmffReader.ReadChildren(new MemoryStream(malformed), 0, malformed.Length).Count); + } + + [Test] + public void FindPathIsDepthLimited() + { + var box = new BmffBox(FourCC.From("moov"), 0, 8, 8, Guid.Empty); + Assert.Throws(() => BmffReader.FindPath(new MemoryStream(new byte[8]), box, [.. Enumerable.Repeat("trak", BmffReader.MaxDepth + 1)])); + Assert.Null(BmffReader.FindPath(new MemoryStream(new byte[8]), box, "trak", "mdia")); + } + + [Test] + public void FourCCRoundTrips() + { + Assert.Equal(0x66747970u, FourCC.From("ftyp")); + Assert.Equal("ftyp", FourCC.Format(0x66747970)); + Assert.Equal("?abc", FourCC.Format(0x01616263)); + } +} diff --git a/tests/Titano.Core.Tests/Metadata/Builders/Box.cs b/tests/Titano.Core.Tests/Metadata/Builders/Box.cs new file mode 100644 index 00000000..d26ee4d1 --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/Builders/Box.cs @@ -0,0 +1,68 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Titano.Core.Tests.Metadata.Builders; + +/// ISO-BMFF / RIFF / PNG byte helpers for synthetic containers. +internal static class Box +{ + public static byte[] Make(string type, params byte[][] content) + { + var size = 8 + content.Sum(c => c.Length); + return [.. U32((uint)size), .. Encoding.Latin1.GetBytes(type), .. content.SelectMany(c => c)]; + } + + public static byte[] Full(string type, byte version, uint flags, params byte[][] content) => + Make(type, [[version, (byte)(flags >> 16), (byte)(flags >> 8), (byte)flags], .. content]); + + public static byte[] Uuid(Guid userType, params byte[][] content) => + Make("uuid", [userType.ToByteArray(bigEndian: true), .. content]); + + public static byte[] U8(byte v) => [v]; + + public static byte[] U16(ushort v) + { + var b = new byte[2]; + BinaryPrimitives.WriteUInt16BigEndian(b, v); + return b; + } + + public static byte[] U32(uint v) + { + var b = new byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(b, v); + return b; + } + + public static byte[] U64(ulong v) + { + var b = new byte[8]; + BinaryPrimitives.WriteUInt64BigEndian(b, v); + return b; + } + + public static byte[] Ascii(string s) => Encoding.Latin1.GetBytes(s); + + public static byte[] Zeros(int n) => new byte[n]; + + /// RIFF chunk: FourCC, little-endian size, data, pad byte to even length. + public static byte[] Riff(string fourCC, byte[] data) + { + var b = new byte[8 + data.Length + (data.Length & 1)]; + Encoding.Latin1.GetBytes(fourCC).CopyTo(b, 0); + BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(4), (uint)data.Length); + data.CopyTo(b, 8); + return b; + } + + /// PNG chunk with a real CRC. + public static byte[] Png(string type, byte[] data) + { + var b = new byte[12 + data.Length]; + BinaryPrimitives.WriteUInt32BigEndian(b, (uint)data.Length); + Encoding.Latin1.GetBytes(type).CopyTo(b, 4); + data.CopyTo(b, 8); + BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(8 + data.Length), Core.Hashing.Crc32.Compute(b.AsSpan(4, 4 + data.Length))); + return b; + } +} diff --git a/tests/Titano.Core.Tests/Metadata/Builders/Fixtures.cs b/tests/Titano.Core.Tests/Metadata/Builders/Fixtures.cs new file mode 100644 index 00000000..01e3b644 --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/Builders/Fixtures.cs @@ -0,0 +1,417 @@ +using System.Buffers.Binary; +using System.Text; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Tests.Metadata.Builders; + +/// Synthetic files for every container Titano reads. The canonical camera values below are what the tests +/// expect back; each RAW-like fixture also exercises its vendor MakerNote and preview layout. +internal static class Fixtures +{ + public const string Make = "TestCam"; + public const string Model = "TC-1"; + public const string Xmp = """ + + + + + Red + + + + + """; + + public static readonly Guid CanonUuid = new("85c0b687-820f-11e0-8111-f4ce462b6a48"); + public static readonly Guid PreviewUuid = new("eaf42b5e-1c98-4b88-b9fb-b7dc406e4d16"); + + /// 12:34:56.123 +02:00 on 2024-05-01. + public static readonly DateTime Captured = new DateTime(2024, 5, 1, 12, 34, 56, DateTimeKind.Unspecified).AddTicks(1_230_000); + + public static IfdSpec Ifd0(string make = Make, string model = Model, ushort orientation = 6) => new IfdSpec() + .Ascii(TiffTags.Make, make) + .Ascii(TiffTags.Model, model) + .Short(TiffTags.Orientation, orientation) + .Ascii(TiffTags.Software, "fw 1.0") + .Ascii(TiffTags.Artist, "Ada") + .Ascii(TiffTags.Copyright, "(c) Ada") + .Short(TiffTags.Rating, 3); + + /// Every standard Exif field Titano reads; adds body serial and lens model. + public static IfdSpec ExifIfd(bool identity = true, ushort iso = 400) + { + var exif = new IfdSpec() + .Rational(TiffTags.ExposureTime, (1, 250)) + .Rational(TiffTags.FNumber, (56, 10)) + .Ascii(TiffTags.DateTimeOriginal, "2024:05:01 12:34:56") + .Ascii(TiffTags.SubSecTimeOriginal, "123") + .Ascii(TiffTags.OffsetTimeOriginal, "+02:00") + .Ascii(TiffTags.DateTimeDigitized, "2024:05:01 12:34:57") + .Rational(TiffTags.FocalLength, (35, 1)) + .Short(TiffTags.FocalLengthIn35mmFilm, 52) + .SRational(TiffTags.ExposureBiasValue, -2, 3) + .Short(TiffTags.ExposureProgram, 3) + .Short(TiffTags.MeteringMode, 5) + .Short(TiffTags.WhiteBalance, 1) + .Short(TiffTags.Flash, 16) + .Long(TiffTags.PixelXDimension, 4000) + .Long(TiffTags.PixelYDimension, 3000); + if (iso > 0) exif.Short(TiffTags.IsoSpeedRatings, iso); + if (identity) exif.Ascii(TiffTags.BodySerialNumber, "SN123").Ascii(TiffTags.LensModel, "TestLens 35mm"); + return exif; + } + + /// 45.5° N, 9.26° W, 120.5 m, 2024-05-01 10:34:56 UTC. + public static IfdSpec GpsIfd() => new IfdSpec() + .Bytes(TiffTags.GpsVersionId, 2, 3, 0, 0) + .Ascii(TiffTags.GpsLatitudeRef, "N") + .Rational(TiffTags.GpsLatitude, (45, 1), (30, 1), (0, 1)) + .Ascii(TiffTags.GpsLongitudeRef, "W") + .Rational(TiffTags.GpsLongitude, (9, 1), (15, 1), (3600, 100)) + .Bytes(TiffTags.GpsAltitudeRef, 0) + .Rational(TiffTags.GpsAltitude, (1205, 10)) + .Rational(TiffTags.GpsTimeStamp, (10, 1), (34, 1), (56, 1)) + .Ascii(TiffTags.GpsDateStamp, "2024:05:01"); + + /// Canonical Exif TIFF block; IFD1 carries a 160×120 JPEG thumbnail. + public static byte[] ExifTiff(bool littleEndian = true, IfdSpec? exif = null, IfdSpec? ifd0 = null) + { + var root = (ifd0 ?? Ifd0()).Child(TiffTags.ExifIfd, exif ?? ExifIfd()).Child(TiffTags.GpsIfd, GpsIfd()); + root.Next = new IfdSpec() + .Short(TiffTags.Compression, 6) + .Blob(TiffTags.JpegInterchangeFormat, TiffTags.JpegInterchangeFormatLength, JpegBuilder.Minimal(160, 120)); + return TiffFile.Build(root, littleEndian); + } + + /// 4000×3000 JPEG: Exif (+thumbnail), XMP, MPF with a 1920×1440 large thumbnail and a disparity image + /// (not a preview). + public static byte[] Jpeg(bool littleEndian = true) => new JpegBuilder() + .Segment(0xE0, [.. "JFIF\0"u8, 1, 2, 0, 0, 1, 0, 1, 0, 0]) + .Exif(ExifTiff(littleEndian)) + .Xmp(Xmp) + .Mpf((JpegBuilder.Minimal(1920, 1440), 0x00010002), (JpegBuilder.Minimal(640, 480), 0x00020002)) + .Build(4000, 3000); + + /// CR2: "CR" marker, IFD0 full-size JPEG strip (6720×4480), IFD1 thumbnail, IFD2 RGB, IFD3 lossless + /// raw (SOF3, 14-bit); Canon MakerNote supplies serial, lens, IS and colour temperature. + public static byte[] Cr2() + { + var makerNote = new IfdSpec() + .Short(0x0001, [.. Enumerable.Range(0, 40).Select(i => (ushort)(i == 34 ? 1 : 0))]) + .Long(0x000C, 123456) + .Long(0x0010, 0x80000349) + .Ascii(0x0095, "EF24-70mm f/2.8L II USM") + .Short(0x00AE, 5200); + var exif = ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [], makerNote, relativeToTiff: true, littleEndian: true); + var ifd0 = Ifd0("Canon", "Canon EOS 5D Mark IV", 1) + .Long(TiffTags.ImageWidth, 6720).Long(TiffTags.ImageLength, 4480) + .Short(TiffTags.BitsPerSample, 8, 8, 8) + .Short(TiffTags.Compression, 6) + .Strip(JpegBuilder.Minimal(6720, 4480)) + .Child(TiffTags.ExifIfd, exif); + var ifd1 = new IfdSpec().Short(TiffTags.Compression, 6) + .Blob(TiffTags.JpegInterchangeFormat, TiffTags.JpegInterchangeFormatLength, JpegBuilder.Minimal(160, 120)); + var ifd2 = new IfdSpec().Long(TiffTags.ImageWidth, 592).Long(TiffTags.ImageLength, 395) + .Short(TiffTags.BitsPerSample, 16, 16, 16).Short(TiffTags.Compression, 1).Strip(new byte[64]); + var ifd3 = new IfdSpec().Short(TiffTags.Compression, 6).Strip(JpegBuilder.Minimal(2784, 3708, 0xC3, 14)); + ifd0.Next = ifd1; + ifd1.Next = ifd2; + ifd2.Next = ifd3; + return TiffFile.Build(ifd0, true, headerExtra: [(byte)'C', (byte)'R', 2, 0, 0, 0, 0, 0]); + } + + /// Big-endian NEF: IFD0 RGB thumbnail; SubIFDs JpgFromRaw (8256×5504) and 14-bit CFA raw (8288×5520); + /// Nikon type-3 MakerNote (serial, shutter count, lens, VR, ISO used because Exif ISO is absent). + public static byte[] Nef() + { + var nikon = new IfdSpec() + .Short(0x0002, 0, 64) + .Ascii(0x001D, "3001234") + .Undefined(0x001F, [.. "0100"u8, 1, 0, 0, 0]) + .Rational(0x0084, (24, 1), (70, 1), (28, 10), (28, 10)) + .Long(0x00A7, 12345); + var exif = ExifIfd(identity: false, iso: 0) + .Undefined(TiffTags.MakerNote, [.. "Nikon\0"u8, 2, 0x11, 0, 0, .. TiffFile.Build(nikon, littleEndian: false)]); + var jpgFromRaw = new IfdSpec().Long(TiffTags.NewSubfileType, 1).Short(TiffTags.Compression, 6) + .Blob(TiffTags.JpegInterchangeFormat, TiffTags.JpegInterchangeFormatLength, JpegBuilder.Minimal(8256, 5504)); + var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0) + .Long(TiffTags.ImageWidth, 8288).Long(TiffTags.ImageLength, 5520) + .Short(TiffTags.BitsPerSample, 14).Short(TiffTags.Compression, 34713) + .Short(TiffTags.PhotometricInterpretation, 32803).Strip(new byte[128]); + var ifd0 = Ifd0("NIKON CORPORATION", "NIKON D850", 1) + .Long(TiffTags.NewSubfileType, 1) + .Long(TiffTags.ImageWidth, 160).Long(TiffTags.ImageLength, 120) + .Short(TiffTags.BitsPerSample, 8, 8, 8).Short(TiffTags.Compression, 1).Strip(new byte[96]) + .Child(TiffTags.SubIfds, jpgFromRaw, raw) + .Child(TiffTags.ExifIfd, exif); + return TiffFile.Build(ifd0, littleEndian: false); + } + + /// DNG: IFD0 thumbnail with CameraSerialNumber; SubIFDs 16-bit CFA raw (4032×3024, lossless JPEG strip, + /// excluded as CFA) and a 1024×768 YCbCr JPEG preview (NewSubfileType 1). + public static byte[] Dng() + { + var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0) + .Long(TiffTags.ImageWidth, 4032).Long(TiffTags.ImageLength, 3024) + .Short(TiffTags.BitsPerSample, 16).Short(TiffTags.Compression, 7) + .Short(TiffTags.PhotometricInterpretation, 32803).Strip(JpegBuilder.Minimal(2016, 3024, 0xC3, 12)); + var preview = new IfdSpec().Long(TiffTags.NewSubfileType, 1) + .Long(TiffTags.ImageWidth, 1024).Long(TiffTags.ImageLength, 768) + .Short(TiffTags.BitsPerSample, 8, 8, 8).Short(TiffTags.Compression, 7) + .Short(TiffTags.PhotometricInterpretation, 6).Strip(JpegBuilder.Minimal(1024, 768)); + var ifd0 = Ifd0("Google", "Pixel 8", 1) + .Long(TiffTags.NewSubfileType, 1) + .Long(TiffTags.ImageWidth, 256).Long(TiffTags.ImageLength, 192) + .Short(TiffTags.BitsPerSample, 8, 8, 8).Short(TiffTags.Compression, 1).Short(TiffTags.PhotometricInterpretation, 2) + .Strip(new byte[48]) + .Bytes(TiffTags.DngVersion, 1, 4, 0, 0) + .Ascii(TiffTags.CameraSerialNumber, "DNGSER1") + .Child(TiffTags.SubIfds, raw, preview) + .Child(TiffTags.ExifIfd, ExifIfd(identity: false)); + return TiffFile.Build(ifd0); + } + + /// ARW: IFD0 is a 1616×1080 JPEG preview, SubIFD the 12-bit raw; "SONY DSC" MakerNote with LensSpec. + public static byte[] Arw() + { + var sony = new IfdSpec() + .Long(0xB021, 5600) + .Long(0xB026, 1) + .Undefined(0xB02A, [0x00, 0x00, 0x24, 0x00, 0x70, 0x28, 0x28, 0x00]); + var exif = ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [.. "SONY DSC \0\0\0"u8], sony, relativeToTiff: true, littleEndian: true); + var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0) + .Long(TiffTags.ImageWidth, 6048).Long(TiffTags.ImageLength, 4024) + .Short(TiffTags.BitsPerSample, 12).Short(TiffTags.Compression, 32767) + .Short(TiffTags.PhotometricInterpretation, 32803).Strip(new byte[64]); + var ifd0 = Ifd0("SONY", "ILCE-7M3", 1) + .Long(TiffTags.NewSubfileType, 1).Short(TiffTags.Compression, 6) + .Blob(TiffTags.JpegInterchangeFormat, TiffTags.JpegInterchangeFormatLength, JpegBuilder.Minimal(1616, 1080)) + .Child(TiffTags.SubIfds, raw) + .Child(TiffTags.ExifIfd, exif); + return TiffFile.Build(ifd0); + } + + /// ORF ("IIRO"): raw in IFD0; "OM SYSTEM" MakerNote with Equipment (serial, lens) and CameraSettings + /// (3200×2400 preview at a MakerNote-relative offset, IS on). + public static byte[] Orf() + { + var equipment = new IfdSpec().Ascii(0x0101, "BHX123").Ascii(0x0203, "M.Zuiko 12-40mm F2.8"); + var settings = new IfdSpec().Long(0x0100, 1).Blob(0x0101, 0x0102, JpegBuilder.Minimal(3200, 2400)).Long(0x0604, 1); + var olympus = new IfdSpec().Child(0x2010, equipment).Child(0x2020, settings); + var exif = ExifIfd(identity: false) + .Embedded(TiffTags.MakerNote, [.. "OM SYSTEM\0\0\0II"u8, 4, 0], olympus, relativeToTiff: false, littleEndian: true); + var ifd0 = Ifd0("OM Digital Solutions", "OM-1", 1) + .Long(TiffTags.ImageWidth, 5240).Long(TiffTags.ImageLength, 3912) + .Short(TiffTags.BitsPerSample, 12).Short(TiffTags.Compression, 1).Strip(new byte[64]) + .Child(TiffTags.ExifIfd, exif); + return TiffFile.Build(ifd0, magic: "IIRO"); + } + + /// RW2 ("IIU\0"): sensor borders give 5776×4344, 12-bit, ISO 800; JpgFromRaw (1920×1440) carries the Exif + /// block with a Panasonic MakerNote (internal serial, lens type, IS, colour temperature). + public static byte[] Rw2() + { + var panasonic = new IfdSpec() + .Short(0x001A, 2) + .Undefined(0x0025, [.. "F541504040123"u8, 0, 0, 0]) + .Short(0x0044, 5000) + .Ascii(0x0051, "LUMIX G VARIO 12-60mm"); + var exif = ExifIfd(identity: false, iso: 800) + .Embedded(TiffTags.MakerNote, [.. "Panasonic\0\0\0"u8], panasonic, relativeToTiff: true, littleEndian: true); + var jpeg = new JpegBuilder().Exif(ExifTiff(true, exif, Ifd0("Panasonic", "DC-GH6", 1))).Build(1920, 1440); + var ifd0 = new IfdSpec() + .Short(0x0002, 5800).Short(0x0003, 4360) + .Short(0x0004, 8).Short(0x0005, 12).Short(0x0006, 4352).Short(0x0007, 5788) + .Short(0x000A, 12).Short(0x0017, 800) + .Undefined(0x002E, jpeg) + .Ascii(TiffTags.Make, "Panasonic").Ascii(TiffTags.Model, "DC-GH6").Short(TiffTags.Orientation, 1); + return TiffFile.Build(ifd0, magic: "IIU\0"); + } + + /// CR3: CMT1–4 + THMB in the Canon uuid, PRVW in the preview uuid, track 1 full-size JPEG (8192×5464), + /// track 2 raw with CMP1 (8352×5586, 14-bit); mdat comes last. + public static byte[] Cr3() => Cr3(out _); + + public static byte[] Cr3(out int mdatStart) + { + var full = JpegBuilder.Minimal(8192, 5464); + var canonMakerNote = TiffFile.Build(new IfdSpec().Long(0x000C, 98765).Ascii(0x0095, "RF24-105mm F4 L IS USM")); + var cmt2 = new IfdSpec() + .Rational(TiffTags.ExposureTime, (1, 100)).Rational(TiffTags.FNumber, (4, 1)).Short(TiffTags.IsoSpeedRatings, 100) + .Ascii(TiffTags.DateTimeOriginal, "2024:06:01 08:00:00").Ascii(TiffTags.SubSecTimeOriginal, "50") + .Ascii(TiffTags.OffsetTimeOriginal, "-04:00"); + var thumb = JpegBuilder.Minimal(160, 120); + var canon = Box.Uuid(CanonUuid, + Box.Make("CNCV", Box.Ascii("CanonCR3_001/00.09.00/00.00.00")), + Box.Make("CMT1", TiffFile.Build(Ifd0("Canon", "Canon EOS R5", 8).Long(TiffTags.ImageWidth, 8192).Long(TiffTags.ImageLength, 5464))), + Box.Make("CMT2", TiffFile.Build(cmt2)), + Box.Make("CMT3", canonMakerNote), + Box.Make("CMT4", TiffFile.Build(GpsIfd())), + Box.Make("THMB", [0, 0, 0, 0], Box.U16(160), Box.U16(120), Box.U32((uint)thumb.Length), Box.U16(0xFF), Box.U16(0xFF), thumb)); + var prvwJpeg = JpegBuilder.Minimal(1620, 1080); + var preview = Box.Uuid(PreviewUuid, Box.U64(0), + Box.Make("PRVW", Box.U32(0), Box.U16(1), Box.U16(1620), Box.U16(1080), Box.U16(1), Box.U32((uint)prvwJpeg.Length), prvwJpeg)); + + byte[] Build(uint jpegOffset) + { + var moov = Box.Make("moov", canon, Box.Make("mvhd", Box.Zeros(100)), + Track(Box.Make("JPEG", Box.Zeros(4)), Box.U32(0), Box.U32(1), Box.U32((uint)full.Length), jpegOffset, 8192, 5464), + Track(Box.Make("CMP1", Box.U16(0), Box.U16(0x30), Box.U32(0x100), Box.U32(8352), Box.U32(5586), Box.U32(512), Box.U32(512), [14, 0x11, 0, 0]), + Box.U32(0), Box.U32(1), Box.U32(1000), jpegOffset + (uint)full.Length, 8352, 5586)); + return [.. Box.Make("ftyp", Box.Ascii("crx "), Box.U32(1), Box.Ascii("crx isom")), .. moov, .. preview]; + } + + var head = Build(0); + var offset = (uint)(head.Length + 8); + head = Build(offset); + mdatStart = head.Length; + var mdat = new byte[8 + full.Length + 1000]; + BinaryPrimitives.WriteUInt32BigEndian(mdat, (uint)mdat.Length); + "mdat"u8.CopyTo(mdat.AsSpan(4)); + full.CopyTo(mdat, 8); + return [.. head, .. mdat]; + + static byte[] Track(byte[] entryChild, byte[] sampleSize, byte[] sampleCount, byte[] firstSize, uint chunkOffset, ushort width, ushort height) + { + var craw = Box.Make("CRAW", Box.Zeros(6), Box.U16(1), Box.Zeros(16), Box.U16(width), Box.U16(height), + Box.U32(0x00480000), Box.U32(0x00480000), Box.U32(0), Box.U16(1), Box.Zeros(32), Box.U16(24), Box.U16(0xFFFF), entryChild); + var stbl = Box.Make("stbl", + Box.Full("stsd", 0, 0, Box.U32(1), craw), + Box.Full("stsz", 0, 0, sampleSize, sampleCount, firstSize), + Box.Full("stco", 0, 0, Box.U32(1), Box.U32(chunkOffset))); + return Box.Make("trak", Box.Make("mdia", Box.Make("minf", stbl))); + } + } + + /// HEIC: primary hvc1 item 4032×3024 (ispe), 10-bit pixi, irot 1 (+ imir axis 1 when ), + /// Exif item (orientation 6, ignored when transforms exist) and a two-extent XMP item. + public static byte[] Heic(bool rotate = true, bool mirror = false, string major = "heic") + { + var exifPayload = (byte[])[.. Box.U32(6), .. "Exif\0\0"u8, .. ExifTiff()]; + var xmp = Encoding.UTF8.GetBytes(Xmp); + var split = xmp.Length / 2; + var codec = major == "avif" ? "av01" : "hvc1"; + + byte[] Build(uint mdatData) + { + var exifAt = mdatData + 64; + var xmpAt = exifAt + (uint)exifPayload.Length; + var properties = new List { Box.Full("ispe", 0, 0, Box.U32(4032), Box.U32(3024)), Box.Full("pixi", 0, 0, [3, 10, 10, 10]) }; + if (rotate) properties.Add(Box.Make("irot", [1])); + if (mirror) properties.Add(Box.Make("imir", [1])); + var associations = Enumerable.Range(1, properties.Count).Select(i => (byte)(0x80 | i)).ToArray(); + var meta = Box.Full("meta", 0, 0, + Box.Full("hdlr", 0, 0, Box.U32(0), Box.Ascii("pict"), Box.Zeros(12), [0]), + Box.Full("pitm", 0, 0, Box.U16(1)), + Box.Full("iinf", 0, 0, Box.U16(3), + Box.Full("infe", 2, 0, Box.U16(1), Box.U16(0), Box.Ascii(codec), [0]), + Box.Full("infe", 2, 0, Box.U16(2), Box.U16(0), Box.Ascii("Exif"), [0]), + Box.Full("infe", 2, 0, Box.U16(3), Box.U16(0), Box.Ascii("mime"), [0], Box.Ascii("application/rdf+xml"), [0])), + Box.Full("iloc", 1, 0, [0x44, 0x00], Box.U16(3), + Box.U16(1), Box.U16(0), Box.U16(0), Box.U16(1), Box.U32(mdatData), Box.U32(64), + Box.U16(2), Box.U16(0), Box.U16(0), Box.U16(1), Box.U32(exifAt), Box.U32((uint)exifPayload.Length), + Box.U16(3), Box.U16(0), Box.U16(0), Box.U16(2), Box.U32(xmpAt), Box.U32((uint)split), Box.U32(xmpAt + (uint)split), Box.U32((uint)(xmp.Length - split))), + Box.Make("iprp", + Box.Make("ipco", [.. properties.SelectMany(p => p)]), + Box.Full("ipma", 0, 0, Box.U32(1), Box.U16(1), [(byte)associations.Length], associations))); + return [.. Box.Make("ftyp", Box.Ascii(major), Box.U32(0), Box.Ascii("mif1"), Box.Ascii(major)), .. meta]; + } + + var head = Build(0); + var data = (uint)(head.Length + 8); + head = Build(data); + return [.. head, .. Box.Make("mdat", Box.Zeros(64), exifPayload, xmp)]; + } + + /// RAF: big-endian directory; embedded 1920×1280 JPEG with Exif and a Fujifilm MakerNote; RAF records give + /// 7752×5178 (cropped) and the FujiIFD 14-bit. + public static byte[] Raf() + { + var fuji = new IfdSpec().Ascii(0x0010, "FF02B1234567").Short(0x1005, 6100).Short(0x1422, 2, 1, 0); + var exif = ExifIfd(identity: false) + .Embedded(TiffTags.MakerNote, [.. "FUJIFILM"u8, 12, 0, 0, 0], fuji, relativeToTiff: false, littleEndian: true); + var jpeg = new JpegBuilder().Exif(ExifTiff(true, exif, Ifd0("FUJIFILM", "X-T5", 1))).Build(1920, 1280); + var records = (byte[])[.. Box.U32(2), .. Box.U16(0x0100), .. Box.U16(4), .. Box.U16(5280), .. Box.U16(7920), + .. Box.U16(0x0111), .. Box.U16(4), .. Box.U16(5178), .. Box.U16(7752)]; + var fujiIfd = TiffFile.Build(new IfdSpec().Child(0xF000, new IfdSpec().Long(0xF001, 7920).Long(0xF002, 5280).Long(0xF003, 14)), littleEndian: false); + var jpegOffset = 0x6C; + var recordsOffset = jpegOffset + jpeg.Length; + var cfaOffset = recordsOffset + records.Length; + var header = new byte[0x6C]; + "FUJIFILMCCD-RAW 0201FF129502"u8.CopyTo(header); + "X-T5"u8.CopyTo(header.AsSpan(0x1C)); + "0100"u8.CopyTo(header.AsSpan(0x3C)); + uint[] directory = [(uint)jpegOffset, (uint)jpeg.Length, (uint)recordsOffset, (uint)records.Length, (uint)cfaOffset, (uint)fujiIfd.Length]; + for (var i = 0; i < directory.Length; i++) BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(0x54 + 4 * i), directory[i]); + return [.. header, .. jpeg, .. records, .. fujiIfd]; + } + + /// WebP with VP8X canvas 3000×2000, a VP8L bitstream, EXIF (no prefix) and XMP chunks. + public static byte[] WebP() + { + byte[] vp8x = [0x0C, 0, 0, 0, .. UInt24(2999), .. UInt24(1999)]; + var body = (byte[])[.. "WEBP"u8, .. Box.Riff("VP8X", vp8x), .. Box.Riff("VP8L", Vp8L(3000, 2000)), + .. Box.Riff("EXIF", ExifTiff(false)), .. Box.Riff("XMP ", Encoding.UTF8.GetBytes(Xmp))]; + return [.. "RIFF"u8, .. LittleEndian32(body.Length), .. body]; + } + + /// Simple lossy WebP (VP8 key frame) without metadata. + public static byte[] WebPLossy(int width, int height) + { + byte[] frame = [0x10, 0x02, 0x00, 0x9D, 0x01, 0x2A, (byte)width, (byte)(width >> 8), (byte)height, (byte)(height >> 8), 0, 0]; + var body = (byte[])[.. "WEBP"u8, .. Box.Riff("VP8 ", frame)]; + return [.. "RIFF"u8, .. LittleEndian32(body.Length), .. body]; + } + + public static byte[] Vp8L(int width, int height) + { + var bits = (uint)(width - 1) | (uint)(height - 1) << 14; + return [0x2F, .. LittleEndian32((int)bits), 0]; + } + + /// PNG 2048×1536 16-bit RGB with eXIf (big-endian TIFF), iTXt XMP (zlib-compressed when asked), IDAT, IEND. + public static byte[] Png(bool compressedXmp = false) + { + var ihdr = (byte[])[.. Box.U32(2048), .. Box.U32(1536), 16, 2, 0, 0, 0]; + var xmp = Encoding.UTF8.GetBytes(Xmp); + if (compressedXmp) + { + using var output = new MemoryStream(); + using (var z = new System.IO.Compression.ZLibStream(output, System.IO.Compression.CompressionLevel.Optimal, leaveOpen: true)) z.Write(xmp); + xmp = output.ToArray(); + } + var itxt = (byte[])[.. "XML:com.adobe.xmp\0"u8, compressedXmp ? (byte)1 : (byte)0, 0, 0, 0, .. xmp]; + return [0x89, .. "PNG\r\n\u001a\n"u8, .. Box.Png("IHDR", ihdr), .. Box.Png("eXIf", ExifTiff(false)), + .. Box.Png("iTXt", itxt), .. Box.Png("IDAT", new byte[32]), .. Box.Png("IEND", [])]; + } + + /// Every fixture by name, for table-driven and fuzz tests. + public static byte[] ByName(string name) => name switch + { + "jpeg" => Jpeg(), + "jpeg-be" => Jpeg(false), + "cr2" => Cr2(), + "nef" => Nef(), + "dng" => Dng(), + "arw" => Arw(), + "orf" => Orf(), + "rw2" => Rw2(), + "cr3" => Cr3(), + "heic" => Heic(), + "avif" => Heic(major: "avif"), + "raf" => Raf(), + "webp" => WebP(), + "png" => Png(), + "png-z" => Png(compressedXmp: true), + _ => throw new ArgumentException(name), + }; + + private static byte[] UInt24(int v) => [(byte)v, (byte)(v >> 8), (byte)(v >> 16)]; + + private static byte[] LittleEndian32(int v) + { + var b = new byte[4]; + BinaryPrimitives.WriteInt32LittleEndian(b, v); + return b; + } +} diff --git a/tests/Titano.Core.Tests/Metadata/Builders/IfdSpec.cs b/tests/Titano.Core.Tests/Metadata/Builders/IfdSpec.cs new file mode 100644 index 00000000..393cbfc0 --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/Builders/IfdSpec.cs @@ -0,0 +1,276 @@ +using System.Buffers.Binary; +using System.Text; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Tests.Metadata.Builders; + +/// Declarative IFD for synthetic test files: typed values, child-IFD pointers, data blobs and embedded +/// (MakerNote-style) IFDs. Serialised by in either byte order. +internal sealed class IfdSpec +{ + internal abstract record Entry(ushort Tag); + + internal sealed record ValueEntry(ushort Tag, TiffType Type, object Data) : Entry(Tag); + + internal sealed record ChildrenEntry(ushort Tag, IfdSpec[] Children) : Entry(Tag); + + internal sealed record BlobEntry(ushort Tag, byte[] Data) : Entry(Tag); + + internal sealed record EmbeddedEntry(ushort Tag, byte[] Prefix, IfdSpec Ifd, bool RelativeToTiff, bool LittleEndian) : Entry(Tag); + + public List Entries { get; } = []; + + /// Next IFD in the chain (IFD1 after IFD0…). + public IfdSpec? Next { get; set; } + + public IfdSpec Ascii(ushort tag, string value) => Add(new ValueEntry(tag, TiffType.Ascii, value)); + + public IfdSpec Short(ushort tag, params ushort[] values) => Add(new ValueEntry(tag, TiffType.Short, values)); + + public IfdSpec Long(ushort tag, params uint[] values) => Add(new ValueEntry(tag, TiffType.Long, values)); + + public IfdSpec Rational(ushort tag, params (uint, uint)[] values) => Add(new ValueEntry(tag, TiffType.Rational, values)); + + public IfdSpec SRational(ushort tag, int numerator, int denominator) => Add(new ValueEntry(tag, TiffType.SRational, new[] { (numerator, denominator) })); + + public IfdSpec Undefined(ushort tag, byte[] data) => Add(new ValueEntry(tag, TiffType.Undefined, data)); + + public IfdSpec Bytes(ushort tag, params byte[] data) => Add(new ValueEntry(tag, TiffType.Byte, data)); + + /// LONG pointer(s) to child IFDs (Exif, GPS, SubIFDs, MakerNote sub-directories). + public IfdSpec Child(ushort tag, params IfdSpec[] children) => Add(new ChildrenEntry(tag, children)); + + /// LONG offset to (placed after all IFDs) plus an optional LONG length tag. + public IfdSpec Blob(ushort offsetTag, ushort? lengthTag, byte[] data) + { + Add(new BlobEntry(offsetTag, data)); + return lengthTag is { } t ? Long(t, (uint)data.Length) : this; + } + + public IfdSpec Strip(byte[] data) => Blob(TiffTags.StripOffsets, TiffTags.StripByteCounts, data); + + /// UNDEFINED value made of and an IFD whose offsets are relative to the TIFF base + /// () or to the start of the value itself. + public IfdSpec Embedded(ushort tag, byte[] prefix, IfdSpec ifd, bool relativeToTiff, bool littleEndian) => + Add(new EmbeddedEntry(tag, prefix, ifd, relativeToTiff, littleEndian)); + + public IfdSpec Without(params ushort[] tags) + { + Entries.RemoveAll(e => tags.Contains(e.Tag)); + return this; + } + + private IfdSpec Add(Entry entry) + { + Entries.RemoveAll(e => e.Tag == entry.Tag); + Entries.Add(entry); + return this; + } +} + +/// Serialises trees: IFDs in depth-first order, each followed by its values, blobs last. +internal static class TiffFile +{ + /// A complete TIFF file/block with header ( overrides "II*\0"/"MM\0*", e.g. "IIRO"); + /// follows the 8-byte header (the CR2 "CR" marker block). + public static byte[] Build(IfdSpec ifd0, bool littleEndian = true, string? magic = null, byte[]? headerExtra = null) + { + var w = new IfdWriter(littleEndian, 0); + w.Raw(Encoding.Latin1.GetBytes(magic ?? (littleEndian ? "II*\0" : "MM\0*"))); + w.Raw(new byte[4]); + if (headerExtra is not null) w.Raw(headerExtra); + w.PatchU32(4, (uint)w.WriteChain(ifd0)); + w.FlushBlobs(); + return w.ToArray(); + } + + /// An IFD and its values laid out as if placed at relative to the offset base. + public static byte[] Block(IfdSpec ifd, bool littleEndian, int origin) + { + var w = new IfdWriter(littleEndian, origin); + w.WriteChain(ifd); + w.FlushBlobs(); + return w.ToArray(); + } + + private sealed class IfdWriter(bool le, int origin) + { + private readonly List _b = []; + private readonly List<(int Patch, byte[] Data)> _blobs = []; + + public byte[] ToArray() => _b.ToArray(); + + public void Raw(byte[] bytes) => _b.AddRange(bytes); + + public int WriteChain(IfdSpec spec) + { + var position = WriteIfd(spec, out var nextPatch); + if (spec.Next is { } next) PatchU32(nextPatch, (uint)WriteChain(next)); + return position; + } + + public void FlushBlobs() + { + foreach (var (patch, data) in _blobs) + { + Align(); + PatchU32(patch, (uint)(origin + _b.Count)); + _b.AddRange(data); + } + _blobs.Clear(); + } + + public void PatchU32(int at, uint value) + { + Span s = stackalloc byte[4]; + if (le) BinaryPrimitives.WriteUInt32LittleEndian(s, value); + else BinaryPrimitives.WriteUInt32BigEndian(s, value); + for (var i = 0; i < 4; i++) _b[at + i] = s[i]; + } + + private void PatchU16(int at, ushort value) + { + Span s = stackalloc byte[2]; + if (le) BinaryPrimitives.WriteUInt16LittleEndian(s, value); + else BinaryPrimitives.WriteUInt16BigEndian(s, value); + _b[at] = s[0]; + _b[at + 1] = s[1]; + } + + private void Align() + { + if ((origin + _b.Count) % 2 != 0) _b.Add(0); + } + + private int WriteIfd(IfdSpec spec, out int nextPatch) + { + Align(); + var start = _b.Count; + var entries = spec.Entries.OrderBy(e => e.Tag).ToList(); + _b.AddRange(new byte[2 + 12 * entries.Count + 4]); + PatchU16(start, (ushort)entries.Count); + nextPatch = start + 2 + 12 * entries.Count; + var children = new List<(int Patch, IfdSpec Child)>(); + for (var i = 0; i < entries.Count; i++) + { + var at = start + 2 + 12 * i; + var e = entries[i]; + PatchU16(at, e.Tag); + switch (e) + { + case IfdSpec.ValueEntry v: + var (bytes, count) = Encode(v); + PutValue(at, v.Type, count, bytes); + break; + case IfdSpec.ChildrenEntry c: + PatchU16(at + 2, (ushort)TiffType.Long); + PatchU32(at + 4, (uint)c.Children.Length); + if (c.Children.Length == 1) + { + children.Add((at + 8, c.Children[0])); + } + else + { + Align(); + PatchU32(at + 8, (uint)(origin + _b.Count)); + for (var k = 0; k < c.Children.Length; k++) + { + children.Add((_b.Count, c.Children[k])); + _b.AddRange(new byte[4]); + } + } + break; + case IfdSpec.BlobEntry blob: + PatchU16(at + 2, (ushort)TiffType.Long); + PatchU32(at + 4, 1); + _blobs.Add((at + 8, blob.Data)); + break; + case IfdSpec.EmbeddedEntry m: + Align(); + var position = origin + _b.Count; + var block = Block(m.Ifd, m.LittleEndian, m.RelativeToTiff ? position + m.Prefix.Length : m.Prefix.Length); + PatchU16(at + 2, (ushort)TiffType.Undefined); + PatchU32(at + 4, (uint)(m.Prefix.Length + block.Length)); + PatchU32(at + 8, (uint)position); + _b.AddRange(m.Prefix); + _b.AddRange(block); + break; + } + } + foreach (var (patch, child) in children) PatchU32(patch, (uint)WriteChain(child)); + return origin + start; + } + + private void PutValue(int at, TiffType type, uint count, byte[] bytes) + { + PatchU16(at + 2, (ushort)type); + PatchU32(at + 4, count); + if (bytes.Length <= 4) + { + for (var i = 0; i < bytes.Length; i++) _b[at + 8 + i] = bytes[i]; + return; + } + Align(); + PatchU32(at + 8, (uint)(origin + _b.Count)); + _b.AddRange(bytes); + } + + private (byte[] Bytes, uint Count) Encode(IfdSpec.ValueEntry v) + { + switch (v.Data) + { + case string s: + var ascii = Encoding.UTF8.GetBytes(s + "\0"); + return (ascii, (uint)ascii.Length); + case byte[] raw: + return (raw, (uint)raw.Length); + case ushort[] shorts: + { + var b = new byte[2 * shorts.Length]; + for (var i = 0; i < shorts.Length; i++) Write16(b.AsSpan(2 * i), shorts[i]); + return (b, (uint)shorts.Length); + } + case uint[] longs: + { + var b = new byte[4 * longs.Length]; + for (var i = 0; i < longs.Length; i++) Write32(b.AsSpan(4 * i), longs[i]); + return (b, (uint)longs.Length); + } + case (uint, uint)[] rationals: + { + var b = new byte[8 * rationals.Length]; + for (var i = 0; i < rationals.Length; i++) + { + Write32(b.AsSpan(8 * i), rationals[i].Item1); + Write32(b.AsSpan(8 * i + 4), rationals[i].Item2); + } + return (b, (uint)rationals.Length); + } + case (int, int)[] signed: + { + var b = new byte[8 * signed.Length]; + for (var i = 0; i < signed.Length; i++) + { + Write32(b.AsSpan(8 * i), (uint)signed[i].Item1); + Write32(b.AsSpan(8 * i + 4), (uint)signed[i].Item2); + } + return (b, (uint)signed.Length); + } + default: + throw new InvalidOperationException("Unsupported test value " + v.Data.GetType()); + } + } + + private void Write16(Span s, ushort v) + { + if (le) BinaryPrimitives.WriteUInt16LittleEndian(s, v); + else BinaryPrimitives.WriteUInt16BigEndian(s, v); + } + + private void Write32(Span s, uint v) + { + if (le) BinaryPrimitives.WriteUInt32LittleEndian(s, v); + else BinaryPrimitives.WriteUInt32BigEndian(s, v); + } + } +} diff --git a/tests/Titano.Core.Tests/Metadata/Builders/JpegBuilder.cs b/tests/Titano.Core.Tests/Metadata/Builders/JpegBuilder.cs new file mode 100644 index 00000000..04a3b1bd --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/Builders/JpegBuilder.cs @@ -0,0 +1,149 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Titano.Core.Tests.Metadata.Builders; + +/// Synthetic JPEG: SOI, arbitrary segments/raw bytes, an optional APP2 MPF index of appended secondary +/// images, SOFn, SOS with a fake scan, EOI. No real entropy data: parsers stop at SOS. +internal sealed class JpegBuilder +{ + public const string XmpSignature = "http://ns.adobe.com/xap/1.0/\0"; + public const string ExtendedXmpSignature = "http://ns.adobe.com/xmp/extension/\0"; + + private readonly List _parts = []; + private readonly List<(byte[] Jpeg, uint Type)> _secondary = []; + private int _mpfPart = -1; + + /// A minimal JPEG with just a frame header (used as embedded previews). + public static byte[] Minimal(int width, int height, byte sofMarker = 0xC0, int precision = 8, int scanBytes = 32) => + new JpegBuilder().Build(width, height, sofMarker, precision, scanBytes); + + public JpegBuilder Segment(byte marker, byte[] payload) + { + var s = new byte[4 + payload.Length]; + s[0] = 0xFF; + s[1] = marker; + BinaryPrimitives.WriteUInt16BigEndian(s.AsSpan(2), (ushort)(payload.Length + 2)); + payload.CopyTo(s, 4); + _parts.Add(s); + return this; + } + + /// Bytes inserted verbatim (fill bytes, garbage). + public JpegBuilder Raw(params byte[] bytes) + { + _parts.Add(bytes); + return this; + } + + public JpegBuilder Exif(byte[] tiff) => Segment(0xE1, [.. "Exif\0\0"u8, .. tiff]); + + public JpegBuilder Xmp(string packet) => Segment(0xE1, [.. Encoding.ASCII.GetBytes(XmpSignature), .. Encoding.UTF8.GetBytes(packet)]); + + /// Extended XMP split into -byte APP1 segments (written in reverse order to prove + /// reassembly uses offsets). + public JpegBuilder ExtendedXmp(string guid, string packet, int chunk) + { + var data = Encoding.UTF8.GetBytes(packet); + var segments = new List(); + for (var offset = 0; offset < data.Length; offset += chunk) + { + var piece = data.AsSpan(offset, Math.Min(chunk, data.Length - offset)); + var payload = new byte[ExtendedXmpSignature.Length + 32 + 8 + piece.Length]; + Encoding.ASCII.GetBytes(ExtendedXmpSignature).CopyTo(payload, 0); + Encoding.ASCII.GetBytes(guid).CopyTo(payload, ExtendedXmpSignature.Length); + BinaryPrimitives.WriteUInt32BigEndian(payload.AsSpan(ExtendedXmpSignature.Length + 32), (uint)data.Length); + BinaryPrimitives.WriteUInt32BigEndian(payload.AsSpan(ExtendedXmpSignature.Length + 36), (uint)offset); + piece.CopyTo(payload.AsSpan(ExtendedXmpSignature.Length + 40)); + segments.Add(payload); + } + segments.Reverse(); + foreach (var s in segments) Segment(0xE1, s); + return this; + } + + /// APP2 MPF index; each secondary JPEG is appended after the primary's EOI with the given MP type code. + public JpegBuilder Mpf(params (byte[] Jpeg, uint Type)[] secondary) + { + _secondary.AddRange(secondary); + _mpfPart = _parts.Count; + _parts.Add([]); + return this; + } + + public byte[] Build(int width, int height, byte sofMarker = 0xC0, int precision = 8, int scanBytes = 32) + { + var tail = new List(); + tail.AddRange(SegmentBytes(sofMarker, [(byte)precision, (byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width, 3, 1, 0x22, 0, 2, 0x11, 1, 3, 0x11, 1])); + tail.AddRange(SegmentBytes(0xDA, [3, 1, 0, 2, 0x11, 3, 0x11, 0, 0x3F, 0])); + for (var i = 0; i < scanBytes; i++) tail.Add((byte)(i * 37 % 255)); + tail.AddRange([0xFF, 0xD9]); + + if (_mpfPart >= 0) _parts[_mpfPart] = SegmentBytes(0xE2, MpfPayload(new uint[_secondary.Count], 0)); + var headLength = 2 + _parts.Sum(p => p.Length); + var primaryLength = headLength + tail.Count; + if (_mpfPart >= 0) + { + var mpHeader = 2 + _parts.Take(_mpfPart).Sum(p => p.Length) + 4 + 4; + var offsets = new uint[_secondary.Count]; + var at = primaryLength; + for (var i = 0; i < offsets.Length; i++) + { + offsets[i] = (uint)(at - mpHeader); + at += _secondary[i].Jpeg.Length; + } + _parts[_mpfPart] = SegmentBytes(0xE2, MpfPayload(offsets, primaryLength)); + } + + var file = new List(primaryLength); + file.AddRange([0xFF, 0xD8]); + foreach (var p in _parts) file.AddRange(p); + file.AddRange(tail); + foreach (var (jpeg, _) in _secondary) file.AddRange(jpeg); + return file.ToArray(); + + byte[] MpfPayload(uint[] offsets, int primarySize) + { + // "MPF\0", big-endian MP header, index IFD (version, count, entries), then 16-byte MP entries. + var n = offsets.Length + 1; + var b = new byte[4 + 8 + 2 + 3 * 12 + 4 + 16 * n]; + var s = b.AsSpan(); + "MPF\0MM\0*"u8.CopyTo(s); + BinaryPrimitives.WriteUInt32BigEndian(s[8..], 8); + var ifd = s[12..]; + BinaryPrimitives.WriteUInt16BigEndian(ifd, 3); + WriteEntry(ifd[2..], 0xB000, 7, 4, BinaryPrimitives.ReadUInt32BigEndian("0100"u8)); + WriteEntry(ifd[14..], 0xB001, 4, 1, (uint)n); + WriteEntry(ifd[26..], 0xB002, 7, (uint)(16 * n), 8 + 2 + 36 + 4); + var entries = s[(4 + 8 + 2 + 36 + 4)..]; + BinaryPrimitives.WriteUInt32BigEndian(entries, 0x20030000); + BinaryPrimitives.WriteUInt32BigEndian(entries[4..], (uint)primarySize); + for (var i = 0; i < offsets.Length; i++) + { + var e = entries[(16 * (i + 1))..]; + BinaryPrimitives.WriteUInt32BigEndian(e, _secondary[i].Type); + BinaryPrimitives.WriteUInt32BigEndian(e[4..], (uint)_secondary[i].Jpeg.Length); + BinaryPrimitives.WriteUInt32BigEndian(e[8..], offsets[i]); + } + return b; + } + } + + private static void WriteEntry(Span s, ushort tag, ushort type, uint count, uint value) + { + BinaryPrimitives.WriteUInt16BigEndian(s, tag); + BinaryPrimitives.WriteUInt16BigEndian(s[2..], type); + BinaryPrimitives.WriteUInt32BigEndian(s[4..], count); + BinaryPrimitives.WriteUInt32BigEndian(s[8..], value); + } + + private static byte[] SegmentBytes(byte marker, byte[] payload) + { + var s = new byte[4 + payload.Length]; + s[0] = 0xFF; + s[1] = marker; + BinaryPrimitives.WriteUInt16BigEndian(s.AsSpan(2), (ushort)(payload.Length + 2)); + payload.CopyTo(s, 4); + return s; + } +} diff --git a/tests/Titano.Core.Tests/Metadata/Builders/TestStreams.cs b/tests/Titano.Core.Tests/Metadata/Builders/TestStreams.cs new file mode 100644 index 00000000..e11ae79c --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/Builders/TestStreams.cs @@ -0,0 +1,86 @@ +namespace Titano.Core.Tests.Metadata.Builders; + +/// Read-only seekable stream: prefix bytes followed by zeros up to length. Simulates a large +/// RAW (image data never materialised) for I/O-bound tests. +internal sealed class SparseStream(byte[] prefix, long length) : Stream +{ + private long _position; + + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + public override long Length => length; + + public override long Position + { + get => _position; + set => _position = value; + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + var n = (int)Math.Max(0, Math.Min(buffer.Length, length - _position)); + for (var i = 0; i < n; i++) + { + var p = _position + i; + buffer[i] = p < prefix.Length ? prefix[p] : (byte)0; + } + _position += n; + return n; + } + + public override long Seek(long offset, SeekOrigin origin) => _position = origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => _position + offset, + _ => length + offset, + }; + + public override void Flush() + { + } + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} + +/// Counts the bytes returned by of the wrapped stream. +internal sealed class CountingStream(Stream inner) : Stream +{ + public long BytesRead { get; private set; } + public int ReadCalls { get; private set; } + + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + public override long Length => inner.Length; + + public override long Position + { + get => inner.Position; + set => inner.Position = value; + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + var n = inner.Read(buffer); + BytesRead += n; + ReadCalls++; + return n; + } + + public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin); + + public override void Flush() + { + } + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} diff --git a/tests/Titano.Core.Tests/Metadata/ExifTests.cs b/tests/Titano.Core.Tests/Metadata/ExifTests.cs new file mode 100644 index 00000000..b990d65e --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/ExifTests.cs @@ -0,0 +1,278 @@ +using Titano.Core.Imaging; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Model; +using Titano.Core.Tests.Metadata.Builders; +using Titano.Testing; +using static Titano.Core.Tests.Metadata.MetadataTestHelpers; + +namespace Titano.Core.Tests.Metadata; + +public sealed class ExifTests +{ + [Theory] + [Case(true)] + [Case(false)] + public void ReadsEveryFieldFromJpeg(bool littleEndian) + { + var m = Read(Fixtures.Jpeg(littleEndian), "IMG_0001.JPG"); + AssertNoFault(m); + Assert.Empty(m.Warnings); + Assert.Equal(ImageFileFormat.Jpeg, m.Format); + Assert.Equal(Fixtures.Make, m.Make); + Assert.Equal(Fixtures.Model, m.Model); + Assert.Equal("SN123", m.BodySerial); + Assert.Equal("TestLens 35mm", m.LensModel); + Assert.Equal("fw 1.0", m.Software); + Assert.Equal("Ada", m.Artist); + Assert.Equal("(c) Ada", m.Copyright); + Assert.Equal(Fixtures.Captured, m.CapturedAt); + Assert.Equal(DateTimeKind.Unspecified, m.CapturedAt!.Value.Kind); + Assert.Equal(120, m.UtcOffsetMinutes); + Assert.Equal(TimestampSource.ExifOriginal, m.TimestampSource); + Assert.Approximately(1 / 250.0, m.ExposureTime!.Value, 1e-12); + Assert.Approximately(5.6, m.FNumber!.Value, 1e-12); + Assert.Equal(400, m.Iso); + Assert.Approximately(35, m.FocalLength!.Value, 1e-12); + Assert.Approximately(52, m.FocalLength35!.Value, 1e-12); + Assert.Approximately(-2 / 3.0, m.ExposureBias!.Value, 1e-12); + Assert.Equal(3, m.ExposureProgram); + Assert.Equal(5, m.MeteringMode); + Assert.Equal(1, m.WhiteBalanceMode); + Assert.Equal(16, m.Flash); + Assert.Null(m.ColorTemperature); + Assert.Equal(6, m.Orientation); + Assert.Equal(4000, m.Width); + Assert.Equal(3000, m.Height); + Assert.Equal((3000, 4000), m.OrientedSize); + Assert.Equal(8, m.BitsPerSample); + var gps = Assert.NotNull(m.Gps); + Assert.Approximately(45.5, gps.Latitude, 1e-9); + Assert.Approximately(-9.26, gps.Longitude, 1e-9); + Assert.Approximately(120.5, gps.Altitude!.Value, 1e-9); + Assert.Equal(new DateTime(2024, 5, 1, 10, 34, 56, DateTimeKind.Utc), gps.UtcTimestamp); + Assert.Equal(4, m.Rating); + Assert.Equal("Red", m.Label); + AssertPreviews(m, (1920, 1440, PreviewKind.Preview), (160, 120, PreviewKind.Thumbnail)); + } + + [Test] + public void PreviewOffsetsPointAtJpegData() + { + var bytes = Fixtures.Jpeg(); + var m = Read(bytes); + foreach (var p in m.Previews) + { + Assert.Equal(0xFF, bytes[p.Offset]); + Assert.Equal(0xD8, bytes[p.Offset + 1]); + Assert.Equal(0xD9, bytes[p.Offset + p.Length - 1]); + } + } + + [Test] + public void FallsBackToDigitizedTime() + { + var m = ReadWithExif(Fixtures.ExifIfd().Without(TiffTags.DateTimeOriginal)); + Assert.Equal(TimestampSource.ExifCreate, m.TimestampSource); + Assert.Equal(new DateTime(2024, 5, 1, 12, 34, 57), m.CapturedAt); + } + + [Test] + public void FallsBackToXmpTime() + { + var xmp = """ + + + + """; + var exif = Fixtures.ExifIfd().Without(TiffTags.DateTimeOriginal, TiffTags.DateTimeDigitized); + var jpeg = new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0().Child(TiffTags.ExifIfd, exif))).Xmp(xmp).Build(64, 48); + var m = Read(jpeg); + Assert.Equal(TimestampSource.Xmp, m.TimestampSource); + Assert.Equal(new DateTime(2023, 12, 31, 23, 59, 58, 250), m.CapturedAt); + Assert.Equal(-300, m.UtcOffsetMinutes); + } + + [Test] + public void FallsBackToGpsTime() + { + var exif = Fixtures.ExifIfd().Without(TiffTags.DateTimeOriginal, TiffTags.DateTimeDigitized); + var m = ReadWithExif(exif); + Assert.Equal(TimestampSource.Gps, m.TimestampSource); + Assert.Equal(new DateTime(2024, 5, 1, 10, 34, 56), m.CapturedAt); + Assert.Equal(DateTimeKind.Unspecified, m.CapturedAt!.Value.Kind); + Assert.Equal(0, m.UtcOffsetMinutes); + } + + [Theory] + [Case(DateTimeKind.Utc, 0)] + [Case(DateTimeKind.Unspecified, null)] + public void FallsBackToFileTime(DateTimeKind kind, int? expectedOffset) + { + var jpeg = new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0())).Build(64, 48); + var modified = new DateTime(2022, 2, 3, 4, 5, 6, kind); + var m = Read(jpeg, null, modified); + Assert.Equal(TimestampSource.FileSystem, m.TimestampSource); + Assert.Equal(new DateTime(2022, 2, 3, 4, 5, 6), m.CapturedAt); + Assert.Equal(expectedOffset, m.UtcOffsetMinutes); + } + + [Test] + public void LocalFileTimeCarriesLocalOffset() + { + var modified = new DateTime(2022, 7, 3, 4, 5, 6, DateTimeKind.Local); + var m = Read(JpegBuilder.Minimal(8, 8), null, modified); + Assert.Equal((int)TimeZoneInfo.Local.GetUtcOffset(modified).TotalMinutes, m.UtcOffsetMinutes); + } + + [Test] + public void NoTimeAtAllIsUnknown() + { + var m = Read(JpegBuilder.Minimal(8, 8)); + Assert.Equal(TimestampSource.Unknown, m.TimestampSource); + Assert.Null(m.CapturedAt); + } + + [Theory] + [Case("5", "+05:30", 5_000_000L, 330)] + [Case("123456789", "-03:00", 1_234_567L, -180)] + [Case("007", "+0100", 70_000L, 60)] + [Case("", "Z", 0L, 0)] + [Case(" ", " : ", 0L, null)] + [Case("12x", "+25:00", 1_200_000L, null, Name = "trailing junk, offset out of range")] + public void ParsesSubSecondsAndOffsets(string subSec, string offset, long ticks, int? minutes) + { + var exif = Fixtures.ExifIfd().Ascii(TiffTags.SubSecTimeOriginal, subSec).Ascii(TiffTags.OffsetTimeOriginal, offset); + var m = ReadWithExif(exif); + Assert.Equal(new DateTime(2024, 5, 1, 12, 34, 56).AddTicks(ticks), m.CapturedAt); + Assert.Equal(minutes, m.UtcOffsetMinutes); + } + + [Test] + public void OffsetTimeIsTheFallbackOffset() + { + var exif = Fixtures.ExifIfd().Without(TiffTags.OffsetTimeOriginal).Ascii(TiffTags.OffsetTime, "-07:00"); + Assert.Equal(-420, ReadWithExif(exif).UtcOffsetMinutes); + } + + [Theory] + [Case("0000:00:00 00:00:00")] + [Case(" : : : : ")] + [Case("2024:13:01 10:00:00")] + [Case("2024:02:30 10:00:00")] + [Case("2024:05")] + public void RejectsInvalidDates(string value) + { + var exif = Fixtures.ExifIfd().Ascii(TiffTags.DateTimeOriginal, value); + Assert.Equal(TimestampSource.ExifCreate, ReadWithExif(exif).TimestampSource); + } + + [Theory] + [Case((ushort)1, 1)] + [Case((ushort)3, 3)] + [Case((ushort)5, 5)] + [Case((ushort)8, 8)] + [Case((ushort)0, 1)] + [Case((ushort)9, 1)] + public void ValidatesOrientation(ushort value, int expected) + { + var m = Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0(orientation: value))).Build(64, 48)); + Assert.Equal(expected, m.Orientation); + if (value is 0 or 9) Assert.Contains($"Invalid orientation {value} ignored", m.Warnings); + } + + [Test] + public void XmpOrientationAppliesWithoutExif() + { + var xmp = """3"""; + Assert.Equal(3, Read(new JpegBuilder().Xmp(xmp).Build(64, 48)).Orientation); + } + + [Theory] + [Case((ushort)65535, 102400u, 102400)] + [Case((ushort)65535, 0u, 65535, Name = "saturated without REI")] + [Case((ushort)0, 51200u, 51200, Name = "ISO absent")] + [Case((ushort)3200, 6400u, 3200, Name = "ISO wins when valid")] + public void ResolvesIso(ushort iso, uint rei, int expected) + { + var exif = Fixtures.ExifIfd(iso: iso); + if (rei > 0) exif.Long(TiffTags.RecommendedExposureIndex, rei); + Assert.Equal(expected, ReadWithExif(exif).Iso); + } + + [Test] + public void UsesStandardOutputSensitivityWhenIsoMissing() + { + var exif = Fixtures.ExifIfd(iso: 0).Long(TiffTags.StandardOutputSensitivity, 250); + Assert.Equal(250, ReadWithExif(exif).Iso); + } + + [Test] + public void DerivesExposureFromApexValues() + { + var exif = Fixtures.ExifIfd().Without(TiffTags.FNumber, TiffTags.ExposureTime) + .SRational(TiffTags.ShutterSpeedValue, 8, 1) + .Rational(TiffTags.ApertureValue, (5, 1)); + var m = ReadWithExif(exif); + Assert.Approximately(1 / 256.0, m.ExposureTime!.Value, 1e-12); + Assert.Approximately(Math.Pow(2, 2.5), m.FNumber!.Value, 1e-12); + } + + [Test] + public void IgnoresVoidGpsFix() + { + var gps = Fixtures.GpsIfd().Ascii(TiffTags.GpsStatus, "V"); + var tiff = TiffFile.Build(Fixtures.Ifd0().Child(TiffTags.GpsIfd, gps)); + var m = Read(new JpegBuilder().Exif(tiff).Build(64, 48)); + Assert.Null(m.Gps); + Assert.Equal(TimestampSource.Gps, m.TimestampSource); + } + + [Test] + public void RejectsOutOfRangeCoordinates() + { + var gps = Fixtures.GpsIfd().Rational(TiffTags.GpsLatitude, (95, 1), (0, 1), (0, 1)); + var m = Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0().Child(TiffTags.GpsIfd, gps))).Build(64, 48)); + Assert.Null(m.Gps); + } + + [Test] + public void ToleratesFillBytesAndGarbageBetweenSegments() + { + var jpeg = new JpegBuilder() + .Raw(0xFF, 0xFF, 0xFF) + .Exif(Fixtures.ExifTiff()) + .Raw(0x00, 0x13, 0x37, 0xFF) + .Segment(0xFE, "comment"u8.ToArray()) + .Build(1234, 567); + var m = Read(jpeg); + Assert.Equal(1234, m.Width); + Assert.Equal(567, m.Height); + Assert.Equal(Fixtures.Make, m.Make); + Assert.Contains("JPEG: garbage between segments skipped", m.Warnings); + } + + [Theory] + [Case((byte)0xC2, 8)] + [Case((byte)0xC1, 12)] + public void ReadsProgressiveAndExtendedFrames(byte sof, int precision) + { + var m = Read(JpegBuilder.Minimal(800, 600, sof, precision)); + Assert.Equal((800, 600), (m.Width, m.Height)); + Assert.Equal(precision, m.BitsPerSample); + } + + [Test] + public void TruncatedExifKeepsWhatWasRead() + { + var full = Fixtures.Jpeg(); + var cut = full.AsSpan(0, 140).ToArray(); + var m = Read(cut); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Jpeg, m.Format); + Assert.NotEmpty(m.Warnings); + } + + private static FrameMetadata ReadWithExif(IfdSpec exif) => + Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0().Child(TiffTags.ExifIfd, exif).Child(TiffTags.GpsIfd, Fixtures.GpsIfd()))).Build(64, 48)); +} diff --git a/tests/Titano.Core.Tests/Metadata/ExifWriterTests.cs b/tests/Titano.Core.Tests/Metadata/ExifWriterTests.cs new file mode 100644 index 00000000..3e962e5c --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/ExifWriterTests.cs @@ -0,0 +1,147 @@ +using System.Buffers.Binary; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Model; +using Titano.Testing; +using static Titano.Core.Tests.Metadata.MetadataTestHelpers; + +namespace Titano.Core.Tests.Metadata; + +public sealed class ExifWriterTests +{ + private static readonly FrameMetadata Sample = new() + { + Make = "TestCam", + Model = "TC-1 Mark II", + Orientation = 8, + Software = "Titano 1.0", + Artist = "Ada Lovelace", + Copyright = "© 2024 Ada", + CapturedAt = new DateTime(2024, 5, 1, 12, 34, 56).AddTicks(1_234_500), + UtcOffsetMinutes = -330, + ExposureTime = 1 / 8000.0, + FNumber = 2.8, + Iso = 3200, + FocalLength = 23.5, + FocalLength35 = 35, + ExposureBias = -1 / 3.0, + BodySerial = "BODY-42", + LensModel = "XF23mmF1.4 R", + Gps = new GpsPosition(-33.8567844, 151.2152967, -12.25, new DateTime(2024, 5, 1, 2, 4, 56, 500, DateTimeKind.Utc)), + }; + + [Test] + public void RoundTripsThroughMetadataReader() + { + var m = Read(Wrap(ExifWriter.BuildJpegApp1(Sample))); + AssertNoFault(m); + Assert.Equal(Sample.Make, m.Make); + Assert.Equal(Sample.Model, m.Model); + Assert.Equal(8, m.Orientation); + Assert.Equal(Sample.Software, m.Software); + Assert.Equal(Sample.Artist, m.Artist); + Assert.Equal(Sample.Copyright, m.Copyright); + Assert.Equal(Sample.CapturedAt, m.CapturedAt); + Assert.Equal(-330, m.UtcOffsetMinutes); + Assert.Equal(TimestampSource.ExifOriginal, m.TimestampSource); + Assert.Approximately(Sample.ExposureTime!.Value, m.ExposureTime!.Value, 1e-15); + Assert.Approximately(2.8, m.FNumber!.Value, 1e-12); + Assert.Equal(3200, m.Iso); + Assert.Approximately(23.5, m.FocalLength!.Value, 1e-12); + Assert.Approximately(35, m.FocalLength35!.Value, 1e-12); + Assert.Approximately(-1 / 3.0, m.ExposureBias!.Value, 1e-4); + Assert.Equal(Sample.BodySerial, m.BodySerial); + Assert.Equal(Sample.LensModel, m.LensModel); + var gps = Assert.NotNull(m.Gps); + Assert.Approximately(-33.8567844, gps.Latitude, 1e-7); + Assert.Approximately(151.2152967, gps.Longitude, 1e-7); + Assert.Approximately(-12.25, gps.Altitude!.Value, 1e-9); + Assert.Equal(Sample.Gps!.UtcTimestamp, gps.UtcTimestamp); + } + + [Test] + public void App1SegmentIsWellFormed() + { + var app1 = ExifWriter.BuildJpegApp1(Sample); + Assert.Equal(0xFF, app1[0]); + Assert.Equal(0xE1, app1[1]); + Assert.Equal(app1.Length - 2, BinaryPrimitives.ReadUInt16BigEndian(app1.AsSpan(2))); + Assert.True(app1.AsSpan(4).StartsWith("Exif\0\0II*\0"u8)); + } + + [Test] + public void TiffIsSortedAndPointersResolve() + { + var tiff = ExifWriter.BuildTiff(Sample); + var reader = Assert.NotNull(TiffReader.Open(new MemoryStream(tiff))); + Assert.True(reader.LittleEndian); + var chain = reader.ReadChain(); + Assert.Equal(1, chain.Count); + var ifd0 = chain[0]; + AssertSorted(reader, ifd0); + var exif = Assert.NotNull(reader.ReadIfd(reader.GetUInt(ifd0, TiffTags.ExifIfd)!.Value)); + AssertSorted(reader, exif); + Assert.Equal("0232", reader.GetString(exif, TiffTags.ExifVersion)); + Assert.NotNull(reader.ReadIfd(reader.GetUInt(ifd0, TiffTags.GpsIfd)!.Value)); + Assert.Empty(reader.Warnings); + } + + [Test] + public void OmitsUnknownValuesAndGps() + { + var tiff = ExifWriter.BuildTiff(new FrameMetadata { Make = "Only" }); + var reader = TiffReader.Open(new MemoryStream(tiff))!; + var ifd0 = reader.ReadChain()[0]; + Assert.False(ifd0.Has(TiffTags.GpsIfd)); + Assert.False(ifd0.Has(TiffTags.DateTime)); + Assert.Equal((ushort)1, (ushort)reader.GetUInt(ifd0, TiffTags.Orientation)!.Value); + var exif = reader.ReadIfd(reader.GetUInt(ifd0, TiffTags.ExifIfd)!.Value)!; + Assert.False(exif.Has(TiffTags.ExposureTime)); + Assert.False(exif.Has(TiffTags.SubSecTimeOriginal)); + Assert.False(exif.Has(TiffTags.OffsetTimeOriginal)); + } + + [Test] + public void HighIsoUsesRecommendedExposureIndex() + { + var m = Read(Wrap(ExifWriter.BuildJpegApp1(Sample with { Iso = 204800 }))); + Assert.Equal(204800, m.Iso); + } + + [Theory] + [Case(1 / 8000.0, 1u, 8000u)] + [Case(0.3, 3u, 10u)] + [Case(2.8, 14u, 5u)] + [Case(30.0, 30u, 1u)] + public void EncodesExposureRationals(double seconds, uint numerator, uint denominator) + { + var tiff = ExifWriter.BuildTiff(new FrameMetadata { ExposureTime = seconds }); + var reader = TiffReader.Open(new MemoryStream(tiff))!; + var exif = reader.ReadIfd(reader.GetUInt(reader.ReadChain()[0], TiffTags.ExifIfd)!.Value)!; + var raw = reader.ReadBytes(exif.Entries[TiffTags.ExposureTime])!; + Assert.Equal(numerator, BinaryPrimitives.ReadUInt32LittleEndian(raw)); + Assert.Equal(denominator, BinaryPrimitives.ReadUInt32LittleEndian(raw.AsSpan(4))); + } + + [Test] + public void TruncatesLongStringsOnCharacterBoundaries() + { + var longText = new string('é', ExifWriter.MaxStringBytes); + var app1 = ExifWriter.BuildJpegApp1(new FrameMetadata { Artist = longText, Copyright = longText, Make = longText, Model = longText, Software = longText, BodySerial = longText, LensModel = longText }); + Assert.Less(app1.Length, 65535); + var m = Read(Wrap(app1)); + Assert.Equal(ExifWriter.MaxStringBytes / 2, m.Artist!.Length); + Assert.True(m.Artist.All(c => c == 'é')); + } + + /// SOI + APP1 + a minimal 64×48 frame. + private static byte[] Wrap(byte[] app1) => [0xFF, 0xD8, .. app1, .. Builders.JpegBuilder.Minimal(64, 48).AsSpan(2)]; + + private static void AssertSorted(TiffReader reader, Ifd ifd) + { + var count = BinaryPrimitives.ReadUInt16LittleEndian(reader.ReadRelative(ifd.Position, 2)!); + var tags = new List(); + for (var i = 0; i < count; i++) tags.Add(BinaryPrimitives.ReadUInt16LittleEndian(reader.ReadRelative(ifd.Position + 2 + 12 * i, 2)!)); + Assert.Monotonic(tags, strict: true); + } +} diff --git a/tests/Titano.Core.Tests/Metadata/ImageSignatureTests.cs b/tests/Titano.Core.Tests/Metadata/ImageSignatureTests.cs new file mode 100644 index 00000000..d45c472d --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/ImageSignatureTests.cs @@ -0,0 +1,112 @@ +using Titano.Core.Imaging; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Tests.Metadata.Builders; +using Titano.Testing; + +namespace Titano.Core.Tests.Metadata; + +public sealed class ImageSignatureTests +{ + [Theory] + [Case("jpeg", "a.jpg", ImageFileFormat.Jpeg)] + [Case("jpeg", "a.png", ImageFileFormat.Jpeg, Name = "extension never overrides the signature")] + [Case("png", null, ImageFileFormat.Png)] + [Case("webp", null, ImageFileFormat.WebP)] + [Case("raf", "a.jpg", ImageFileFormat.Raf)] + [Case("cr2", "a.tif", ImageFileFormat.Cr2, Name = "CR marker beats .tif")] + [Case("cr3", null, ImageFileFormat.Cr3)] + [Case("heic", null, ImageFileFormat.Heif)] + [Case("avif", null, ImageFileFormat.Avif)] + [Case("nef", null, ImageFileFormat.Nef)] + [Case("nef", "x.NRW", ImageFileFormat.Nrw)] + [Case("nef", "x.tif", ImageFileFormat.Tiff, Name = "Nikon-made TIFF")] + [Case("arw", "x.arw", ImageFileFormat.Arw)] + [Case("arw", "x.sr2", ImageFileFormat.Sr2)] + [Case("arw", "x.srf", ImageFileFormat.Srf)] + [Case("dng", "x.dng", ImageFileFormat.Dng)] + [Case("dng", "x.gpr", ImageFileFormat.Gpr)] + [Case("dng", "x.tif", ImageFileFormat.Dng, Name = "DNGVersion beats .tif")] + [Case("orf", null, ImageFileFormat.Orf)] + [Case("rw2", null, ImageFileFormat.Rw2)] + [Case("rw2", "x.rwl", ImageFileFormat.Rwl)] + [Case("rw2", "x.raw", ImageFileFormat.Raw)] + public void DetectsFixtures(string fixture, string? fileName, ImageFileFormat expected) => + Assert.Equal(expected, ImageSignature.Detect(new MemoryStream(Fixtures.ByName(fixture)), fileName)); + + [Theory] + [Case("PENTAX Corporation", null, ImageFileFormat.Pef)] + [Case("RICOH IMAGING COMPANY, LTD.", null, ImageFileFormat.Pef)] + [Case("SAMSUNG", null, ImageFileFormat.Srw)] + [Case("Hasselblad", null, ImageFileFormat.ThreeFr)] + [Case("Hasselblad", "x.fff", ImageFileFormat.Fff)] + [Case("Phase One", null, ImageFileFormat.Iiq)] + [Case("Leaf", null, ImageFileFormat.Iiq)] + [Case("Canon", "x.cr2", ImageFileFormat.Cr2, Name = "Canon without CR marker, .cr2")] + [Case("Canon", null, ImageFileFormat.Tiff)] + [Case("OLYMPUS", "x.orf", ImageFileFormat.Orf)] + [Case("Scanner Inc", "x.pef", ImageFileFormat.Pef, Name = "unknown make, raw extension breaks the tie")] + [Case("Scanner Inc", null, ImageFileFormat.Tiff)] + [Case("SAMSUNG", "x.tiff", ImageFileFormat.Tiff, Name = ".tiff keeps a camera-made TIFF a TIFF")] + public void RefinesTiffByMake(string make, string? fileName, ImageFileFormat expected) + { + var tiff = TiffFile.Build(new IfdSpec().Ascii(TiffTags.Make, make).Long(TiffTags.ImageWidth, 8), littleEndian: false); + Assert.Equal(expected, ImageSignature.Detect(new MemoryStream(tiff), fileName)); + } + + [Theory] + [Case("LEICA CAMERA AG", null, ImageFileFormat.Rwl)] + [Case("Panasonic", null, ImageFileFormat.Rw2)] + public void PanasonicHeaderUsesMake(string make, string? fileName, ImageFileFormat expected) + { + var rw = TiffFile.Build(new IfdSpec().Ascii(TiffTags.Make, make), magic: "IIU\0"); + Assert.Equal(expected, ImageSignature.Detect(new MemoryStream(rw), fileName)); + } + + [Theory] + [Case("mif1", "heic", ImageFileFormat.Heif)] + [Case("mif1", "avif", ImageFileFormat.Avif)] + [Case("msf1", "hevc", ImageFileFormat.Heif)] + [Case("heix", "mif1", ImageFileFormat.Heif)] + [Case("avis", "msf1", ImageFileFormat.Avif)] + [Case("qt ", "qt ", ImageFileFormat.Unknown, Name = "QuickTime movie")] + [Case("isom", "mp41", ImageFileFormat.Unknown, Name = "MP4 video")] + public void ClassifiesFtypBrands(string major, string compatible, ImageFileFormat expected) + { + var ftyp = Box.Make("ftyp", Box.Ascii(major), Box.U32(0), Box.Ascii(compatible)); + Assert.Equal(expected, ImageSignature.Detect(new MemoryStream([.. ftyp, .. Box.Make("free")]), null)); + } + + [Theory] + [Case(new byte[] { (byte)'G', (byte)'I', (byte)'F', (byte)'8', (byte)'9', (byte)'a', 1, 0, 1, 0 }, ImageFileFormat.Gif)] + [Case(new byte[] { (byte)'G', (byte)'I', (byte)'F', (byte)'8', (byte)'7', (byte)'a', 1, 0, 1, 0 }, ImageFileFormat.Gif)] + [Case(new byte[] { 0xFF, 0x0A, 0x7F, 0 }, ImageFileFormat.JpegXl)] + [Case(new byte[] { 0, 0, 0, 0x0C, (byte)'J', (byte)'X', (byte)'L', (byte)' ', 0x0D, 0x0A, 0x87, 0x0A }, ImageFileFormat.JpegXl)] + [Case(new byte[] { (byte)'I', (byte)'I', 0xBC, 0x01, 8, 0, 0, 0 }, ImageFileFormat.JpegXr)] + [Case(new byte[] { (byte)'I', (byte)'I', 0x1A, 0, 0, 0, (byte)'H', (byte)'E', (byte)'A', (byte)'P', (byte)'C', (byte)'C', (byte)'D', (byte)'R' }, ImageFileFormat.Crw)] + [Case(new byte[] { (byte)'M', (byte)'M', (byte)'O', (byte)'R', 0, 0, 0, 8 }, ImageFileFormat.Orf)] + [Case(new byte[] { 0xFF, 0xD8, 0xFF, 0xE1 }, ImageFileFormat.Jpeg)] + [Case(new byte[] { 0xFF, 0xD8 }, ImageFileFormat.Unknown, Name = "two bytes of SOI only")] + [Case(new byte[] { (byte)'B', (byte)'M', 0, 0 }, ImageFileFormat.Unknown, Name = "BM without a DIB header")] + [Case(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, ImageFileFormat.Unknown)] + [Case(new byte[0], ImageFileFormat.Unknown)] + public void DetectsMagicBytes(byte[] head, ImageFileFormat expected) => + Assert.Equal(expected, ImageSignature.Detect(new MemoryStream(head), "file.jpg")); + + [Test] + public void DetectsBmpWithInfoHeader() + { + var bmp = new byte[54]; + "BM"u8.CopyTo(bmp); + bmp[14] = 40; + Assert.Equal(ImageFileFormat.Bmp, ImageSignature.Detect(new MemoryStream(bmp), null)); + } + + [Test] + public void RestoresStreamPosition() + { + var stream = new MemoryStream(Fixtures.Nef()) { Position = 5 }; + ImageSignature.Detect(stream, null); + Assert.Equal(5L, stream.Position); + } +} diff --git a/tests/Titano.Core.Tests/Metadata/MetadataTestHelpers.cs b/tests/Titano.Core.Tests/Metadata/MetadataTestHelpers.cs new file mode 100644 index 00000000..4bf6ea89 --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/MetadataTestHelpers.cs @@ -0,0 +1,25 @@ +using Titano.Core.Metadata; +using Titano.Testing; + +namespace Titano.Core.Tests.Metadata; + +internal static class MetadataTestHelpers +{ + public static FrameMetadata Read(byte[] data, string? fileName = null, DateTime? modified = null) => + MetadataReader.Read(new MemoryStream(data, writable: false), fileName, modified); + + /// The reader's safety net turns parser defects into "Parser fault" warnings; tests require none. + public static void AssertNoFault(FrameMetadata m) + { + foreach (var w in m.Warnings) + { + if (w.StartsWith("Parser fault", StringComparison.Ordinal)) Assert.Fail(w); + } + } + + public static void AssertPreviews(FrameMetadata m, params (int Width, int Height, PreviewKind Kind)[] expected) + { + Assert.SequenceEqual(expected, m.Previews.Select(p => (p.Width, p.Height, p.Kind)), "previews"); + foreach (var p in m.Previews) Assert.True(p.Offset > 0 && p.Length > 0, $"preview at {p.Offset} length {p.Length}"); + } +} diff --git a/tests/Titano.Core.Tests/Metadata/OtherFormatTests.cs b/tests/Titano.Core.Tests/Metadata/OtherFormatTests.cs new file mode 100644 index 00000000..e7f3ec0f --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/OtherFormatTests.cs @@ -0,0 +1,202 @@ +using System.Buffers.Binary; +using Titano.Core.Imaging; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Tests.Metadata.Builders; +using Titano.Testing; +using static Titano.Core.Tests.Metadata.MetadataTestHelpers; + +namespace Titano.Core.Tests.Metadata; + +/// RAF, WebP, PNG and the minimal formats (GIF, BMP, JPEG XL, JPEG XR). +public sealed class OtherFormatTests +{ + [Test] + public void Raf() + { + var m = Read(Fixtures.Raf(), "DSCF0001.RAF"); + AssertNoFault(m); + Assert.Empty(m.Warnings); + Assert.Equal(ImageFileFormat.Raf, m.Format); + Assert.Equal("FUJIFILM", m.Make); + Assert.Equal("X-T5", m.Model); + Assert.Equal((7752, 5178), (m.Width, m.Height)); + Assert.Equal(14, m.BitsPerSample); + AssertPreviews(m, (1920, 1280, PreviewKind.Preview), (160, 120, PreviewKind.Thumbnail)); + Assert.Equal("FF02B1234567", m.BodySerial); + Assert.Equal(6100, m.ColorTemperature); + Assert.Equal(true, m.ImageStabilization); + Assert.Equal(Fixtures.Captured, m.CapturedAt); + } + + [Test] + public void RafHeaderModelIsTheFallback() + { + var raf = Fixtures.Raf(); + BinaryPrimitives.WriteUInt32BigEndian(raf.AsSpan(0x54), 0); + var m = Read(raf); + Assert.Equal("FUJIFILM", m.Make); + Assert.Equal("X-T5", m.Model); + Assert.Equal((7752, 5178), (m.Width, m.Height)); + Assert.Contains("RAF embedded JPEG missing", m.Warnings); + } + + [Test] + public void WebPWithVp8xExifAndXmp() + { + var m = Read(Fixtures.WebP(), "a.webp"); + AssertNoFault(m); + Assert.Empty(m.Warnings); + Assert.Equal(ImageFileFormat.WebP, m.Format); + Assert.Equal((3000, 2000), (m.Width, m.Height)); + Assert.Equal(8, m.BitsPerSample); + Assert.Equal(Fixtures.Make, m.Make); + Assert.Equal(Fixtures.Captured, m.CapturedAt); + Assert.Equal(4, m.Rating); + Assert.Equal(6, m.Orientation); + } + + [Test] + public void WebPSimpleFormats() + { + Assert.Equal((640, 480), Size(Read(Fixtures.WebPLossy(640, 480)))); + var body = (byte[])[.. "WEBP"u8, .. Box.Riff("VP8L", Fixtures.Vp8L(400, 300))]; + Assert.Equal((400, 300), Size(Read([.. "RIFF"u8, .. LittleEndian(body.Length), .. body]))); + } + + [Test] + public void WebPExifWithPrefix() + { + var body = (byte[])[.. "WEBP"u8, .. Box.Riff("VP8L", Fixtures.Vp8L(8, 8)), .. Box.Riff("EXIF", [.. "Exif\0\0"u8, .. Fixtures.ExifTiff()])]; + Assert.Equal(Fixtures.Model, Read([.. "RIFF"u8, .. LittleEndian(body.Length), .. body]).Model); + } + + [Theory] + [Case(false)] + [Case(true)] + public void Png(bool compressedXmp) + { + var m = Read(Fixtures.Png(compressedXmp), "a.png"); + AssertNoFault(m); + Assert.Empty(m.Warnings); + Assert.Equal(ImageFileFormat.Png, m.Format); + Assert.Equal((2048, 1536), (m.Width, m.Height)); + Assert.Equal(16, m.BitsPerSample); + Assert.Equal(Fixtures.Model, m.Model); + Assert.Equal(400, m.Iso); + Assert.Equal("Red", m.Label); + } + + [Test] + public void Gif() => Assert.Equal((320, 200), Size(Read([.. "GIF89a"u8, 0x40, 0x01, 0xC8, 0x00, 0, 0, 0]))); + + [Theory] + [Case(40, 640, -480)] + [Case(124, 1024, 768)] + public void Bmp(int headerSize, int width, int height) + { + var bmp = new byte[54]; + "BM"u8.CopyTo(bmp); + BinaryPrimitives.WriteInt32LittleEndian(bmp.AsSpan(14), headerSize); + BinaryPrimitives.WriteInt32LittleEndian(bmp.AsSpan(18), width); + BinaryPrimitives.WriteInt32LittleEndian(bmp.AsSpan(22), height); + Assert.Equal((width, Math.Abs(height)), Size(Read(bmp))); + } + + [Test] + public void BmpCoreHeader() + { + var bmp = new byte[26]; + "BM"u8.CopyTo(bmp); + bmp[14] = 12; + BinaryPrimitives.WriteUInt16LittleEndian(bmp.AsSpan(18), 300); + BinaryPrimitives.WriteUInt16LittleEndian(bmp.AsSpan(20), 200); + Assert.Equal((300, 200), Size(Read(bmp))); + } + + [Theory] + [Case(256, 128)] + [Case(1000, 750, Name = "4:3 ratio")] + [Case(1921, 1081)] + [Case(300000, 270000, Name = "two 30-bit sizes (68-bit header)")] + public void JpegXlCodestream(int width, int height) + { + var m = Read(BuildJpegXlCodestream(width, height), "a.jxl"); + Assert.Equal(ImageFileFormat.JpegXl, m.Format); + Assert.Equal((width, height), Size(m)); + } + + [Test] + public void JpegXlContainer() + { + byte[] file = [.. Box.Make("JXL ", [0x0D, 0x0A, 0x87, 0x0A]), .. Box.Make("ftyp", Box.Ascii("jxl "), Box.U32(0), Box.Ascii("jxl ")), + .. Box.Make("Exif", Box.U32(0), Fixtures.ExifTiff()), .. Box.Make("jxlp", Box.U32(0), BuildJpegXlCodestream(512, 384))]; + var m = Read(file); + Assert.Equal(ImageFileFormat.JpegXl, m.Format); + Assert.Equal((512, 384), Size(m)); + Assert.Equal(Fixtures.Make, m.Make); + } + + [Test] + public void JpegXr() + { + var ifd = new IfdSpec().Ascii(TiffTags.Make, "Microsoft").Long(0xBC80, 1600).Long(0xBC81, 900); + var m = Read(TiffFile.Build(ifd, magic: "II¼\u0001"), "a.jxr"); + Assert.Equal(ImageFileFormat.JpegXr, m.Format); + Assert.Equal((1600, 900), Size(m)); + Assert.Equal("Microsoft", m.Make); + } + + [Test] + public void UnknownFilesYieldAWarning() + { + var m = Read("hello world, not an image"u8.ToArray(), "notes.jpg"); + Assert.Equal(ImageFileFormat.Unknown, m.Format); + Assert.Contains("Unrecognised file signature", m.Warnings); + } + + private static (int, int) Size(FrameMetadata m) => (m.Width, m.Height); + + private static byte[] LittleEndian(int v) + { + var b = new byte[4]; + BinaryPrimitives.WriteInt32LittleEndian(b, v); + return b; + } + + /// FF 0A + SizeHeader (ISO/IEC 18181-1): small multiples of 8 or U32 distributions; a 4:3 ratio when exact. + private static byte[] BuildJpegXlCodestream(int width, int height) + { + var bits = new List(); + void Put(ulong value, int count) + { + for (var i = 0; i < count; i++) bits.Add(((value >> i) & 1) != 0); + } + void PutU32(int value) + { + var v = (ulong)(value - 1); + var (selector, n) = v < 1 << 9 ? (0, 9) : v < 1 << 13 ? (1, 13) : v < 1 << 18 ? (2, 18) : (3, 30); + Put((ulong)selector, 2); + Put(v, n); + } + var small = width % 8 == 0 && height % 8 == 0 && width <= 256 && height <= 256; + Put(small ? 1UL : 0UL, 1); + if (small) Put((ulong)(height / 8 - 1), 5); + else PutU32(height); + var ratio = height * 4 / 3 == width && height % 3 == 0 ? 3 : 0; + Put((ulong)ratio, 3); + if (ratio == 0) + { + if (small) Put((ulong)(width / 8 - 1), 5); + else PutU32(width); + } + var bytes = new byte[2 + (bits.Count + 7) / 8 + 8]; + bytes[0] = 0xFF; + bytes[1] = 0x0A; + for (var i = 0; i < bits.Count; i++) + { + if (bits[i]) bytes[2 + i / 8] |= (byte)(1 << (i % 8)); + } + return bytes; + } +} diff --git a/tests/Titano.Core.Tests/Metadata/RawContainerTests.cs b/tests/Titano.Core.Tests/Metadata/RawContainerTests.cs new file mode 100644 index 00000000..e8fff67d --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/RawContainerTests.cs @@ -0,0 +1,190 @@ +using Titano.Core.Imaging; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Model; +using Titano.Core.Tests.Metadata.Builders; +using Titano.Testing; +using static Titano.Core.Tests.Metadata.MetadataTestHelpers; + +namespace Titano.Core.Tests.Metadata; + +/// TIFF-based RAWs: main-image selection across IFDs/SubIFDs, embedded previews and MakerNote fallbacks. +public sealed class RawContainerTests +{ + [Test] + public void Cr2() + { + var m = Read(Fixtures.Cr2(), "IMG_0001.CR2"); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Cr2, m.Format); + Assert.Equal("Canon", m.Make); + Assert.Equal((6720, 4480), (m.Width, m.Height)); + Assert.Equal(14, m.BitsPerSample); + AssertPreviews(m, (6720, 4480, PreviewKind.FullSize), (160, 120, PreviewKind.Thumbnail)); + Assert.Equal("0000123456", m.BodySerial); + Assert.Equal("EF24-70mm f/2.8L II USM", m.LensModel); + Assert.Equal(true, m.ImageStabilization); + Assert.Equal(5200, m.ColorTemperature); + Assert.Equal(Fixtures.Captured, m.CapturedAt); + Assert.Equal(1, m.Orientation); + } + + [Test] + public void Nef() + { + var m = Read(Fixtures.Nef(), "DSC_0001.NEF"); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Nef, m.Format); + Assert.Equal("NIKON CORPORATION", m.Make); + Assert.Equal((8288, 5520), (m.Width, m.Height)); + Assert.Equal(14, m.BitsPerSample); + AssertPreviews(m, (8256, 5504, PreviewKind.FullSize)); + Assert.Equal("3001234", m.BodySerial); + Assert.Equal(12345L, m.ShutterCount); + Assert.Equal("24-70mm f/2.8", m.LensModel); + Assert.Equal(true, m.ImageStabilization); + Assert.Equal(64, m.Iso); + } + + [Test] + public void Dng() + { + var m = Read(Fixtures.Dng(), "PXL_0001.dng"); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Dng, m.Format); + Assert.Equal((4032, 3024), (m.Width, m.Height)); + Assert.Equal(16, m.BitsPerSample); + AssertPreviews(m, (1024, 768, PreviewKind.Preview)); + Assert.Equal("DNGSER1", m.BodySerial); + Assert.Equal("Pixel 8", m.Model); + } + + [Test] + public void Arw() + { + var m = Read(Fixtures.Arw(), "DSC00001.ARW"); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Arw, m.Format); + Assert.Equal((6048, 4024), (m.Width, m.Height)); + Assert.Equal(12, m.BitsPerSample); + AssertPreviews(m, (1616, 1080, PreviewKind.Preview)); + Assert.Equal("24-70mm F2.8", m.LensModel); + Assert.Equal(5600, m.ColorTemperature); + Assert.Equal(true, m.ImageStabilization); + } + + [Test] + public void Orf() + { + var m = Read(Fixtures.Orf(), "P0000001.ORF"); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Orf, m.Format); + Assert.Equal((5240, 3912), (m.Width, m.Height)); + Assert.Equal(12, m.BitsPerSample); + AssertPreviews(m, (3200, 2400, PreviewKind.Preview)); + Assert.Equal("BHX123", m.BodySerial); + Assert.Equal("M.Zuiko 12-40mm F2.8", m.LensModel); + Assert.Equal(true, m.ImageStabilization); + } + + [Test] + public void Rw2() + { + var m = Read(Fixtures.Rw2(), "P1000001.RW2"); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Rw2, m.Format); + Assert.Equal("Panasonic", m.Make); + Assert.Equal("DC-GH6", m.Model); + Assert.Equal((5776, 4344), (m.Width, m.Height)); + Assert.Equal(12, m.BitsPerSample); + Assert.Equal(800, m.Iso); + AssertPreviews(m, (1920, 1440, PreviewKind.Preview), (160, 120, PreviewKind.Thumbnail)); + Assert.Equal("F541504040123", m.BodySerial); + Assert.Equal("LUMIX G VARIO 12-60mm", m.LensModel); + Assert.Equal(true, m.ImageStabilization); + Assert.Equal(5000, m.ColorTemperature); + Assert.Equal(TimestampSource.ExifOriginal, m.TimestampSource); + Assert.Equal(1, m.Orientation); + } + + [Test] + public void StandardTagsBeatMakerNote() + { + var makerNote = new IfdSpec().Long(0x000C, 42).Ascii(0x0095, "MakerNote Lens"); + var exif = Fixtures.ExifIfd().Embedded(TiffTags.MakerNote, [], makerNote, relativeToTiff: true, littleEndian: true); + var tiff = TiffFile.Build(Fixtures.Ifd0("Canon", "Canon EOS R6").Child(TiffTags.ExifIfd, exif)); + var m = Read(new JpegBuilder().Exif(tiff).Build(64, 48)); + Assert.Equal("SN123", m.BodySerial); + Assert.Equal("TestLens 35mm", m.LensModel); + } + + [Theory] + [Case("Canon EOS-1D X Mark III", "042000")] + [Case("Canon EOS R6", "0000042000")] + public void FormatsCanonSerialByModel(string model, string expected) + { + var makerNote = new IfdSpec().Long(0x000C, 42000); + var exif = Fixtures.ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [], makerNote, relativeToTiff: true, littleEndian: false); + var tiff = TiffFile.Build(Fixtures.Ifd0("Canon", model).Child(TiffTags.ExifIfd, exif), littleEndian: false); + Assert.Equal(expected, Read(new JpegBuilder().Exif(tiff).Build(64, 48)).BodySerial); + } + + [Test] + public void ReadsHeaderlessNikonMakerNote() + { + var nikon = new IfdSpec().Ascii(0x001D, "TYPE2").Long(0x00A7, 7); + var exif = Fixtures.ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [], nikon, relativeToTiff: true, littleEndian: true); + var tiff = TiffFile.Build(Fixtures.Ifd0("NIKON", "E5700").Child(TiffTags.ExifIfd, exif)); + var m = Read(new JpegBuilder().Exif(tiff).Build(64, 48)); + Assert.Equal("TYPE2", m.BodySerial); + Assert.Equal(7L, m.ShutterCount); + } + + [Test] + public void ReadsLegacyOlympusAndFujifilmMakerNotes() + { + var olympus = new IfdSpec().Child(0x2010, new IfdSpec().Ascii(0x0101, "OLD-SN")); + var exif = Fixtures.ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [.. "OLYMP\0"u8, 1, 0], olympus, relativeToTiff: true, littleEndian: true); + var m = Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0("OLYMPUS", "E-1").Child(TiffTags.ExifIfd, exif))).Build(64, 48)); + Assert.Equal("OLD-SN", m.BodySerial); + + var fuji = new IfdSpec().Short(0x1422, 0, 0, 0); + exif = Fixtures.ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [.. "FUJIFILM"u8, 12, 0, 0, 0], fuji, relativeToTiff: false, littleEndian: true); + m = Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0("FUJIFILM", "X100V").Child(TiffTags.ExifIfd, exif), littleEndian: false)).Build(64, 48)); + Assert.Equal(false, m.ImageStabilization); + } + + [Test] + public void MakerNoteOutsideFileIsReported() + { + var exif = Fixtures.ExifIfd(identity: false).Undefined(TiffTags.MakerNote, new byte[64]); + var tiff = TiffFile.Build(Fixtures.Ifd0("Canon", "Canon EOS R6").Child(TiffTags.ExifIfd, exif)); + var cut = tiff.AsSpan(0, tiff.Length - 40).ToArray(); + var m = Read(cut, "a.tif"); + AssertNoFault(m); + Assert.Contains("MakerNote outside the file", m.Warnings); + } + + [Test] + public void SubIfdLoopsAreBroken() + { + // IFD0's SubIFDs entry points back at IFD0 itself. + var tiff = TiffFile.Build(new IfdSpec().Ascii(TiffTags.Make, "Loop").Long(TiffTags.ImageWidth, 10).Long(TiffTags.ImageLength, 10).Long(TiffTags.SubIfds, 8)); + var m = Read(tiff, "loop.tif"); + AssertNoFault(m); + Assert.Equal((10, 10), (m.Width, m.Height)); + Assert.Contains("IFD loop at 8", m.Warnings); + } + + [Test] + public void PlainTiffUsesLargestFullResolutionIfd() + { + var reduced = new IfdSpec().Long(TiffTags.NewSubfileType, 1).Long(TiffTags.ImageWidth, 9000).Long(TiffTags.ImageLength, 9000); + var ifd0 = new IfdSpec().Long(TiffTags.ImageWidth, 3000).Long(TiffTags.ImageLength, 2000).Short(TiffTags.BitsPerSample, 16, 16, 16); + ifd0.Next = reduced; + var m = Read(TiffFile.Build(ifd0, littleEndian: false), "scan.tif"); + Assert.Equal(ImageFileFormat.Tiff, m.Format); + Assert.Equal((3000, 2000), (m.Width, m.Height)); + Assert.Equal(16, m.BitsPerSample); + } +} diff --git a/tests/Titano.Core.Tests/Metadata/RobustnessTests.cs b/tests/Titano.Core.Tests/Metadata/RobustnessTests.cs new file mode 100644 index 00000000..bead02a9 --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/RobustnessTests.cs @@ -0,0 +1,189 @@ +using System.Buffers.Binary; +using System.Diagnostics; +using Titano.Core.Imaging; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Model; +using Titano.Core.Tests.Metadata.Builders; +using Titano.Testing; +using static Titano.Core.Tests.Metadata.MetadataTestHelpers; + +namespace Titano.Core.Tests.Metadata; + +/// Fuzzing, I/O bounds, speed, cancellation and file access. +public sealed class RobustnessTests(TestContext context) +{ + private const int Truncations = 200; + private const int Corruptions = 500; + private const long FiftyMegabytes = 50L * 1024 * 1024; + private const long ReadBudget = 512 * 1024; + + [Theory] + [Case("jpeg")] + [Case("jpeg-be")] + [Case("cr2")] + [Case("nef")] + [Case("dng")] + [Case("arw")] + [Case("orf")] + [Case("rw2")] + [Case("cr3")] + [Case("heic")] + [Case("avif")] + [Case("raf")] + [Case("webp")] + [Case("png")] + [Case("png-z")] + [Timeout(5000)] + public void SurvivesTruncationAndCorruption(string fixture) + { + var original = Fixtures.ByName(fixture); + var random = new Random(fixture.Aggregate(0x5EED, (seed, c) => seed * 31 + c)); + var parses = 0; + for (var i = 0; i < Truncations; i++) + { + var length = (int)((long)original.Length * i / Truncations) + random.Next(0, 3); + Check(original.AsSpan(0, Math.Min(length, original.Length)).ToArray(), $"truncated at {length}"); + parses++; + } + var buffer = new byte[original.Length]; + for (var i = 0; i < Corruptions; i++) + { + original.CopyTo(buffer, 0); + var flips = random.Next(1, 9); + for (var f = 0; f < flips; f++) buffer[random.Next(buffer.Length)] = (byte)random.Next(256); + Check(buffer, $"corruption {i}"); + parses++; + } + Assert.Equal(Truncations + Corruptions, parses); + } + + [Test] + public void FuzzedFieldsStaySane() + { + var random = new Random(7); + var original = Fixtures.Jpeg(); + for (var i = 0; i < 300; i++) + { + var bytes = (byte[])original.Clone(); + for (var f = 0; f < 6; f++) bytes[random.Next(bytes.Length)] ^= (byte)(1 << random.Next(8)); + var m = Read(bytes, "fuzz.jpg"); + Assert.InRange(m.Orientation, 1, 8); + Assert.True(m.Width >= 0 && m.Height >= 0); + foreach (var p in m.Previews) Assert.True(p.Offset >= 0 && p.Offset + p.Length <= bytes.Length, "preview inside file"); + } + } + + [Test] + public void LargeDngReadsWellUnderHalfAMegabyte() + { + var preview = new IfdSpec().Long(TiffTags.NewSubfileType, 1).Long(TiffTags.ImageWidth, 4000).Long(TiffTags.ImageLength, 3000) + .Short(TiffTags.Compression, 7).Short(TiffTags.PhotometricInterpretation, 6) + .Strip(JpegBuilder.Minimal(4000, 3000, scanBytes: 1_500_000)); + var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0).Long(TiffTags.ImageWidth, 8000).Long(TiffTags.ImageLength, 6000) + .Short(TiffTags.BitsPerSample, 16).Short(TiffTags.Compression, 7).Short(TiffTags.PhotometricInterpretation, 32803) + .Long(TiffTags.StripOffsets, 2_000_000).Long(TiffTags.StripByteCounts, 48_000_000); + var ifd0 = Fixtures.Ifd0("Leica Camera AG", "M11", 1).Long(TiffTags.NewSubfileType, 1).Bytes(TiffTags.DngVersion, 1, 6, 0, 0) + .Child(TiffTags.SubIfds, raw, preview).Child(TiffTags.ExifIfd, Fixtures.ExifIfd()).Child(TiffTags.GpsIfd, Fixtures.GpsIfd()); + var bytes = TiffFile.Build(ifd0); + Assert.Less(bytes.Length, 2_000_000); + using var stream = new CountingStream(new SparseStream(bytes, FiftyMegabytes)); + var m = MetadataReader.Read(stream, "L1000001.DNG"); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Dng, m.Format); + Assert.Equal((8000, 6000), (m.Width, m.Height)); + AssertPreviews(m, (4000, 3000, PreviewKind.Preview)); + Assert.Equal(Fixtures.Captured, m.CapturedAt); + context.Log($"DNG: {stream.BytesRead} bytes in {stream.ReadCalls} reads"); + Assert.Less(stream.BytesRead, ReadBudget); + } + + [Test] + public void LargeCr3ReadsWellUnderHalfAMegabyte() + { + var bytes = Fixtures.Cr3(out var mdatStart); + BinaryPrimitives.WriteUInt32BigEndian(bytes.AsSpan(mdatStart), (uint)(FiftyMegabytes - mdatStart)); + using var stream = new CountingStream(new SparseStream(bytes, FiftyMegabytes)); + var m = MetadataReader.Read(stream, "IMG_0001.CR3"); + AssertNoFault(m); + Assert.Equal((8352, 5586), (m.Width, m.Height)); + Assert.Count(3, m.Previews); + context.Log($"CR3: {stream.BytesRead} bytes in {stream.ReadCalls} reads"); + Assert.Less(stream.BytesRead, ReadBudget); + } + + [Test] + public void ParsesTwoThousandJpegHeadersQuickly() + { + var jpeg = Fixtures.Jpeg(); + Read(jpeg); + var watch = Stopwatch.StartNew(); + for (var i = 0; i < 2000; i++) + { + var m = MetadataReader.Read(new MemoryStream(jpeg, writable: false), "IMG.JPG"); + if (m.Width != 4000) Assert.Fail("unexpected width"); + } + watch.Stop(); + context.Log($"2000 JPEG headers in {watch.ElapsedMilliseconds} ms"); + Assert.Less(watch.Elapsed.TotalSeconds, 2.0); + } + + [Test] + public void HonoursCancellation() + { + using var cts = new CancellationTokenSource(); + cts.Cancel(); + Assert.Throws(() => MetadataReader.Read(new MemoryStream(Fixtures.Nef()), "a.nef", null, cts.Token)); + } + + [Test] + public void RejectsNonSeekableStreams() + { + Assert.Throws(() => MetadataReader.Read(new NonSeekable(), null)); + Assert.Throws(() => ImageSignature.Detect(new NonSeekable(), null)); + } + + [Test] + public void ReadsFilesSharedWithAWriter() + { + var path = Path.Combine(context.CreateTempDirectory(), "IMG_0002.JPG"); + File.WriteAllBytes(path, JpegBuilder.Minimal(320, 240)); + var modified = new DateTime(2021, 6, 7, 8, 9, 10, DateTimeKind.Local); + File.SetLastWriteTime(path, modified); + using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) + { + var m = MetadataReader.Read(path); + Assert.Equal((320, 240), (m.Width, m.Height)); + Assert.Equal(TimestampSource.FileSystem, m.TimestampSource); + Assert.Equal(new DateTime(2021, 6, 7, 8, 9, 10), m.CapturedAt); + } + } + + private static void Check(byte[] bytes, string what) + { + FrameMetadata m; + try + { + m = MetadataReader.Read(new MemoryStream(bytes, writable: false), "fuzz"); + } + catch (Exception ex) + { + Assert.Fail($"{what}: {ex.GetType().Name}: {ex.Message}"); + return; + } + foreach (var w in m.Warnings) + { + if (w.StartsWith("Parser fault", StringComparison.Ordinal)) Assert.Fail($"{what}: {w}"); + } + foreach (var p in m.Previews) + { + if (p.Offset < 0 || p.Length <= 0 || p.Offset + p.Length > bytes.Length) Assert.Fail($"{what}: preview {p} outside the file"); + } + if (m.Orientation is < 1 or > 8 || m.Width < 0 || m.Height < 0) Assert.Fail($"{what}: invalid geometry"); + } + + private sealed class NonSeekable : MemoryStream + { + public override bool CanSeek => false; + } +} diff --git a/tests/Titano.Core.Tests/Metadata/XmpTests.cs b/tests/Titano.Core.Tests/Metadata/XmpTests.cs new file mode 100644 index 00000000..5dfda915 --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/XmpTests.cs @@ -0,0 +1,196 @@ +using System.Text; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Metadata.Xmp; +using Titano.Core.Model; +using Titano.Core.Tests.Metadata.Builders; +using Titano.Testing; +using static Titano.Core.Tests.Metadata.MetadataTestHelpers; + +namespace Titano.Core.Tests.Metadata; + +public sealed class XmpTests +{ + private const string Head = """"""; + private const string Tail = ""; + private const string Namespaces = """ + xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:exif="http://ns.adobe.com/exif/1.0/" + xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" + xmlns:aux="http://ns.adobe.com/exif/1.0/aux/" xmlns:exifEX="http://cipa.jp/exif/1.0/" + xmlns:xmpNote="http://ns.adobe.com/xmp/note/" + """; + + [Test] + public void ReadsAttributeForm() + { + var v = Parse($""" + {Head}{Tail} + """); + Assert.Equal(5, v.Rating); + Assert.Equal("Green", v.Label); + Assert.Equal(new DateTime(2024, 3, 4, 5, 6, 7, 500), v.DateTimeOriginal!.Value.Value); + Assert.Equal(60, v.DateTimeOriginal!.Value.OffsetMinutes); + Assert.Equal(8, v.Orientation); + Assert.Equal("BODY1", v.BodySerial); + Assert.Equal("CipaLens", v.Lens); + } + + [Test] + public void ReadsElementForm() + { + var v = Parse($""" + {Head} + -1 + + 2021-01-02T03:04Z + 2020-01-01T00:00:00 + 2 + AUX2 + Nested Lens + {Tail} + """); + Assert.Equal(-1, v.Rating); + Assert.Equal("Purple", v.Label); + Assert.Equal(new DateTime(2021, 1, 2, 3, 4, 0), v.CaptureTime!.Value.Value); + Assert.Equal(0, v.CaptureTime!.Value.OffsetMinutes); + Assert.Equal(2, v.Orientation); + Assert.Equal("AUX2", v.BodySerial); + Assert.Equal("Nested Lens", v.Lens); + } + + [Theory] + [Case("exif:DateTimeOriginal=\"2001-01-01T01:01:01\" photoshop:DateCreated=\"2002-02-02T02:02:02\" xmp:CreateDate=\"2003-03-03T03:03:03\"", 2001)] + [Case("photoshop:DateCreated=\"2002-02-02T02:02:02\" xmp:CreateDate=\"2003-03-03T03:03:03\"", 2002)] + [Case("xmp:CreateDate=\"2003-03-03T03:03:03\"", 2003)] + [Case("photoshop:DateCreated=\"2002-02-02\" xmp:CreateDate=\"2003-03-03T03:03:03\"", 2003, Name = "date-only values are not capture times")] + public void CaptureTimeFollowsMwgOrder(string attributes, int year) => + Assert.Equal(year, Parse($"{Head}{Tail}").CaptureTime!.Value.Value.Year); + + [Test] + public void FirstPacketWins() + { + var v = new XmpValues(); + Assert.Null(XmpParser.Parse(Encoding.UTF8.GetBytes($"{Head}{Tail}"), v)); + Assert.Null(XmpParser.Parse(Encoding.UTF8.GetBytes($"{Head}{Tail}"), v)); + Assert.Equal(2, v.Rating); + Assert.Equal("Blue", v.Label); + } + + [Test] + public void RefusesDtdsAndEntities() + { + var packet = $"""]>{Head}{Tail}"""; + var v = new XmpValues(); + var problem = XmpParser.Parse(Encoding.UTF8.GetBytes(packet), v); + Assert.NotNull(problem); + Assert.Null(v.Label); + } + + [Test] + public void MalformedPacketKeepsEarlierValues() + { + var v = new XmpValues(); + var problem = XmpParser.Parse(Encoding.UTF8.GetBytes($"{Head}Yel"), v); + Assert.Contains("Malformed XMP", problem); + Assert.Equal(3, v.Rating); + } + + [Test] + public void RejectsPacketsOverFourMegabytes() + { + var packet = new byte[XmpParser.MaxPacketBytes + 1]; + packet.AsSpan().Fill((byte)' '); + Assert.Equal("XMP packet larger than 4 MB ignored", XmpParser.Parse(packet, new XmpValues())); + } + + [Test] + public void IgnoresTrailingNulPaddingAndInvalidValues() + { + var v = new XmpValues(); + var bytes = Encoding.UTF8.GetBytes($"{Head}{Tail}\0\0\0"); + Assert.Null(XmpParser.Parse(bytes, v)); + Assert.Null(v.Rating); + Assert.Null(v.Orientation); + Assert.Null(v.CreateDate); + } + + [Test] + public void ReassemblesExtendedXmpInJpeg() + { + const string guid = "0123456789ABCDEF0123456789ABCDEF"; + var main = $"{Head}{Tail}"; + var extended = $"{Head}{Tail}"; + var jpeg = new JpegBuilder().Xmp(main).ExtendedXmp(guid, extended, 200).Build(64, 48); + var m = Read(jpeg); + AssertNoFault(m); + Assert.Equal(1, m.Rating); + Assert.Equal(TimestampSource.Xmp, m.TimestampSource); + Assert.Equal(new DateTime(2019, 9, 9, 9, 9, 9), m.CapturedAt); + Assert.Contains("Extended Lens", m.LensModel); + } + + [Test] + public void IgnoresUnreferencedOrIncompleteExtendedXmp() + { + const string guid = "0123456789ABCDEF0123456789ABCDEF"; + var extended = $"{Head}{Tail}"; + var unreferenced = Read(new JpegBuilder().ExtendedXmp(guid, extended, 64).Build(64, 48)); + Assert.Null(unreferenced.Label); + Assert.Contains("Extended XMP present but not referenced by the main packet", unreferenced.Warnings); + + var main = $"{Head}{Tail}"; + var builder = new JpegBuilder().Xmp(main).ExtendedXmp(guid, extended, 64); + var bytes = builder.Build(64, 48); + var withoutFirstChunk = Read(RemoveFirstExtendedChunk(bytes)); + Assert.Null(withoutFirstChunk.Label); + Assert.Contains("Extended XMP incomplete", withoutFirstChunk.Warnings); + } + + [Test] + public void SuppliesSerialAndLensFallbacks() + { + var xmp = $"{Head}{Tail}"; + var exif = Fixtures.ExifIfd(identity: false); + var jpeg = new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0().Child(TiffTags.ExifIfd, exif))).Xmp(xmp).Build(64, 48); + var m = Read(jpeg); + Assert.Equal("XMPSN", m.BodySerial); + Assert.Equal("XMP Lens", m.LensModel); + } + + [Test] + public void ExifIdentityBeatsXmp() + { + var xmp = $"{Head}{Tail}"; + var m = Read(new JpegBuilder().Exif(Fixtures.ExifTiff()).Xmp(xmp).Build(64, 48)); + Assert.Equal("SN123", m.BodySerial); + Assert.Equal("TestLens 35mm", m.LensModel); + } + + [Test] + public void ReadsXmpTagInTiff() + { + var xmp = Encoding.UTF8.GetBytes($"{Head}{Tail}"); + var tiff = TiffFile.Build(Fixtures.Ifd0().Undefined(TiffTags.Xmp, xmp).Long(TiffTags.ImageWidth, 10).Long(TiffTags.ImageLength, 10)); + Assert.Equal("FromTiff", Read(tiff, "a.tif").Label); + } + + private static XmpValues Parse(string packet) + { + var values = new XmpValues(); + Assert.Null(XmpParser.Parse(Encoding.UTF8.GetBytes(packet), values)); + return values; + } + + /// Drops the extended-XMP segment holding offset 0 (written last by ). + private static byte[] RemoveFirstExtendedChunk(byte[] jpeg) + { + var signature = Encoding.ASCII.GetBytes(JpegBuilder.ExtendedXmpSignature); + var last = -1; + for (var i = 0; i + signature.Length < jpeg.Length; i++) + { + if (jpeg.AsSpan(i).StartsWith(signature)) last = i - 4; + } + var length = jpeg[last + 2] << 8 | jpeg[last + 3]; + return [.. jpeg.AsSpan(0, last), .. jpeg.AsSpan(last + 2 + length)]; + } +}