Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
322 lines
10 KiB
C#
322 lines
10 KiB
C#
using System.Buffers.Binary;
|
|
using System.Globalization;
|
|
using Febe.Core.Domain;
|
|
|
|
namespace Febe.Core.Import;
|
|
|
|
/// <summary>
|
|
/// Reads the shooting date of a photo from its EXIF block (spec §3: «la lettura della data di scatto dai metadati di una
|
|
/// foto si scrive a mano»). Only the few fields that matter: <c>DateTimeOriginal</c> (0x9003), then <c>CreateDate</c>
|
|
/// (0x9004, «DateTimeDigitized»), with <c>OffsetTimeOriginal</c>/<c>OffsetTimeDigitized</c>/<c>OffsetTime</c> when the
|
|
/// camera wrote the zone. The modification date of IFD0 (0x0132) is not used: editors rewrite it.
|
|
/// <para>
|
|
/// Containers: JPEG (APP1 «Exif»), TIFF and raw formats built on it, PNG (<c>eXIf</c> chunk), WebP (<c>EXIF</c> chunk).
|
|
/// HEIC keeps its EXIF in an item of the <c>meta</c> box and is not read. Every offset is checked: a damaged block gives
|
|
/// no date, never an exception.
|
|
/// </para>
|
|
/// </summary>
|
|
public static class ExifDateReader
|
|
{
|
|
/// <summary>Bytes to read from the start of a file: EXIF blocks sit near the start.</summary>
|
|
public const int HeadLength = 512 * 1024;
|
|
|
|
private const ushort TagExifIfd = 0x8769;
|
|
private const ushort TagDateTimeOriginal = 0x9003;
|
|
private const ushort TagCreateDate = 0x9004;
|
|
private const ushort TagOffsetTime = 0x9010;
|
|
private const ushort TagOffsetTimeOriginal = 0x9011;
|
|
private const ushort TagOffsetTimeDigitized = 0x9012;
|
|
private const int MaxEntries = 512;
|
|
|
|
/// <summary>
|
|
/// The shooting date in the first bytes of a photo; null when there is none. Without a zone in the file, the time
|
|
/// is read in <paramref name="zone"/> (Alberto's: cameras write local time).
|
|
/// </summary>
|
|
public static DateTimeOffset? Read(ReadOnlySpan<byte> data, TimeZoneInfo zone)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(zone);
|
|
try
|
|
{
|
|
var tiff = FindTiff(data);
|
|
return tiff.IsEmpty ? null : ReadTiff(tiff, zone);
|
|
}
|
|
catch (ArgumentOutOfRangeException)
|
|
{
|
|
return null; // a damaged block: no date
|
|
}
|
|
}
|
|
|
|
/// <summary>The TIFF structure holding the EXIF data of a JPEG, TIFF, PNG or WebP; empty when there is none.</summary>
|
|
internal static ReadOnlySpan<byte> FindTiff(ReadOnlySpan<byte> data)
|
|
{
|
|
if (data.Length < 8)
|
|
{
|
|
return [];
|
|
}
|
|
|
|
if (data[0] == 0xFF && data[1] == 0xD8)
|
|
{
|
|
return FindInJpeg(data);
|
|
}
|
|
|
|
if (data.StartsWith("II*\0"u8) || data.StartsWith("MM\0*"u8))
|
|
{
|
|
return data;
|
|
}
|
|
|
|
if (data[0] == 0x89 && data.Slice(1, 3).SequenceEqual("PNG"u8))
|
|
{
|
|
return FindInPng(data);
|
|
}
|
|
|
|
if (data.Length >= 12 && data.StartsWith("RIFF"u8) && data.Slice(8, 4).SequenceEqual("WEBP"u8))
|
|
{
|
|
return FindInWebp(data);
|
|
}
|
|
|
|
return [];
|
|
}
|
|
|
|
private static ReadOnlySpan<byte> FindInJpeg(ReadOnlySpan<byte> data)
|
|
{
|
|
var offset = 2;
|
|
while (offset + 4 <= data.Length)
|
|
{
|
|
if (data[offset] != 0xFF)
|
|
{
|
|
return [];
|
|
}
|
|
|
|
var marker = data[offset + 1];
|
|
if (marker == 0xFF)
|
|
{
|
|
offset++; // fill byte
|
|
continue;
|
|
}
|
|
|
|
if (marker is 0xD8 or 0x01 or (>= 0xD0 and <= 0xD7))
|
|
{
|
|
offset += 2; // markers without length
|
|
continue;
|
|
}
|
|
|
|
if (marker is 0xDA or 0xD9)
|
|
{
|
|
return []; // start of scan or end of image: no EXIF before the picture data
|
|
}
|
|
|
|
var length = BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset + 2, 2));
|
|
if (length < 2 || offset + 2 + length > data.Length)
|
|
{
|
|
return [];
|
|
}
|
|
|
|
var segment = data.Slice(offset + 4, length - 2);
|
|
if (marker == 0xE1 && segment.StartsWith("Exif\0\0"u8))
|
|
{
|
|
return segment[6..];
|
|
}
|
|
|
|
offset += 2 + length;
|
|
}
|
|
|
|
return [];
|
|
}
|
|
|
|
private static ReadOnlySpan<byte> FindInPng(ReadOnlySpan<byte> data)
|
|
{
|
|
var offset = 8;
|
|
while (offset + 12 <= data.Length)
|
|
{
|
|
var length = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(offset, 4));
|
|
var type = data.Slice(offset + 4, 4);
|
|
if (length > int.MaxValue || offset + 12 + (long)length > data.Length)
|
|
{
|
|
return [];
|
|
}
|
|
|
|
if (type.SequenceEqual("eXIf"u8))
|
|
{
|
|
var chunk = data.Slice(offset + 8, (int)length);
|
|
return chunk.StartsWith("Exif\0\0"u8) ? chunk[6..] : chunk;
|
|
}
|
|
|
|
if (type.SequenceEqual("IEND"u8))
|
|
{
|
|
return [];
|
|
}
|
|
|
|
offset += 12 + (int)length;
|
|
}
|
|
|
|
return [];
|
|
}
|
|
|
|
private static ReadOnlySpan<byte> FindInWebp(ReadOnlySpan<byte> data)
|
|
{
|
|
var offset = 12;
|
|
while (offset + 8 <= data.Length)
|
|
{
|
|
var type = data.Slice(offset, 4);
|
|
var length = BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(offset + 4, 4));
|
|
if (length > int.MaxValue || offset + 8 + (long)length > data.Length)
|
|
{
|
|
return [];
|
|
}
|
|
|
|
if (type.SequenceEqual("EXIF"u8))
|
|
{
|
|
var chunk = data.Slice(offset + 8, (int)length);
|
|
return chunk.StartsWith("Exif\0\0"u8) ? chunk[6..] : chunk;
|
|
}
|
|
|
|
offset += 8 + (int)length + ((int)length & 1); // chunks are padded to an even size
|
|
}
|
|
|
|
return [];
|
|
}
|
|
|
|
private static DateTimeOffset? ReadTiff(ReadOnlySpan<byte> tiff, TimeZoneInfo zone)
|
|
{
|
|
if (tiff.Length < 8)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
bool little;
|
|
if (tiff.StartsWith("II"u8))
|
|
{
|
|
little = true;
|
|
}
|
|
else if (tiff.StartsWith("MM"u8))
|
|
{
|
|
little = false;
|
|
}
|
|
else
|
|
{
|
|
return null;
|
|
}
|
|
|
|
if (U16(tiff, 2, little) != 42)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var ifd0 = U32(tiff, 4, little);
|
|
var exifIfd = FindTag(tiff, ifd0, TagExifIfd, little) is { } pointer ? U32(tiff, pointer.ValueOffset, little) : (uint?)null;
|
|
|
|
string? original = null, created = null, offsetOriginal = null, offsetCreated = null, offsetAny = null;
|
|
if (exifIfd is { } exif)
|
|
{
|
|
original = AsciiTag(tiff, exif, TagDateTimeOriginal, little);
|
|
created = AsciiTag(tiff, exif, TagCreateDate, little);
|
|
offsetOriginal = AsciiTag(tiff, exif, TagOffsetTimeOriginal, little);
|
|
offsetCreated = AsciiTag(tiff, exif, TagOffsetTimeDigitized, little);
|
|
offsetAny = AsciiTag(tiff, exif, TagOffsetTime, little);
|
|
}
|
|
|
|
return Parse(original, offsetOriginal ?? offsetAny, zone) ?? Parse(created, offsetCreated ?? offsetAny, zone);
|
|
}
|
|
|
|
/// <summary>«2021:05:06 07:08:09» with an optional «+02:00» zone.</summary>
|
|
internal static DateTimeOffset? Parse(string? value, string? offset, TimeZoneInfo zone)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(value))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var text = value.Trim().TrimEnd('\0').Trim();
|
|
if (text.Length < 19
|
|
|| !DateTime.TryParseExact(text[..19], ["yyyy:MM:dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss", "yyyy:MM:dd'T'HH:mm:ss"], CultureInfo.InvariantCulture, DateTimeStyles.None, out var local)
|
|
|| local.Year < 1900)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
if (TryParseOffset(offset, out var zoneOffset))
|
|
{
|
|
return new DateTimeOffset(DateTime.SpecifyKind(local, DateTimeKind.Unspecified), zoneOffset);
|
|
}
|
|
|
|
return LocalCalendar.FromLocal(local, zone);
|
|
}
|
|
|
|
/// <summary>«+02:00» or «-05:00».</summary>
|
|
private static bool TryParseOffset(string? text, out TimeSpan offset)
|
|
{
|
|
offset = default;
|
|
if (string.IsNullOrWhiteSpace(text))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var trimmed = text.Trim().TrimEnd('\0').Trim();
|
|
if (trimmed.Length != 6 || trimmed[0] is not ('+' or '-')
|
|
|| !TimeSpan.TryParseExact(trimmed[1..], @"hh\:mm", CultureInfo.InvariantCulture, out var span)
|
|
|| span > TimeSpan.FromHours(14))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
offset = trimmed[0] == '-' ? -span : span;
|
|
return true;
|
|
}
|
|
|
|
private readonly record struct IfdEntry(ushort Tag, ushort Type, uint Count, int ValueOffset);
|
|
|
|
private static IfdEntry? FindTag(ReadOnlySpan<byte> tiff, uint ifdOffset, ushort tag, bool little)
|
|
{
|
|
if (ifdOffset < 8 || ifdOffset + 2 > (uint)tiff.Length)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var count = U16(tiff, (int)ifdOffset, little);
|
|
if (count > MaxEntries)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
for (var i = 0; i < count; i++)
|
|
{
|
|
var at = (int)ifdOffset + 2 + (i * 12);
|
|
if (at + 12 > tiff.Length)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
if (U16(tiff, at, little) == tag)
|
|
{
|
|
return new IfdEntry(tag, U16(tiff, at + 2, little), U32(tiff, at + 4, little), at + 8);
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private static string? AsciiTag(ReadOnlySpan<byte> tiff, uint ifdOffset, ushort tag, bool little)
|
|
{
|
|
if (FindTag(tiff, ifdOffset, tag, little) is not { Type: 2 } entry || entry.Count == 0 || entry.Count > 64)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var start = entry.Count <= 4 ? entry.ValueOffset : (int)U32(tiff, entry.ValueOffset, little);
|
|
if (start < 0 || start + entry.Count > tiff.Length)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return System.Text.Encoding.ASCII.GetString(tiff.Slice(start, (int)entry.Count)).TrimEnd('\0');
|
|
}
|
|
|
|
private static ushort U16(ReadOnlySpan<byte> data, int offset, bool little) => little
|
|
? BinaryPrimitives.ReadUInt16LittleEndian(data.Slice(offset, 2))
|
|
: BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset, 2));
|
|
|
|
private static uint U32(ReadOnlySpan<byte> data, int offset, bool little) => little
|
|
? BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(offset, 4))
|
|
: BinaryPrimitives.ReadUInt32BigEndian(data.Slice(offset, 4));
|
|
}
|