feat(metadata): parse TIFF/Exif, JPEG segments and MakerNotes
ExifParser walks IFD0, Exif, GPS and SubIFDs, selects the main raster (largest full-resolution IFD), and enumerates embedded JPEG previews (JPEGInterchangeFormat, single-strip/tile Compression 6/7, lossless raw strips excluded). JpegParser scans APP1 Exif/XMP/extended XMP, APP2 MPF large thumbnails and SOFn up to SOS, tolerating fill bytes and garbage. Vendor MakerNotes (Canon, Nikon, Sony, Fujifilm, Olympus/OM, Panasonic) fill serial, lens, shutter count, stabiliser, ISO and colour temperature only when standard tags did not. TiffTags gains GPSVersionID, GPSStatus, YCbCrPositioning, StandardOutputSensitivity and ISOSpeed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
11 files changed
+918
No files matched your search
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Maps TIFF/Exif structures onto a <see cref="MetadataBuilder"/>: 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.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>Parses a TIFF-based file (TIFF, DNG, TIFF-like RAWs) whose header is at offset 0.</summary>
|
||||
public static void ParseFile(MetadataBuilder m) => Walk(m, 0, isFile: true);
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public static void ParseEmbedded(MetadataBuilder m, long tiffBase) => Walk(m, tiffBase, isFile: false);
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public static void ParseOffsetPrefixed(MetadataBuilder m, long start, long length)
|
||||
{
|
||||
Span<byte> 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");
|
||||
}
|
||||
|
||||
/// <summary>IFD0 fields plus the Exif and GPS sub-IFDs it points to.</summary>
|
||||
public static void ReadTree(TiffReader r, Ifd ifd0, MetadataBuilder m, HashSet<long> 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);
|
||||
}
|
||||
|
||||
/// <summary>Camera identity, authorship, orientation, rating and XMP from IFD0.</summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>Exposure, capture time, lens/body identity and the MakerNote from an Exif IFD.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Position (status "V" = void is ignored), altitude and the UTC date/time stamp from a GPS IFD.</summary>
|
||||
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<long>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Raster candidate, embedded previews and SubIFDs (depth- and count-capped) of one image IFD.</summary>
|
||||
private static void VisitImage(TiffReader r, Ifd ifd, MetadataBuilder m, HashSet<long> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>JPEGInterchangeFormat thumbnails/previews and single-strip/tile JPEG images (Compression 6/7, not CFA).</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Panasonic RW2 header: sensor crop size, bit depth, ISO and the JpgFromRaw that carries the Exif block.</summary>
|
||||
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<long> 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;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
namespace Titano.Core.Metadata.Tiff;
|
||||
|
||||
/// <summary>Single-value accessors over <see cref="TiffReader"/> that refuse oversized counts, so a corrupt
|
||||
/// count can never trigger a large read when only the first value is needed.</summary>
|
||||
internal static class IfdValue
|
||||
{
|
||||
/// <summary>Largest value count read for scalar/array tags (GPS triples, lens info, Canon camera settings…).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>First value as a finite double (rationals divided).</summary>
|
||||
public static double? Double(TiffReader r, Ifd ifd, ushort tag) => Doubles(r, ifd, tag, 1) is [var v, ..] ? v : null;
|
||||
|
||||
/// <summary>All values when at least <paramref name="minCount"/> are present and every one is finite.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Text value with control characters removed; null when empty.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user