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/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/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/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;
+}