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/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/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