using System.Buffers.Binary; using System.Text; using Chronos.Core.Metadata.Tiff; namespace Chronos.Core.Tests.Metadata.Builders; /// Declarative IFD for synthetic test files: typed values, child-IFD pointers, data blobs and embedded /// (MakerNote-style) IFDs. Serialised by in either byte order. internal sealed class IfdSpec { internal abstract record Entry(ushort Tag); internal sealed record ValueEntry(ushort Tag, TiffType Type, object Data) : Entry(Tag); internal sealed record ChildrenEntry(ushort Tag, IfdSpec[] Children) : Entry(Tag); internal sealed record BlobEntry(ushort Tag, byte[] Data) : Entry(Tag); internal sealed record EmbeddedEntry(ushort Tag, byte[] Prefix, IfdSpec Ifd, bool RelativeToTiff, bool LittleEndian) : Entry(Tag); public List Entries { get; } = []; /// Next IFD in the chain (IFD1 after IFD0…). public IfdSpec? Next { get; set; } public IfdSpec Ascii(ushort tag, string value) => Add(new ValueEntry(tag, TiffType.Ascii, value)); public IfdSpec Short(ushort tag, params ushort[] values) => Add(new ValueEntry(tag, TiffType.Short, values)); public IfdSpec Long(ushort tag, params uint[] values) => Add(new ValueEntry(tag, TiffType.Long, values)); public IfdSpec Rational(ushort tag, params (uint, uint)[] values) => Add(new ValueEntry(tag, TiffType.Rational, values)); public IfdSpec SRational(ushort tag, int numerator, int denominator) => Add(new ValueEntry(tag, TiffType.SRational, new[] { (numerator, denominator) })); public IfdSpec Undefined(ushort tag, byte[] data) => Add(new ValueEntry(tag, TiffType.Undefined, data)); public IfdSpec Bytes(ushort tag, params byte[] data) => Add(new ValueEntry(tag, TiffType.Byte, data)); /// LONG pointer(s) to child IFDs (Exif, GPS, SubIFDs, MakerNote sub-directories). public IfdSpec Child(ushort tag, params IfdSpec[] children) => Add(new ChildrenEntry(tag, children)); /// LONG offset to (placed after all IFDs) plus an optional LONG length tag. public IfdSpec Blob(ushort offsetTag, ushort? lengthTag, byte[] data) { Add(new BlobEntry(offsetTag, data)); return lengthTag is { } t ? Long(t, (uint)data.Length) : this; } public IfdSpec Strip(byte[] data) => Blob(TiffTags.StripOffsets, TiffTags.StripByteCounts, data); /// UNDEFINED value made of and an IFD whose offsets are relative to the TIFF base /// () or to the start of the value itself. public IfdSpec Embedded(ushort tag, byte[] prefix, IfdSpec ifd, bool relativeToTiff, bool littleEndian) => Add(new EmbeddedEntry(tag, prefix, ifd, relativeToTiff, littleEndian)); public IfdSpec Without(params ushort[] tags) { Entries.RemoveAll(e => tags.Contains(e.Tag)); return this; } private IfdSpec Add(Entry entry) { Entries.RemoveAll(e => e.Tag == entry.Tag); Entries.Add(entry); return this; } } /// Serialises trees: IFDs in depth-first order, each followed by its values, blobs last. internal static class TiffFile { /// A complete TIFF file/block with header ( overrides "II*\0"/"MM\0*", e.g. "IIRO"); /// follows the 8-byte header (the CR2 "CR" marker block). public static byte[] Build(IfdSpec ifd0, bool littleEndian = true, string? magic = null, byte[]? headerExtra = null) { var w = new IfdWriter(littleEndian, 0); w.Raw(Encoding.Latin1.GetBytes(magic ?? (littleEndian ? "II*\0" : "MM\0*"))); w.Raw(new byte[4]); if (headerExtra is not null) w.Raw(headerExtra); w.PatchU32(4, (uint)w.WriteChain(ifd0)); w.FlushBlobs(); return w.ToArray(); } /// An IFD and its values laid out as if placed at relative to the offset base. public static byte[] Block(IfdSpec ifd, bool littleEndian, int origin) { var w = new IfdWriter(littleEndian, origin); w.WriteChain(ifd); w.FlushBlobs(); return w.ToArray(); } private sealed class IfdWriter(bool le, int origin) { private readonly List _b = []; private readonly List<(int Patch, byte[] Data)> _blobs = []; public byte[] ToArray() => _b.ToArray(); public void Raw(byte[] bytes) => _b.AddRange(bytes); public int WriteChain(IfdSpec spec) { var position = WriteIfd(spec, out var nextPatch); if (spec.Next is { } next) PatchU32(nextPatch, (uint)WriteChain(next)); return position; } public void FlushBlobs() { foreach (var (patch, data) in _blobs) { Align(); PatchU32(patch, (uint)(origin + _b.Count)); _b.AddRange(data); } _blobs.Clear(); } public void PatchU32(int at, uint value) { Span s = stackalloc byte[4]; if (le) BinaryPrimitives.WriteUInt32LittleEndian(s, value); else BinaryPrimitives.WriteUInt32BigEndian(s, value); for (var i = 0; i < 4; i++) _b[at + i] = s[i]; } private void PatchU16(int at, ushort value) { Span s = stackalloc byte[2]; if (le) BinaryPrimitives.WriteUInt16LittleEndian(s, value); else BinaryPrimitives.WriteUInt16BigEndian(s, value); _b[at] = s[0]; _b[at + 1] = s[1]; } private void Align() { if ((origin + _b.Count) % 2 != 0) _b.Add(0); } private int WriteIfd(IfdSpec spec, out int nextPatch) { Align(); var start = _b.Count; var entries = spec.Entries.OrderBy(e => e.Tag).ToList(); _b.AddRange(new byte[2 + 12 * entries.Count + 4]); PatchU16(start, (ushort)entries.Count); nextPatch = start + 2 + 12 * entries.Count; var children = new List<(int Patch, IfdSpec Child)>(); for (var i = 0; i < entries.Count; i++) { var at = start + 2 + 12 * i; var e = entries[i]; PatchU16(at, e.Tag); switch (e) { case IfdSpec.ValueEntry v: var (bytes, count) = Encode(v); PutValue(at, v.Type, count, bytes); break; case IfdSpec.ChildrenEntry c: PatchU16(at + 2, (ushort)TiffType.Long); PatchU32(at + 4, (uint)c.Children.Length); if (c.Children.Length == 1) { children.Add((at + 8, c.Children[0])); } else { Align(); PatchU32(at + 8, (uint)(origin + _b.Count)); for (var k = 0; k < c.Children.Length; k++) { children.Add((_b.Count, c.Children[k])); _b.AddRange(new byte[4]); } } break; case IfdSpec.BlobEntry blob: PatchU16(at + 2, (ushort)TiffType.Long); PatchU32(at + 4, 1); _blobs.Add((at + 8, blob.Data)); break; case IfdSpec.EmbeddedEntry m: Align(); var position = origin + _b.Count; var block = Block(m.Ifd, m.LittleEndian, m.RelativeToTiff ? position + m.Prefix.Length : m.Prefix.Length); PatchU16(at + 2, (ushort)TiffType.Undefined); PatchU32(at + 4, (uint)(m.Prefix.Length + block.Length)); PatchU32(at + 8, (uint)position); _b.AddRange(m.Prefix); _b.AddRange(block); break; } } foreach (var (patch, child) in children) PatchU32(patch, (uint)WriteChain(child)); return origin + start; } private void PutValue(int at, TiffType type, uint count, byte[] bytes) { PatchU16(at + 2, (ushort)type); PatchU32(at + 4, count); if (bytes.Length <= 4) { for (var i = 0; i < bytes.Length; i++) _b[at + 8 + i] = bytes[i]; return; } Align(); PatchU32(at + 8, (uint)(origin + _b.Count)); _b.AddRange(bytes); } private (byte[] Bytes, uint Count) Encode(IfdSpec.ValueEntry v) { switch (v.Data) { case string s: var ascii = Encoding.UTF8.GetBytes(s + "\0"); return (ascii, (uint)ascii.Length); case byte[] raw: return (raw, (uint)raw.Length); case ushort[] shorts: { var b = new byte[2 * shorts.Length]; for (var i = 0; i < shorts.Length; i++) Write16(b.AsSpan(2 * i), shorts[i]); return (b, (uint)shorts.Length); } case uint[] longs: { var b = new byte[4 * longs.Length]; for (var i = 0; i < longs.Length; i++) Write32(b.AsSpan(4 * i), longs[i]); return (b, (uint)longs.Length); } case (uint, uint)[] rationals: { var b = new byte[8 * rationals.Length]; for (var i = 0; i < rationals.Length; i++) { Write32(b.AsSpan(8 * i), rationals[i].Item1); Write32(b.AsSpan(8 * i + 4), rationals[i].Item2); } return (b, (uint)rationals.Length); } case (int, int)[] signed: { var b = new byte[8 * signed.Length]; for (var i = 0; i < signed.Length; i++) { Write32(b.AsSpan(8 * i), (uint)signed[i].Item1); Write32(b.AsSpan(8 * i + 4), (uint)signed[i].Item2); } return (b, (uint)signed.Length); } default: throw new InvalidOperationException("Unsupported test value " + v.Data.GetType()); } } private void Write16(Span s, ushort v) { if (le) BinaryPrimitives.WriteUInt16LittleEndian(s, v); else BinaryPrimitives.WriteUInt16BigEndian(s, v); } private void Write32(Span s, uint v) { if (le) BinaryPrimitives.WriteUInt32LittleEndian(s, v); else BinaryPrimitives.WriteUInt32BigEndian(s, v); } } }