diff --git a/src/Titano.Core/Metadata/ExifWriter.cs b/src/Titano.Core/Metadata/ExifWriter.cs new file mode 100644 index 00000000..9fdd6416 --- /dev/null +++ b/src/Titano.Core/Metadata/ExifWriter.cs @@ -0,0 +1,254 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Text; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata; + +/// +/// Writes a minimal, valid little-endian Exif block for proxies and exports (BRIEF §8.5, §9): IFD0 (camera, orientation, +/// software, date, authorship), the Exif IFD (capture time with sub-seconds and offset, exposure, lens and body) and, +/// when known, the GPS IFD. Strings longer than UTF-8 bytes are truncated. +/// +public static class ExifWriter +{ + /// Longest string written, in UTF-8 bytes; keeps the APP1 segment far below its 64 KB limit. + public const int MaxStringBytes = 2000; + + private const int MaxShortIso = 65535; + private const uint GpsDegreeDenominator = 10_000_000; + + private static ReadOnlySpan ExifHeader => "Exif\0\0"u8; + + /// A complete TIFF structure ("II*\0" header, IFD0, Exif IFD, optional GPS IFD). + public static byte[] BuildTiff(FrameMetadata metadata) + { + ArgumentNullException.ThrowIfNull(metadata); + var m = metadata; + var date = m.CapturedAt?.ToString("yyyy':'MM':'dd HH':'mm':'ss", CultureInfo.InvariantCulture); + + var ifd0 = new IfdBuilder(); + ifd0.Ascii(TiffTags.Make, m.Make); + ifd0.Ascii(TiffTags.Model, m.Model); + ifd0.Short(TiffTags.Orientation, (ushort)(m.Orientation is >= 1 and <= 8 ? m.Orientation : 1)); + ifd0.Rational(TiffTags.XResolution, 72, 1); + ifd0.Rational(TiffTags.YResolution, 72, 1); + ifd0.Short(TiffTags.ResolutionUnit, 2); + ifd0.Ascii(TiffTags.Software, m.Software); + ifd0.Ascii(TiffTags.DateTime, date); + ifd0.Ascii(TiffTags.Artist, m.Artist); + ifd0.Short(TiffTags.YCbCrPositioning, 1); + ifd0.Ascii(TiffTags.Copyright, m.Copyright); + + var exif = new IfdBuilder(); + exif.Rational(TiffTags.ExposureTime, m.ExposureTime); + exif.Rational(TiffTags.FNumber, m.FNumber); + if (m.Iso is { } iso and > 0) + { + exif.Short(TiffTags.IsoSpeedRatings, (ushort)Math.Min(iso, MaxShortIso)); + if (iso >= MaxShortIso) + { + // ISOSpeedRatings saturates at 65535; SensitivityType 2 declares RecommendedExposureIndex as the value. + exif.Short(TiffTags.SensitivityType, 2); + exif.Long(TiffTags.RecommendedExposureIndex, (uint)iso); + } + } + exif.Undefined(TiffTags.ExifVersion, "0232"u8); + exif.Ascii(TiffTags.DateTimeOriginal, date); + if (m.CapturedAt is { } captured && captured.Ticks % TimeSpan.TicksPerSecond is > 0 and var fraction) + exif.Ascii(TiffTags.SubSecTimeOriginal, fraction.ToString("D7", CultureInfo.InvariantCulture).TrimEnd('0')); + if (m.UtcOffsetMinutes is { } offset && Math.Abs(offset) < 24 * 60) + exif.Ascii(TiffTags.OffsetTimeOriginal, $"{(offset < 0 ? '-' : '+')}{Math.Abs(offset) / 60:D2}:{Math.Abs(offset) % 60:D2}"); + exif.SRational(TiffTags.ExposureBiasValue, m.ExposureBias); + exif.Rational(TiffTags.FocalLength, m.FocalLength); + if (m.FocalLength35 is { } f35 and > 0 and < MaxShortIso) exif.Short(TiffTags.FocalLengthIn35mmFilm, (ushort)Math.Round(f35)); + exif.Ascii(TiffTags.BodySerialNumber, m.BodySerial); + exif.Ascii(TiffTags.LensModel, m.LensModel); + + var gps = m.Gps is { } position ? BuildGps(position) : null; + + // Pointers are fixed-size LONGs, so the IFD sizes are known before their offsets. + ifd0.Long(TiffTags.ExifIfd, 0); + if (gps is not null) ifd0.Long(TiffTags.GpsIfd, 0); + var exifOffset = 8 + ifd0.Size; + var gpsOffset = exifOffset + exif.Size; + ifd0.Long(TiffTags.ExifIfd, (uint)exifOffset); + if (gps is not null) ifd0.Long(TiffTags.GpsIfd, (uint)gpsOffset); + + var tiff = new byte[gpsOffset + (gps?.Size ?? 0)]; + "II*\0"u8.CopyTo(tiff); + BinaryPrimitives.WriteUInt32LittleEndian(tiff.AsSpan(4), 8); + ifd0.Write(tiff, 8); + exif.Write(tiff, exifOffset); + gps?.Write(tiff, gpsOffset); + return tiff; + } + + /// A complete JPEG APP1 segment: FF E1, big-endian length, "Exif\0\0", then . + public static byte[] BuildJpegApp1(FrameMetadata metadata) + { + var tiff = BuildTiff(metadata); + var segment = new byte[4 + ExifHeader.Length + tiff.Length]; + segment[0] = 0xFF; + segment[1] = 0xE1; + BinaryPrimitives.WriteUInt16BigEndian(segment.AsSpan(2), checked((ushort)(segment.Length - 2))); + ExifHeader.CopyTo(segment.AsSpan(4)); + tiff.CopyTo(segment, 4 + ExifHeader.Length); + return segment; + } + + /// Coordinates as decimal degrees (1e-7° resolution) in the degrees rational, minutes and seconds zero. + private static IfdBuilder BuildGps(GpsPosition gps) + { + var ifd = new IfdBuilder(); + ifd.Bytes(TiffTags.GpsVersionId, TiffType.Byte, [2, 3, 0, 0]); + if (double.IsFinite(gps.Latitude) && double.IsFinite(gps.Longitude)) + { + ifd.Ascii(TiffTags.GpsLatitudeRef, gps.Latitude < 0 ? "S" : "N"); + ifd.Rationals(TiffTags.GpsLatitude, [((uint)Math.Round(Math.Min(Math.Abs(gps.Latitude), 90) * GpsDegreeDenominator), GpsDegreeDenominator), (0, 1), (0, 1)]); + ifd.Ascii(TiffTags.GpsLongitudeRef, gps.Longitude < 0 ? "W" : "E"); + ifd.Rationals(TiffTags.GpsLongitude, [((uint)Math.Round(Math.Min(Math.Abs(gps.Longitude), 180) * GpsDegreeDenominator), GpsDegreeDenominator), (0, 1), (0, 1)]); + } + if (gps.Altitude is { } altitude && double.IsFinite(altitude)) + { + ifd.Bytes(TiffTags.GpsAltitudeRef, TiffType.Byte, [altitude < 0 ? (byte)1 : (byte)0]); + ifd.Rationals(TiffTags.GpsAltitude, [ToRational(Math.Abs(altitude))]); + } + if (gps.UtcTimestamp is { } utc) + { + var t = utc.TimeOfDay; + ifd.Rationals(TiffTags.GpsTimeStamp, [((uint)t.Hours, 1), ((uint)t.Minutes, 1), ((uint)Math.Round((t.Seconds + t.Milliseconds / 1000.0) * 1000), 1000)]); + ifd.Ascii(TiffTags.GpsDateStamp, utc.ToString("yyyy':'MM':'dd", CultureInfo.InvariantCulture)); + } + return ifd; + } + + /// Exact 1/n for exposure-style fractions, else a fixed denominator reduced by the GCD. + private static (uint Numerator, uint Denominator) ToRational(double value) + { + if (!double.IsFinite(value) || value <= 0) return (0, 1); + if (value < 1) + { + var inverse = Math.Round(1 / value); + if (inverse <= uint.MaxValue && Math.Abs(1 / inverse - value) <= value * 1e-6) return (1, (uint)inverse); + } + var denominator = value < 400_000 ? 10_000u : 1u; + var numerator = Math.Round(value * denominator); + if (numerator > uint.MaxValue) return (uint.MaxValue, 1); + var n = (uint)numerator; + var gcd = Gcd(n, denominator); + return (n / gcd, denominator / gcd); + } + + private static uint Gcd(uint a, uint b) + { + while (b != 0) (a, b) = (b, a % b); + return a == 0 ? 1 : a; + } + + /// Collects entries of one IFD and serialises them sorted by tag, values over 4 bytes word-aligned after it. + private sealed class IfdBuilder + { + private readonly SortedDictionary _entries = new(); + + /// Bytes taken by the IFD including its out-of-line values. + public int Size + { + get + { + var size = 2 + 12 * _entries.Count + 4; + foreach (var e in _entries.Values) + { + if (e.Data.Length > 4) size += e.Data.Length + (e.Data.Length & 1); + } + return size; + } + } + + public void Bytes(ushort tag, TiffType type, byte[] data) => _entries[tag] = (type, (uint)(data.Length / TiffTypeInfo.Size(type)), data); + + public void Undefined(ushort tag, ReadOnlySpan data) => Bytes(tag, TiffType.Undefined, data.ToArray()); + + public void Ascii(ushort tag, string? value) + { + if (string.IsNullOrWhiteSpace(value)) return; + var text = value.Trim(); + var nul = text.IndexOf('\0'); + if (nul >= 0) text = text[..nul]; + var bytes = Encoding.UTF8.GetBytes(text); + var length = Math.Min(bytes.Length, MaxStringBytes); + while (length < bytes.Length && length > 0 && (bytes[length] & 0xC0) == 0x80) length--; + var data = new byte[length + 1]; + bytes.AsSpan(0, length).CopyTo(data); + Bytes(tag, TiffType.Ascii, data); + } + + public void Short(ushort tag, ushort value) + { + var data = new byte[2]; + BinaryPrimitives.WriteUInt16LittleEndian(data, value); + Bytes(tag, TiffType.Short, data); + } + + public void Long(ushort tag, uint value) + { + var data = new byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(data, value); + Bytes(tag, TiffType.Long, data); + } + + public void Rational(ushort tag, double? value) + { + if (value is { } v and > 0 && double.IsFinite(v)) Rationals(tag, [ToRational(v)]); + } + + public void Rational(ushort tag, uint numerator, uint denominator) => Rationals(tag, [(numerator, denominator)]); + + public void Rationals(ushort tag, ReadOnlySpan<(uint Numerator, uint Denominator)> values) + { + var data = new byte[8 * values.Length]; + for (var i = 0; i < values.Length; i++) + { + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(8 * i), values[i].Numerator); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(8 * i + 4), values[i].Denominator); + } + Bytes(tag, TiffType.Rational, data); + } + + public void SRational(ushort tag, double? value) + { + if (value is not { } v || !double.IsFinite(v) || Math.Abs(v) >= 200_000) return; + var (n, d) = ToRational(Math.Abs(v)); + var data = new byte[8]; + BinaryPrimitives.WriteInt32LittleEndian(data, v < 0 ? -(int)n : (int)n); + BinaryPrimitives.WriteInt32LittleEndian(data.AsSpan(4), (int)d); + Bytes(tag, TiffType.SRational, data); + } + + public void Write(byte[] tiff, int offset) + { + var span = tiff.AsSpan(); + BinaryPrimitives.WriteUInt16LittleEndian(span[offset..], (ushort)_entries.Count); + var entry = offset + 2; + var data = offset + 2 + 12 * _entries.Count + 4; + foreach (var (tag, (type, count, bytes)) in _entries) + { + BinaryPrimitives.WriteUInt16LittleEndian(span[entry..], tag); + BinaryPrimitives.WriteUInt16LittleEndian(span[(entry + 2)..], (ushort)type); + BinaryPrimitives.WriteUInt32LittleEndian(span[(entry + 4)..], count); + if (bytes.Length <= 4) + { + bytes.CopyTo(span[(entry + 8)..]); + } + else + { + BinaryPrimitives.WriteUInt32LittleEndian(span[(entry + 8)..], (uint)data); + bytes.CopyTo(span[data..]); + data += bytes.Length + (bytes.Length & 1); + } + entry += 12; + } + BinaryPrimitives.WriteUInt32LittleEndian(span[entry..], 0); + } + } +}