feat(metadata): add parser infrastructure and XMP reader
Bounds-checked positional stream reads, an in-memory span reader, Exif/XMP date parsing, and the MetadataBuilder accumulator that applies every fallback chain (timestamps, ISO, serial/lens, orientation, preview kinds) in one place. XMP is read with XmlReader (no DTDs, no resolver, 4 MB cap) in both attribute and element forms. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
7 files changed
+704
No files matched your search
@@ -0,0 +1,12 @@
|
||||
namespace Titano.Core.Metadata.MakerNotes;
|
||||
|
||||
/// <summary>Values recovered from a vendor MakerNote. They fill a field only when the standard tags left it empty.</summary>
|
||||
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; }
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Mutable accumulator shared by the container parsers. Parsers assign standard values with <c>??=</c> in the order
|
||||
/// of authority (so the first source wins); MakerNote and XMP values are kept apart and <see cref="Build"/> applies
|
||||
/// every fallback chain in one place.
|
||||
/// </summary>
|
||||
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<string> _warnings = [];
|
||||
private readonly List<PreviewCandidate> _previews = [];
|
||||
private readonly List<Raster> _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; }
|
||||
|
||||
/// <summary>Exif ISOSpeedRatings (first value); 65535 means "at least 65535".</summary>
|
||||
public int? IsoSpeedRatings { get; set; }
|
||||
|
||||
/// <summary>RecommendedExposureIndex, StandardOutputSensitivity, ISOSpeed or a RAW-header ISO.</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>Raw Exif/TIFF orientation value (validated in <see cref="Build"/>).</summary>
|
||||
public int? ExifOrientation { get; set; }
|
||||
|
||||
/// <summary>Orientation implied by container transforms (HEIF irot/imir); overrides Exif.</summary>
|
||||
public int? ContainerOrientation { get; set; }
|
||||
|
||||
public int? PixelXDimension { get; set; }
|
||||
public int? PixelYDimension { get; set; }
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public int? CodedBitsPerSample { get; set; }
|
||||
|
||||
/// <summary>GPS position without its timestamp (merged in <see cref="Build"/>).</summary>
|
||||
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<string> Warnings => _warnings;
|
||||
|
||||
public void Warn(string message)
|
||||
{
|
||||
if (_warnings.Count < MaxWarnings && !_warnings.Contains(message)) _warnings.Add(message);
|
||||
}
|
||||
|
||||
public void AddWarnings(IEnumerable<string> messages)
|
||||
{
|
||||
foreach (var message in messages) Warn(message);
|
||||
}
|
||||
|
||||
public void ThrowIfCancelled() => Cancellation.ThrowIfCancellationRequested();
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>A raster IFD; <paramref name="primary"/> is false for reduced-resolution images (NewSubfileType bit 0).</summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>Records a validated embedded JPEG; duplicates (same offset) keep the first.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Applies the fallback rules and produces the immutable result.</summary>
|
||||
/// <param name="fileModified">File modification time; used when no capture time is recorded.</param>
|
||||
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(),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Largest full-resolution raster (NewSubfileType bit 0 clear); any raster when none is full-resolution.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Exif original → Exif digitized → XMP → GPS (UTC) → file time.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>ISOSpeedRatings unless absent or saturated (65535), then REI/SOS/ISOSpeed, then the MakerNote.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Largest first; kinds by long edge: < 640 px thumbnail, ≥ 90 % of the main image full size.</summary>
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
namespace Titano.Core.Metadata;
|
||||
|
||||
/// <summary>Camera wall-clock time (DateTimeKind.Unspecified) plus the UTC offset when the file records one.</summary>
|
||||
internal readonly record struct CaptureStamp(DateTime Value, int? OffsetMinutes);
|
||||
|
||||
/// <summary>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.</summary>
|
||||
internal static class MetadataDates
|
||||
{
|
||||
private const int MaxOffsetMinutes = 14 * 60;
|
||||
|
||||
/// <summary>Exif date-time; separators are not checked so "YYYY-MM-DD HH:MM:SS" also parses.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Exif date ("YYYY:MM:DD", e.g. GPSDateStamp) at midnight.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>SubSecTime digits as a fraction of a second in ticks ("5" → 0.5 s, "123" → 0.123 s).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>"+HH:MM", "-HH:MM", "+HHMM" or "Z" as minutes east of UTC.</summary>
|
||||
public static int? ParseOffset(ReadOnlySpan<char> 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());
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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<char> 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
|
||||
namespace Titano.Core.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Forward-only reader over bytes already in memory. Reading past the end returns zeros and clears <see cref="Ok"/>,
|
||||
/// so a parser can read a whole structure and validate once.
|
||||
/// </summary>
|
||||
internal ref struct SpanReader
|
||||
{
|
||||
private readonly ReadOnlySpan<byte> _data;
|
||||
private readonly bool _bigEndian;
|
||||
private int _position;
|
||||
|
||||
public SpanReader(ReadOnlySpan<byte> 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);
|
||||
}
|
||||
|
||||
/// <summary>Unsigned integer stored in 0, 4 or 8 bytes (ISO-BMFF <c>iloc</c> field sizes); other sizes fail.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>The next <paramref name="count"/> bytes; empty (and <see cref="Ok"/> cleared) when fewer remain.</summary>
|
||||
public ReadOnlySpan<byte> 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;
|
||||
}
|
||||
|
||||
/// <summary>NUL-terminated UTF-8 string (the terminator is consumed); the rest of the data when unterminated.</summary>
|
||||
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]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace Titano.Core.Metadata;
|
||||
|
||||
/// <summary>Bounds-checked positional reads shared by the container parsers (windowed access, never whole files).</summary>
|
||||
internal static class StreamExtensions
|
||||
{
|
||||
/// <summary>Fills <paramref name="buffer"/> from <paramref name="position"/>; false when the range leaves the stream.</summary>
|
||||
public static bool TryReadAt(this Stream stream, long position, Span<byte> buffer)
|
||||
{
|
||||
if (position < 0 || position > stream.Length - buffer.Length) return false;
|
||||
stream.Position = position;
|
||||
return stream.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) == buffer.Length;
|
||||
}
|
||||
|
||||
/// <summary>Reads <paramref name="length"/> bytes at <paramref name="position"/>; null when out of range or above <paramref name="maxLength"/>.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Reads up to <paramref name="buffer"/>.Length bytes at <paramref name="position"/>; returns the count read.</summary>
|
||||
public static int ReadUpTo(this Stream stream, long position, Span<byte> 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
using System.Globalization;
|
||||
using System.Xml;
|
||||
|
||||
namespace Titano.Core.Metadata.Xmp;
|
||||
|
||||
/// <summary>
|
||||
/// Streaming XMP reader (no DTDs, no external resolution, 4 MB cap). Reads both the attribute form
|
||||
/// (<c><rdf:Description xmp:Rating="5"/></c>) and the element form (<c><xmp:Rating>5</xmp:Rating></c>,
|
||||
/// including values nested in <c>rdf:Alt</c>/<c>rdf:Seq</c>) of the properties in <see cref="XmpValues"/>.
|
||||
/// </summary>
|
||||
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,
|
||||
}
|
||||
|
||||
/// <summary>Parses one packet into <paramref name="values"/>, keeping values that are already set.</summary>
|
||||
/// <returns>Null on success; otherwise why parsing stopped (values read before the problem are kept).</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
namespace Titano.Core.Metadata.Xmp;
|
||||
|
||||
/// <summary>The XMP properties Titano reads. Each is set by the first packet that carries it.</summary>
|
||||
internal sealed class XmpValues
|
||||
{
|
||||
public int? Rating { get; set; }
|
||||
public string? Label { get; set; }
|
||||
|
||||
/// <summary>exif:DateTimeOriginal.</summary>
|
||||
public CaptureStamp? DateTimeOriginal { get; set; }
|
||||
|
||||
/// <summary>photoshop:DateCreated.</summary>
|
||||
public CaptureStamp? DateCreated { get; set; }
|
||||
|
||||
/// <summary>xmp:CreateDate.</summary>
|
||||
public CaptureStamp? CreateDate { get; set; }
|
||||
|
||||
public int? Orientation { get; set; }
|
||||
|
||||
/// <summary>aux:SerialNumber.</summary>
|
||||
public string? AuxSerialNumber { get; set; }
|
||||
|
||||
/// <summary>exifEX:BodySerialNumber.</summary>
|
||||
public string? BodySerialNumber { get; set; }
|
||||
|
||||
/// <summary>aux:Lens.</summary>
|
||||
public string? AuxLens { get; set; }
|
||||
|
||||
/// <summary>exifEX:LensModel.</summary>
|
||||
public string? LensModel { get; set; }
|
||||
|
||||
/// <summary>xmpNote:HasExtendedXMP: GUID of the extended packet split across JPEG APP1 segments.</summary>
|
||||
public string? ExtendedXmpGuid { get; set; }
|
||||
|
||||
/// <summary>Capture time in MWG order: DateTimeOriginal, DateCreated, CreateDate.</summary>
|
||||
public CaptureStamp? CaptureTime => DateTimeOriginal ?? DateCreated ?? CreateDate;
|
||||
|
||||
public string? BodySerial => BodySerialNumber ?? AuxSerialNumber;
|
||||
|
||||
public string? Lens => LensModel ?? AuxLens;
|
||||
}
|
||||
Reference in new issue
Block a user