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
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:
1 parent
c99842cc86
commit
f2b58522b9
1801 files changed
+11804
-10676
No files matched your search
@@ -0,0 +1,127 @@
|
||||
using System.Buffers.Binary;
|
||||
|
||||
namespace Chronos.Core.Metadata.Bmff;
|
||||
|
||||
/// <summary>One ISO-BMFF box header: four-character type, absolute start, total size and header size
|
||||
/// (8, 16 with a 64-bit size, plus 16 for a <c>uuid</c> user type).</summary>
|
||||
public readonly record struct BmffBox(uint Type, long Start, long Size, int HeaderSize, Guid UserType)
|
||||
{
|
||||
public long End => Start + Size;
|
||||
public long PayloadStart => Start + HeaderSize;
|
||||
public long PayloadLength => Size - HeaderSize;
|
||||
|
||||
public bool Is(string fourCC) => Type == FourCC.From(fourCC);
|
||||
|
||||
public override string ToString() => $"{FourCC.Format(Type)} @{Start} ({Size} bytes)";
|
||||
}
|
||||
|
||||
/// <summary>Four-character codes as big-endian 32-bit integers.</summary>
|
||||
public static class FourCC
|
||||
{
|
||||
public static uint From(ReadOnlySpan<char> code)
|
||||
{
|
||||
if (code.Length != 4) throw new ArgumentException("A four-character code has exactly four characters.", nameof(code));
|
||||
return (uint)(byte)code[0] << 24 | (uint)(byte)code[1] << 16 | (uint)(byte)code[2] << 8 | (byte)code[3];
|
||||
}
|
||||
|
||||
public static string Format(uint code) =>
|
||||
string.Create(4, code, static (span, c) =>
|
||||
{
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
var b = (char)((c >> (24 - 8 * i)) & 0xFF);
|
||||
span[i] = b is >= ' ' and <= '~' ? b : '?';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fuzz-safe ISO-BMFF box walker over a seekable stream: 32-bit, 64-bit (<c>largesize</c>) and to-end (size 0) boxes,
|
||||
/// <c>uuid</c> user types, a cap on boxes per container and on descent depth. Only headers are read.
|
||||
/// </summary>
|
||||
public static class BmffReader
|
||||
{
|
||||
public const int MaxBoxesPerContainer = 4096;
|
||||
public const int MaxDepth = 16;
|
||||
|
||||
private static readonly uint Uuid = FourCC.From("uuid");
|
||||
|
||||
/// <summary>Box headers inside [<paramref name="start"/>, <paramref name="end"/>). Stops at the first malformed header;
|
||||
/// a box running past <paramref name="end"/> is clamped so truncated files still expose their leading boxes.</summary>
|
||||
public static IReadOnlyList<BmffBox> ReadChildren(Stream stream, long start, long end, ICollection<string>? warnings = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
var boxes = new List<BmffBox>();
|
||||
end = Math.Min(end, stream.Length);
|
||||
Span<byte> h = stackalloc byte[32];
|
||||
var pos = Math.Max(0, start);
|
||||
while (pos <= end - 8)
|
||||
{
|
||||
if (boxes.Count == MaxBoxesPerContainer)
|
||||
{
|
||||
warnings?.Add($"More than {MaxBoxesPerContainer} boxes at {start}; rest ignored");
|
||||
break;
|
||||
}
|
||||
var n = stream.ReadUpTo(pos, h[..(int)Math.Min(h.Length, end - pos)]);
|
||||
if (n < 8) break;
|
||||
long size = BinaryPrimitives.ReadUInt32BigEndian(h);
|
||||
var type = BinaryPrimitives.ReadUInt32BigEndian(h[4..]);
|
||||
var header = 8;
|
||||
if (size == 1)
|
||||
{
|
||||
if (n < 16) break;
|
||||
size = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(h[8..]), long.MaxValue);
|
||||
header = 16;
|
||||
}
|
||||
else if (size == 0)
|
||||
{
|
||||
size = end - pos;
|
||||
}
|
||||
var userType = Guid.Empty;
|
||||
if (type == Uuid)
|
||||
{
|
||||
if (n < header + 16) break;
|
||||
userType = new Guid(h.Slice(header, 16), bigEndian: true);
|
||||
header += 16;
|
||||
}
|
||||
if (size < header)
|
||||
{
|
||||
warnings?.Add($"Malformed box header at {pos}");
|
||||
break;
|
||||
}
|
||||
if (size > end - pos)
|
||||
{
|
||||
warnings?.Add($"Box '{FourCC.Format(type)}' at {pos} runs past its container");
|
||||
size = end - pos;
|
||||
}
|
||||
boxes.Add(new BmffBox(type, pos, size, header, userType));
|
||||
pos += size;
|
||||
}
|
||||
return boxes;
|
||||
}
|
||||
|
||||
/// <summary>First box of <paramref name="type"/> in <paramref name="boxes"/>, or null.</summary>
|
||||
public static BmffBox? Find(IReadOnlyList<BmffBox> boxes, string type)
|
||||
{
|
||||
var code = FourCC.From(type);
|
||||
foreach (var b in boxes)
|
||||
{
|
||||
if (b.Type == code) return b;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Follows a path of plain (non-full) container boxes from <paramref name="parent"/>'s payload,
|
||||
/// taking the first match at each level.</summary>
|
||||
public static BmffBox? FindPath(Stream stream, BmffBox parent, params ReadOnlySpan<string> path)
|
||||
{
|
||||
if (path.Length > MaxDepth) throw new ArgumentException($"Paths are limited to {MaxDepth} levels.", nameof(path));
|
||||
BmffBox? current = parent;
|
||||
foreach (var type in path)
|
||||
{
|
||||
if (current is not { } box) return null;
|
||||
current = Find(ReadChildren(stream, box.PayloadStart, box.End), type);
|
||||
}
|
||||
return current;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
using System.Buffers.Binary;
|
||||
using Chronos.Core.Metadata.Jpeg;
|
||||
using Chronos.Core.Metadata.MakerNotes;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
using Chronos.Core.Metadata.Xmp;
|
||||
|
||||
namespace Chronos.Core.Metadata.Bmff;
|
||||
|
||||
/// <summary>
|
||||
/// Canon CR3 (ISO-BMFF, brand <c>crx </c>): the Canon <c>uuid</c> box in <c>moov</c> holds CMT1 (IFD0), CMT2 (Exif IFD),
|
||||
/// CMT3 (Canon MakerNote), CMT4 (GPS IFD) as little TIFF files plus the THMB thumbnail; a top-level <c>uuid</c> holds the
|
||||
/// PRVW preview and another the XMP packet. Track 1's first sample is the full-size JPEG; the main size and bit depth come
|
||||
/// from the largest raw track (<c>CRAW</c> sample entry with a <c>CMP1</c> header), else from CMT1.
|
||||
/// </summary>
|
||||
internal static class Cr3Parser
|
||||
{
|
||||
private static readonly Guid CanonUuid = new("85c0b687-820f-11e0-8111-f4ce462b6a48");
|
||||
private static readonly Guid PreviewUuid = new("eaf42b5e-1c98-4b88-b9fb-b7dc406e4d16");
|
||||
private static readonly Guid XmpUuid = new("be7acfcb-97a9-42e8-9c71-999491e3afac");
|
||||
|
||||
/// <summary>Offset of the child boxes inside a CRAW visual sample entry (8-byte header + 78 bytes of fields).</summary>
|
||||
private const int CrawChildrenOffset = 86;
|
||||
|
||||
/// <summary>The JPEG of THMB and PRVW starts within this many bytes of the box payload.</summary>
|
||||
private const int JpegSearchBytes = 32;
|
||||
|
||||
public static void Parse(MetadataBuilder m)
|
||||
{
|
||||
var s = m.Stream;
|
||||
var warnings = new List<string>();
|
||||
var top = BmffReader.ReadChildren(s, 0, m.Length, warnings);
|
||||
var trackIndex = 0;
|
||||
(int Width, int Height, int Bits) raw = default;
|
||||
foreach (var box in top)
|
||||
{
|
||||
m.ThrowIfCancelled();
|
||||
if (box.Is("moov"))
|
||||
{
|
||||
foreach (var child in BmffReader.ReadChildren(s, box.PayloadStart, box.End, warnings))
|
||||
{
|
||||
m.ThrowIfCancelled();
|
||||
if (child.Is("uuid") && child.UserType == CanonUuid) ReadCanonBox(m, child, warnings);
|
||||
else if (child.Is("trak")) ReadTrack(m, child, trackIndex++ == 0, ref raw);
|
||||
}
|
||||
}
|
||||
else if (box.Is("uuid") && box.UserType == PreviewUuid)
|
||||
{
|
||||
ReadPreviewBox(m, box);
|
||||
}
|
||||
else if (box.Is("uuid") && box.UserType == XmpUuid)
|
||||
{
|
||||
m.AddXmp(s.ReadAt(box.PayloadStart, box.PayloadLength, XmpParser.MaxPacketBytes));
|
||||
}
|
||||
}
|
||||
m.AddWarnings(warnings);
|
||||
if (raw.Width > 0) m.SetContainerSize(raw.Width, raw.Height, raw.Bits > 0 ? raw.Bits : null);
|
||||
}
|
||||
|
||||
private static void ReadCanonBox(MetadataBuilder m, BmffBox canon, List<string> warnings)
|
||||
{
|
||||
foreach (var box in BmffReader.ReadChildren(m.Stream, canon.PayloadStart, canon.End, warnings))
|
||||
{
|
||||
if (box.Is("THMB"))
|
||||
{
|
||||
AddJpeg(m, box);
|
||||
continue;
|
||||
}
|
||||
if (!(box.Is("CMT1") || box.Is("CMT2") || box.Is("CMT3") || box.Is("CMT4"))) continue;
|
||||
var r = TiffReader.Open(m.Stream, box.PayloadStart);
|
||||
if (r?.ReadIfd(r.FirstIfdOffset) is not { } ifd)
|
||||
{
|
||||
m.Warn($"CR3 {FourCC.Format(box.Type)} is not a TIFF block");
|
||||
continue;
|
||||
}
|
||||
if (box.Is("CMT1"))
|
||||
{
|
||||
ExifParser.ReadIfd0(r, ifd, m);
|
||||
m.AddRaster(IfdValue.Int(r, ifd, TiffTags.ImageWidth) ?? 0, IfdValue.Int(r, ifd, TiffTags.ImageLength) ?? 0, null, true);
|
||||
}
|
||||
else if (box.Is("CMT2"))
|
||||
{
|
||||
ExifParser.ReadExif(r, ifd, m);
|
||||
}
|
||||
else if (box.Is("CMT3"))
|
||||
{
|
||||
CanonMakerNote.Parse(r, ifd, m);
|
||||
}
|
||||
else
|
||||
{
|
||||
ExifParser.ReadGps(r, ifd, m);
|
||||
}
|
||||
m.AddWarnings(r.Warnings);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Track 1's first sample is the full-size JPEG; any track whose CRAW entry has a CMP1 header is raw data.</summary>
|
||||
private static void ReadTrack(MetadataBuilder m, BmffBox trak, bool first, ref (int Width, int Height, int Bits) raw)
|
||||
{
|
||||
var s = m.Stream;
|
||||
if (BmffReader.FindPath(s, trak, "mdia", "minf", "stbl") is not { } stbl) return;
|
||||
var tables = BmffReader.ReadChildren(s, stbl.PayloadStart, stbl.End);
|
||||
if (BmffReader.Find(tables, "stsd") is { } stsd && FirstSampleEntry(s, stsd) is { } entry && entry.Is("CRAW")
|
||||
&& BmffReader.Find(BmffReader.ReadChildren(s, entry.Start + CrawChildrenOffset, entry.End), "CMP1") is { } cmp1)
|
||||
{
|
||||
// CMP1 (big-endian): +8 width, +12 height, +24 bits per sample.
|
||||
Span<byte> h = stackalloc byte[25];
|
||||
if (s.TryReadAt(cmp1.PayloadStart, h))
|
||||
{
|
||||
var width = BinaryPrimitives.ReadInt32BigEndian(h[8..]);
|
||||
var height = BinaryPrimitives.ReadInt32BigEndian(h[12..]);
|
||||
if (width > 0 && height > 0 && (long)width * height > (long)raw.Width * raw.Height) raw = (width, height, h[24]);
|
||||
}
|
||||
}
|
||||
if (first && FirstSample(s, tables) is { } sample) JpegParser.AddPreview(m, sample.Offset, sample.Length, PreviewKind.FullSize);
|
||||
}
|
||||
|
||||
private static BmffBox? FirstSampleEntry(Stream s, BmffBox stsd) =>
|
||||
BmffReader.ReadChildren(s, stsd.PayloadStart + 8, stsd.End) is [var entry, ..] ? entry : null;
|
||||
|
||||
/// <summary>Offset (stco/co64) and size (stsz) of a track's first sample.</summary>
|
||||
private static (long Offset, long Length)? FirstSample(Stream s, IReadOnlyList<BmffBox> tables)
|
||||
{
|
||||
Span<byte> b = stackalloc byte[16];
|
||||
if (BmffReader.Find(tables, "stsz") is not { } stsz || !s.TryReadAt(stsz.PayloadStart, b)) return null;
|
||||
long size = BinaryPrimitives.ReadUInt32BigEndian(b[4..]);
|
||||
if (size == 0) size = BinaryPrimitives.ReadUInt32BigEndian(b[8..]) > 0 ? BinaryPrimitives.ReadUInt32BigEndian(b[12..]) : 0;
|
||||
long offset;
|
||||
if (BmffReader.Find(tables, "co64") is { } co64 && s.TryReadAt(co64.PayloadStart, b))
|
||||
offset = BinaryPrimitives.ReadUInt32BigEndian(b[4..]) > 0 ? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(b[8..]), long.MaxValue) : 0;
|
||||
else if (BmffReader.Find(tables, "stco") is { } stco && s.TryReadAt(stco.PayloadStart, b[..12]))
|
||||
offset = BinaryPrimitives.ReadUInt32BigEndian(b[4..]) > 0 ? BinaryPrimitives.ReadUInt32BigEndian(b[8..]) : 0;
|
||||
else
|
||||
return null;
|
||||
return offset > 0 && size > 0 ? (offset, size) : null;
|
||||
}
|
||||
|
||||
/// <summary>The preview uuid holds 8 bytes of header fields, then a PRVW box.</summary>
|
||||
private static void ReadPreviewBox(MetadataBuilder m, BmffBox uuid)
|
||||
{
|
||||
if (BmffReader.Find(BmffReader.ReadChildren(m.Stream, uuid.PayloadStart + 8, uuid.End), "PRVW") is { } prvw) AddJpeg(m, prvw);
|
||||
else m.Warn("CR3 PRVW box not found");
|
||||
}
|
||||
|
||||
/// <summary>THMB/PRVW: a few header fields (version, size, dimensions) followed by the JPEG to the end of the box.</summary>
|
||||
private static void AddJpeg(MetadataBuilder m, BmffBox box)
|
||||
{
|
||||
Span<byte> head = stackalloc byte[JpegSearchBytes];
|
||||
var n = m.Stream.ReadUpTo(box.PayloadStart, head[..(int)Math.Min(head.Length, box.PayloadLength)]);
|
||||
var at = head[..n].IndexOf([(byte)0xFF, (byte)0xD8, (byte)0xFF]);
|
||||
if (at < 0)
|
||||
{
|
||||
m.Warn($"CR3 {FourCC.Format(box.Type)} holds no JPEG");
|
||||
return;
|
||||
}
|
||||
var start = box.PayloadStart + at;
|
||||
JpegParser.AddPreview(m, start, box.End - start);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
using System.Buffers.Binary;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
using Chronos.Core.Metadata.Xmp;
|
||||
|
||||
namespace Chronos.Core.Metadata.Bmff;
|
||||
|
||||
/// <summary>
|
||||
/// HEIF / HEIC / AVIF: <c>meta</c> → <c>hdlr</c>, <c>pitm</c>, <c>iinf</c>/<c>infe</c> (v2/v3), <c>iloc</c> (v0–v2),
|
||||
/// <c>iprp</c>/<c>ipco</c>/<c>ipma</c>. Main size from the primary item's <c>ispe</c>, bit depth from <c>pixi</c>,
|
||||
/// Exif from the <c>Exif</c> item and XMP from the <c>application/rdf+xml</c> mime item.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Orientation rule: when the primary item carries <c>irot</c> and/or <c>imir</c>, their composition (in association
|
||||
/// order) defines <see cref="FrameMetadata.Orientation"/> and the Exif orientation is ignored — HEIF decoders apply those
|
||||
/// transforms themselves (ISO/IEC 23008-12), so honouring Exif as well would rotate twice. Without them, Exif applies.
|
||||
/// <c>imir</c> axis 0 mirrors top↔bottom and axis 1 left↔right (23008-12 2nd edition, as libheif).
|
||||
/// </remarks>
|
||||
internal static class HeifParser
|
||||
{
|
||||
private const int MaxPropertyBytes = 64;
|
||||
private const int MaxTableBytes = 1024 * 1024;
|
||||
private const int MaxInfeBytes = 4096;
|
||||
private const int MaxExtentsPerItem = 1024;
|
||||
private static readonly uint Exif = FourCC.From("Exif");
|
||||
private static readonly uint Mime = FourCC.From("mime");
|
||||
|
||||
// Exif orientations 1–8 as integer matrices (a, b, c, d) mapping stored (x, y) to displayed (ax + by, cx + dy), y down.
|
||||
private static readonly (int A, int B, int C, int D)[] Orientations =
|
||||
[
|
||||
(1, 0, 0, 1), (-1, 0, 0, 1), (-1, 0, 0, -1), (1, 0, 0, -1),
|
||||
(0, 1, 1, 0), (0, -1, 1, 0), (0, -1, -1, 0), (0, 1, -1, 0),
|
||||
];
|
||||
|
||||
public static void Parse(MetadataBuilder m)
|
||||
{
|
||||
var warnings = new List<string>();
|
||||
var meta = BmffReader.Find(BmffReader.ReadChildren(m.Stream, 0, m.Length, warnings), "meta");
|
||||
m.AddWarnings(warnings);
|
||||
if (meta is { } box) ParseMeta(m, box);
|
||||
else m.Warn("HEIF meta box not found");
|
||||
}
|
||||
|
||||
private static void ParseMeta(MetadataBuilder m, BmffBox meta)
|
||||
{
|
||||
var s = m.Stream;
|
||||
var warnings = new List<string>();
|
||||
var children = BmffReader.ReadChildren(s, meta.PayloadStart + 4, meta.End, warnings);
|
||||
var items = new Dictionary<uint, Item>();
|
||||
uint? primary = null;
|
||||
BmffBox? iprp = null;
|
||||
long idat = -1;
|
||||
foreach (var child in children)
|
||||
{
|
||||
m.ThrowIfCancelled();
|
||||
if (child.Is("hdlr")) CheckHandler(m, child);
|
||||
else if (child.Is("pitm")) primary = ReadPrimary(s, child);
|
||||
else if (child.Is("iinf")) ReadItemInfo(m, child, items, warnings);
|
||||
else if (child.Is("iloc")) ReadLocations(m, child, items);
|
||||
else if (child.Is("iprp")) iprp = child;
|
||||
else if (child.Is("idat")) idat = child.PayloadStart;
|
||||
}
|
||||
m.AddWarnings(warnings);
|
||||
if (primary is { } id && iprp is { } properties) ReadPrimaryProperties(m, properties, id);
|
||||
else m.Warn("HEIF primary item or properties missing");
|
||||
|
||||
foreach (var item in items.Values)
|
||||
{
|
||||
if (item.ConstructionMethod == 1 && idat < 0) continue;
|
||||
var origin = item.ConstructionMethod == 1 ? idat : 0;
|
||||
if (item.Type == Exif) ReadExifItem(m, item, origin);
|
||||
else if (item.Type == Mime && item.ContentType == "application/rdf+xml") ReadXmpItem(m, item, origin);
|
||||
}
|
||||
}
|
||||
|
||||
private static void CheckHandler(MetadataBuilder m, BmffBox hdlr)
|
||||
{
|
||||
Span<byte> b = stackalloc byte[12];
|
||||
if (!m.Stream.TryReadAt(hdlr.PayloadStart, b) || !b[8..].SequenceEqual("pict"u8)) m.Warn("HEIF handler is not 'pict'");
|
||||
}
|
||||
|
||||
private static uint? ReadPrimary(Stream s, BmffBox pitm)
|
||||
{
|
||||
Span<byte> b = stackalloc byte[8];
|
||||
var n = s.ReadUpTo(pitm.PayloadStart, b[..(int)Math.Min(b.Length, pitm.PayloadLength)]);
|
||||
if (n < 6) return null;
|
||||
return b[0] == 0 ? BinaryPrimitives.ReadUInt16BigEndian(b[4..]) : n >= 8 ? BinaryPrimitives.ReadUInt32BigEndian(b[4..]) : null;
|
||||
}
|
||||
|
||||
/// <summary>iinf → infe v2/v3: item id, type and (for mime items) content type. Earlier infe versions carry no type.</summary>
|
||||
private static void ReadItemInfo(MetadataBuilder m, BmffBox iinf, Dictionary<uint, Item> items, List<string> warnings)
|
||||
{
|
||||
Span<byte> head = stackalloc byte[1];
|
||||
if (!m.Stream.TryReadAt(iinf.PayloadStart, head)) return;
|
||||
var first = iinf.PayloadStart + (head[0] == 0 ? 6 : 8);
|
||||
foreach (var infe in BmffReader.ReadChildren(m.Stream, first, iinf.End, warnings))
|
||||
{
|
||||
m.ThrowIfCancelled();
|
||||
if (!infe.Is("infe") || m.Stream.ReadAt(infe.PayloadStart, Math.Min(infe.PayloadLength, MaxInfeBytes), MaxInfeBytes) is not { } data) continue;
|
||||
var r = new SpanReader(data);
|
||||
var version = r.U8();
|
||||
r.Skip(3);
|
||||
if (version < 2) continue;
|
||||
var id = version == 2 ? r.U16() : r.U32();
|
||||
r.Skip(2);
|
||||
var type = r.U32();
|
||||
if (!r.Ok) continue;
|
||||
r.CString();
|
||||
var item = Get(items, id);
|
||||
item.Type = type;
|
||||
if (type == Mime && r.Remaining > 0) item.ContentType = r.CString();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>iloc v0–v2: offset/length/base-offset/index field sizes, construction methods 0 (file) and 1 (idat),
|
||||
/// any number of extents.</summary>
|
||||
private static void ReadLocations(MetadataBuilder m, BmffBox iloc, Dictionary<uint, Item> items)
|
||||
{
|
||||
if (m.Stream.ReadAt(iloc.PayloadStart, iloc.PayloadLength, MaxTableBytes) is not { } data)
|
||||
{
|
||||
m.Warn("HEIF iloc unreadable");
|
||||
return;
|
||||
}
|
||||
var r = new SpanReader(data);
|
||||
var version = r.U8();
|
||||
r.Skip(3);
|
||||
var sizes = r.U8();
|
||||
var sizes2 = r.U8();
|
||||
int offsetSize = sizes >> 4, lengthSize = sizes & 0xF, baseOffsetSize = sizes2 >> 4;
|
||||
var indexSize = version is 1 or 2 ? sizes2 & 0xF : 0;
|
||||
if (version > 2)
|
||||
{
|
||||
m.Warn($"HEIF iloc version {version} unsupported");
|
||||
return;
|
||||
}
|
||||
var count = version < 2 ? r.U16() : r.U32();
|
||||
for (uint i = 0; i < count && r.Ok; i++)
|
||||
{
|
||||
var id = version < 2 ? r.U16() : r.U32();
|
||||
var method = version is 1 or 2 ? r.U16() & 0xF : 0;
|
||||
r.Skip(2);
|
||||
var baseOffset = r.Sized(baseOffsetSize);
|
||||
var extents = r.U16();
|
||||
var item = Get(items, id);
|
||||
item.ConstructionMethod = method;
|
||||
for (var e = 0; e < extents && r.Ok; e++)
|
||||
{
|
||||
r.Sized(indexSize);
|
||||
var offset = baseOffset + r.Sized(offsetSize);
|
||||
var length = r.Sized(lengthSize);
|
||||
if (r.Ok && e < MaxExtentsPerItem && offset <= long.MaxValue && length <= long.MaxValue)
|
||||
item.Extents.Add(((long)offset, (long)length));
|
||||
}
|
||||
}
|
||||
if (!r.Ok) m.Warn("HEIF iloc truncated or malformed");
|
||||
}
|
||||
|
||||
/// <summary>ispe, pixi, irot and imir associated with the primary item through ipma (1-based ipco indices).</summary>
|
||||
private static void ReadPrimaryProperties(MetadataBuilder m, BmffBox iprp, uint primary)
|
||||
{
|
||||
var s = m.Stream;
|
||||
var children = BmffReader.ReadChildren(s, iprp.PayloadStart, iprp.End);
|
||||
if (BmffReader.Find(children, "ipco") is not { } ipco || BmffReader.Find(children, "ipma") is not { } ipma) return;
|
||||
var properties = BmffReader.ReadChildren(s, ipco.PayloadStart, ipco.End);
|
||||
var transform = Orientations[0];
|
||||
var transformed = false;
|
||||
foreach (var index in Associations(m, ipma, primary))
|
||||
{
|
||||
if (index < 1 || index > properties.Count) continue;
|
||||
var p = properties[index - 1];
|
||||
var data = s.ReadAt(p.PayloadStart, Math.Min(p.PayloadLength, MaxPropertyBytes), MaxPropertyBytes);
|
||||
if (data is null) continue;
|
||||
if (p.Is("ispe") && data.Length >= 12)
|
||||
{
|
||||
var width = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(4));
|
||||
var height = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(8));
|
||||
if (width <= int.MaxValue && height <= int.MaxValue) m.SetContainerSize((int)width, (int)height);
|
||||
}
|
||||
else if (p.Is("pixi") && data.Length >= 6 && data[4] > 0)
|
||||
{
|
||||
m.CodedBitsPerSample ??= data[5];
|
||||
}
|
||||
else if (p.Is("irot") && data.Length >= 1)
|
||||
{
|
||||
// Anticlockwise quarter turns: 1 → orientation 8, 2 → 3, 3 → 6.
|
||||
transform = Multiply(Orientations[(data[0] & 3) switch { 1 => 7, 2 => 2, 3 => 5, _ => 0 }], transform);
|
||||
transformed = true;
|
||||
}
|
||||
else if (p.Is("imir") && data.Length >= 1)
|
||||
{
|
||||
transform = Multiply(Orientations[(data[0] & 1) == 0 ? 3 : 1], transform);
|
||||
transformed = true;
|
||||
}
|
||||
}
|
||||
if (transformed) m.ContainerOrientation = Array.IndexOf(Orientations, transform) + 1;
|
||||
}
|
||||
|
||||
private static List<int> Associations(MetadataBuilder m, BmffBox ipma, uint primary)
|
||||
{
|
||||
var result = new List<int>();
|
||||
if (m.Stream.ReadAt(ipma.PayloadStart, ipma.PayloadLength, MaxTableBytes) is not { } data) return result;
|
||||
var r = new SpanReader(data);
|
||||
var version = r.U8();
|
||||
r.Skip(2);
|
||||
var wideIndex = (r.U8() & 1) != 0;
|
||||
var count = r.U32();
|
||||
for (uint i = 0; i < count && r.Ok; i++)
|
||||
{
|
||||
var id = version < 1 ? r.U16() : r.U32();
|
||||
var associations = r.U8();
|
||||
for (var a = 0; a < associations && r.Ok; a++)
|
||||
{
|
||||
var index = wideIndex ? r.U16() & 0x7FFF : r.U8() & 0x7F;
|
||||
if (id == primary && r.Ok) result.Add(index);
|
||||
}
|
||||
}
|
||||
if (!r.Ok) m.Warn("HEIF ipma truncated");
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void ReadExifItem(MetadataBuilder m, Item item, long origin)
|
||||
{
|
||||
if (item.Extents.Count == 0) return;
|
||||
var (start, length) = item.Extents[0];
|
||||
for (var i = 1; i < item.Extents.Count; i++)
|
||||
{
|
||||
if (item.Extents[i].Offset != start + length)
|
||||
{
|
||||
m.Warn("Fragmented HEIF Exif item not supported");
|
||||
return;
|
||||
}
|
||||
length += item.Extents[i].Length;
|
||||
}
|
||||
start += origin;
|
||||
if (length == 0) length = m.Length - start;
|
||||
if (start < 0 || length <= 0 || start > m.Length - length)
|
||||
{
|
||||
m.Warn("HEIF Exif item outside the file");
|
||||
return;
|
||||
}
|
||||
ExifParser.ParseOffsetPrefixed(m, start, length);
|
||||
}
|
||||
|
||||
private static void ReadXmpItem(MetadataBuilder m, Item item, long origin)
|
||||
{
|
||||
long total = 0;
|
||||
foreach (var (_, length) in item.Extents) total += length;
|
||||
if (total <= 0 || total > XmpParser.MaxPacketBytes)
|
||||
{
|
||||
m.Warn("HEIF XMP item empty or too large");
|
||||
return;
|
||||
}
|
||||
var packet = new byte[total];
|
||||
var at = 0;
|
||||
foreach (var (offset, length) in item.Extents)
|
||||
{
|
||||
if (!m.Stream.TryReadAt(origin + offset, packet.AsSpan(at, (int)length)))
|
||||
{
|
||||
m.Warn("HEIF XMP item outside the file");
|
||||
return;
|
||||
}
|
||||
at += (int)length;
|
||||
}
|
||||
m.AddXmp(packet);
|
||||
}
|
||||
|
||||
private static (int, int, int, int) Multiply((int A, int B, int C, int D) x, (int A, int B, int C, int D) y) =>
|
||||
(x.A * y.A + x.B * y.C, x.A * y.B + x.B * y.D, x.C * y.A + x.D * y.C, x.C * y.B + x.D * y.D);
|
||||
|
||||
private static Item Get(Dictionary<uint, Item> items, uint id)
|
||||
{
|
||||
if (!items.TryGetValue(id, out var item)) items[id] = item = new Item();
|
||||
return item;
|
||||
}
|
||||
|
||||
private sealed class Item
|
||||
{
|
||||
public uint Type { get; set; }
|
||||
public string? ContentType { get; set; }
|
||||
public int ConstructionMethod { get; set; }
|
||||
public List<(long Offset, long Length)> Extents { get; } = [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
|
||||
namespace Chronos.Core.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="MaxStringBytes"/> UTF-8 bytes are truncated.
|
||||
/// </summary>
|
||||
public static class ExifWriter
|
||||
{
|
||||
/// <summary>Longest string written, in UTF-8 bytes; keeps the APP1 segment far below its 64 KB limit.</summary>
|
||||
public const int MaxStringBytes = 2000;
|
||||
|
||||
private const int MaxShortIso = 65535;
|
||||
private const uint GpsDegreeDenominator = 10_000_000;
|
||||
|
||||
private static ReadOnlySpan<byte> ExifHeader => "Exif\0\0"u8;
|
||||
|
||||
/// <summary>A complete TIFF structure ("II*\0" header, IFD0, Exif IFD, optional GPS IFD).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A complete JPEG APP1 segment: FF E1, big-endian length, "Exif\0\0", then <see cref="BuildTiff"/>.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Coordinates as decimal degrees (1e-7° resolution) in the degrees rational, minutes and seconds zero.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Exact 1/n for exposure-style fractions, else a fixed denominator reduced by the GCD.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Collects entries of one IFD and serialises them sorted by tag, values over 4 bytes word-aligned after it.</summary>
|
||||
private sealed class IfdBuilder
|
||||
{
|
||||
private readonly SortedDictionary<ushort, (TiffType Type, uint Count, byte[] Data)> _entries = new();
|
||||
|
||||
/// <summary>Bytes taken by the IFD including its out-of-line values.</summary>
|
||||
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<byte> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Core.Metadata;
|
||||
|
||||
public enum PreviewKind
|
||||
{
|
||||
Thumbnail,
|
||||
Preview,
|
||||
FullSize,
|
||||
}
|
||||
|
||||
/// <summary>Resolution a camera recorded its RAW at (BRIEF §9 sRaw flags).</summary>
|
||||
public enum RawSize
|
||||
{
|
||||
/// <summary>Full sensor resolution.</summary>
|
||||
Full,
|
||||
|
||||
/// <summary>Canon mRAW (sRAW1), Nikon RAW M.</summary>
|
||||
Medium,
|
||||
|
||||
/// <summary>Canon sRAW (sRAW2), Nikon RAW S and sRAW.</summary>
|
||||
Small,
|
||||
}
|
||||
|
||||
/// <summary>An embedded JPEG inside a RAW/TIFF/HEIF/JPEG(MPF) container.</summary>
|
||||
public sealed record EmbeddedPreview(long Offset, long Length, int Width, int Height, PreviewKind Kind);
|
||||
|
||||
public sealed record GpsPosition(double Latitude, double Longitude, double? Altitude, DateTime? UtcTimestamp);
|
||||
|
||||
/// <summary>Everything Chronos reads from one photo's metadata (BRIEF §9). Never throws while parsing:
|
||||
/// malformed input yields partial data plus <see cref="Warnings"/>.</summary>
|
||||
public sealed record FrameMetadata
|
||||
{
|
||||
public ImageFileFormat Format { get; init; }
|
||||
public string? Make { get; init; }
|
||||
public string? Model { get; init; }
|
||||
public string? BodySerial { get; init; }
|
||||
public string? LensModel { get; init; }
|
||||
public string? Software { get; init; }
|
||||
public string? Artist { get; init; }
|
||||
public string? Copyright { get; init; }
|
||||
|
||||
/// <summary>Camera wall-clock time including sub-seconds (DateTimeKind.Unspecified).</summary>
|
||||
public DateTime? CapturedAt { get; init; }
|
||||
|
||||
public int? UtcOffsetMinutes { get; init; }
|
||||
public TimestampSource TimestampSource { get; init; }
|
||||
public double? ExposureTime { get; init; }
|
||||
public double? FNumber { get; init; }
|
||||
public int? Iso { get; init; }
|
||||
public double? FocalLength { get; init; }
|
||||
public double? FocalLength35 { get; init; }
|
||||
public double? ExposureBias { get; init; }
|
||||
public int? ExposureProgram { get; init; }
|
||||
public int? MeteringMode { get; init; }
|
||||
public int? WhiteBalanceMode { get; init; }
|
||||
public int? ColorTemperature { get; init; }
|
||||
public int? Flash { get; init; }
|
||||
|
||||
/// <summary>Exif orientation 1–8.</summary>
|
||||
public int Orientation { get; init; } = 1;
|
||||
|
||||
/// <summary>Dimensions of the main (largest) image as stored, before orientation.</summary>
|
||||
public int Width { get; init; }
|
||||
|
||||
public int Height { get; init; }
|
||||
public int? BitsPerSample { get; init; }
|
||||
public GpsPosition? Gps { get; init; }
|
||||
public int? Rating { get; init; }
|
||||
public string? Label { get; init; }
|
||||
public long? ShutterCount { get; init; }
|
||||
public bool? ImageStabilization { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Intervalometer hint from the MakerNote: true when the camera's own interval-shooting or time-lapse mode took the
|
||||
/// photo, false when the MakerNote names another drive mode, null when it says nothing (BRIEF §9).
|
||||
/// </summary>
|
||||
public bool? IntervalShooting { get; init; }
|
||||
|
||||
/// <summary>Resolution of a camera RAW from the MakerNote (sRAW/mRAW, RAW M/S); null when not recorded.</summary>
|
||||
public RawSize? RawSize { get; init; }
|
||||
|
||||
/// <summary>Embedded JPEGs, largest first.</summary>
|
||||
public IReadOnlyList<EmbeddedPreview> Previews { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<string> Warnings { get; init; } = [];
|
||||
|
||||
/// <summary>Width/height after applying orientation 5–8 (90° rotations).</summary>
|
||||
public (int Width, int Height) OrientedSize => Orientation is >= 5 and <= 8 ? (Height, Width) : (Width, Height);
|
||||
|
||||
public EmbeddedPreview? LargestPreview => Previews.Count > 0 ? Previews[0] : null;
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using System.Buffers.Binary;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
|
||||
namespace Chronos.Core.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Identifies a file's format from its leading bytes. TIFF-based files are refined by the CR2 marker, IFD0
|
||||
/// <c>DNGVersion</c> and <c>Make</c>; ISO-BMFF files by their <c>ftyp</c> brands. The file-name extension only breaks
|
||||
/// ties between formats that share a container (NEF/NRW, ARW/SRF/SR2, 3FR/FFF, RW2/RWL/RAW, TIFF vs camera RAW).
|
||||
/// </summary>
|
||||
public static class ImageSignature
|
||||
{
|
||||
private const int HeadBytes = 32;
|
||||
private const int MaxFtypBytes = 256;
|
||||
|
||||
private static ReadOnlySpan<byte> PngSignature => [0x89, (byte)'P', (byte)'N', (byte)'G', 0x0D, 0x0A, 0x1A, 0x0A];
|
||||
private static ReadOnlySpan<byte> JpegXrSignature => [(byte)'I', (byte)'I', 0xBC];
|
||||
private static ReadOnlySpan<byte> JpegXlBox => [0, 0, 0, 0x0C, (byte)'J', (byte)'X', (byte)'L', (byte)' ', 0x0D, 0x0A, 0x87, 0x0A];
|
||||
|
||||
private static readonly HashSet<ImageFileFormat> TiffBasedRaws =
|
||||
[
|
||||
ImageFileFormat.Dng, ImageFileFormat.Cr2, ImageFileFormat.Nef, ImageFileFormat.Nrw, ImageFileFormat.Arw,
|
||||
ImageFileFormat.Srf, ImageFileFormat.Sr2, ImageFileFormat.Orf, ImageFileFormat.Rw2, ImageFileFormat.Raw,
|
||||
ImageFileFormat.Rwl, ImageFileFormat.Pef, ImageFileFormat.Srw, ImageFileFormat.ThreeFr, ImageFileFormat.Fff,
|
||||
ImageFileFormat.Iiq, ImageFileFormat.Gpr,
|
||||
];
|
||||
|
||||
/// <summary>Detects the format of the bytes in <paramref name="stream"/> (read from offset 0; the position is restored).</summary>
|
||||
/// <param name="fileName">Optional name or path whose extension breaks ties; never overrides the signature.</param>
|
||||
/// <returns><see cref="ImageFileFormat.Unknown"/> when no known signature matches.</returns>
|
||||
public static ImageFileFormat Detect(Stream stream, string? fileName)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
if (!stream.CanSeek || !stream.CanRead) throw new ArgumentException("The stream must be readable and seekable.", nameof(stream));
|
||||
var position = stream.Position;
|
||||
try
|
||||
{
|
||||
var extension = string.IsNullOrEmpty(fileName) ? ImageFileFormat.Unknown : ImageFormatInfo.FromPath(fileName).Format;
|
||||
return DetectCore(stream, extension);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return ImageFileFormat.Unknown;
|
||||
}
|
||||
finally
|
||||
{
|
||||
stream.Position = position;
|
||||
}
|
||||
}
|
||||
|
||||
private static ImageFileFormat DetectCore(Stream stream, ImageFileFormat extension)
|
||||
{
|
||||
Span<byte> buffer = stackalloc byte[HeadBytes];
|
||||
var h = buffer[..stream.ReadUpTo(0, buffer)];
|
||||
if (h.StartsWith((ReadOnlySpan<byte>)[0xFF, 0xD8, 0xFF])) return ImageFileFormat.Jpeg;
|
||||
if (h.StartsWith(PngSignature)) return ImageFileFormat.Png;
|
||||
if (h.StartsWith("GIF87a"u8) || h.StartsWith("GIF89a"u8)) return ImageFileFormat.Gif;
|
||||
if (h.StartsWith("FUJIFILMCCD-RAW "u8)) return ImageFileFormat.Raf;
|
||||
if (h.Length >= 12 && h.StartsWith("RIFF"u8) && h[8..12].SequenceEqual("WEBP"u8)) return ImageFileFormat.WebP;
|
||||
if (h.StartsWith((ReadOnlySpan<byte>)[0xFF, 0x0A]) || h.StartsWith(JpegXlBox)) return ImageFileFormat.JpegXl;
|
||||
if (h.Length >= 12 && h[4..8].SequenceEqual("ftyp"u8)) return FromBrands(stream, BinaryPrimitives.ReadUInt32BigEndian(h));
|
||||
if (h.Length >= 4 && h.StartsWith(JpegXrSignature) && h[3] <= 1) return ImageFileFormat.JpegXr;
|
||||
if (h.Length >= 14 && h[6..14].SequenceEqual("HEAPCCDR"u8)) return ImageFileFormat.Crw;
|
||||
if (h.StartsWith("IIRO"u8) || h.StartsWith("IIRS"u8) || h.StartsWith("MMOR"u8)) return ImageFileFormat.Orf;
|
||||
if (h.StartsWith("IIU\0"u8)) return Panasonic(stream, extension);
|
||||
if (h.StartsWith("II*\0"u8) || h.StartsWith("MM\0*"u8)) return Tiff(stream, h, extension);
|
||||
if (h.Length >= 18 && h.StartsWith("BM"u8) && BinaryPrimitives.ReadUInt32LittleEndian(h[14..]) is 12 or 16 or 40 or 52 or 56 or 64 or 108 or 124)
|
||||
return ImageFileFormat.Bmp;
|
||||
return ImageFileFormat.Unknown;
|
||||
}
|
||||
|
||||
/// <summary>CR3 (crx), AVIF (avif/avis) or HEIF (heic, heix, hevc, hevx, heim, heis, mif1, msf1); major brand first.</summary>
|
||||
private static ImageFileFormat FromBrands(Stream stream, uint ftypSize)
|
||||
{
|
||||
Span<byte> buffer = stackalloc byte[MaxFtypBytes];
|
||||
var n = stream.ReadUpTo(0, buffer[..(int)Math.Clamp(ftypSize, 16, MaxFtypBytes)]);
|
||||
if (n < 12) return ImageFileFormat.Unknown;
|
||||
var major = Brand(buffer[8..12]);
|
||||
if (major == BrandKind.Cr3) return ImageFileFormat.Cr3;
|
||||
if (major == BrandKind.Avif) return ImageFileFormat.Avif;
|
||||
if (major == BrandKind.Heif) return ImageFileFormat.Heif;
|
||||
var heif = major == BrandKind.Image;
|
||||
for (var i = 16; i + 4 <= n; i += 4)
|
||||
{
|
||||
var brand = Brand(buffer.Slice(i, 4));
|
||||
if (brand == BrandKind.Avif) return ImageFileFormat.Avif;
|
||||
heif |= brand is BrandKind.Heif or BrandKind.Image;
|
||||
}
|
||||
return heif ? ImageFileFormat.Heif : ImageFileFormat.Unknown;
|
||||
}
|
||||
|
||||
private enum BrandKind
|
||||
{
|
||||
Other,
|
||||
Cr3,
|
||||
Avif,
|
||||
Heif,
|
||||
Image,
|
||||
}
|
||||
|
||||
private static BrandKind Brand(ReadOnlySpan<byte> b) =>
|
||||
b.SequenceEqual("crx "u8) ? BrandKind.Cr3
|
||||
: b.SequenceEqual("avif"u8) || b.SequenceEqual("avis"u8) ? BrandKind.Avif
|
||||
: b.SequenceEqual("heic"u8) || b.SequenceEqual("heix"u8) || b.SequenceEqual("hevc"u8) || b.SequenceEqual("hevx"u8)
|
||||
|| b.SequenceEqual("heim"u8) || b.SequenceEqual("heis"u8) ? BrandKind.Heif
|
||||
: b.SequenceEqual("mif1"u8) || b.SequenceEqual("msf1"u8) ? BrandKind.Image
|
||||
: BrandKind.Other;
|
||||
|
||||
private static ImageFileFormat Panasonic(Stream stream, ImageFileFormat extension)
|
||||
{
|
||||
if (extension is ImageFileFormat.Rwl or ImageFileFormat.Raw) return extension;
|
||||
return Make(stream)?.StartsWith("LEICA", StringComparison.OrdinalIgnoreCase) == true ? ImageFileFormat.Rwl : ImageFileFormat.Rw2;
|
||||
}
|
||||
|
||||
private static ImageFileFormat Tiff(Stream stream, ReadOnlySpan<byte> h, ImageFileFormat extension)
|
||||
{
|
||||
if (h.Length >= 10 && h[8..10].SequenceEqual("CR"u8)) return ImageFileFormat.Cr2;
|
||||
var reader = TiffReader.Open(stream);
|
||||
var ifd0 = reader?.ReadIfd(reader.FirstIfdOffset);
|
||||
var make = reader is not null && ifd0 is not null ? IfdValue.String(reader, ifd0, TiffTags.Make) : null;
|
||||
// A GoPro DNG is GPR only when its raw image is VC-5: one converted by Adobe software (Lightroom, DNG Converter) is
|
||||
// an ordinary DNG the managed DNG decoder develops (R4, owner review 1).
|
||||
if (ifd0?.Has(TiffTags.DngVersion) == true)
|
||||
return extension == ImageFileFormat.Gpr || Codecs.Dng.DngReader.IsVc5(reader!) ? ImageFileFormat.Gpr : ImageFileFormat.Dng;
|
||||
if (extension == ImageFileFormat.Tiff) return ImageFileFormat.Tiff;
|
||||
var byMake = ByMake(make, extension);
|
||||
if (byMake != ImageFileFormat.Unknown) return byMake;
|
||||
return TiffBasedRaws.Contains(extension) ? extension : ImageFileFormat.Tiff;
|
||||
}
|
||||
|
||||
private static ImageFileFormat ByMake(string? make, ImageFileFormat extension)
|
||||
{
|
||||
if (make is null) return ImageFileFormat.Unknown;
|
||||
bool Is(string prefix) => make.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
|
||||
if (Is("NIKON")) return extension == ImageFileFormat.Nrw ? ImageFileFormat.Nrw : ImageFileFormat.Nef;
|
||||
if (Is("SONY")) return extension is ImageFileFormat.Srf or ImageFileFormat.Sr2 ? extension : ImageFileFormat.Arw;
|
||||
if (Is("PENTAX") || Is("RICOH")) return ImageFileFormat.Pef;
|
||||
if (Is("SAMSUNG")) return ImageFileFormat.Srw;
|
||||
if (Is("Hasselblad")) return extension == ImageFileFormat.Fff ? ImageFileFormat.Fff : ImageFileFormat.ThreeFr;
|
||||
if (Is("Imacon")) return ImageFileFormat.Fff;
|
||||
if (Is("Phase One") || Is("Leaf")) return ImageFileFormat.Iiq;
|
||||
return ImageFileFormat.Unknown;
|
||||
}
|
||||
|
||||
private static string? Make(Stream stream)
|
||||
{
|
||||
var reader = TiffReader.Open(stream);
|
||||
return reader?.ReadIfd(reader.FirstIfdOffset) is { } ifd ? IfdValue.String(reader, ifd, TiffTags.Make) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
using Chronos.Core.Metadata.Xmp;
|
||||
|
||||
namespace Chronos.Core.Metadata.Jpeg;
|
||||
|
||||
/// <summary>Frame header (SOFn) of a JPEG.</summary>
|
||||
internal readonly record struct JpegFrame(int Width, int Height, int Precision, bool Lossless);
|
||||
|
||||
/// <summary>
|
||||
/// JPEG marker scan: APP1 Exif, APP1 XMP and extended XMP (reassembled by GUID/offset), APP2 MPF large-thumbnail
|
||||
/// entries, SOFn. Reads only segment headers and the payloads it parses, stops at SOS, and tolerates fill bytes and
|
||||
/// garbage between segments.
|
||||
/// </summary>
|
||||
internal static class JpegParser
|
||||
{
|
||||
/// <summary>Most bytes read while looking for an embedded JPEG's frame header.</summary>
|
||||
public const int MaxFrameScanBytes = 64 * 1024;
|
||||
|
||||
private const int MaxSegments = 1024;
|
||||
private const int MaxGarbageBytes = 64 * 1024;
|
||||
private const int MaxMpEntries = 64;
|
||||
private const ushort MpEntryTag = 0xB002;
|
||||
private const uint MpLargeThumbnailVga = 0x010001;
|
||||
private const uint MpLargeThumbnailFullHd = 0x010002;
|
||||
private const int ExtendedHeaderLength = 75;
|
||||
|
||||
private static ReadOnlySpan<byte> ExifSignature => "Exif\0"u8;
|
||||
private static ReadOnlySpan<byte> XmpSignature => "http://ns.adobe.com/xap/1.0/\0"u8;
|
||||
private static ReadOnlySpan<byte> ExtendedXmpSignature => "http://ns.adobe.com/xmp/extension/\0"u8;
|
||||
private static ReadOnlySpan<byte> MpfSignature => "MPF\0"u8;
|
||||
|
||||
/// <summary>Scans the JPEG at [<paramref name="start"/>, <paramref name="end"/>). A primary JPEG defines the main image
|
||||
/// size; an embedded one (RAF, RW2 JpgFromRaw) contributes its Exif/XMP and is recorded as a preview.</summary>
|
||||
public static void Parse(MetadataBuilder m, long start, long end, bool primary)
|
||||
{
|
||||
var scanner = new SegmentScanner(m.Stream, start, Math.Min(end, m.Length), long.MaxValue);
|
||||
if (!scanner.StartsWithSoi())
|
||||
{
|
||||
m.Warn("JPEG start-of-image marker not found");
|
||||
return;
|
||||
}
|
||||
JpegFrame? frame = null;
|
||||
var exifSeen = false;
|
||||
List<ExtendedXmpChunk>? extended = null;
|
||||
while (scanner.Next(out var segment))
|
||||
{
|
||||
m.ThrowIfCancelled();
|
||||
if (segment.Marker is 0xDA or 0xD9) break;
|
||||
if (segment.Marker == 0xE1) ReadApp1(m, segment, ref exifSeen, ref extended);
|
||||
else if (segment.Marker == 0xE2) ReadMpf(m, segment);
|
||||
else if (frame is null && IsFrameMarker(segment.Marker)) frame = ReadFrameHeader(m.Stream, segment);
|
||||
}
|
||||
if (scanner.Garbage) m.Warn("JPEG: garbage between segments skipped");
|
||||
if (scanner.Truncated) m.Warn("JPEG: truncated segment");
|
||||
if (frame is { } f)
|
||||
{
|
||||
if (primary) m.SetContainerSize(f.Width, f.Height, f.Precision);
|
||||
else if (!f.Lossless && end <= m.Length) m.AddPreview(start, end - start, f.Width, f.Height);
|
||||
}
|
||||
else if (primary)
|
||||
{
|
||||
m.Warn("JPEG frame header not found");
|
||||
}
|
||||
if (extended is not null) AssembleExtendedXmp(m, extended);
|
||||
}
|
||||
|
||||
/// <summary>Frame header of an embedded JPEG reading at most <see cref="MaxFrameScanBytes"/>; null when the bytes are
|
||||
/// not a JPEG or no SOFn precedes the scan data.</summary>
|
||||
public static JpegFrame? ReadFrame(Stream stream, long offset, long length)
|
||||
{
|
||||
if (offset < 0 || length < 4 || offset > stream.Length - length) return null;
|
||||
var scanner = new SegmentScanner(stream, offset, offset + length, MaxFrameScanBytes);
|
||||
if (!scanner.StartsWithSoi()) return null;
|
||||
while (scanner.Next(out var segment))
|
||||
{
|
||||
if (segment.Marker is 0xDA or 0xD9) return null;
|
||||
if (IsFrameMarker(segment.Marker)) return ReadFrameHeader(stream, segment);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Validates an embedded JPEG and records it as a preview unless it is lossless (raw data).</summary>
|
||||
/// <returns>The frame header, or null when the range holds no readable JPEG.</returns>
|
||||
public static JpegFrame? AddPreview(MetadataBuilder m, long offset, long length, PreviewKind? kind = null)
|
||||
{
|
||||
if (offset < 0 || length <= 0 || offset > m.Length - length)
|
||||
{
|
||||
m.Warn("Embedded JPEG outside the file");
|
||||
return null;
|
||||
}
|
||||
var frame = ReadFrame(m.Stream, offset, length);
|
||||
if (frame is { Lossless: false } f) m.AddPreview(offset, length, f.Width, f.Height, kind);
|
||||
return frame;
|
||||
}
|
||||
|
||||
private static bool IsFrameMarker(byte marker) => marker is >= 0xC0 and <= 0xCF and not (0xC4 or 0xC8 or 0xCC);
|
||||
|
||||
private static JpegFrame? ReadFrameHeader(Stream stream, Segment segment)
|
||||
{
|
||||
Span<byte> sof = stackalloc byte[6];
|
||||
if (segment.Length < 6 || !stream.TryReadAt(segment.Payload, sof)) return null;
|
||||
var lossless = segment.Marker is 0xC3 or 0xC7 or 0xCB or 0xCF;
|
||||
return new JpegFrame(BinaryPrimitives.ReadUInt16BigEndian(sof[3..]), BinaryPrimitives.ReadUInt16BigEndian(sof[1..]), sof[0], lossless);
|
||||
}
|
||||
|
||||
private static void ReadApp1(MetadataBuilder m, Segment segment, ref bool exifSeen, ref List<ExtendedXmpChunk>? extended)
|
||||
{
|
||||
Span<byte> head = stackalloc byte[ExtendedHeaderLength];
|
||||
var n = m.Stream.ReadUpTo(segment.Payload, head[..Math.Min(head.Length, segment.Length)]);
|
||||
var h = head[..n];
|
||||
if (h.StartsWith(ExifSignature) && segment.Length > 6)
|
||||
{
|
||||
if (!exifSeen) ExifParser.ParseEmbedded(m, segment.Payload + 6);
|
||||
exifSeen = true;
|
||||
}
|
||||
else if (h.StartsWith(XmpSignature))
|
||||
{
|
||||
m.AddXmp(m.Stream.ReadAt(segment.Payload + XmpSignature.Length, segment.Length - XmpSignature.Length, XmpParser.MaxPacketBytes));
|
||||
}
|
||||
else if (h.StartsWith(ExtendedXmpSignature) && n == ExtendedHeaderLength)
|
||||
{
|
||||
var guid = Encoding.ASCII.GetString(h.Slice(ExtendedXmpSignature.Length, 32));
|
||||
var full = BinaryPrimitives.ReadUInt32BigEndian(h[67..]);
|
||||
var offset = BinaryPrimitives.ReadUInt32BigEndian(h[71..]);
|
||||
(extended ??= []).Add(new ExtendedXmpChunk(guid, full, offset, segment.Payload + ExtendedHeaderLength, segment.Length - ExtendedHeaderLength));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>APP2 Multi-Picture Format: secondary large thumbnails (type 0x010001/0x010002) become previews. Offsets are
|
||||
/// relative to the MP header; other secondary types (disparity, gain maps…) are not previews.</summary>
|
||||
private static void ReadMpf(MetadataBuilder m, Segment segment)
|
||||
{
|
||||
Span<byte> head = stackalloc byte[4];
|
||||
if (segment.Length < 16 || !m.Stream.TryReadAt(segment.Payload, head) || !head.SequenceEqual(MpfSignature)) return;
|
||||
var mpBase = segment.Payload + 4;
|
||||
var r = TiffReader.Open(m.Stream, mpBase);
|
||||
if (r?.ReadIfd(r.FirstIfdOffset) is not { } index || !index.Entries.TryGetValue(MpEntryTag, out var entry)) return;
|
||||
if (entry.Count % 16 != 0 || entry.Count > 16 * MaxMpEntries || r.ReadBytes(entry) is not { } entries)
|
||||
{
|
||||
m.Warn("MPF entry table malformed");
|
||||
return;
|
||||
}
|
||||
for (var i = 16; i + 16 <= entries.Length; i += 16)
|
||||
{
|
||||
var e = entries.AsSpan(i, 16);
|
||||
var type = r.U32(e) & 0xFFFFFF;
|
||||
var size = r.U32(e[4..]);
|
||||
var offset = r.U32(e[8..]);
|
||||
if (type is MpLargeThumbnailVga or MpLargeThumbnailFullHd && offset > 0 && size > 0) AddPreview(m, mpBase + offset, size);
|
||||
}
|
||||
m.AddWarnings(r.Warnings);
|
||||
}
|
||||
|
||||
private static void AssembleExtendedXmp(MetadataBuilder m, List<ExtendedXmpChunk> chunks)
|
||||
{
|
||||
var guid = m.Xmp.ExtendedXmpGuid;
|
||||
if (guid is null)
|
||||
{
|
||||
m.Warn("Extended XMP present but not referenced by the main packet");
|
||||
return;
|
||||
}
|
||||
uint full = 0;
|
||||
long covered = 0;
|
||||
foreach (var c in chunks)
|
||||
{
|
||||
if (!string.Equals(c.Guid, guid, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
if (full == 0) full = c.FullLength;
|
||||
if (c.FullLength == full) covered += c.Length;
|
||||
}
|
||||
if (full == 0 || full > XmpParser.MaxPacketBytes || covered < full)
|
||||
{
|
||||
m.Warn("Extended XMP incomplete");
|
||||
return;
|
||||
}
|
||||
var buffer = new byte[full];
|
||||
foreach (var c in chunks)
|
||||
{
|
||||
if (!string.Equals(c.Guid, guid, StringComparison.OrdinalIgnoreCase) || c.FullLength != full || (long)c.Offset + c.Length > full) continue;
|
||||
if (!m.Stream.TryReadAt(c.Position, buffer.AsSpan((int)c.Offset, c.Length)))
|
||||
{
|
||||
m.Warn("Extended XMP chunk unreadable");
|
||||
return;
|
||||
}
|
||||
}
|
||||
m.AddXmp(buffer);
|
||||
}
|
||||
|
||||
private readonly record struct Segment(byte Marker, long Payload, int Length);
|
||||
|
||||
private readonly record struct ExtendedXmpChunk(string Guid, uint FullLength, uint Offset, long Position, int Length);
|
||||
|
||||
/// <summary>Walks marker segments of one JPEG, reading only marker and length bytes within a read budget.</summary>
|
||||
private sealed class SegmentScanner(Stream stream, long start, long end, long readBudget)
|
||||
{
|
||||
private readonly byte[] _buffer = new byte[16];
|
||||
private long _position = start + 2;
|
||||
private long _budget = readBudget;
|
||||
private int _count;
|
||||
|
||||
public bool Garbage { get; private set; }
|
||||
|
||||
public bool Truncated { get; private set; }
|
||||
|
||||
public bool StartsWithSoi() => Read(start, 2) == 2 && _buffer[0] == 0xFF && _buffer[1] == 0xD8;
|
||||
|
||||
public bool Next(out Segment segment)
|
||||
{
|
||||
segment = default;
|
||||
if (++_count > MaxSegments) return false;
|
||||
long skipped = 0;
|
||||
while (true)
|
||||
{
|
||||
var n = Read(_position, _buffer.Length);
|
||||
if (n < 2)
|
||||
{
|
||||
if (_position < end) Truncated = true;
|
||||
return false;
|
||||
}
|
||||
var i = 0;
|
||||
while (i < n - 1 && !(_buffer[i] == 0xFF && _buffer[i + 1] is not (0xFF or 0x00))) i++;
|
||||
if (i == n - 1)
|
||||
{
|
||||
Garbage |= _buffer.AsSpan(0, n - 1).ContainsAnyExcept((byte)0xFF);
|
||||
_position += n - 1;
|
||||
skipped += n - 1;
|
||||
if (skipped > MaxGarbageBytes) return false;
|
||||
continue;
|
||||
}
|
||||
Garbage |= _buffer.AsSpan(0, i).ContainsAnyExcept((byte)0xFF);
|
||||
var marker = _buffer[i + 1];
|
||||
var markerPosition = _position + i + 1;
|
||||
if (marker is 0xD8 or 0xD9 or 0x01 or (>= 0xD0 and <= 0xD7))
|
||||
{
|
||||
_position = markerPosition + 1;
|
||||
segment = new Segment(marker, _position, 0);
|
||||
return true;
|
||||
}
|
||||
int length;
|
||||
if (i + 3 < n)
|
||||
{
|
||||
length = _buffer[i + 2] << 8 | _buffer[i + 3];
|
||||
}
|
||||
else if (Read(markerPosition + 1, 2) == 2)
|
||||
{
|
||||
length = _buffer[0] << 8 | _buffer[1];
|
||||
}
|
||||
else
|
||||
{
|
||||
Truncated = true;
|
||||
return false;
|
||||
}
|
||||
if (length < 2)
|
||||
{
|
||||
Garbage = true;
|
||||
return false;
|
||||
}
|
||||
var payload = markerPosition + 3;
|
||||
var available = (int)Math.Clamp(end - payload, 0, length - 2);
|
||||
Truncated |= available < length - 2;
|
||||
segment = new Segment(marker, payload, available);
|
||||
_position = payload + length - 2;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private int Read(long position, int count)
|
||||
{
|
||||
if (position >= end || _budget <= 0) return 0;
|
||||
var n = (int)Math.Min(Math.Min(count, end - position), _budget);
|
||||
n = stream.ReadUpTo(position, _buffer.AsSpan(0, n));
|
||||
_budget -= n;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
|
||||
namespace Chronos.Core.Metadata.MakerNotes;
|
||||
|
||||
/// <summary>
|
||||
/// Canon MakerNote: a bare IFD whose offsets are relative to the enclosing TIFF header (also CR3 CMT3). CameraSettings
|
||||
/// gives the stabiliser, the exposure mode and the sRAW size; Canon records no interval-shooting hint there.
|
||||
/// </summary>
|
||||
internal static class CanonMakerNote
|
||||
{
|
||||
private const ushort CameraSettings = 0x0001;
|
||||
private const ushort SerialNumber = 0x000C;
|
||||
private const ushort LensModel = 0x0095;
|
||||
private const ushort InternalSerialNumber = 0x0096;
|
||||
private const ushort ColorTemperature = 0x00AE;
|
||||
private const int ExposureModeIndex = 20;
|
||||
private const int ImageStabilizationIndex = 34;
|
||||
private const int SRawQualityIndex = 46;
|
||||
|
||||
public static void Parse(TiffReader r, Ifd ifd, MetadataBuilder m)
|
||||
{
|
||||
var v = m.MakerNote;
|
||||
if (IfdValue.UInt(r, ifd, SerialNumber) is { } serial and > 0)
|
||||
{
|
||||
// Canon prints 6 digits on EOS-1D bodies and 10 elsewhere.
|
||||
var digits = m.Model?.Contains("EOS-1D", StringComparison.OrdinalIgnoreCase) == true ? "D6" : "D10";
|
||||
v.BodySerial ??= serial.ToString(digits, CultureInfo.InvariantCulture);
|
||||
}
|
||||
v.BodySerial ??= IfdValue.String(r, ifd, InternalSerialNumber);
|
||||
v.LensModel ??= IfdValue.String(r, ifd, LensModel);
|
||||
v.ColorTemperature ??= IfdValue.Int(r, ifd, ColorTemperature) is { } kelvin and > 0 and < 65535 ? kelvin : null;
|
||||
if (IfdValue.UInts(r, ifd, CameraSettings) is not { } settings) return;
|
||||
if (settings.Length > ExposureModeIndex)
|
||||
{
|
||||
// CanonExposureMode: 1 Program, 2 Tv, 3 Av, 4 Manual, 5 Depth-of-field AE, 6 M-Dep, 7 Bulb, 8 Fv; 0 Easy (scene).
|
||||
v.ExposureProgram ??= settings[ExposureModeIndex] switch
|
||||
{
|
||||
1 or 8 => 2,
|
||||
2 => 4,
|
||||
3 => 3,
|
||||
4 or 7 => 1,
|
||||
5 or 6 => 5,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
if (settings.Length > ImageStabilizationIndex)
|
||||
{
|
||||
// 0 Off, 1 On, 2 Shoot only, 3 Panning, 4 Dynamic; +256 for the "(2)" variants.
|
||||
v.ImageStabilization ??= (settings[ImageStabilizationIndex] & 0xFF) switch
|
||||
{
|
||||
0 => false,
|
||||
>= 1 and <= 4 => true,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
if (settings.Length > SRawQualityIndex && m.Format is ImageFileFormat.Cr2 or ImageFileFormat.Cr3)
|
||||
{
|
||||
// SRAWQuality: 0 full-size RAW, 1 sRAW1 (mRAW), 2 sRAW2 (sRAW).
|
||||
v.RawSize ??= settings[SRawQualityIndex] switch
|
||||
{
|
||||
0 => RawSize.Full,
|
||||
1 => RawSize.Medium,
|
||||
2 => RawSize.Small,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System.Buffers.Binary;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
|
||||
namespace Chronos.Core.Metadata.MakerNotes;
|
||||
|
||||
/// <summary>Fujifilm MakerNote: "FUJIFILM" + little-endian IFD offset, offsets relative to the MakerNote start,
|
||||
/// always little-endian.</summary>
|
||||
internal static class FujifilmMakerNote
|
||||
{
|
||||
private const ushort SerialNumber = 0x0010;
|
||||
private const ushort ColorTemperature = 0x1005;
|
||||
private const ushort PictureMode = 0x1031;
|
||||
private const ushort ImageStabilization = 0x1422;
|
||||
|
||||
public static void Parse(MetadataBuilder m, long start, ReadOnlySpan<byte> header)
|
||||
{
|
||||
if (header.Length < 12) return;
|
||||
var reader = TiffReader.ForEmbedded(m.Stream, start, littleEndian: true);
|
||||
MakerNoteParser.Vendor(reader, BinaryPrimitives.ReadUInt32LittleEndian(header[8..]), m, ParseIfd);
|
||||
m.AddWarnings(reader.Warnings);
|
||||
}
|
||||
|
||||
private static void ParseIfd(TiffReader r, Ifd ifd, MetadataBuilder m)
|
||||
{
|
||||
var v = m.MakerNote;
|
||||
v.BodySerial ??= IfdValue.String(r, ifd, SerialNumber);
|
||||
v.ColorTemperature ??= IfdValue.Int(r, ifd, ColorTemperature) is { } kelvin and > 0 and < 65535 ? kelvin : null;
|
||||
// [0] type (0 none, 1 optical, 2 sensor-shift, …), [1] mode (0 off, 1/2 on).
|
||||
if (IfdValue.UInts(r, ifd, ImageStabilization) is [var type, var mode, ..])
|
||||
v.ImageStabilization ??= type != 0 && mode != 0;
|
||||
// PictureMode: 0x300 Manual, 6 Program AE, 0x100 Aperture priority, 0x200 Shutter priority, 1 Portrait, 2 Landscape, 4 Sports.
|
||||
v.ExposureProgram ??= IfdValue.UInt(r, ifd, PictureMode) switch
|
||||
{
|
||||
0x300 => 1,
|
||||
6 => 2,
|
||||
0x100 => 3,
|
||||
0x200 => 4,
|
||||
4 => 6,
|
||||
1 => 7,
|
||||
2 => 8,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
|
||||
namespace Chronos.Core.Metadata.MakerNotes;
|
||||
|
||||
/// <summary>
|
||||
/// Locates the vendor IFD inside an Exif MakerNote (by header signature, then by camera make) and hands it to the
|
||||
/// vendor parser. Best effort: unknown layouts are skipped, and every read goes through the bounds-checked
|
||||
/// <see cref="TiffReader"/>.
|
||||
/// </summary>
|
||||
internal static class MakerNoteParser
|
||||
{
|
||||
private const int HeaderBytes = 16;
|
||||
|
||||
/// <param name="exif">Reader of the TIFF block holding the Exif IFD (base and byte order of relative offsets).</param>
|
||||
/// <param name="makerNote">The Exif 0x927C entry.</param>
|
||||
public static void Parse(TiffReader exif, IfdEntry makerNote, MetadataBuilder m)
|
||||
{
|
||||
if (makerNote.IsInline || makerNote.ByteLength < 14) return;
|
||||
var start = makerNote.ValuePosition(exif.Base);
|
||||
if (start < exif.Base || start > m.Length - makerNote.ByteLength)
|
||||
{
|
||||
m.Warn("MakerNote outside the file");
|
||||
return;
|
||||
}
|
||||
Span<byte> head = stackalloc byte[HeaderBytes];
|
||||
var h = head[..m.Stream.ReadUpTo(start, head[..(int)Math.Min(HeaderBytes, makerNote.ByteLength)])];
|
||||
var make = m.Make ?? string.Empty;
|
||||
var relative = (uint)(start - exif.Base);
|
||||
|
||||
if (h.StartsWith("Nikon\0"u8))
|
||||
{
|
||||
NikonMakerNote.Parse(exif, start, h, m);
|
||||
}
|
||||
else if (h.StartsWith("OLYMPUS\0"u8) || h.StartsWith("OM SYSTEM\0"u8) || h.StartsWith("OLYMP\0"u8))
|
||||
{
|
||||
OlympusMakerNote.Parse(exif, start, h, m);
|
||||
}
|
||||
else if (h.StartsWith("FUJIFILM"u8))
|
||||
{
|
||||
FujifilmMakerNote.Parse(m, start, h);
|
||||
}
|
||||
else if (h.StartsWith("Panasonic\0"u8))
|
||||
{
|
||||
Vendor(exif, relative + 12, m, PanasonicMakerNote.Parse);
|
||||
}
|
||||
else if (h.StartsWith("SONY"u8))
|
||||
{
|
||||
Vendor(exif, relative + 12, m, SonyMakerNote.Parse);
|
||||
}
|
||||
else if (make.StartsWith("Canon", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Vendor(exif, relative, m, CanonMakerNote.Parse);
|
||||
}
|
||||
else if (make.StartsWith("NIKON", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Vendor(exif, relative, m, NikonMakerNote.ParseIfd);
|
||||
}
|
||||
else if (make.StartsWith("SONY", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Vendor(exif, relative, m, SonyMakerNote.Parse);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the IFD at a base-relative offset with <paramref name="reader"/> and runs <paramref name="parse"/> on it.</summary>
|
||||
internal static void Vendor(TiffReader reader, uint offset, MetadataBuilder m, Action<TiffReader, Ifd, MetadataBuilder> parse)
|
||||
{
|
||||
if (reader.ReadIfd(offset) is { } ifd) parse(reader, ifd, m);
|
||||
else m.Warn("MakerNote IFD unreadable");
|
||||
}
|
||||
|
||||
/// <summary>"24-70mm f/2.8", "50mm f/1.8" or "18-55mm F3.5-5.6" from focal-length and aperture ranges.</summary>
|
||||
internal static string FormatLens(double minFocal, double maxFocal, double minAperture, double maxAperture, string aperturePrefix)
|
||||
{
|
||||
static string N(double v) => Math.Round(v, 1).ToString("0.#", CultureInfo.InvariantCulture);
|
||||
var focal = maxFocal > minFocal ? $"{N(minFocal)}-{N(maxFocal)}mm" : $"{N(minFocal)}mm";
|
||||
if (minAperture <= 0) return focal;
|
||||
var aperture = maxAperture > minAperture ? $"{N(minAperture)}-{N(maxAperture)}" : N(minAperture);
|
||||
return $"{focal} {aperturePrefix}{aperture}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Chronos.Core.Metadata.MakerNotes;
|
||||
|
||||
/// <summary>Values recovered from a vendor MakerNote. They fill a field only when the standard tags left it empty.</summary>
|
||||
internal sealed class MakerNoteValues
|
||||
{
|
||||
public string? BodySerial { get; set; }
|
||||
public string? LensModel { get; set; }
|
||||
public long? ShutterCount { get; set; }
|
||||
public bool? ImageStabilization { get; set; }
|
||||
public int? Iso { get; set; }
|
||||
public int? ColorTemperature { get; set; }
|
||||
|
||||
/// <summary>The vendor's exposure mode as an Exif <c>ExposureProgram</c> value (1 manual, 2 program, 3 aperture
|
||||
/// priority, 4 shutter priority, 5 creative, 6 action, 7 portrait, 8 landscape); scene modes without one stay null.</summary>
|
||||
public int? ExposureProgram { get; set; }
|
||||
|
||||
/// <summary>True when the camera's own interval-shooting or time-lapse mode took the photo, false for another known mode.</summary>
|
||||
public bool? IntervalShooting { get; set; }
|
||||
|
||||
/// <summary>Resolution of a camera RAW (Canon sRAW/mRAW, Nikon RAW M/S).</summary>
|
||||
public RawSize? RawSize { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
|
||||
namespace Chronos.Core.Metadata.MakerNotes;
|
||||
|
||||
/// <summary>Nikon MakerNote. Type 3 ("Nikon\0" + version 2.x) embeds its own TIFF header 10 bytes in; type 1
|
||||
/// ("Nikon\0" + version 1) has an IFD at +8 and headerless type 2 an IFD at +0, both relative to the Exif TIFF.
|
||||
/// The RAW size comes from ImageSizeRAW or the "small" NEF compression; the interval-shooting state lives only in the
|
||||
/// encrypted ShotInfo, which is not decoded.</summary>
|
||||
internal static class NikonMakerNote
|
||||
{
|
||||
private const ushort Iso = 0x0002;
|
||||
private const ushort SerialNumber = 0x001D;
|
||||
private const ushort VrInfo = 0x001F;
|
||||
private const ushort ImageSizeRaw = 0x003E;
|
||||
private const ushort Lens = 0x0084;
|
||||
private const ushort NefCompression = 0x0093;
|
||||
private const ushort ShutterCount = 0x00A7;
|
||||
private const uint SmallNef = 8;
|
||||
|
||||
public static void Parse(TiffReader exif, long start, ReadOnlySpan<byte> header, MetadataBuilder m)
|
||||
{
|
||||
if (header.Length > 6 && header[6] == 2)
|
||||
{
|
||||
if (TiffReader.Open(m.Stream, start + 10) is { } inner)
|
||||
{
|
||||
MakerNoteParser.Vendor(inner, inner.FirstIfdOffset, m, ParseIfd);
|
||||
m.AddWarnings(inner.Warnings);
|
||||
}
|
||||
else
|
||||
{
|
||||
m.Warn("Nikon MakerNote TIFF header missing");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
MakerNoteParser.Vendor(exif, (uint)(start - exif.Base + 8), m, ParseIfd);
|
||||
}
|
||||
}
|
||||
|
||||
public static void ParseIfd(TiffReader r, Ifd ifd, MetadataBuilder m)
|
||||
{
|
||||
var v = m.MakerNote;
|
||||
v.BodySerial ??= IfdValue.String(r, ifd, SerialNumber);
|
||||
v.ShutterCount ??= IfdValue.UInt(r, ifd, ShutterCount);
|
||||
v.Iso ??= IfdValue.UInts(r, ifd, Iso) is [_, var iso, ..] && iso is > 0 and <= int.MaxValue ? (int)iso : null;
|
||||
if (IfdValue.Doubles(r, ifd, Lens, 4) is [var minFocal, var maxFocal, var minAperture, var maxAperture, ..] && minFocal > 0)
|
||||
v.LensModel ??= MakerNoteParser.FormatLens(minFocal, maxFocal, minAperture, maxAperture, "f/");
|
||||
if (ifd.Entries.TryGetValue(VrInfo, out var vr) && vr.Count is >= 5 and <= 64 && r.ReadBytes(vr) is { } bytes)
|
||||
{
|
||||
// Byte 4: 1 = on, 2 = off.
|
||||
v.ImageStabilization ??= bytes[4] switch
|
||||
{
|
||||
1 => true,
|
||||
2 => false,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
// ImageSizeRAW: 1 Large, 2 Medium, 3 Small; NEFCompression 8 is the older sRAW ("Small").
|
||||
v.RawSize ??= IfdValue.UInt(r, ifd, ImageSizeRaw) switch
|
||||
{
|
||||
1 => RawSize.Full,
|
||||
2 => RawSize.Medium,
|
||||
3 => RawSize.Small,
|
||||
_ => IfdValue.UInt(r, ifd, NefCompression) is SmallNef ? RawSize.Small : null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
using Chronos.Core.Metadata.Jpeg;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
|
||||
namespace Chronos.Core.Metadata.MakerNotes;
|
||||
|
||||
/// <summary>
|
||||
/// Olympus / OM System MakerNote. "OLYMPUS\0II\3\0" (IFD at +12) and "OM SYSTEM\0\0\0II\4\0" (IFD at +16) use offsets
|
||||
/// relative to the MakerNote start and their own byte order; legacy "OLYMP\0" has its IFD at +8 relative to the
|
||||
/// Exif TIFF. Equipment (0x2010) gives serial and lens; CameraSettings (0x2020) gives the ORF preview, the stabiliser
|
||||
/// and the exposure mode.
|
||||
/// </summary>
|
||||
internal static class OlympusMakerNote
|
||||
{
|
||||
private const ushort Equipment = 0x2010;
|
||||
private const ushort CameraSettings = 0x2020;
|
||||
private const ushort EquipmentSerialNumber = 0x0101;
|
||||
private const ushort EquipmentLensModel = 0x0203;
|
||||
private const ushort PreviewImageValid = 0x0100;
|
||||
private const ushort PreviewImageStart = 0x0101;
|
||||
private const ushort PreviewImageLength = 0x0102;
|
||||
private const ushort ExposureMode = 0x0200;
|
||||
private const ushort ImageStabilization = 0x0604;
|
||||
|
||||
public static void Parse(TiffReader exif, long start, ReadOnlySpan<byte> header, MetadataBuilder m)
|
||||
{
|
||||
if (header.StartsWith("OLYMP\0"u8))
|
||||
{
|
||||
MakerNoteParser.Vendor(exif, (uint)(start - exif.Base + 8), m, ParseIfd);
|
||||
return;
|
||||
}
|
||||
var orderAt = header.StartsWith("OM SYSTEM\0"u8) ? 12 : 8;
|
||||
if (header.Length < orderAt + 4 || header[orderAt] != header[orderAt + 1] || header[orderAt] is not ((byte)'I' or (byte)'M'))
|
||||
{
|
||||
m.Warn("Olympus MakerNote header malformed");
|
||||
return;
|
||||
}
|
||||
var reader = TiffReader.ForEmbedded(m.Stream, start, header[orderAt] == 'I');
|
||||
MakerNoteParser.Vendor(reader, (uint)(orderAt + 4), m, ParseIfd);
|
||||
m.AddWarnings(reader.Warnings);
|
||||
}
|
||||
|
||||
private static void ParseIfd(TiffReader r, Ifd ifd, MetadataBuilder m)
|
||||
{
|
||||
var v = m.MakerNote;
|
||||
if (SubIfd(r, ifd, Equipment) is { } equipment)
|
||||
{
|
||||
v.BodySerial ??= IfdValue.String(r, equipment, EquipmentSerialNumber);
|
||||
v.LensModel ??= IfdValue.String(r, equipment, EquipmentLensModel);
|
||||
}
|
||||
if (SubIfd(r, ifd, CameraSettings) is not { } settings) return;
|
||||
v.ImageStabilization ??= IfdValue.UInt(r, settings, ImageStabilization) switch
|
||||
{
|
||||
0 => false,
|
||||
>= 1 and <= 4 => true,
|
||||
_ => null,
|
||||
};
|
||||
// 1 Manual, 2 Program, 3 Aperture priority, 4 Shutter priority, 5 Program shift.
|
||||
v.ExposureProgram ??= IfdValue.UInt(r, settings, ExposureMode) switch
|
||||
{
|
||||
1 => 1,
|
||||
2 or 5 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
_ => null,
|
||||
};
|
||||
if (IfdValue.UInt(r, settings, PreviewImageValid) != 0
|
||||
&& IfdValue.UInt(r, settings, PreviewImageStart) is { } offset and > 0
|
||||
&& IfdValue.UInt(r, settings, PreviewImageLength) is { } length and > 0)
|
||||
{
|
||||
JpegParser.AddPreview(m, r.Base + offset, length);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sub-IFD stored either as an IFD/LONG pointer or as an UNDEFINED block; both resolve to the value offset.</summary>
|
||||
private static Ifd? SubIfd(TiffReader r, Ifd ifd, ushort tag) =>
|
||||
ifd.Entries.TryGetValue(tag, out var e) && !(e.IsInline && e.Type == TiffType.Undefined) ? r.ReadIfd(e.ValueOffset) : null;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
|
||||
namespace Chronos.Core.Metadata.MakerNotes;
|
||||
|
||||
/// <summary>Panasonic MakerNote: "Panasonic\0\0\0" then an IFD whose offsets are relative to the Exif TIFF. Besides
|
||||
/// identity and stabiliser it gives the shooting mode and TimerRecording, which says whether the camera's time-lapse
|
||||
/// mode took the photo.</summary>
|
||||
internal static class PanasonicMakerNote
|
||||
{
|
||||
private const ushort ImageStabilization = 0x001A;
|
||||
private const ushort ShootingMode = 0x001F;
|
||||
private const ushort InternalSerialNumber = 0x0025;
|
||||
private const ushort ColorTempKelvin = 0x0044;
|
||||
private const ushort LensType = 0x0051;
|
||||
private const ushort TimerRecording = 0x0096;
|
||||
|
||||
public static void Parse(TiffReader r, Ifd ifd, MetadataBuilder m)
|
||||
{
|
||||
var v = m.MakerNote;
|
||||
v.BodySerial ??= IfdValue.String(r, ifd, InternalSerialNumber);
|
||||
v.LensModel ??= IfdValue.String(r, ifd, LensType);
|
||||
v.ColorTemperature ??= IfdValue.Int(r, ifd, ColorTempKelvin) is { } kelvin and > 0 and < 65535 ? kelvin : null;
|
||||
// 3 = off; 2, 4–7, 9–12 = optical/body/dual IS modes.
|
||||
v.ImageStabilization ??= IfdValue.UInt(r, ifd, ImageStabilization) switch
|
||||
{
|
||||
3 => false,
|
||||
2 or (>= 4 and <= 7) or (>= 9 and <= 12) => true,
|
||||
_ => null,
|
||||
};
|
||||
// ShootingMode: 2 Portrait, 3 Scenery, 4 Sports, 6 Program, 7 Aperture priority, 8 Shutter priority, 11 Manual.
|
||||
v.ExposureProgram ??= IfdValue.UInt(r, ifd, ShootingMode) switch
|
||||
{
|
||||
11 => 1,
|
||||
6 => 2,
|
||||
7 => 3,
|
||||
8 => 4,
|
||||
4 => 6,
|
||||
2 => 7,
|
||||
3 => 8,
|
||||
_ => null,
|
||||
};
|
||||
// TimerRecording: 0 Off, 1 Time Lapse, 2 Stop-motion Animation, 3 Focus Bracketing.
|
||||
v.IntervalShooting ??= IfdValue.UInt(r, ifd, TimerRecording) switch
|
||||
{
|
||||
1 => true,
|
||||
0 or 2 or 3 => false,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
|
||||
namespace Chronos.Core.Metadata.MakerNotes;
|
||||
|
||||
/// <summary>Sony MakerNote ("SONY DSC/CAM" 12-byte header or headerless; offsets relative to the Exif TIFF).
|
||||
/// Lens: the unencrypted LensSpec (BCD focal/aperture range); numeric LensType tables are not shipped. Exposure mode
|
||||
/// from ExposureMode (0xB041).</summary>
|
||||
internal static class SonyMakerNote
|
||||
{
|
||||
private const ushort ColorTemperature = 0xB021;
|
||||
private const ushort ImageStabilization = 0xB026;
|
||||
private const ushort LensSpec = 0xB02A;
|
||||
private const ushort ExposureMode = 0xB041;
|
||||
|
||||
public static void Parse(TiffReader r, Ifd ifd, MetadataBuilder m)
|
||||
{
|
||||
var v = m.MakerNote;
|
||||
if (ifd.Entries.TryGetValue(LensSpec, out var spec) && spec.Count == 8 && r.ReadBytes(spec) is { } bytes)
|
||||
v.LensModel ??= DecodeLensSpec(bytes);
|
||||
v.ColorTemperature ??= IfdValue.UInt(r, ifd, ColorTemperature) is { } kelvin and > 0 and < 65535 ? (int)kelvin : null;
|
||||
v.ImageStabilization ??= IfdValue.UInt(r, ifd, ImageStabilization) switch
|
||||
{
|
||||
0 => false,
|
||||
1 => true,
|
||||
_ => null,
|
||||
};
|
||||
// 0 Program AE, 1 Portrait, 3 Sports, 5 Landscape, 7 Aperture priority, 8 Shutter priority, 15 Manual.
|
||||
v.ExposureProgram ??= IfdValue.UInt(r, ifd, ExposureMode) switch
|
||||
{
|
||||
15 => 1,
|
||||
0 => 2,
|
||||
7 => 3,
|
||||
8 => 4,
|
||||
3 => 6,
|
||||
1 => 7,
|
||||
5 => 8,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Bytes 1–2 short focal, 3–4 long focal (BCD mm), 5–6 apertures (BCD ×10); flags 0 and 7 are not decoded.</summary>
|
||||
private static string? DecodeLensSpec(ReadOnlySpan<byte> s)
|
||||
{
|
||||
if (!TryBcd(s.Slice(1, 2), out var minFocal) || !TryBcd(s.Slice(3, 2), out var maxFocal)
|
||||
|| !TryBcd(s.Slice(5, 1), out var minAperture) || !TryBcd(s.Slice(6, 1), out var maxAperture) || minFocal == 0)
|
||||
return null;
|
||||
return MakerNoteParser.FormatLens(minFocal, maxFocal, minAperture / 10.0, maxAperture / 10.0, "F");
|
||||
}
|
||||
|
||||
private static bool TryBcd(ReadOnlySpan<byte> bytes, out int value)
|
||||
{
|
||||
value = 0;
|
||||
foreach (var b in bytes)
|
||||
{
|
||||
if (b >> 4 > 9 || (b & 0xF) > 9) return false;
|
||||
value = value * 100 + (b >> 4) * 10 + (b & 0xF);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Metadata.MakerNotes;
|
||||
using Chronos.Core.Metadata.Xmp;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Core.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Mutable accumulator shared by the container parsers. Parsers assign standard values with <c>??=</c> in the order
|
||||
/// of authority (so the first source wins); MakerNote and XMP values are kept apart and <see cref="Build"/> applies
|
||||
/// every fallback chain in one place.
|
||||
/// </summary>
|
||||
internal sealed class MetadataBuilder
|
||||
{
|
||||
private const int MaxWarnings = 64;
|
||||
private const int MaxPreviews = 32;
|
||||
private const int MaxRasters = 64;
|
||||
private const int ThumbnailLongEdge = 640;
|
||||
private const double FullSizeRatio = 0.9;
|
||||
private const int SaturatedIso = 65535;
|
||||
|
||||
private readonly List<string> _warnings = [];
|
||||
private readonly List<PreviewCandidate> _previews = [];
|
||||
private readonly List<Raster> _rasters = [];
|
||||
private Raster? _container;
|
||||
|
||||
public MetadataBuilder(Stream stream, CancellationToken cancellation)
|
||||
{
|
||||
Stream = stream;
|
||||
Length = stream.Length;
|
||||
Cancellation = cancellation;
|
||||
}
|
||||
|
||||
public Stream Stream { get; }
|
||||
public long Length { get; }
|
||||
public CancellationToken Cancellation { get; }
|
||||
public ImageFileFormat Format { get; set; }
|
||||
|
||||
public string? Make { get; set; }
|
||||
public string? Model { get; set; }
|
||||
public string? BodySerial { get; set; }
|
||||
public string? LensModel { get; set; }
|
||||
public string? Software { get; set; }
|
||||
public string? Artist { get; set; }
|
||||
public string? Copyright { get; set; }
|
||||
public CaptureStamp? DateTimeOriginal { get; set; }
|
||||
public CaptureStamp? DateTimeDigitized { get; set; }
|
||||
public double? ExposureTime { get; set; }
|
||||
public double? FNumber { get; set; }
|
||||
|
||||
/// <summary>Exif ISOSpeedRatings (first value); 65535 means "at least 65535".</summary>
|
||||
public int? IsoSpeedRatings { get; set; }
|
||||
|
||||
/// <summary>RecommendedExposureIndex, StandardOutputSensitivity, ISOSpeed or a RAW-header ISO.</summary>
|
||||
public int? IsoFallback { get; set; }
|
||||
|
||||
public double? FocalLength { get; set; }
|
||||
public double? FocalLength35 { get; set; }
|
||||
public double? ExposureBias { get; set; }
|
||||
public int? ExposureProgram { get; set; }
|
||||
public int? MeteringMode { get; set; }
|
||||
public int? WhiteBalanceMode { get; set; }
|
||||
public int? Flash { get; set; }
|
||||
|
||||
/// <summary>Raw Exif/TIFF orientation value (validated in <see cref="Build"/>).</summary>
|
||||
public int? ExifOrientation { get; set; }
|
||||
|
||||
/// <summary>Orientation implied by container transforms (HEIF irot/imir); overrides Exif.</summary>
|
||||
public int? ContainerOrientation { get; set; }
|
||||
|
||||
public int? PixelXDimension { get; set; }
|
||||
public int? PixelYDimension { get; set; }
|
||||
|
||||
/// <summary>Bit depth of the coded main image when the container states it apart from the raster size (CR2 lossless-JPEG
|
||||
/// SOF3, RAF FujiIFD, HEIF pixi); preferred over IFD BitsPerSample.</summary>
|
||||
public int? CodedBitsPerSample { get; set; }
|
||||
|
||||
/// <summary>GPS position without its timestamp (merged in <see cref="Build"/>).</summary>
|
||||
public GpsPosition? Gps { get; set; }
|
||||
|
||||
public DateTime? GpsUtc { get; set; }
|
||||
public int? ExifRating { get; set; }
|
||||
public MakerNoteValues MakerNote { get; } = new();
|
||||
public XmpValues Xmp { get; } = new();
|
||||
public IReadOnlyList<string> Warnings => _warnings;
|
||||
|
||||
public void Warn(string message)
|
||||
{
|
||||
if (_warnings.Count < MaxWarnings && !_warnings.Contains(message)) _warnings.Add(message);
|
||||
}
|
||||
|
||||
public void AddWarnings(IEnumerable<string> messages)
|
||||
{
|
||||
foreach (var message in messages) Warn(message);
|
||||
}
|
||||
|
||||
public void ThrowIfCancelled() => Cancellation.ThrowIfCancellationRequested();
|
||||
|
||||
/// <summary>Main-image size defined by the container itself (JPEG SOF, PNG IHDR, HEIF ispe, RAF header…); first call wins
|
||||
/// and it overrides TIFF raster IFDs.</summary>
|
||||
public void SetContainerSize(int width, int height, int? bitsPerSample = null)
|
||||
{
|
||||
if (_container is null && width > 0 && height > 0) _container = new Raster(width, height, bitsPerSample, true);
|
||||
}
|
||||
|
||||
/// <summary>A raster IFD; <paramref name="primary"/> is false for reduced-resolution images (NewSubfileType bit 0).</summary>
|
||||
public void AddRaster(int width, int height, int? bitsPerSample, bool primary)
|
||||
{
|
||||
if (width > 0 && height > 0 && _rasters.Count < MaxRasters) _rasters.Add(new Raster(width, height, bitsPerSample, primary));
|
||||
}
|
||||
|
||||
/// <summary>Records a validated embedded JPEG; duplicates (same offset) keep the first.</summary>
|
||||
public void AddPreview(long offset, long length, int width, int height, PreviewKind? kind = null)
|
||||
{
|
||||
if (width <= 0 || height <= 0 || length <= 0 || _previews.Count >= MaxPreviews) return;
|
||||
foreach (var p in _previews)
|
||||
{
|
||||
if (p.Offset == offset) return;
|
||||
}
|
||||
_previews.Add(new PreviewCandidate(offset, length, width, height, kind));
|
||||
}
|
||||
|
||||
public void AddXmp(byte[]? packet)
|
||||
{
|
||||
if (packet is not null && XmpParser.Parse(packet, Xmp) is { } problem) Warn(problem);
|
||||
}
|
||||
|
||||
/// <summary>Applies the fallback rules and produces the immutable result.</summary>
|
||||
/// <param name="fileModified">File modification time; used when no capture time is recorded.</param>
|
||||
public FrameMetadata Build(DateTime? fileModified)
|
||||
{
|
||||
var main = _container ?? BestRaster() ?? (PixelXDimension is > 0 && PixelYDimension is > 0
|
||||
? new Raster(PixelXDimension.Value, PixelYDimension.Value, null, true)
|
||||
: default(Raster?));
|
||||
var (captured, offset, source) = ResolveCaptureTime(fileModified);
|
||||
var orientation = ResolveOrientation();
|
||||
return new FrameMetadata
|
||||
{
|
||||
Format = Format,
|
||||
Make = Make,
|
||||
Model = Model,
|
||||
BodySerial = BodySerial ?? MakerNote.BodySerial ?? Xmp.BodySerial,
|
||||
LensModel = LensModel ?? MakerNote.LensModel ?? Xmp.Lens,
|
||||
Software = Software,
|
||||
Artist = Artist,
|
||||
Copyright = Copyright,
|
||||
CapturedAt = captured,
|
||||
UtcOffsetMinutes = offset,
|
||||
TimestampSource = source,
|
||||
ExposureTime = ExposureTime,
|
||||
FNumber = FNumber,
|
||||
Iso = ResolveIso(),
|
||||
FocalLength = FocalLength,
|
||||
FocalLength35 = FocalLength35,
|
||||
ExposureBias = ExposureBias,
|
||||
ExposureProgram = ExposureProgram ?? MakerNote.ExposureProgram,
|
||||
MeteringMode = MeteringMode,
|
||||
WhiteBalanceMode = WhiteBalanceMode,
|
||||
ColorTemperature = MakerNote.ColorTemperature,
|
||||
Flash = Flash,
|
||||
Orientation = orientation,
|
||||
Width = main?.Width ?? 0,
|
||||
Height = main?.Height ?? 0,
|
||||
BitsPerSample = CodedBitsPerSample ?? main?.Bits,
|
||||
Gps = Gps is { } g ? g with { UtcTimestamp = GpsUtc } : null,
|
||||
Rating = Xmp.Rating ?? (ExifRating is >= -1 and <= 5 ? ExifRating : null),
|
||||
Label = Xmp.Label,
|
||||
ShutterCount = MakerNote.ShutterCount,
|
||||
ImageStabilization = MakerNote.ImageStabilization,
|
||||
IntervalShooting = MakerNote.IntervalShooting,
|
||||
RawSize = MakerNote.RawSize,
|
||||
Previews = ResolvePreviews(main is { } m ? Math.Max(m.Width, m.Height) : 0),
|
||||
Warnings = _warnings.ToArray(),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Largest full-resolution raster (NewSubfileType bit 0 clear); any raster when none is full-resolution.</summary>
|
||||
private Raster? BestRaster()
|
||||
{
|
||||
Raster? best = null;
|
||||
foreach (var r in _rasters)
|
||||
{
|
||||
if (best is not { } b || (r.Primary && !b.Primary) || (r.Primary == b.Primary && r.Area > b.Area)) best = r;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>Exif original → Exif digitized → XMP → GPS (UTC) → file time.</summary>
|
||||
private (DateTime? Value, int? Offset, TimestampSource Source) ResolveCaptureTime(DateTime? fileModified)
|
||||
{
|
||||
if (DateTimeOriginal is { } original) return (original.Value, original.OffsetMinutes, TimestampSource.ExifOriginal);
|
||||
if (DateTimeDigitized is { } digitized) return (digitized.Value, digitized.OffsetMinutes, TimestampSource.ExifCreate);
|
||||
if (Xmp.CaptureTime is { } xmp) return (xmp.Value, xmp.OffsetMinutes, TimestampSource.Xmp);
|
||||
if (GpsUtc is { } utc) return (DateTime.SpecifyKind(utc, DateTimeKind.Unspecified), 0, TimestampSource.Gps);
|
||||
if (fileModified is { } file)
|
||||
{
|
||||
int? fileOffset = file.Kind switch
|
||||
{
|
||||
DateTimeKind.Local => (int)TimeZoneInfo.Local.GetUtcOffset(file).TotalMinutes,
|
||||
DateTimeKind.Utc => 0,
|
||||
_ => null,
|
||||
};
|
||||
return (DateTime.SpecifyKind(file, DateTimeKind.Unspecified), fileOffset, TimestampSource.FileSystem);
|
||||
}
|
||||
return (null, null, TimestampSource.Unknown);
|
||||
}
|
||||
|
||||
/// <summary>ISOSpeedRatings unless absent or saturated (65535), then REI/SOS/ISOSpeed, then the MakerNote.</summary>
|
||||
private int? ResolveIso()
|
||||
{
|
||||
if (IsoSpeedRatings is > 0 and < SaturatedIso) return IsoSpeedRatings;
|
||||
return (IsoFallback is > 0 ? IsoFallback : null)
|
||||
?? (MakerNote.Iso is > 0 ? MakerNote.Iso : null)
|
||||
?? (IsoSpeedRatings is > 0 ? IsoSpeedRatings : null);
|
||||
}
|
||||
|
||||
private int ResolveOrientation()
|
||||
{
|
||||
if (ContainerOrientation is >= 1 and <= 8) return ContainerOrientation.Value;
|
||||
if (ExifOrientation is >= 1 and <= 8) return ExifOrientation.Value;
|
||||
if (ExifOrientation is { } invalid) Warn($"Invalid orientation {invalid} ignored");
|
||||
return Xmp.Orientation ?? 1;
|
||||
}
|
||||
|
||||
/// <summary>Largest first; kinds by long edge: < 640 px thumbnail, ≥ 90 % of the main image full size.</summary>
|
||||
private EmbeddedPreview[] ResolvePreviews(int mainLongEdge)
|
||||
{
|
||||
var result = new EmbeddedPreview[_previews.Count];
|
||||
for (var i = 0; i < result.Length; i++)
|
||||
{
|
||||
var p = _previews[i];
|
||||
var longEdge = Math.Max(p.Width, p.Height);
|
||||
var kind = p.Kind ?? (longEdge < ThumbnailLongEdge ? PreviewKind.Thumbnail
|
||||
: mainLongEdge > 0 && longEdge >= FullSizeRatio * mainLongEdge ? PreviewKind.FullSize
|
||||
: PreviewKind.Preview);
|
||||
result[i] = new EmbeddedPreview(p.Offset, p.Length, p.Width, p.Height, kind);
|
||||
}
|
||||
Array.Sort(result, static (a, b) =>
|
||||
{
|
||||
var byArea = ((long)b.Width * b.Height).CompareTo((long)a.Width * a.Height);
|
||||
return byArea != 0 ? byArea : b.Length.CompareTo(a.Length);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
private readonly record struct Raster(int Width, int Height, int? Bits, bool Primary)
|
||||
{
|
||||
public long Area => (long)Width * Height;
|
||||
}
|
||||
|
||||
private readonly record struct PreviewCandidate(long Offset, long Length, int Width, int Height, PreviewKind? Kind);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
namespace Chronos.Core.Metadata;
|
||||
|
||||
/// <summary>Camera wall-clock time (DateTimeKind.Unspecified) plus the UTC offset when the file records one.</summary>
|
||||
internal readonly record struct CaptureStamp(DateTime Value, int? OffsetMinutes);
|
||||
|
||||
/// <summary>Parsers for Exif ("YYYY:MM:DD HH:MM:SS"), sub-second, UTC-offset, GPS-date and XMP (ISO 8601) strings.
|
||||
/// Blank, zeroed or out-of-range values yield null rather than a guess.</summary>
|
||||
internal static class MetadataDates
|
||||
{
|
||||
private const int MaxOffsetMinutes = 14 * 60;
|
||||
|
||||
/// <summary>Exif date-time; separators are not checked so "YYYY-MM-DD HH:MM:SS" also parses.</summary>
|
||||
public static DateTime? ParseExif(string? text)
|
||||
{
|
||||
if (text is null) return null;
|
||||
var s = text.AsSpan().Trim();
|
||||
if (s.Length < 19) return null;
|
||||
return Number(s, 0, 4) is { } y && Number(s, 5, 2) is { } mo && Number(s, 8, 2) is { } d
|
||||
&& Number(s, 11, 2) is { } h && Number(s, 14, 2) is { } mi && Number(s, 17, 2) is { } sec
|
||||
? Create(y, mo, d, h, mi, sec, 0)
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>Exif date ("YYYY:MM:DD", e.g. GPSDateStamp) at midnight.</summary>
|
||||
public static DateTime? ParseDate(string? text)
|
||||
{
|
||||
if (text is null) return null;
|
||||
var s = text.AsSpan().Trim();
|
||||
if (s.Length < 10) return null;
|
||||
return Number(s, 0, 4) is { } y && Number(s, 5, 2) is { } mo && Number(s, 8, 2) is { } d ? Create(y, mo, d, 0, 0, 0, 0) : null;
|
||||
}
|
||||
|
||||
/// <summary>SubSecTime digits as a fraction of a second in ticks ("5" → 0.5 s, "123" → 0.123 s).</summary>
|
||||
public static long SubSecondTicks(string? text)
|
||||
{
|
||||
if (text is null) return 0;
|
||||
long ticks = 0;
|
||||
var digits = 0;
|
||||
foreach (var c in text.AsSpan().Trim())
|
||||
{
|
||||
if (c is < '0' or > '9' || digits == 7) break;
|
||||
ticks = ticks * 10 + (c - '0');
|
||||
digits++;
|
||||
}
|
||||
if (digits == 0) return 0;
|
||||
for (; digits < 7; digits++) ticks *= 10;
|
||||
return ticks;
|
||||
}
|
||||
|
||||
/// <summary>"+HH:MM", "-HH:MM", "+HHMM" or "Z" as minutes east of UTC.</summary>
|
||||
public static int? ParseOffset(ReadOnlySpan<char> text)
|
||||
{
|
||||
var s = text.Trim();
|
||||
if (s is "Z") return 0;
|
||||
if (s.Length < 5 || s[0] is not ('+' or '-')) return null;
|
||||
var minuteStart = s[3] == ':' ? 4 : 3;
|
||||
if (Number(s, 1, 2) is not { } h || Number(s, minuteStart, 2) is not { } m || m > 59) return null;
|
||||
var total = h * 60 + m;
|
||||
if (total > MaxOffsetMinutes) return null;
|
||||
return s[0] == '-' ? -total : total;
|
||||
}
|
||||
|
||||
public static int? ParseOffset(string? text) => text is null ? null : ParseOffset(text.AsSpan());
|
||||
|
||||
/// <summary>XMP date "YYYY-MM-DDThh:mm[:ss[.f…]][Z|±hh:mm]"; Exif-style ':' date separators are tolerated.
|
||||
/// Date-only values return null because midnight would be a fabricated capture time.</summary>
|
||||
public static CaptureStamp? ParseIso8601(string? text)
|
||||
{
|
||||
if (text is null) return null;
|
||||
var s = text.AsSpan().Trim();
|
||||
if (s.Length < 16 || s[10] is not ('T' or ' ')) return null;
|
||||
if (Number(s, 0, 4) is not { } y || Number(s, 5, 2) is not { } mo || Number(s, 8, 2) is not { } d
|
||||
|| Number(s, 11, 2) is not { } h || Number(s, 14, 2) is not { } mi)
|
||||
return null;
|
||||
var pos = 16;
|
||||
var sec = 0;
|
||||
long ticks = 0;
|
||||
if (pos < s.Length && s[pos] == ':')
|
||||
{
|
||||
if (Number(s, 17, 2) is not { } parsed) return null;
|
||||
sec = parsed;
|
||||
pos = 19;
|
||||
if (pos < s.Length && s[pos] is '.' or ',')
|
||||
{
|
||||
var end = pos + 1;
|
||||
while (end < s.Length && char.IsAsciiDigit(s[end])) end++;
|
||||
ticks = SubSecondTicks(s[(pos + 1)..end].ToString());
|
||||
pos = end;
|
||||
}
|
||||
}
|
||||
var offset = pos < s.Length ? ParseOffset(s[pos..]) : null;
|
||||
return Create(y, mo, d, h, mi, sec, ticks) is { } value ? new CaptureStamp(value, offset) : null;
|
||||
}
|
||||
|
||||
private static int? Number(ReadOnlySpan<char> s, int start, int length)
|
||||
{
|
||||
if (start + length > s.Length) return null;
|
||||
var value = 0;
|
||||
foreach (var c in s.Slice(start, length))
|
||||
{
|
||||
if (!char.IsAsciiDigit(c)) return null;
|
||||
value = value * 10 + (c - '0');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static DateTime? Create(int y, int mo, int d, int h, int mi, int s, long ticks)
|
||||
{
|
||||
if (y < 1 || mo is < 1 or > 12 || d < 1 || d > DateTime.DaysInMonth(y, mo) || h > 23 || mi > 59 || s > 59) return null;
|
||||
return new DateTime(y, mo, d, h, mi, s, DateTimeKind.Unspecified).AddTicks(ticks);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Metadata.Bmff;
|
||||
using Chronos.Core.Metadata.Jpeg;
|
||||
using Chronos.Core.Metadata.Png;
|
||||
using Chronos.Core.Metadata.Raf;
|
||||
using Chronos.Core.Metadata.Riff;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
|
||||
namespace Chronos.Core.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Reads <see cref="FrameMetadata"/> from any supported photo (BRIEF §9). Detects the container by signature, then
|
||||
/// reads only the structures it needs through bounded seeks (a RAW's image data is never read). Malformed input never
|
||||
/// throws: the result carries whatever was readable plus <see cref="FrameMetadata.Warnings"/>.
|
||||
/// </summary>
|
||||
public static class MetadataReader
|
||||
{
|
||||
private const string LogCategory = "Metadata";
|
||||
private const int FileBufferSize = 4096;
|
||||
|
||||
/// <summary>Reads the file at <paramref name="path"/>; its modification time is the last-resort capture time.</summary>
|
||||
/// <exception cref="IOException">The file cannot be opened (missing or locked).</exception>
|
||||
/// <exception cref="UnauthorizedAccessException">Access to the file is denied.</exception>
|
||||
public static FrameMetadata Read(string path, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(path);
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileBufferSize, FileOptions.RandomAccess);
|
||||
return Read(stream, Path.GetFileName(path), File.GetLastWriteTime(path), cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Reads metadata from a readable, seekable stream (the position is left undefined).</summary>
|
||||
/// <param name="fileName">Name used only to break signature ties (see <see cref="ImageSignature"/>).</param>
|
||||
/// <param name="fileModifiedLocal">File time used when no capture time is recorded (<see cref="Model.TimestampSource.FileSystem"/>);
|
||||
/// its UTC offset is taken from the local zone for <see cref="DateTimeKind.Local"/> values.</param>
|
||||
/// <exception cref="OperationCanceledException">Cancelled through <paramref name="cancellationToken"/>.</exception>
|
||||
public static FrameMetadata Read(Stream stream, string? fileName, DateTime? fileModifiedLocal = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
if (!stream.CanSeek || !stream.CanRead) throw new ArgumentException("The stream must be readable and seekable.", nameof(stream));
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var m = new MetadataBuilder(stream, cancellationToken);
|
||||
try
|
||||
{
|
||||
m.Format = ImageSignature.Detect(stream, fileName);
|
||||
Parse(m);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
m.Warn("I/O error: " + ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Safety net: parsers are written not to throw, but a defect must cost one file's metadata, not the import.
|
||||
m.Warn($"Parser fault: {ex.GetType().Name}: {ex.Message}");
|
||||
Log.Warning(LogCategory, $"Metadata parser fault in {fileName ?? "stream"}", ex);
|
||||
}
|
||||
return m.Build(fileModifiedLocal);
|
||||
}
|
||||
|
||||
private static void Parse(MetadataBuilder m)
|
||||
{
|
||||
switch (m.Format)
|
||||
{
|
||||
case ImageFileFormat.Jpeg:
|
||||
JpegParser.Parse(m, 0, m.Length, primary: true);
|
||||
break;
|
||||
case ImageFileFormat.Png:
|
||||
PngParser.Parse(m);
|
||||
break;
|
||||
case ImageFileFormat.WebP:
|
||||
WebPParser.Parse(m);
|
||||
break;
|
||||
case ImageFileFormat.Heif or ImageFileFormat.Avif:
|
||||
HeifParser.Parse(m);
|
||||
break;
|
||||
case ImageFileFormat.Cr3:
|
||||
Cr3Parser.Parse(m);
|
||||
break;
|
||||
case ImageFileFormat.Raf:
|
||||
RafParser.Parse(m);
|
||||
break;
|
||||
case ImageFileFormat.Gif:
|
||||
MinimalFormatParser.ParseGif(m);
|
||||
break;
|
||||
case ImageFileFormat.Bmp:
|
||||
MinimalFormatParser.ParseBmp(m);
|
||||
break;
|
||||
case ImageFileFormat.JpegXr:
|
||||
MinimalFormatParser.ParseJpegXr(m);
|
||||
break;
|
||||
case ImageFileFormat.JpegXl:
|
||||
MinimalFormatParser.ParseJpegXl(m);
|
||||
break;
|
||||
case ImageFileFormat.Crw:
|
||||
m.Warn("CRW (CIFF) metadata is not supported");
|
||||
break;
|
||||
case ImageFileFormat.Unknown:
|
||||
m.Warn("Unrecognised file signature");
|
||||
break;
|
||||
default:
|
||||
ExifParser.ParseFile(m);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using System.Buffers.Binary;
|
||||
using Chronos.Core.Metadata.Bmff;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
using Chronos.Core.Metadata.Xmp;
|
||||
|
||||
namespace Chronos.Core.Metadata;
|
||||
|
||||
/// <summary>Formats with "minimal" metadata (BRIEF §8.1): GIF and BMP sizes; JPEG XR IFD (size, Exif, GPS, XMP);
|
||||
/// JPEG XL size header plus the container's Exif and XML boxes.</summary>
|
||||
internal static class MinimalFormatParser
|
||||
{
|
||||
private const ushort JxrImageWidth = 0xBC80;
|
||||
private const ushort JxrImageHeight = 0xBC81;
|
||||
|
||||
public static void ParseGif(MetadataBuilder m)
|
||||
{
|
||||
Span<byte> h = stackalloc byte[10];
|
||||
if (m.Stream.TryReadAt(0, h)) m.SetContainerSize(BinaryPrimitives.ReadUInt16LittleEndian(h[6..]), BinaryPrimitives.ReadUInt16LittleEndian(h[8..]));
|
||||
else m.Warn("GIF header truncated");
|
||||
}
|
||||
|
||||
/// <summary>BITMAPCOREHEADER (16-bit sizes) or BITMAPINFOHEADER and later (signed 32-bit; negative height = top-down).</summary>
|
||||
public static void ParseBmp(MetadataBuilder m)
|
||||
{
|
||||
Span<byte> h = stackalloc byte[26];
|
||||
if (!m.Stream.TryReadAt(0, h))
|
||||
{
|
||||
m.Warn("BMP header truncated");
|
||||
return;
|
||||
}
|
||||
if (BinaryPrimitives.ReadUInt32LittleEndian(h[14..]) == 12)
|
||||
{
|
||||
m.SetContainerSize(BinaryPrimitives.ReadUInt16LittleEndian(h[18..]), BinaryPrimitives.ReadUInt16LittleEndian(h[20..]));
|
||||
return;
|
||||
}
|
||||
var width = BinaryPrimitives.ReadInt32LittleEndian(h[18..]);
|
||||
var height = BinaryPrimitives.ReadInt32LittleEndian(h[22..]);
|
||||
if (height != int.MinValue) m.SetContainerSize(width, Math.Abs(height));
|
||||
}
|
||||
|
||||
/// <summary>JPEG XR: a little-endian TIFF-like IFD (magic 0x01BC) with standard Make/Exif/GPS/XMP tags.</summary>
|
||||
public static void ParseJpegXr(MetadataBuilder m)
|
||||
{
|
||||
Span<byte> h = stackalloc byte[8];
|
||||
if (!m.Stream.TryReadAt(0, h))
|
||||
{
|
||||
m.Warn("JPEG XR header truncated");
|
||||
return;
|
||||
}
|
||||
var r = TiffReader.ForEmbedded(m.Stream, 0, littleEndian: true);
|
||||
if (r.ReadIfd(BinaryPrimitives.ReadUInt32LittleEndian(h[4..])) is { } ifd)
|
||||
{
|
||||
ExifParser.ReadTree(r, ifd, m, [ifd.Position]);
|
||||
m.SetContainerSize(IfdValue.Int(r, ifd, JxrImageWidth) ?? 0, IfdValue.Int(r, ifd, JxrImageHeight) ?? 0);
|
||||
}
|
||||
m.AddWarnings(r.Warnings);
|
||||
}
|
||||
|
||||
/// <summary>JPEG XL: bare codestream (FF 0A) or ISO-BMFF container with jxlc/jxlp, Exif and "xml " boxes.</summary>
|
||||
public static void ParseJpegXl(MetadataBuilder m)
|
||||
{
|
||||
Span<byte> h = stackalloc byte[2];
|
||||
if (m.Stream.TryReadAt(0, h) && h[0] == 0xFF && h[1] == 0x0A)
|
||||
{
|
||||
ReadSizeHeader(m, 0);
|
||||
return;
|
||||
}
|
||||
var codestream = false;
|
||||
foreach (var box in BmffReader.ReadChildren(m.Stream, 0, m.Length))
|
||||
{
|
||||
m.ThrowIfCancelled();
|
||||
if (box.Is("Exif")) ExifParser.ParseOffsetPrefixed(m, box.PayloadStart, box.PayloadLength);
|
||||
else if (box.Is("xml ")) m.AddXmp(m.Stream.ReadAt(box.PayloadStart, box.PayloadLength, XmpParser.MaxPacketBytes));
|
||||
else if (!codestream && box.Is("jxlc")) codestream = ReadSizeHeader(m, box.PayloadStart);
|
||||
else if (!codestream && box.Is("jxlp")) codestream = ReadSizeHeader(m, box.PayloadStart + 4);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Codestream SizeHeader (ISO/IEC 18181-1 §D.2): small sizes in multiples of 8, else U32 distributions;
|
||||
/// width either explicit or derived from a fixed aspect ratio.</summary>
|
||||
private static bool ReadSizeHeader(MetadataBuilder m, long position)
|
||||
{
|
||||
Span<byte> b = stackalloc byte[18];
|
||||
var n = m.Stream.ReadUpTo(position, b);
|
||||
if (n < 3 || b[0] != 0xFF || b[1] != 0x0A)
|
||||
{
|
||||
m.Warn("JPEG XL codestream signature missing");
|
||||
return false;
|
||||
}
|
||||
b[n..].Clear();
|
||||
var bits = new BitReader(BinaryPrimitives.ReadUInt128LittleEndian(b[2..]));
|
||||
var small = bits.Read(1) == 1;
|
||||
var height = small ? (bits.Read(5) + 1) * 8 : Distribution(ref bits) + 1;
|
||||
var ratio = (int)bits.Read(3);
|
||||
var width = ratio != 0
|
||||
? height * (ulong)RatioNumerator[ratio] / (ulong)RatioDenominator[ratio]
|
||||
: small ? (bits.Read(5) + 1) * 8 : Distribution(ref bits) + 1;
|
||||
if (width <= int.MaxValue && height <= int.MaxValue) m.SetContainerSize((int)width, (int)height);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static ReadOnlySpan<int> RatioNumerator => [0, 1, 12, 4, 3, 16, 5, 2];
|
||||
private static ReadOnlySpan<int> RatioDenominator => [1, 1, 10, 3, 2, 9, 4, 1];
|
||||
|
||||
private static ulong Distribution(ref BitReader bits) => bits.Read(bits.Read(2) switch { 0 => 9, 1 => 13, 2 => 18, _ => 30 });
|
||||
|
||||
/// <summary>LSB-first bit reader over the 128 bits following the signature (a SizeHeader uses at most 68).</summary>
|
||||
private struct BitReader(UInt128 value)
|
||||
{
|
||||
private UInt128 _value = value;
|
||||
|
||||
public ulong Read(int count)
|
||||
{
|
||||
var v = (ulong)(_value & ((UInt128.One << count) - 1));
|
||||
_value >>= count;
|
||||
return v;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.IO.Compression;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
using Chronos.Core.Metadata.Xmp;
|
||||
|
||||
namespace Chronos.Core.Metadata.Png;
|
||||
|
||||
/// <summary>PNG chunks: IHDR (size, bit depth), eXIf (TIFF), iTXt/tEXt "XML:com.adobe.xmp" (XMP, zlib-compressed iTXt
|
||||
/// supported). Image data chunks are skipped by seeking; CRCs are not verified.</summary>
|
||||
internal static class PngParser
|
||||
{
|
||||
private const int MaxChunks = 4096;
|
||||
private const int KeywordProbeBytes = 80;
|
||||
private static ReadOnlySpan<byte> XmpKeyword => "XML:com.adobe.xmp\0"u8;
|
||||
|
||||
public static void Parse(MetadataBuilder m)
|
||||
{
|
||||
var s = m.Stream;
|
||||
Span<byte> head = stackalloc byte[8 + 13];
|
||||
long pos = 8;
|
||||
for (var i = 0; i < MaxChunks; i++)
|
||||
{
|
||||
m.ThrowIfCancelled();
|
||||
var n = s.ReadUpTo(pos, head);
|
||||
if (n < 8)
|
||||
{
|
||||
m.Warn("PNG truncated before IEND");
|
||||
return;
|
||||
}
|
||||
var length = BinaryPrimitives.ReadUInt32BigEndian(head);
|
||||
var type = head.Slice(4, 4);
|
||||
var data = pos + 8;
|
||||
if (length > int.MaxValue || data > m.Length - length)
|
||||
{
|
||||
m.Warn("PNG chunk runs past the end of the file");
|
||||
return;
|
||||
}
|
||||
if (type.SequenceEqual("IHDR"u8) && length >= 13 && n == head.Length)
|
||||
{
|
||||
var width = BinaryPrimitives.ReadUInt32BigEndian(head[8..]);
|
||||
var height = BinaryPrimitives.ReadUInt32BigEndian(head[12..]);
|
||||
if (width <= int.MaxValue && height <= int.MaxValue) m.SetContainerSize((int)width, (int)height, head[16]);
|
||||
}
|
||||
else if (type.SequenceEqual("eXIf"u8) && length >= 8)
|
||||
{
|
||||
var exif = n >= 14 && head[8..].StartsWith("Exif\0\0"u8) ? data + 6 : data;
|
||||
ExifParser.ParseEmbedded(m, exif);
|
||||
}
|
||||
else if (type.SequenceEqual("iTXt"u8) || type.SequenceEqual("tEXt"u8))
|
||||
{
|
||||
ReadText(m, data, (int)length, international: type[0] == 'i');
|
||||
}
|
||||
else if (type.SequenceEqual("IEND"u8))
|
||||
{
|
||||
return;
|
||||
}
|
||||
pos = data + length + 4;
|
||||
}
|
||||
m.Warn("PNG has too many chunks; rest ignored");
|
||||
}
|
||||
|
||||
/// <summary>XMP text chunk: keyword "XML:com.adobe.xmp"; iTXt adds compression flag/method, language and translated keyword.</summary>
|
||||
private static void ReadText(MetadataBuilder m, long data, int length, bool international)
|
||||
{
|
||||
Span<byte> probe = stackalloc byte[XmpKeyword.Length];
|
||||
if (length < probe.Length || !m.Stream.TryReadAt(data, probe) || !probe.SequenceEqual(XmpKeyword)) return;
|
||||
if (m.Stream.ReadAt(data, length, XmpParser.MaxPacketBytes + KeywordProbeBytes) is not { } chunk)
|
||||
{
|
||||
m.Warn("PNG XMP chunk too large");
|
||||
return;
|
||||
}
|
||||
var r = new SpanReader(chunk);
|
||||
r.Skip(XmpKeyword.Length);
|
||||
var compressed = false;
|
||||
if (international)
|
||||
{
|
||||
compressed = r.U8() == 1;
|
||||
r.Skip(1);
|
||||
r.CString();
|
||||
r.CString();
|
||||
}
|
||||
if (!r.Ok) return;
|
||||
var text = chunk.AsMemory(r.Position);
|
||||
if (!compressed)
|
||||
{
|
||||
m.AddXmp(text.ToArray());
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
using var z = new ZLibStream(new MemoryStream(chunk, r.Position, text.Length, writable: false), CompressionMode.Decompress);
|
||||
using var packet = new MemoryStream();
|
||||
var buffer = new byte[16 * 1024];
|
||||
int read;
|
||||
while ((read = z.Read(buffer)) > 0)
|
||||
{
|
||||
if (packet.Length + read > XmpParser.MaxPacketBytes)
|
||||
{
|
||||
m.Warn("PNG XMP larger than 4 MB ignored");
|
||||
return;
|
||||
}
|
||||
packet.Write(buffer, 0, read);
|
||||
}
|
||||
m.AddXmp(packet.ToArray());
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
m.Warn("PNG compressed XMP is corrupt");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
using Chronos.Core.Metadata.Jpeg;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
|
||||
namespace Chronos.Core.Metadata.Raf;
|
||||
|
||||
/// <summary>
|
||||
/// Fujifilm RAF: "FUJIFILMCCD-RAW " header with a big-endian directory (0x54 JPEG offset/length, 0x5C RAF-directory
|
||||
/// offset/length, 0x64 CFA offset/length). Camera fields come from the embedded JPEG's Exif, which is also the
|
||||
/// preview; the main size from the RAF directory records (0x0111 cropped, else 0x0100 full), bit depth from the
|
||||
/// FujiIFD at the CFA offset when that is a TIFF block.
|
||||
/// </summary>
|
||||
internal static class RafParser
|
||||
{
|
||||
private const int HeaderLength = 0x6C;
|
||||
private const int MaxDirectoryBytes = 64 * 1024;
|
||||
private const int MaxRecords = 512;
|
||||
private const ushort RawImageFullSize = 0x0100;
|
||||
private const ushort RawImageCroppedSize = 0x0111;
|
||||
private const ushort FujiIfd = 0xF000;
|
||||
private const ushort FujiRawWidth = 0xF001;
|
||||
private const ushort FujiRawHeight = 0xF002;
|
||||
private const ushort FujiBitsPerSample = 0xF003;
|
||||
|
||||
public static void Parse(MetadataBuilder m)
|
||||
{
|
||||
var header = m.Stream.ReadAt(0, HeaderLength, HeaderLength);
|
||||
if (header is null)
|
||||
{
|
||||
m.Warn("RAF header truncated");
|
||||
return;
|
||||
}
|
||||
var h = header.AsSpan();
|
||||
var jpegOffset = BinaryPrimitives.ReadUInt32BigEndian(h[0x54..]);
|
||||
var jpegLength = BinaryPrimitives.ReadUInt32BigEndian(h[0x58..]);
|
||||
if (jpegOffset >= HeaderLength && jpegLength > 0 && jpegOffset <= m.Length - jpegLength)
|
||||
JpegParser.Parse(m, jpegOffset, (long)jpegOffset + jpegLength, primary: false);
|
||||
else
|
||||
m.Warn("RAF embedded JPEG missing");
|
||||
ReadDirectory(m, BinaryPrimitives.ReadUInt32BigEndian(h[0x5C..]), BinaryPrimitives.ReadUInt32BigEndian(h[0x60..]));
|
||||
ReadFujiIfd(m, BinaryPrimitives.ReadUInt32BigEndian(h[0x64..]));
|
||||
m.Make ??= "FUJIFILM";
|
||||
m.Model ??= Ascii(h.Slice(0x1C, 32));
|
||||
}
|
||||
|
||||
/// <summary>RAF directory: u32 count, then (u16 tag, u16 size, data) records; sizes are (height, width) pairs.</summary>
|
||||
private static void ReadDirectory(MetadataBuilder m, uint offset, uint length)
|
||||
{
|
||||
if (offset == 0 || m.Stream.ReadAt(offset, Math.Min(length, MaxDirectoryBytes), MaxDirectoryBytes) is not { } data) return;
|
||||
var r = new SpanReader(data);
|
||||
var count = Math.Min(r.U32(), MaxRecords);
|
||||
(int Width, int Height) full = default, cropped = default;
|
||||
for (var i = 0; i < count && r.Ok; i++)
|
||||
{
|
||||
var tag = r.U16();
|
||||
var record = r.Take(r.U16());
|
||||
if (!r.Ok || record.Length < 4) continue;
|
||||
var size = (BinaryPrimitives.ReadUInt16BigEndian(record[2..]), BinaryPrimitives.ReadUInt16BigEndian(record));
|
||||
if (tag == RawImageFullSize) full = size;
|
||||
else if (tag == RawImageCroppedSize) cropped = size;
|
||||
}
|
||||
var best = cropped.Width > 0 && cropped.Height > 0 ? cropped : full;
|
||||
m.SetContainerSize(best.Width, best.Height);
|
||||
}
|
||||
|
||||
private static void ReadFujiIfd(MetadataBuilder m, uint offset)
|
||||
{
|
||||
if (offset == 0 || TiffReader.Open(m.Stream, offset) is not { } r) return;
|
||||
if (r.ReadIfd(r.FirstIfdOffset) is not { } ifd0 || IfdValue.UInt(r, ifd0, FujiIfd) is not { } sub || r.ReadIfd(sub) is not { } fuji) return;
|
||||
m.CodedBitsPerSample ??= IfdValue.Int(r, fuji, FujiBitsPerSample);
|
||||
m.AddRaster(IfdValue.Int(r, fuji, FujiRawWidth) ?? 0, IfdValue.Int(r, fuji, FujiRawHeight) ?? 0, null, true);
|
||||
}
|
||||
|
||||
private static string? Ascii(ReadOnlySpan<byte> field)
|
||||
{
|
||||
var end = field.IndexOf((byte)0);
|
||||
var s = Encoding.ASCII.GetString(end < 0 ? field : field[..end]).Trim();
|
||||
return s.Length > 0 && !s.Any(char.IsControl) ? s : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Buffers.Binary;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
using Chronos.Core.Metadata.Xmp;
|
||||
|
||||
namespace Chronos.Core.Metadata.Riff;
|
||||
|
||||
/// <summary>RIFF/WebP: canvas size from VP8X, else the VP8 key-frame or VP8L header; Exif from "EXIF" (with or without
|
||||
/// an "Exif\0\0" prefix) and XMP from "XMP ". Image data is skipped by seeking.</summary>
|
||||
internal static class WebPParser
|
||||
{
|
||||
private const int MaxChunks = 1024;
|
||||
|
||||
public static void Parse(MetadataBuilder m)
|
||||
{
|
||||
var s = m.Stream;
|
||||
Span<byte> h = stackalloc byte[8 + 10];
|
||||
if (!s.TryReadAt(0, h[..12]))
|
||||
{
|
||||
m.Warn("WebP header truncated");
|
||||
return;
|
||||
}
|
||||
var end = Math.Min(m.Length, 8 + (long)BinaryPrimitives.ReadUInt32LittleEndian(h[4..]));
|
||||
long pos = 12;
|
||||
for (var i = 0; i < MaxChunks && pos <= end - 8; i++)
|
||||
{
|
||||
m.ThrowIfCancelled();
|
||||
var n = s.ReadUpTo(pos, h);
|
||||
var size = BinaryPrimitives.ReadUInt32LittleEndian(h[4..]);
|
||||
var data = pos + 8;
|
||||
var payload = h[8..n];
|
||||
if (size > end - data)
|
||||
{
|
||||
m.Warn("WebP chunk runs past the end of the file");
|
||||
size = (uint)(end - data);
|
||||
}
|
||||
var fourCC = h[..4];
|
||||
if (fourCC.SequenceEqual("VP8X"u8) && payload.Length >= 10)
|
||||
{
|
||||
m.SetContainerSize(1 + UInt24(payload[4..]), 1 + UInt24(payload[7..]), 8);
|
||||
}
|
||||
else if (fourCC.SequenceEqual("VP8 "u8) && payload.Length >= 10 && payload[3..6].SequenceEqual((ReadOnlySpan<byte>)[0x9D, 0x01, 0x2A]))
|
||||
{
|
||||
m.SetContainerSize(BinaryPrimitives.ReadUInt16LittleEndian(payload[6..]) & 0x3FFF, BinaryPrimitives.ReadUInt16LittleEndian(payload[8..]) & 0x3FFF, 8);
|
||||
}
|
||||
else if (fourCC.SequenceEqual("VP8L"u8) && payload.Length >= 5 && payload[0] == 0x2F)
|
||||
{
|
||||
var bits = BinaryPrimitives.ReadUInt32LittleEndian(payload[1..]);
|
||||
m.SetContainerSize((int)(bits & 0x3FFF) + 1, (int)((bits >> 14) & 0x3FFF) + 1, 8);
|
||||
}
|
||||
else if (fourCC.SequenceEqual("EXIF"u8) && size >= 8)
|
||||
{
|
||||
ExifParser.ParseEmbedded(m, payload.StartsWith("Exif\0\0"u8) ? data + 6 : data);
|
||||
}
|
||||
else if (fourCC.SequenceEqual("XMP "u8))
|
||||
{
|
||||
m.AddXmp(s.ReadAt(data, size, XmpParser.MaxPacketBytes));
|
||||
}
|
||||
pos = data + size + (size & 1);
|
||||
}
|
||||
}
|
||||
|
||||
private static int UInt24(ReadOnlySpan<byte> b) => b[0] | b[1] << 8 | b[2] << 16;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
|
||||
namespace Chronos.Core.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Forward-only reader over bytes already in memory. Reading past the end returns zeros and clears <see cref="Ok"/>,
|
||||
/// so a parser can read a whole structure and validate once.
|
||||
/// </summary>
|
||||
internal ref struct SpanReader
|
||||
{
|
||||
private readonly ReadOnlySpan<byte> _data;
|
||||
private readonly bool _bigEndian;
|
||||
private int _position;
|
||||
|
||||
public SpanReader(ReadOnlySpan<byte> data, bool bigEndian = true)
|
||||
{
|
||||
_data = data;
|
||||
_bigEndian = bigEndian;
|
||||
Ok = true;
|
||||
}
|
||||
|
||||
public bool Ok { get; private set; }
|
||||
|
||||
public readonly int Position => _position;
|
||||
|
||||
public readonly int Remaining => _data.Length - _position;
|
||||
|
||||
public byte U8() => Take(1) is [var b] ? b : (byte)0;
|
||||
|
||||
public ushort U16()
|
||||
{
|
||||
var s = Take(2);
|
||||
return s.Length < 2 ? (ushort)0 : _bigEndian ? BinaryPrimitives.ReadUInt16BigEndian(s) : BinaryPrimitives.ReadUInt16LittleEndian(s);
|
||||
}
|
||||
|
||||
public uint U32()
|
||||
{
|
||||
var s = Take(4);
|
||||
return s.Length < 4 ? 0 : _bigEndian ? BinaryPrimitives.ReadUInt32BigEndian(s) : BinaryPrimitives.ReadUInt32LittleEndian(s);
|
||||
}
|
||||
|
||||
public ulong U64()
|
||||
{
|
||||
var s = Take(8);
|
||||
return s.Length < 8 ? 0 : _bigEndian ? BinaryPrimitives.ReadUInt64BigEndian(s) : BinaryPrimitives.ReadUInt64LittleEndian(s);
|
||||
}
|
||||
|
||||
/// <summary>Unsigned integer stored in 0, 4 or 8 bytes (ISO-BMFF <c>iloc</c> field sizes); other sizes fail.</summary>
|
||||
public ulong Sized(int bytes)
|
||||
{
|
||||
switch (bytes)
|
||||
{
|
||||
case 0: return 0;
|
||||
case 4: return U32();
|
||||
case 8: return U64();
|
||||
default:
|
||||
Ok = false;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public void Skip(int count) => Take(count);
|
||||
|
||||
/// <summary>The next <paramref name="count"/> bytes; empty (and <see cref="Ok"/> cleared) when fewer remain.</summary>
|
||||
public ReadOnlySpan<byte> Take(int count)
|
||||
{
|
||||
if (count < 0 || count > Remaining)
|
||||
{
|
||||
Ok = false;
|
||||
_position = _data.Length;
|
||||
return default;
|
||||
}
|
||||
var s = _data.Slice(_position, count);
|
||||
_position += count;
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>NUL-terminated UTF-8 string (the terminator is consumed); the rest of the data when unterminated.</summary>
|
||||
public string CString()
|
||||
{
|
||||
var rest = _data[_position..];
|
||||
var end = rest.IndexOf((byte)0);
|
||||
var length = end < 0 ? rest.Length : end;
|
||||
_position += end < 0 ? length : length + 1;
|
||||
return Encoding.UTF8.GetString(rest[..length]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace Chronos.Core.Metadata;
|
||||
|
||||
/// <summary>Bounds-checked positional reads shared by the container parsers (windowed access, never whole files).</summary>
|
||||
internal static class StreamExtensions
|
||||
{
|
||||
/// <summary>Fills <paramref name="buffer"/> from <paramref name="position"/>; false when the range leaves the stream.</summary>
|
||||
public static bool TryReadAt(this Stream stream, long position, Span<byte> buffer)
|
||||
{
|
||||
if (position < 0 || position > stream.Length - buffer.Length) return false;
|
||||
stream.Position = position;
|
||||
return stream.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) == buffer.Length;
|
||||
}
|
||||
|
||||
/// <summary>Reads <paramref name="length"/> bytes at <paramref name="position"/>; null when out of range or above <paramref name="maxLength"/>.</summary>
|
||||
public static byte[]? ReadAt(this Stream stream, long position, long length, long maxLength)
|
||||
{
|
||||
if (length < 0 || length > maxLength || position < 0 || position > stream.Length - length) return null;
|
||||
var buffer = new byte[length];
|
||||
return stream.TryReadAt(position, buffer) ? buffer : null;
|
||||
}
|
||||
|
||||
/// <summary>Reads up to <paramref name="buffer"/>.Length bytes at <paramref name="position"/>; returns the count read.</summary>
|
||||
public static int ReadUpTo(this Stream stream, long position, Span<byte> buffer)
|
||||
{
|
||||
if (position < 0 || position >= stream.Length) return 0;
|
||||
var n = (int)Math.Min(buffer.Length, stream.Length - position);
|
||||
stream.Position = position;
|
||||
return stream.ReadAtLeast(buffer[..n], n, throwOnEndOfStream: false);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
using System.Globalization;
|
||||
using System.Xml;
|
||||
|
||||
namespace Chronos.Core.Metadata.Xmp;
|
||||
|
||||
/// <summary>
|
||||
/// Streaming XMP reader (no DTDs, no external resolution, 4 MB cap). Reads both the attribute form
|
||||
/// (<c><rdf:Description xmp:Rating="5"/></c>) and the element form (<c><xmp:Rating>5</xmp:Rating></c>,
|
||||
/// including values nested in <c>rdf:Alt</c>/<c>rdf:Seq</c>) of the properties in <see cref="XmpValues"/>.
|
||||
/// </summary>
|
||||
internal static class XmpParser
|
||||
{
|
||||
public const int MaxPacketBytes = 4 * 1024 * 1024;
|
||||
|
||||
private const string NsXmp = "http://ns.adobe.com/xap/1.0/";
|
||||
private const string NsExif = "http://ns.adobe.com/exif/1.0/";
|
||||
private const string NsAux = "http://ns.adobe.com/exif/1.0/aux/";
|
||||
private const string NsExifEx = "http://cipa.jp/exif/1.0/";
|
||||
private const string NsPhotoshop = "http://ns.adobe.com/photoshop/1.0/";
|
||||
private const string NsTiff = "http://ns.adobe.com/tiff/1.0/";
|
||||
private const string NsXmpNote = "http://ns.adobe.com/xmp/note/";
|
||||
|
||||
private static readonly XmlReaderSettings Settings = new()
|
||||
{
|
||||
DtdProcessing = DtdProcessing.Prohibit,
|
||||
XmlResolver = null,
|
||||
IgnoreComments = true,
|
||||
IgnoreProcessingInstructions = true,
|
||||
IgnoreWhitespace = true,
|
||||
MaxCharactersInDocument = MaxPacketBytes,
|
||||
CloseInput = true,
|
||||
};
|
||||
|
||||
private enum Property
|
||||
{
|
||||
None,
|
||||
Rating,
|
||||
Label,
|
||||
DateTimeOriginal,
|
||||
DateCreated,
|
||||
CreateDate,
|
||||
Orientation,
|
||||
AuxSerialNumber,
|
||||
BodySerialNumber,
|
||||
AuxLens,
|
||||
LensModel,
|
||||
HasExtendedXmp,
|
||||
}
|
||||
|
||||
/// <summary>Parses one packet into <paramref name="values"/>, keeping values that are already set.</summary>
|
||||
/// <returns>Null on success; otherwise why parsing stopped (values read before the problem are kept).</returns>
|
||||
public static string? Parse(byte[] packet, XmpValues values)
|
||||
{
|
||||
var length = packet.Length;
|
||||
while (length > 0 && packet[length - 1] == 0) length--;
|
||||
if (length == 0) return "Empty XMP packet";
|
||||
if (length > MaxPacketBytes) return "XMP packet larger than 4 MB ignored";
|
||||
try
|
||||
{
|
||||
using var reader = XmlReader.Create(new MemoryStream(packet, 0, length, writable: false), Settings);
|
||||
var pending = Property.None;
|
||||
var pendingDepth = 0;
|
||||
while (reader.Read())
|
||||
{
|
||||
switch (reader.NodeType)
|
||||
{
|
||||
case XmlNodeType.Element:
|
||||
if (reader.MoveToFirstAttribute())
|
||||
{
|
||||
do Assign(values, Lookup(reader.NamespaceURI, reader.LocalName), reader.Value);
|
||||
while (reader.MoveToNextAttribute());
|
||||
reader.MoveToElement();
|
||||
}
|
||||
if (pending == Property.None && !reader.IsEmptyElement)
|
||||
{
|
||||
pending = Lookup(reader.NamespaceURI, reader.LocalName);
|
||||
pendingDepth = reader.Depth;
|
||||
}
|
||||
break;
|
||||
case XmlNodeType.Text or XmlNodeType.CDATA:
|
||||
if (pending != Property.None)
|
||||
{
|
||||
Assign(values, pending, reader.Value);
|
||||
pending = Property.None;
|
||||
}
|
||||
break;
|
||||
case XmlNodeType.EndElement:
|
||||
if (reader.Depth <= pendingDepth) pending = Property.None;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
catch (XmlException ex)
|
||||
{
|
||||
return "Malformed XMP: " + ex.Message;
|
||||
}
|
||||
}
|
||||
|
||||
private static Property Lookup(string ns, string name) => ns switch
|
||||
{
|
||||
NsXmp => name switch
|
||||
{
|
||||
"Rating" => Property.Rating,
|
||||
"Label" => Property.Label,
|
||||
"CreateDate" => Property.CreateDate,
|
||||
_ => Property.None,
|
||||
},
|
||||
NsExif when name == "DateTimeOriginal" => Property.DateTimeOriginal,
|
||||
NsPhotoshop when name == "DateCreated" => Property.DateCreated,
|
||||
NsTiff when name == "Orientation" => Property.Orientation,
|
||||
NsAux => name switch
|
||||
{
|
||||
"SerialNumber" => Property.AuxSerialNumber,
|
||||
"Lens" => Property.AuxLens,
|
||||
_ => Property.None,
|
||||
},
|
||||
NsExifEx => name switch
|
||||
{
|
||||
"BodySerialNumber" => Property.BodySerialNumber,
|
||||
"LensModel" => Property.LensModel,
|
||||
_ => Property.None,
|
||||
},
|
||||
NsXmpNote when name == "HasExtendedXMP" => Property.HasExtendedXmp,
|
||||
_ => Property.None,
|
||||
};
|
||||
|
||||
private static void Assign(XmpValues v, Property property, string raw)
|
||||
{
|
||||
var text = raw.Trim();
|
||||
if (property == Property.None || text.Length == 0) return;
|
||||
switch (property)
|
||||
{
|
||||
case Property.Rating:
|
||||
if (double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var rating) && rating is >= -1 and <= 5)
|
||||
v.Rating ??= (int)Math.Round(rating);
|
||||
break;
|
||||
case Property.Label:
|
||||
v.Label ??= text;
|
||||
break;
|
||||
case Property.DateTimeOriginal:
|
||||
v.DateTimeOriginal ??= MetadataDates.ParseIso8601(text);
|
||||
break;
|
||||
case Property.DateCreated:
|
||||
v.DateCreated ??= MetadataDates.ParseIso8601(text);
|
||||
break;
|
||||
case Property.CreateDate:
|
||||
v.CreateDate ??= MetadataDates.ParseIso8601(text);
|
||||
break;
|
||||
case Property.Orientation:
|
||||
if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var o) && o is >= 1 and <= 8)
|
||||
v.Orientation ??= o;
|
||||
break;
|
||||
case Property.AuxSerialNumber:
|
||||
v.AuxSerialNumber ??= text;
|
||||
break;
|
||||
case Property.BodySerialNumber:
|
||||
v.BodySerialNumber ??= text;
|
||||
break;
|
||||
case Property.AuxLens:
|
||||
v.AuxLens ??= text;
|
||||
break;
|
||||
case Property.LensModel:
|
||||
v.LensModel ??= text;
|
||||
break;
|
||||
case Property.HasExtendedXmp:
|
||||
v.ExtendedXmpGuid ??= text;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
namespace Chronos.Core.Metadata.Xmp;
|
||||
|
||||
/// <summary>The XMP properties Chronos reads. Each is set by the first packet that carries it.</summary>
|
||||
internal sealed class XmpValues
|
||||
{
|
||||
public int? Rating { get; set; }
|
||||
public string? Label { get; set; }
|
||||
|
||||
/// <summary>exif:DateTimeOriginal.</summary>
|
||||
public CaptureStamp? DateTimeOriginal { get; set; }
|
||||
|
||||
/// <summary>photoshop:DateCreated.</summary>
|
||||
public CaptureStamp? DateCreated { get; set; }
|
||||
|
||||
/// <summary>xmp:CreateDate.</summary>
|
||||
public CaptureStamp? CreateDate { get; set; }
|
||||
|
||||
public int? Orientation { get; set; }
|
||||
|
||||
/// <summary>aux:SerialNumber.</summary>
|
||||
public string? AuxSerialNumber { get; set; }
|
||||
|
||||
/// <summary>exifEX:BodySerialNumber.</summary>
|
||||
public string? BodySerialNumber { get; set; }
|
||||
|
||||
/// <summary>aux:Lens.</summary>
|
||||
public string? AuxLens { get; set; }
|
||||
|
||||
/// <summary>exifEX:LensModel.</summary>
|
||||
public string? LensModel { get; set; }
|
||||
|
||||
/// <summary>xmpNote:HasExtendedXMP: GUID of the extended packet split across JPEG APP1 segments.</summary>
|
||||
public string? ExtendedXmpGuid { get; set; }
|
||||
|
||||
/// <summary>Capture time in MWG order: DateTimeOriginal, DateCreated, CreateDate.</summary>
|
||||
public CaptureStamp? CaptureTime => DateTimeOriginal ?? DateCreated ?? CreateDate;
|
||||
|
||||
public string? BodySerial => BodySerialNumber ?? AuxSerialNumber;
|
||||
|
||||
public string? Lens => LensModel ?? AuxLens;
|
||||
}
|
||||
Reference in new issue
Block a user