using System.Buffers.Binary;
using System.Globalization;
using Febe.Core.Domain;
namespace Febe.Core.Import;
///
/// 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: DateTimeOriginal (0x9003), then CreateDate
/// (0x9004, «DateTimeDigitized»), with OffsetTimeOriginal/OffsetTimeDigitized/OffsetTime when the
/// camera wrote the zone. The modification date of IFD0 (0x0132) is not used: editors rewrite it.
///
/// Containers: JPEG (APP1 «Exif»), TIFF and raw formats built on it, PNG (eXIf chunk), WebP (EXIF chunk).
/// HEIC keeps its EXIF in an item of the meta box and is not read. Every offset is checked: a damaged block gives
/// no date, never an exception.
///
///
public static class ExifDateReader
{
/// Bytes to read from the start of a file: EXIF blocks sit near the start.
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;
///
/// 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 (Alberto's: cameras write local time).
///
public static DateTimeOffset? Read(ReadOnlySpan 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
}
}
/// The TIFF structure holding the EXIF data of a JPEG, TIFF, PNG or WebP; empty when there is none.
internal static ReadOnlySpan FindTiff(ReadOnlySpan 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 FindInJpeg(ReadOnlySpan 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 FindInPng(ReadOnlySpan 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 FindInWebp(ReadOnlySpan 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 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);
}
/// «2021:05:06 07:08:09» with an optional «+02:00» zone.
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);
}
/// «+02:00» or «-05:00».
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 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 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 data, int offset, bool little) => little
? BinaryPrimitives.ReadUInt16LittleEndian(data.Slice(offset, 2))
: BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset, 2));
private static uint U32(ReadOnlySpan data, int offset, bool little) => little
? BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(offset, 4))
: BinaryPrimitives.ReadUInt32BigEndian(data.Slice(offset, 4));
}