refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

@@ -0,0 +1,247 @@
using System.Buffers.Binary;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata.Jpeg;
using Chronos.Core.Metadata.MakerNotes;
using Chronos.Core.Metadata.Xmp;
namespace Chronos.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 Chronos.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;
}
}
@@ -0,0 +1,251 @@
using System.Buffers.Binary;
using System.Text;
namespace Chronos.Core.Metadata.Tiff;
/// <summary>One IFD entry. Small values (≤ 4 bytes) are inline; larger ones live at <see cref="ValueOffset"/>.</summary>
public readonly record struct IfdEntry(ushort Tag, TiffType Type, uint Count, uint ValueOffset, long EntryPosition)
{
public long ByteLength => (long)Count * TiffTypeInfo.Size(Type);
public bool IsInline => ByteLength <= 4;
/// <summary>Absolute file position of the value bytes (inline values sit inside the entry).</summary>
public long ValuePosition(long tiffBase) => IsInline ? EntryPosition + 8 : tiffBase + ValueOffset;
}
/// <summary>An image file directory: its entries and the offset of the next IFD (0 = none).</summary>
public sealed class Ifd(long position, IReadOnlyDictionary<ushort, IfdEntry> entries, uint nextOffset)
{
public long Position { get; } = position;
public IReadOnlyDictionary<ushort, IfdEntry> Entries { get; } = entries;
public uint NextOffset { get; } = nextOffset;
public bool Has(ushort tag) => Entries.ContainsKey(tag);
}
/// <summary>
/// Fuzz-safe TIFF structure reader over a seekable stream. Reads only the bytes it needs (never the whole
/// file), validates every offset against the stream length, caps entry counts and detects IFD loops.
/// Also used for TIFF structures embedded at a base offset (Exif APP1, RAF, CR3 CMT boxes, MakerNotes).
/// </summary>
public sealed class TiffReader
{
public const int MaxEntriesPerIfd = 4096;
public const int MaxIfdChain = 64;
public const long MaxValueBytes = 64L * 1024 * 1024;
private readonly Stream _stream;
private readonly List<string> _warnings = [];
private TiffReader(Stream stream, long tiffBase, bool littleEndian, uint firstIfdOffset)
{
_stream = stream;
Base = tiffBase;
LittleEndian = littleEndian;
FirstIfdOffset = firstIfdOffset;
}
/// <summary>Absolute position of the TIFF header ("II*\0"/"MM\0*"); IFD offsets are relative to it.</summary>
public long Base { get; }
public bool LittleEndian { get; }
public uint FirstIfdOffset { get; }
public IReadOnlyList<string> Warnings => _warnings;
public long StreamLength => _stream.Length;
/// <summary>Opens a TIFF header at <paramref name="tiffBase"/>; null when the bytes are not a TIFF header.
/// Accepts the ORF ("IIRO"/"IIRS") and RW2 ("IIU\0") header variants.</summary>
public static TiffReader? Open(Stream stream, long tiffBase = 0)
{
if (!stream.CanSeek || tiffBase < 0 || tiffBase + 8 > stream.Length) return null;
Span<byte> h = stackalloc byte[8];
stream.Position = tiffBase;
if (stream.ReadAtLeast(h, 8, throwOnEndOfStream: false) < 8) return null;
bool le;
if (h[0] == 'I' && h[1] == 'I') le = true;
else if (h[0] == 'M' && h[1] == 'M') le = false;
else return null;
var magic = le ? BinaryPrimitives.ReadUInt16LittleEndian(h[2..]) : BinaryPrimitives.ReadUInt16BigEndian(h[2..]);
if (magic is not (42 or 0x4F52 or 0x5352 or 0x0055)) return null;
var first = le ? BinaryPrimitives.ReadUInt32LittleEndian(h[4..]) : BinaryPrimitives.ReadUInt32BigEndian(h[4..]);
return new TiffReader(stream, tiffBase, le, first);
}
/// <summary>Creates a reader for an IFD structure without a header (e.g. maker notes) with a known byte order.</summary>
public static TiffReader ForEmbedded(Stream stream, long tiffBase, bool littleEndian) => new(stream, tiffBase, littleEndian, 0);
/// <summary>Reads the chain of top-level IFDs (IFD0, IFD1, …).</summary>
public IReadOnlyList<Ifd> ReadChain()
{
var list = new List<Ifd>();
var seen = new HashSet<long>();
var offset = FirstIfdOffset;
while (offset != 0 && list.Count < MaxIfdChain)
{
var ifd = ReadIfd(offset, seen);
if (ifd is null) break;
list.Add(ifd);
offset = ifd.NextOffset;
}
return list;
}
/// <summary>Reads one IFD at a base-relative offset; null if out of bounds or already visited.</summary>
public Ifd? ReadIfd(uint offset, HashSet<long>? visited = null)
{
var pos = Base + offset;
if (pos + 2 > _stream.Length || pos < 0)
{
Warn($"IFD offset {offset} beyond end of file");
return null;
}
if (visited is not null && !visited.Add(pos))
{
Warn($"IFD loop at {offset}");
return null;
}
Span<byte> two = stackalloc byte[2];
if (!ReadAt(pos, two)) return null;
var count = U16(two);
if (count == 0 || count > MaxEntriesPerIfd)
{
Warn($"IFD at {offset} has {count} entries");
return null;
}
var bytes = new byte[count * 12 + 4];
var available = (int)Math.Min(bytes.Length, _stream.Length - (pos + 2));
if (!ReadAt(pos + 2, bytes.AsSpan(0, available))) return null;
var entries = new Dictionary<ushort, IfdEntry>(count);
var complete = available / 12;
for (var i = 0; i < Math.Min(count, complete); i++)
{
var e = bytes.AsSpan(i * 12, 12);
var tag = U16(e);
var type = (TiffType)U16(e[2..]);
var n = U32(e[4..]);
var value = U32(e[8..]);
if (TiffTypeInfo.Size(type) == 0) continue;
entries.TryAdd(tag, new IfdEntry(tag, type, n, value, pos + 2 + i * 12));
}
if (complete < count) Warn($"IFD at {offset} truncated");
var next = available >= count * 12 + 4 ? U32(bytes.AsSpan(count * 12)) : 0u;
return new Ifd(pos, entries, next);
}
/// <summary>Raw value bytes of an entry (bounded by <see cref="MaxValueBytes"/>); null when invalid.</summary>
public byte[]? ReadBytes(IfdEntry e, long maxBytes = MaxValueBytes)
{
var length = e.ByteLength;
if (length <= 0 || length > maxBytes) return null;
var pos = e.ValuePosition(Base);
if (pos < 0 || pos + length > _stream.Length)
{
Warn($"Tag 0x{e.Tag:X4} value outside file");
return null;
}
var buffer = new byte[length];
return ReadAt(pos, buffer) ? buffer : null;
}
public uint? GetUInt(Ifd ifd, ushort tag) => ifd.Entries.TryGetValue(tag, out var e) ? GetUInts(e) is { Length: > 0 } v ? v[0] : null : null;
public uint[]? GetUInts(Ifd ifd, ushort tag) => ifd.Entries.TryGetValue(tag, out var e) ? GetUInts(e) : null;
/// <summary>Integer values of BYTE/SHORT/LONG/IFD (and signed variants) entries.</summary>
public uint[]? GetUInts(IfdEntry e)
{
var raw = ReadBytes(e);
if (raw is null) return null;
var size = TiffTypeInfo.Size(e.Type);
var result = new uint[e.Count];
for (var i = 0; i < e.Count; i++)
{
var s = raw.AsSpan(i * size);
result[i] = e.Type switch
{
TiffType.Byte or TiffType.Undefined or TiffType.Ascii => s[0],
TiffType.SByte => (uint)(sbyte)s[0],
TiffType.Short => U16(s),
TiffType.SShort => (uint)(short)U16(s),
TiffType.Long or TiffType.Ifd or TiffType.SLong => U32(s),
_ => 0,
};
}
return result;
}
public double? GetDouble(Ifd ifd, ushort tag) => GetDoubles(ifd, tag) is { Length: > 0 } v ? v[0] : null;
public double[]? GetDoubles(Ifd ifd, ushort tag) => ifd.Entries.TryGetValue(tag, out var e) ? GetDoubles(e) : null;
/// <summary>Numeric values of any numeric type as doubles (rationals divided; 0-denominator → NaN skipped as 0).</summary>
public double[]? GetDoubles(IfdEntry e)
{
var raw = ReadBytes(e);
if (raw is null) return null;
var size = TiffTypeInfo.Size(e.Type);
var result = new double[e.Count];
for (var i = 0; i < e.Count; i++)
{
var s = raw.AsSpan(i * size);
result[i] = e.Type switch
{
TiffType.Rational => U32(s[4..]) == 0 ? 0 : (double)U32(s) / U32(s[4..]),
TiffType.SRational => (int)U32(s[4..]) == 0 ? 0 : (double)(int)U32(s) / (int)U32(s[4..]),
TiffType.Float => BitConverter.Int32BitsToSingle((int)U32(s)),
TiffType.Double => BitConverter.Int64BitsToDouble((long)U64(s)),
TiffType.Byte or TiffType.Undefined => s[0],
TiffType.SByte => (sbyte)s[0],
TiffType.Short => U16(s),
TiffType.SShort => (short)U16(s),
TiffType.Long or TiffType.Ifd => U32(s),
TiffType.SLong => (int)U32(s),
_ => 0,
};
}
return result;
}
/// <summary>ASCII/UTF-8 string value with trailing NULs and spaces trimmed; null when empty.</summary>
public string? GetString(Ifd ifd, ushort tag)
{
if (!ifd.Entries.TryGetValue(tag, out var e)) return null;
var raw = ReadBytes(e, 1 << 20);
if (raw is null) return null;
var end = Array.IndexOf(raw, (byte)0);
var s = Encoding.UTF8.GetString(raw, 0, end < 0 ? raw.Length : end).Trim();
return s.Length == 0 ? null : s;
}
/// <summary>Reads arbitrary bytes at a base-relative offset (bounds-checked).</summary>
public byte[]? ReadRelative(long offset, int length)
{
if (length <= 0 || length > MaxValueBytes) return null;
var pos = Base + offset;
if (pos < 0 || pos + length > _stream.Length) return null;
var buffer = new byte[length];
return ReadAt(pos, buffer) ? buffer : null;
}
public ushort U16(ReadOnlySpan<byte> s) => LittleEndian ? BinaryPrimitives.ReadUInt16LittleEndian(s) : BinaryPrimitives.ReadUInt16BigEndian(s);
public uint U32(ReadOnlySpan<byte> s) => LittleEndian ? BinaryPrimitives.ReadUInt32LittleEndian(s) : BinaryPrimitives.ReadUInt32BigEndian(s);
public ulong U64(ReadOnlySpan<byte> s) => LittleEndian ? BinaryPrimitives.ReadUInt64LittleEndian(s) : BinaryPrimitives.ReadUInt64BigEndian(s);
public void Warn(string message)
{
if (_warnings.Count < 32) _warnings.Add(message);
}
private bool ReadAt(long position, Span<byte> buffer)
{
try
{
_stream.Position = position;
return _stream.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) == buffer.Length;
}
catch (IOException ex)
{
Warn("I/O error: " + ex.Message);
return false;
}
}
}
+131
View File
@@ -0,0 +1,131 @@
namespace Chronos.Core.Metadata.Tiff;
/// <summary>Tag numbers used across TIFF, Exif, GPS and DNG.</summary>
public static class TiffTags
{
// Baseline TIFF
public const ushort NewSubfileType = 0x00FE;
public const ushort ImageWidth = 0x0100;
public const ushort ImageLength = 0x0101;
public const ushort BitsPerSample = 0x0102;
public const ushort Compression = 0x0103;
public const ushort PhotometricInterpretation = 0x0106;
public const ushort ImageDescription = 0x010E;
public const ushort Make = 0x010F;
public const ushort Model = 0x0110;
public const ushort StripOffsets = 0x0111;
public const ushort Orientation = 0x0112;
public const ushort SamplesPerPixel = 0x0115;
public const ushort RowsPerStrip = 0x0116;
public const ushort StripByteCounts = 0x0117;
public const ushort XResolution = 0x011A;
public const ushort YResolution = 0x011B;
public const ushort PlanarConfiguration = 0x011C;
public const ushort ResolutionUnit = 0x0128;
public const ushort Software = 0x0131;
public const ushort DateTime = 0x0132;
public const ushort Artist = 0x013B;
public const ushort Predictor = 0x013D;
public const ushort TileWidth = 0x0142;
public const ushort TileLength = 0x0143;
public const ushort TileOffsets = 0x0144;
public const ushort TileByteCounts = 0x0145;
public const ushort SubIfds = 0x014A;
public const ushort ExtraSamples = 0x0152;
public const ushort SampleFormat = 0x0153;
public const ushort JpegTables = 0x015B;
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;
public const ushort ExifIfd = 0x8769;
public const ushort GpsIfd = 0x8825;
public const ushort InteropIfd = 0xA005;
// Exif
public const ushort ExposureTime = 0x829A;
public const ushort FNumber = 0x829D;
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;
public const ushort OffsetTime = 0x9010;
public const ushort OffsetTimeOriginal = 0x9011;
public const ushort OffsetTimeDigitized = 0x9012;
public const ushort ShutterSpeedValue = 0x9201;
public const ushort ApertureValue = 0x9202;
public const ushort ExposureBiasValue = 0x9204;
public const ushort MeteringMode = 0x9207;
public const ushort Flash = 0x9209;
public const ushort FocalLength = 0x920A;
public const ushort MakerNote = 0x927C;
public const ushort SubSecTime = 0x9290;
public const ushort SubSecTimeOriginal = 0x9291;
public const ushort SubSecTimeDigitized = 0x9292;
public const ushort ColorSpace = 0xA001;
public const ushort PixelXDimension = 0xA002;
public const ushort PixelYDimension = 0xA003;
public const ushort WhiteBalance = 0xA403;
public const ushort FocalLengthIn35mmFilm = 0xA405;
public const ushort BodySerialNumber = 0xA431;
public const ushort LensSpecification = 0xA432;
public const ushort LensMake = 0xA433;
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;
public const ushort GpsLongitude = 0x0004;
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
public const ushort CfaRepeatPatternDim = 0x828D;
public const ushort CfaPattern = 0x828E;
public const ushort DngVersion = 0xC612;
public const ushort DngBackwardVersion = 0xC613;
public const ushort UniqueCameraModel = 0xC614;
public const ushort CfaPlaneColor = 0xC616;
public const ushort CfaLayout = 0xC617;
public const ushort LinearizationTable = 0xC618;
public const ushort BlackLevelRepeatDim = 0xC619;
public const ushort BlackLevel = 0xC61A;
public const ushort BlackLevelDeltaH = 0xC61B;
public const ushort BlackLevelDeltaV = 0xC61C;
public const ushort WhiteLevel = 0xC61D;
public const ushort DefaultScale = 0xC61E;
public const ushort DefaultCropOrigin = 0xC61F;
public const ushort DefaultCropSize = 0xC620;
public const ushort ColorMatrix1 = 0xC621;
public const ushort ColorMatrix2 = 0xC622;
public const ushort CameraCalibration1 = 0xC623;
public const ushort CameraCalibration2 = 0xC624;
public const ushort AnalogBalance = 0xC627;
public const ushort AsShotNeutral = 0xC628;
public const ushort AsShotWhiteXy = 0xC629;
public const ushort BaselineExposure = 0xC62A;
public const ushort CameraSerialNumber = 0xC62F;
public const ushort LensInfo = 0xC630;
public const ushort ActiveArea = 0xC68D;
public const ushort CalibrationIlluminant1 = 0xC65A;
public const ushort CalibrationIlluminant2 = 0xC65B;
public const ushort OpcodeList1 = 0xC740;
public const ushort OpcodeList2 = 0xC741;
public const ushort OpcodeList3 = 0xC74E;
public const ushort ForwardMatrix1 = 0xC714;
public const ushort ForwardMatrix2 = 0xC715;
public const ushort NewRawImageDigest = 0xC7A7;
}
@@ -0,0 +1,32 @@
namespace Chronos.Core.Metadata.Tiff;
/// <summary>TIFF 6.0 field types (plus IFD = 13).</summary>
public enum TiffType : ushort
{
Byte = 1,
Ascii = 2,
Short = 3,
Long = 4,
Rational = 5,
SByte = 6,
Undefined = 7,
SShort = 8,
SLong = 9,
SRational = 10,
Float = 11,
Double = 12,
Ifd = 13,
}
public static class TiffTypeInfo
{
/// <summary>Size in bytes of one value; 0 for unknown types.</summary>
public static int Size(TiffType type) => type switch
{
TiffType.Byte or TiffType.Ascii or TiffType.SByte or TiffType.Undefined => 1,
TiffType.Short or TiffType.SShort => 2,
TiffType.Long or TiffType.SLong or TiffType.Float or TiffType.Ifd => 4,
TiffType.Rational or TiffType.SRational or TiffType.Double => 8,
_ => 0,
};
}